text:
Q: ReactiveCrudRepository to use Hibernate in spring Is it possible to use Hibernate and RDBMS(Mysql, Postgres etc) with ReactiveCrudRepository instead of CrudRepository?  I have tried some samples with Spring Data Jpa and Hibernate, but couldn't get it done.  I was only able to find a few samples on ReactiveCrudRepository for MongoDB and cassandra.

A:
Is it possible to use Hibernate and Mysql with ReactiveCrudRepository instead of CrudRepository?

TL;DR:
Not with Hibernate and MySQL, but with R2DBC and Postgres, Microsoft SQL Server or H2.
Take a look at Spring Data R2DBC.
Long Version
Why not JPA?
With Hibernate/JPA included this won't happen in the foreseeable future.
JPA is based on the idea that you load part of your data model into memory, manipulate the resulting object model and let JPA transform these changes.
All this within a single transaction.
This is kind of the opposite how one deals with a reactive store where you try to make atomic changes and try to decouple the loading, processing and storing and all this without blocking.
Why not JDBC?
So we have to look at the technology level below JPA: JDBC.
But JDBC is still blocking: You send a SQL statement to your database and then JDBC will block until you get the result.
And again this goes against the idea of reactive: Never block.
One could wrap this in a thread pool to mitigate this to some extent, but that is more of a workaround than a solution.
Why R2DBC?
There are some suitable drivers for some databases that could be used for reactive repositories.
But they are proprietary and thereby not a good basis for something that really should eventually work across all (relevant) relational databases.
For some time the Spring Data team hoped that ADBA would fill that gap.
But discussions on the mailing list made it clear that ADBA was not aiming for reactive but only for asynchronous.
Again not what we needed for a reactive repository abstraction.
So early in 2018 various people living at the intersection or reactive and relational decided that we need a standard for reactive database access.
R2DBC (Reactive Relational Database Connectivity)
is a proposal for such a standard.
The hope is that it either helps convincing Oracle to move ADBA to a reactive approach or if that doesn't happen it becomes the standard itself.
And with already three implementations available chances for the second option look promising.
R2DBC itself is mainly an SPI, i.e. an API that is to be implemented by database providers.
The SPI is designed in a way that puts minimal requirements on implementers.
But this also makes R2DBC somewhat cumbersome to use.
The idea is that other libraries will step up and build libraries designed for usability on top of that SPI, as it happened with JDBC.
Spring Data R2DBC
Spring Data R2DBC is one such library and it offers what you asked for: Support for ReactiveCrudRepository although it is independent of JPA/Hibernate and there is no support for MySQL yet.
State of the projects
Both R2DBC and Spring Data R2DBC didn't have a production release yet and it will take at least several months to get there.
Spring Data R2DBC just released the first milestone.
See the release article for its current capabilities.
R2DBC is on its 6th milestone. See the release article for details.
See also this answer: Why does Spring not provide reactive (non-blocking) clients for relational databases?
Original answer as a reference for archeologists:
As of now (Jan 2017) it is not possible.
The currently relevant release for the reactive part of Spring Data is  Spring Data Kay M1  (You can check if there is a newer version available on the project home page)
And a blog post from the Spring Data team about that release and specifically the reactive parts in it starts with (emphasis mine):

Spring Data Kay M1 is the first release ever that comes with support for reactive data access. Its initial set of supported stores — MongoDB, Apache Cassandra, and Redis — all ship reactive drivers already, which made them very natural candidates for such a prototype.

The reason is that there is no standard non-blocking way to access a relational database. So only those that support this kind of API are supported right now.
One could implement a ReactiveCrudRepository using JPA or JDBC and delegate the work to a thread pool. This would provide an async API on the outside, but would still consume the resources for the Threads and block between independent data accesses, so only a small part of the benefits of the reactive approach would get realized.

A: Hibernate started a new Hibernate Reactive subproject for reactive streams support which provides Hibernate/JPA similar APIs to access RDBMS. But unfortunately at the moment, Spring Data does not support it. So there is no a ReactiveCrudRepoisoty for Hibernate Reactive.
But you can integrate Hibernate with Spring yourself and get reactive support.

*

*Define a persistence.xml file, note the provider class must be specified as the one in Hibernate Reactive.

*Declare a Mutiny.SessionFactory bean.

*Then inject it in your repository class.

I have created a complete example demos Hibernate Reactive + Spring.
Update: Till now Spring team has no plan to support it, if you are willing to taste other framework, check Quarkus and Micronaunt, both have seamless Hibernate Reactive support. Check my Quarkus Hibernate Reactive example and Micronaut Hibernate Reactive example.

A: According to quote from previous answer

One could implement a ReactiveCrudRepository using JPA or JDBC and delegating the work to a thread pool. This would provide an async API on the outside, but would still consume the resources for the Threads and block between independent data accesses, so only a small part of the benefits of the reactive approach would get realized.

James Ward claims it can be non-blocking. I mean I asked him:

yeah ok, but isn't ScalikeJDBC-Async doing exactly the same? just putting query invocation into another thread pool?

and he replied

No because ScalalikeJDBC-Async uses https://github.com/mauricio... which is actually a non-blocking (NIO) JDBCish database driver.

source
So you can be reactive by replacing hibernate + spring data with postgresql-async (should work with mysql).

A: you could try with quarkus framework and panache mongo hibernate reactive repositories. https://quarkus.io/guides/mongodb-panache  .It is easy manage a reactive repository over mongoDB, It is later but hope helps.


text:
Q: Keycloak Hardcoded Group Mapper So I have been adding a specific group to just one set of federated users in Keycloak with the hardcoded ldap group mapper.  This happens on user registration and successfully adds them to the group in KC.  However, I also need this same group to map back to the federated ldap and this is not happening due I am presuming to this line of code in the mapper (which I am looking at on keycloak github):
@Override  public void onRegisterUserToLDAP(LDAPObject ldapUser, UserModel localUser, RealmModel realm)
My issue is that I cannot find this file anywhere on my Keycloak server (HardcodedLDAPGroupStorageMapper.java) to try commenting it out and am also presuming (lots of that going on right now!!) that it is renamed or hidden in some other jar file or something...
Would appreciate any help on this or another method to be able to add users to a group for just one of my three federated clients that will also allow it to sync back to the ldap server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Preventing cookies sharing in the same domain in ASP.NET I have two sites in the same domain. This sites are sharing cookies across this domain. In web.config I have
<system.web>
 <authentication mode="none">
  <forms loginUrl="login.aspx" />
 </authentication>

I can't predict the domain name too.
How to stop this?


text:
Q: Why do my .GIFs written with MatLab always skip the second image frame in the first display loop? Consider the following MCVE:
B = 50 - randi(100,100,100,4);

% Show each of the 4 layers of A for 0.50 seconds each, and save image frames:
fig=figure();
for idx = 1:size(B,3)
    imagesc( B(:,:,idx) ); title(num2str(idx)); caxis([-50 50]); drawnow;
    frame = getframe(fig);
    img{idx} = frame2im(frame);
    pause(0.50);
end

% Write a .gif file, show each image 1 second in infinite loop.
filename = 'whatsgoingon.gif'; dlyt = 1;
for idx=1:length(img)
    [A,map]=rgb2ind(img{idx},256);
    if idx==1;  imwrite(A,map,filename,'gif','LoopCount',Inf,'DelayTime',dlyt);
    else;       imwrite(A,map,filename,'gif','WriteMode','append','DelayTime',dlyt);
    end
end

Each image shows a layer of the cube B. I wrote some code to make a .gif file out of this to make it easier to share. The problem I have with that is: each time I open the .gif file, it will skip the second frame (i.e. the one associated with B(:,:,2)) on the first loop of showing. Essentially, the .gif shows the following frames in chronological order:
1, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, etc.
This is not a huge problem, just a bit embarassing when I am sharing some results with others. I can't seem to find any topic on a similar issue (neither here nor on Matlab's website), so I would be very curious to hear if you see the same issue when you make a gif using the above code, and if you would have any idea where it originates.
FYI: I am using Matlab R2018a on a Windows machine.
EDIT: here is an example image I created:

A: Just a summary of the comments for future readers...
You can check the delays and details in an animated GIF with ImageMgick on the command line like this:
magick identify -format "%f[%s] %T\n" matlab.gif

Sample Output
matlab.gif[0] 100      <--- this frame has a 100 centisecond delay
matlab.gif[1] 100
matlab.gif[2] 100
matlab.gif[3] 100

This command is similar - use FINDSTR on Windows in place of grep:
magick identify -verbose matlab.gif | grep Delay
Delay: 100x100
Delay: 100x100
Delay: 100x100
Delay: 100x100

If you want to debug an animated GIF but it is too fast to see, you can reset all the timings - say to 3s per frame - like this:
magick input.gif -coalesce -set delay 300 slooooow.gif

Note that some applications display animated GIFs incorrectly, so try using Open->File in a web-browser to check. Try Chrome, Firefox, Opera, Safari etc.

If you are really having problems passing GIFs to colleagues and getting understood, you can make a cartoon-strip out of an animation like this:
magick input.gif -coalesce +append result.gif

Or, you can make a montage on a grid like this:
magick input.gif -coalesce miff:- | magick montage -geometry +10+10 -  result.gif


text:
Q: Library not loaded: /opt/local/lib/libffi.5.dylib I am compiling some C++ code on Mac OX Snow Leopard (MacPorts).
I got error message:
collect2: error: ld terminated with signal 5 [Trace/BPT trap]
dyld: Library not loaded: /opt/local/lib/libffi.5.dylib
Referenced from: /opt/local/libexec/llvm-3.3/lib/libLTO.dylib
Reason: image not found
I know libffi was updated to a newer version which now provides libffi version 6 that I have now.
Any help? Thanks.

A: Try 'sudo port rev-upgrade' first.* This should identify missing / mis-linked files and rebuild the required ports. (Will use pre-compiled binaries rather than build when permitted by licenses and config.)
In general, you may find the mailing list the most productive place to ask these questions. https://lists.macosforge.org/mailman/listinfo/macports-users

*

*actually, do 'sudo port selfupdate && sudo port upgrade outdated' first if you haven't recently.


text:
Q: Using setAttributeNS in each loop I need to change the url on all svg's on my page. I have the following code, but get a error when i try to use setAttributeNS.
jQuery("[*|href*='icons.svg']:not([href])").each(function () {

  hashedIconUrl = jQuery(this).attr('xlink:href').replace('icons.svg', hashedIcon);
  console.log(hashedIconUrl);

  jQuery(this).setAttributeNS('http://www.w3.org/1999/xlink', 'href', hashedIconUrl);
});

A: You need to convert from the jQuery object to the native DOM object to call setAttributeNS. The usual way to do this is via [0]
jQuery("[*|href*='icons.svg']:not([href])").each(function () {

  hashedIconUrl = jQuery(this).attr('xlink:href').replace('icons.svg', hashedIcon);
  console.log(hashedIconUrl);

  jQuery(this)[0].setAttributeNS('http://www.w3.org/1999/xlink', 'href', hashedIconUrl);
});


text:
Q: How is low starting torque of asynchronous AC motors addressed when driving elevators? Long before variable frequency drives became popular elevators were often driven by dual-speed asynchronous AC motors. Switching speeds was done by changing the number of poles (which is done by changing how stator coils are interconnected) - the motor would first run on lower speed, then switch to higher speed, then back to lower speed and then stop.
I've read many times that asynchronous AC motors have very low torque when starting. Looks like low starting torque would be a serious problem for driving an elevator - to such extent that a fully loaded elevator could stall the motor.
How is this problem resolved?

A: Large elevators were and many still are, DC. There are a bunch of reasons.
A fully loaded elevator only has to move half the apparent mass because there is a counterweight. At half mass there is very little work done going up or down.
A DC motor can be locked magnetically. Polyphase variable frequency drives use DC injection ito hold a position.
However the answer you seek is that the winding motors operating on AC were slow. They had/have many poles, unlike the grinder mentioned above. The winding drum is slow. Why use gearing when many more poles will slow things. Think of a 720 RPM motor, or 350.
Also remember that a motor frame size reflects the number of start cycles per hour so an elevator is 'heavy duty'. The reason is cooling. So the motors are wa-ay over spec'd, many poles, big diameter for the kW and extremely reliable.
I am sure no one here has heard of an elevator motor burning out from overheating.


text:
Q: Get the Sum of all positive numbers in a Circularly ordered array in O(Log N) I've been given an exercise in class that requires the following:

An array v formed by N integers is circularly ordered if, either the array is ordered, or else v[N‐1] ≤ v[0] and ∃k with 0<k<N such as ∀i≠k v[i] ≤ v[i+1].
Example:

Given a circularly ordered array with as much as 10 positive items, calculate the sum of the positive values. For this last example the answer would be 27.

I've been required to implement it using a Divide-and-Conquer scheme in java, given that the complexity is in the worst case O(Log N), being N the array size.
So far I tried to pivot a value until I find a positive value, then knowing the other positive values are adjacent, it's possible to sum the maximum of 10 positive values with a O(1) complexity.
I thought of doing a binary search to achieve O(Log N) complexity, but this would not follow the divide and conquer pattern.
I'm easily able to implement it through a O(N) complexity like this:
public static int addPositives(int[] vector){

    return addPositives(vector,0,vector.length-1
}

public static int addPositives(int[] vector, int i0, int iN){
    int k = (i0+iN)/2;
    if (iN-i0 > 1){
        return addPositives(vector,i0,k) + addPositives(vector,k+1,iN);
    }else{
        int temp = 0;
        for (int i = i0; i <= iN; i++) {
            if (vector[i]>0) temp+=vector[i];
        }
        return temp;
    }
}

However trying to land the O(Log N) gets me nowhere, how could I achieve it?

A: You can improve your divide and conquer implementation to meet the required running time if you prune irrelevant branches of the recursion.
After you divide the current array into two sub-arrays, compare the first and last elements of each sub-array. If both are negative and the first is smaller than the last, you know for sure that all the elements in this sub-array are negative and you don't have to make the recursive call on it (since you know it will contribute 0 to the total sum).
You can also stop the recursion if all the elements in a sub-array are positive (which can also be verified by comparing the first and last elements of the sub-array) - in that case you have to sum all the elements of that sub-array, so there's no point to continue the recursion.

A: My advice for the O(Log N) would be a direct comparison to meet the second of the two criteria: the last item being less than the first.
return vector[0] >= vector[iN-1]
If you want something with greater complexity, I forget the algorithm name, but you could get the array at the halfway point, and do two ordered searches from there: from the mid to the start and then the mid to the end


text:
Q: command to know table has a primary key along with table name in sybase I am using sybase as I am new to sybase prior to that I have used oracle now I have an database which consists of many table in sybase now there is a table named tarty now can you please advise the command that I can execute in sybase to know is there any primary key is there in tarty table or not .
here i got the solution for this..
select name
from sysindexes
where indid > 0
and status2 & 2 = 2

Can you also please advise that i want the table name also to be get listed for example the above command will show the primary key only i want the primary key plus the table name also to be listed so that i can know that this primary key belongs to this table please advise what necessary changes i need to do to achieve this..!

A: Including the table name is easy:
select name, object_name(id) as table_name
from sysindexes
where indid > 0
and status2 & 2 = 2

Also see "SQL query to get primary keys for all tables in sybase ase 15.x along with column names" for a related discussion. There's a catalog query sp_pkeys that's included with ASE that you can use or borrow from.


text:
Q: Give an example of an (complex) orthogonal matrix that isn't unitary and vice versa. Can you give the simplest example you could think of please.
I'm kind of collecting such awkward examples at the moment and have collected quite a few concerning e.g. normal matrices that aren't unitary or hermitian etc. but I'm having trouble getting examples as in the question.
Thanks in advance.

A: I only know the term "orthogonal matrix" applied to real matrices; I assume that in applying it to complex matrices you intend to require $O^\top O=1$ as for real matrices.
A matrix that is unitary but not orthogonal is $\pmatrix{\mathrm i}$.
A matric that is orthogonal but not unitary is $\displaystyle\frac1{\sqrt3}\pmatrix{\mathrm 2&\mathrm i\\\mathrm i&-\mathrm 2}$.


text:
Q: MariaDB 5.5 and Ubuntu 13.10 -> 14.04 upgrade I have installed MariaDB (5.5.37+maria-1~saucy) on Ubuntu Server 13.10. Then I have upgraded Ubuntu to 14.04 LTS. Upgrade process has disabled repository for MariaDB 5.5. Current part of sources.list after dist-upgrade.
# deb http://mirrors.linsrv.net/mariadb/repo/5.5/ubuntu trusty main # disabled on upgrade to trusty
# deb-src http://mirrors.linsrv.net/mariadb/repo/5.5/ubuntu saucy main

How do I keep future updates working? Repository configuration tool doesn't offer MariaDB 5.5 for Ubuntu 14.04. Even if it would, I don't know how to change the repo and keep updates working. What should I do?
Thanks

A: # deb http://mirrors.linsrv.net/mariadb/repo/5.5/ubuntu trusty main # disabled on upgrade to trusty

Just remove the # before this line and the text after the last #, so that the line looks like this:
deb http://mirrors.linsrv.net/mariadb/repo/5.5/ubuntu trusty main

And you will receive updates as usual.


text:
Q: Is calling repaint from paintComponent a good practice For some UI components in our application, we override paintComponent, which under some conditions "recursively" calls itself by invoking repaint. We use this approach to achieve high refresh rate of animations in the component.
For instance, a progress bar we use looks something like:
public class SimpleProgressBar extends JPanel {
    private boolean inProgress;

    ....

    @Override
    protected void paintComponent(Graphics g) {
        if (inProgress) {
            paintBar(g);
            repaint();
        } else {
            doSomeOtherThings();
        }
    }
}

Is this a good practice (especially in terms of performance / efficiency / CPU usage)?
Is it better to use a Timer or a background thread to repaint our components?

A:
Is this a good practice (especially in terms of performance / efficiency / CPU usage)?

No, it is not good practice. Calling repaint from within paintComponent is bad practice because:

*

*A high frame rate like this is virtually never required

*The frame rate is not guaranteed (repaint does not directly call the painting method, but causes a call to this component's paint method as soon as possible' (which may not be immediately))

*Places priority on painting of a single component, and can result in poor performance not only in painting of that one component, but also painting of other Components as well as response to other EDT specific tasks (eg events)

Is it better to use a Timer or a background thread to repaint our components?

Yes, using a Timer or Thread gives you much better control over the frame rate, without bogging down the EDT while doing so. Depending upon the context, a Timer runs on the EDT (as opposed to a Thread) so no dispatching to the EDT is required.

A: There are very few situations where overriding paintComponent is a good thing. Your situation seems to be one of them; however, it is important to remember that it is not your job to call paintComponent. What I mean by this, is that it is an office of the System to decide when to repaint certain components. This is especially evident when you drag the screen around, or when you put another screen over yours. That being said, it is very difficult to say how many times your method will be called; therein, making it difficult to say when it would be worth using that implementation.On a side note, a background thread, as you put it, would more than likely not make it better, and Swing is notoriously not thread-safe.I hope this helps, and best of luck to you!


text:
Q: Xamarin.Essentials DeviceDisplay class in .NET6 MAUI Xamarin.Essentials' class DeviceDisplay.KeepScreenOn does not have an equivalent in .NET6 MAUI as yet.
Is this intentional? or should I be using something else to stop the screen timing out?

A: DeviceDisplay class is now in namespace Microsoft.Maui.Devices.
This namespace is automatically referenced in new Maui projects, so you may refer to simply as DeviceDisplay, without needing any using ..; statement.
Typical usage is described in Device Display Information:
... DeviceDisplay.Current.MainDisplayInfo.Width   // get Width in pixels.

// To keep screen on:
DeviceDisplay.Current.KeepScreenOn = true;

When accessing multiple properties, it is convenient to copy to a local variable:
IDeviceDisplay devinfo = DeviceDisplay.Current;
// OR if just want MainDisplayInfo:
DisplayInfo display = DeviceDisplay.Current.MainDisplayInfo;


text:
Q: Best way to symbolically express this statement?
*

*Let $a$ and $b$ be parameters.

How can we say formally that if $d_{ij}\in [a,b]$, then $c_{ij}=f(d_{ij})$ and if $d_{ij}\notin [a,b]$, then $c_{ij}=0$?

*I want to define $M_{i}$ as the combination of $j$ indexes while $d_{ij}< b$. Is the following notation correct?

$$M_{i}=\{j \in J :d_{ij}< b\}$$

A: *

*You can use an indicator function, (also known as a characteristic function). Then, we would notate this as

$$c_{ij} = \chi_{[a,b]}(d_{ij}) f(d_{ij})$$
(Edit: I agree with PrincessEev that for most uses a definition by cases would tend to be more readable.)

*Yes, that notation is perfect. You have defined $M_i$ as the set of all $j$ in $J$ such that $d_{ij}$ is less than $b$.


text:
Q: How do I store objects if I want to search them by multiple attributes later? I want to code a simple project in java in order to keep track of my watched/owned tv shows, movies, books, etc.
Searching and retrieving the metadata from an API (themovieDB, Google Books) is already working.
How would I store some of this metadata together with user-input (like progress or rating)?
I'm planning on displaying the data in a table like form (example). Users should also be able to search the local data with multiple attributes. Is there any easy way to do this? I already thought about a database since it seemed that was the easiest solution.
Any suggestions?
Thanks in advance!

A: You can use lightweight database as H2, HSQLDB or SqlLite. These databases can be embedded in the Java app itself and does not require extra server.
If your data is less, you can also save it in XML or Json by using any XMLParser or JsonParser (e.g. Gson()).
Your DB table will have various attributes which are fetched from API as well as user inputs. You can write query on the top of these DBs to fetch and show the various results.

A: There are many ways to accomplish this but as another user posted, a database is the clear choice.
However, if you're looking to make a program to learn with or something simple for personal use, you could also use a multi dimensional array of strings to hold the name of the program, as well as any other metadata fields and treat the array like a table in excel. This is not the best way to do it, but you can get away with it with very simple code. To search you would only need to loop through the array elements and check that the name of the program (i.e. movieArray[x][0] matches the search string. Once located you can perform actions or edit the other array indexes pertaining to that movie.
For a little more versatility, you would create a class to hold the movie information with fields to hold any metadata. The advantage here is that the metadata fields can be different types rather than having to conform to the array type, and their packaged together in the instance of the class. If you're getting the info from an API then you can update or create the classes from the API response. These objects can be stored in an ArrayList and searched with a loop that checks for a certain value i.e.
for (Movie M : movieArrayList){
   if(m.getTitle().equals("Arrival")){
      return m;
  }
}

Alternatively of course for large scale, a database would be the best answer but it all depends what this is really for and what it's needs will be in the real world.

A: Either write everything to files, or store everything on a database. It depends on what you want though.
If you choose to write everything to files, you'll have to implement both the writing and the reading to suit your needs. You'll also have to deal with read/write bugs and performance issues yourself.
If you choose a database, you'll just have to implement the high level read and write methods, i.e., the methods that format the data and store it on the appropriate tables. The actual reading and writing is already implemented and optimized for performance.
Overall, databases are usually the smart choice. Although, be careful of which one you choose. Some types might be better for reading, while others are better for writting. You should carefully evaluate what's best, given your problem's domain.


text:
Q: Is there a way to shorten this jQuery script? I'm new to jQuery, and I've coded this to fade out three thumbnails when hovering over the remaining thumbnail. It just seems messy, and I'm interested to know if there was a way to code this in a cleaner way to improve my knowledge of selectors and identifiers. Many thanks to anyone who posts!
<script type="text/javascript">
    $(function() {
        $(".christmas-list-1,").css("opacity","1.0");
        $(".christmas-list-1").hover(
            function () {
                $(".christmas-list-2,.christmas-list-3,.christmas-list-4").stop().animate({ opacity: 0.5 }, "fast");
            },
            function () {
                $(".christmas-list-2,.christmas-list-3,.christmas-list-4").stop().animate({ opacity: 1.0 }, "fast");
            }
        );

        $(".christmas-list-2,").css("opacity","1.0");
        $(".christmas-list-2").hover(
            function () {
                $(".christmas-list-1,.christmas-list-3,.christmas-list-4").stop().animate({ opacity: 0.5 }, "fast");
            },
            function () {
                $(".christmas-list-1,.christmas-list-3,.christmas-list-4").stop().animate({ opacity: 1.0 }, "fast");
            }
        );

        $(".christmas-list-3,").css("opacity","1.0");
        $(".christmas-list-3").hover(
            function () {
                $(".christmas-list-1,.christmas-list-2,.christmas-list-4").stop().animate({ opacity: 0.5 }, "fast");
            },
            function () {
                $(".christmas-list-1,.christmas-list-2,.christmas-list-4").stop().animate({ opacity: 1.0 }, "fast");
            }
        );

        $(".christmas-list-4,").css("opacity","1.0");
        $(".christmas-list-4").hover(
            function () {
                $(".christmas-list-1,.christmas-list-2,.christmas-list-3").stop().animate({ opacity: 0.5 }, "fast");
            },
            function () {
                $(".christmas-list-1,.christmas-list-2,.christmas-list-3").stop().animate({ opacity: 1.0 }, "fast");
            }
        );
    });
</script>

A: Don't give them separate class names, just use .christmas-list for all 4:
$(".christmas-list").css("opacity","1.0").hover(function() {
   $(this).siblings(".christmas-list").stop().animate({opacity: 1.0}, "fast");
}, function() {
   $(".christmas-list").stop().animate({opacity: 1.0}, "fast");
});

A: $(function() {
    var elms = ".christmas-list-1, .christmas-list-2, .christmas-list-3, .christmas-list-4";
    $(elms).css("opacity", "1").hover(
        function () { $(elms).not($(this)).stop().animate({ opacity: .5 }, "fast"); },
        function () { $(elms).not($(this)).stop().animate({ opacity: 1  }, "fast"); }
    );
});

A: Have you thought about using fadeOut http://api.jquery.com/fadeOut/ alongside a for loop.

A: You are calling to many times to the function $. Try to avoid it (read the point 4 of this article).
I think you can do something like this:
<script type="text/javascript">
$(function() {

var arrJChr = {};

    for(i=1;i<=4;i++){
        arrJChr[i] = $(".christmas-list-"+i);
    }
    var animateFun = function(idNot, nOpacity){
        for(i=1;i<=4;i++){
            if(i!=idNot){
                arrJChr[i].stop().animate(
                    { opacity: nOpacity },
                    "fast"
                );
            }
        }
    };

    for(i=1;i<=4;i++){
        arrJChr[i].css("opacity","1.0");
        arrJChr[i].hover(function(){
            animateFun(i,0.5);
        },function(){
            animateFun(i,1.0);
        });
    }

});
</script>


text:
Q: Preview PDF file with e-signature in Angular I'm using pdf-viewer on the frontend with Angular 8. When my backend (in NodeJS) signs the PDF using a third-party service, the returned PDF contains the e-signature in an additional page at the end of the document.
If I download the document to my computer, I can see that the signature is OK. But when trying to preview it using pdf-viewer, it does not show the e-signature. It shows the additional page (where the signature was supposed to be) but only a blank page.
Example here:
https://drive.google.com/open?id=1f6pB6iqi6BwxzGOxv_Rxehc1TFFDEed8
I have tried to use the direct URL to the file:
<pdf-viewer *ngIf="file" [src]="file.url" [render-text]="false" style="display: block;"></pdf-viewer>

And also I tried to download the file on the backend, convert it to base64:
<pdf-viewer *ngIf="file" [src]="file.base64" [render-text]="false" style="display: block;"></pdf-viewer>

Nothing shows the signature.
When using the URL, the console shows a warning message: "Warning: Unimplemented widget field type "Sig", falling back to base field type."
Any idea about how can I show the document with the e-signature?

A: download the pdf.worker.js https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.worker.js and remove these lines
// Hide unsupported Widget signatures.
if (data.fieldType === 'Sig') {
    data.fieldValue = null;
    _this3.setFlags(_util.AnnotationFlag.HIDDEN);
}

put the edited pdf.worker.js inside your project and update the code as follows, you have to set these line before pdf-viewer component is rendered
(<any>window).pdfWorkerSrc = '<path_to_file>/pdf.worker.js';

For example:
(<any>window).pdfWorkerSrc = '/assets/lib/pdf.worker.js';

A: For me - uncommenting "Sig" condition in pdf.worker.js didnt work. I tried it selveral way - updating the existiing one, Downloading the new worker - changing it and then referencing it in my code. No success.
What worked for me is - below solution.
In pdf.worker.js add this on line 19544 - there is a switch case for fieldType i.e. switch (fieldType)
if you dont find that in your code - search for below line. The switch case would be above this line
(0, _util.warn)('Unimplemented widget field type "' + fieldType + '", ' + "falling back to base field type.");
Once you locate that switch statement - add below case
case "Sig":
return new SquareAnnotation(parameters);
This was a success for me.

A: in my case, im not working with Angular, im just working with a native js code, so i wasnt able to find this part of the code in both of my files "pdf.worker.js" or "pdf.viewer.js".
// Hide unsupported Widget signatures
if (data.fieldType === 'Sig') {
    data.fieldValue = null;
    _this3.setFlags(_util.AnnotationFlag.HIDDEN);
}

I did solve this problem based on the Ninad Desai comment below. so I searched for the condition where the data.fieldType === "Sig and change the return to display the signatures directly without any condition.
the code before :
return "Sig" === this.data.fieldType
? (K("unimplemented annotation type: Widget signature"), !1)
: a.isViewable.call(this);

the code after :
return a.isViewable.call(this);

I'm not sure if it's the best solution, but at least its working for now!
file name : pdf.worker.js
line : 3321
here is an example of what the pdf.js display right now :
enter image description here
hope that this comment help u guys...


text:
Q: Python 3 decimal module and limiting Decimal length Just moving from 2.7 to 3.4 I ran into this issue with decimal:
I'm trying to replicate SQL numeric data type with decimal module.
In 2.7, I did this:
def copy_ctx(places, prec):
    res = DefaultContext.copy()
    res.prec = places
    res.Emin = res.Emax = places - prec - 1
    return res

This effectively limited any resulting Decimals to specified number of places or less.
Trying to instantiate a number too large would yield an OverflowError.
For example:
x = Decimal(1000000, copy_ctx(5,2))  # Error! number is too much
x = Decimal(100, copy_ctx(5,2))  # == 100.00

However, In Python 3.4, decimal won't let me set Emin to a positive number.
How can I achieve the same behaviour as in 2.7?

A: Well, ultimately even the 2.7 version of decimal module wasn't exactly SQL Numeric friendly. I had to check every single result against my desired context. I have now added an additional quantization step in the class constructor.


text:
Q: isNull(NULL +" and"," on") return " and" in PHP MSSQL Why 'select isNull(NULL +" and"," on")' returns "on" in sql server but its return " and" in php mssql?
while directly executing the query in sql server it returns " on".
But using PHP [ mssql_quey] it returns " and".
I need " on".
PHP v 5.3
Xampp v3
MS SQL Server 2008

Not: I Tried COALESCE(NULL + ' and', ' on') ..same problem

A: try this
SET CONCAT_NULL_YIELDS_NULL ON

A: You are probably facing the problem with NULL value passing. At least, it looks that way as asp.net works ok.
I suggest you to try to substitute expression with null-valued variable like:
declare @test varchar(10); select isNull(@test + " and"," on")


text:
Q: inFile - reading different files I am curious to know from the more experienced c++ programmers out there if there is a way to have a function read in files that have different formats. Example is one file has a template of house # then street name and the other file is the opposite, house name then street #. Again, just curious if there was some sleek code that I could add to my knowledge and tool box, instead of writing two different inFile functions.
Thank you all for your time.
EDIT
Here is some of the code:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct WH
{
    int inum;
    string iname;
    string warname;
    int quant;
    float whole;
    float markup;
    float retail;
};

void readinprime(WH);

ifstream inFile;
ofstream outFile;

int main()
{
    WH ware[100];

    //inFile.open("WLL1.txt", ios::in);
    //inFile.open("WLL2.txt", ios::in);
    //inFile.open("WLL3.txt", ios::in);
    //inFile.open("WLL4.txt", ios::in);

    return 0;
}
void readinprime(WH ware[])
{
    int c;
    for(c = 0; c < 100; c++)
    {
        inFile << ware.inum[c] << ware.iname[c];
    }
}

So essentially the first file (WLL1.txt) has the format integer->string and then the next file (WLL2.txt) will have the format string->integer. My question is, is there another way to write the read in function where it can read in int then string & string then int without writing another function? I dont mind writing another function for every file format, but I was just curious if someone had some good tricks that I could add to my tool box. Again thank you for your time.

A: you can use the getline method to read every line from the text and store it in a variable


text:
Q: Background Image Wont Re-size When Changing Browser Size I've been fiddling with my background image in CSS for a couple hours now and have tried searching through articles to find a solution but still have nothing. I'm trying to make my background image fit the screen no matter what the browser size.
At first I was using this CSS code which seemed to be working:
body {
    background-image: url(images/background.jpg);
    background-repeat: no-repeat;
    background-size: cover;
}

But then when I re-sized the browser this happened: http://prntscr.com/j1d4kv
I then went and found another solution that said I should put the background image in the html tag, which i tried:
html {
    background-image: url(images/background.jpg);
    background-repeat: no-repeat;
}

This fixed the issue of the background image not fitting to the bottom when the browser size changed, but then I had this issue when I was full screened: http://prntscr.com/j1d742 It left a gap on the right side!

A: Most likely your body doesn't reach the full height of the browser window, if it doesn't have much content. Add this to correct that:
html, body {
  height: 100%;
}

A: You want to add,
background-attachment: fixed;
Here's an example: https://embed.plnkr.co/3Y7O1TQa8ssPQKVq0tCW/


text:
Q: Apply seq.Date using two dataframe columns I tried to use the varies answers from
Expanding a sequence in a data frame
to my dataframe, but nothing I tried works.
Sample Data
library(dplyr)
p1 <- c(1:5)
p2 <- as.Date(c("2013-01-01","2013-01-22","2014-02-01","2014-05-12","2015-02-22"))
p3 <- as.Date(c("2013-01-11","2013-01-30","2014-02-20","2014-05-22","2015-02-28"))
p4 <- c(11,9,20,11,7)
df2 <- data_frame(p1,p2,p3,p4)
names(df2) <- c("ID", "StartDate", "EndDate", "NoDays")
df2

Desired Result
ID  datelist    NoDays
1   2013-01-01   1
1   2013-01-02   1
1   2013-01-03   1
etc..
1   2013-01-10   1
1   2013-01-11   1
2   2013-01-22   1
2   2013-01-23   1
etc.
2   2013-01-28   1
2   2013-01-29   1
2   2013-01-30   1

Here are three code trials - all of which I tried in numerous variants (e.g. verious members of the apply family), but all failed (i.e. giving diverse error messages):
code example 1
datelist <- seq.Date(from = df2$StartDate, to=df2$StartDate, by="days")

code example 2
datelist <- seq.Date(from = df2$StartDate, by="days", length.out = df2$NoDays)

code example 2
datelist <- apply(df2, 1, seq.Date(from = df2$StartDate, to=df2$StartDate, by="days"))

A: Your problem is that you give a vector to seq.Date which takes a unique value as from or to.
On the same idea as your apply call it should be:
apply(df2,1,function(x) { seq.Date( as.Date(x['StartDate']), as.Date(x['EndDate']), by='days') } )

Which gives you a list with each row sequence:
[[1]]
 [1] "2013-01-01" "2013-01-02" "2013-01-03" "2013-01-04" "2013-01-05" "2013-01-06" "2013-01-07" "2013-01-08" "2013-01-09"
[10] "2013-01-10" "2013-01-11"

[[2]]
[1] "2013-01-22" "2013-01-23" "2013-01-24" "2013-01-25" "2013-01-26" "2013-01-27" "2013-01-28" "2013-01-29" "2013-01-30"

[[3]]
 [1] "2014-02-01" "2014-02-02" "2014-02-03" "2014-02-04" "2014-02-05" "2014-02-06" "2014-02-07" "2014-02-08" "2014-02-09"
[10] "2014-02-10" "2014-02-11" "2014-02-12" "2014-02-13" "2014-02-14" "2014-02-15" "2014-02-16" "2014-02-17" "2014-02-18"
[19] "2014-02-19" "2014-02-20"

[[4]]
 [1] "2014-05-12" "2014-05-13" "2014-05-14" "2014-05-15" "2014-05-16" "2014-05-17" "2014-05-18" "2014-05-19" "2014-05-20"
[10] "2014-05-21" "2014-05-22"

[[5]]
[1] "2015-02-22" "2015-02-23" "2015-02-24" "2015-02-25" "2015-02-26" "2015-02-27" "2015-02-28"

To get your desired output, we should return id and NoDays columns too.
In base R I would do it like this:
getDfForDates <- function(row) {
  dseq <- seq.Date( as.Date(row['StartDate']), as.Date(row['EndDate']), by='days')
  data.frame( ID=row['ID'], datelist=dseq, NoDays=1)
}

rbindlist(
  apply(df2,1,function(x) {
    getDfForDates(x)
  } )
)

Another solution with data.table package is:
setDT(df2)
df2[, list(datelist=seq.Date( StartDate, EndDate, by='days'), NoDays=1), by=ID]

Both will give desired result if I didn't miss a point.
I'll see if I can craft a correct dplyr answer as you seems to be using this package. Finally found a dupe when looking for dplyr examples, voted to close.

A: We can do this easily with data.table.  Convert the 'data.frame' to 'data.table' (setDT(df2), if the 'ID's are unique, then group by 'ID', and get the seq of 'StartDate' to 'EndDate' by 'ID'.
library(data.table)
res <- setDT(df2)[,list(datelist=seq(StartDate, EndDate, by='1 day'),
                      NoDays = 1) , by = ID]

head(res)
#   ID   datelist NoDays
#1:  1 2013-01-01      1
#2:  1 2013-01-02      1
#3:  1 2013-01-03      1
#4:  1 2013-01-04      1
#5:  1 2013-01-05      1
#6:  1 2013-01-06      1

If we need to do this in dplyr, we may need the do as mutate doesn't support this kind of operations
library(dplyr)
df2 %>%
   rowwise() %>%
   do(data.frame(ID= .$ID, datelist = seq(.$StartDate,
             .$EndDate, by = '1 day'), NoDays= 1))


text:
Q: Помощь в парсинге JSON с помощью Json.NET Имеется следующий Json:
{
"status":"ok",
"count":1,
"data":{
    **"1"**:{
        "members_count":100,
        "description":"Закрытый клан, в состав которого входят _лишь_ разработчики игры "World of Tanks". Заявки, посланные командиру клана через форум, _НЕ РАССМАТРИВАЮТСЯ_ . ",
        "description_html":"
Закрытый клан, в состав которого входят _лишь_ разработчики игры "World of Tanks".

Заявки, посланные командиру клана через форум, _НЕ РАССМАТРИВАЮТСЯ_ .
",
        "created_at":1293024672,
        "request_availability":false,
        "updated_at":1381187704,
        "private":null,
        "abbreviation":"WG",
        "emblems":{
            "large":"http://clans.worldoftanks.ru/media/clans/emblems/clans_1/1/emblem_64x64.png",
            "small":"http://clans.worldoftanks.ru/media/clans/emblems/clans_1/1/emblem_24x24.png",
            "bw_tank":"http://clans.worldoftanks.ru/media/clans/emblems/clans_1/1/emblem_64x64_tank.png",
            "medium":"http://clans.worldoftanks.ru/media/clans/emblems/clans_1/1/emblem_32x32.png"
        },
        "clan_id":1,
        "members":{
            **"196632"**:{
                "account_id":196632,
                "created_at":1293126248,
                "updated_at":0,
                "account_name":"Wrobel",
                "role":"private",
                "role_i18n":{
                    "ru":"солдат",
                    "fr":"Soldat",
                    "en":"Soldier",
                    "th":"ทหาร",
                    "vi":"Quân nhân",
                    "de":"Schütze",
                    "tr":"Asker",
                    "it":"солдат",
                    "hu":"солдат",
                    "zh-cn":"战士",
                    "pl":"żołnierz",
                    "ms":"солдат",
                    "cs":"Voják",
                    "es":"Soldado"
                }
            },
            "18458":{
                "account_id":18458,
                "created_at":1360836543,
                "updated_at":0,
                "account_name":"alienraven",
                "role":"diplomat",
                "role_i18n":{
                    "ru":"дипломат",
                    "fr":"Diplomate",
                    "en":"Diplomat",
                    "th":"ทูต",
                    "vi":"ngoại giao",
                    "de":"Diplomat",
                    "tr":"Diplomat",
                    "it":"дипломат",
                    "hu":"дипломат",
                    "zh-cn":"外交官",
                    "pl":"dyplomata",
                    "ms":"дипломат",
                    "cs":"Diplomat",
                    "es":"Diplomático"
                }
            },

Возникла проблема с описанием класса для newtown json т.к. имеются ключи("1","196632"), которые имеют нестатические названия ("1","196632"). Их названия меняются в зависимости от того к какому id я обращаюсь, через API.
[JsonObject(MemberSerialization.OptIn)]
public class Clan
{
    [JsonProperty("status")]
    public string Status { get; set; }
    [JsonProperty("count")]
    public int Count { get; set; }
    public Data Data { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class Data
{
    //[JsonProperty("что писать вместо 1")]
    //public что писать вместо 1 { get; set; }
}

A: Такие json-ы можно десериализовать в Dictionary. Вот сильно упрощенный пример:
public class TestClass
{
    public const string Json = @"{""Name"":""Foo"",Bs:{""100"":{""Value"":1,""Flag"":false},""500"":{""Value"":2,""Flag"":true}}}";

    [Test]
    public void Test()
    {
        var a = JsonConvert.DeserializeObject(Json);
    }
}

public class A
{
    public string Name { get; set; }
    public Dictionary<string, B> Bs { get; set; }
}

public class B
{
    public int Value { get; set; }
    public bool Flag { get; set; }
}


text:
Q: MongoDB - Update field in nested array This is my collection structure in MongoDB:
{
  _id: id,
  name: name,
  loans: [
    [{id: 1, acName: "ABC"}],
    [{id: 2, acName: "DEF"}],
    [{id: 3, acName: "GHI"}]
  ]
}

How can I update acName of a specific ID? Let's say, I want to update acName of id 2. How can I do that?

A: Solution 1: Without arrayFilters

*

*Use $elemMatch to find the existence of id: 2 in nested arrays.

*With all positional operator ($[]) to update the respective document field.
db.collection.update({
  "loans": {
    $elemMatch: {
      $elemMatch: {
        id: 2
      }
    }
  }
},
{
  $set: {
    "loans.$.$[].acName": "<NEW VALUE>"
  }
})

Demo Solution 1 @ MongoPlayground

Solution 2: With arrayFilters

*

*Use $elemMatch to find the existence of id: 2 in nested arrays.

*With filtered positional operator ($[<identifier>]) and arrayFilters to update the respective document field.
db.collection.update({
  "loans": {
    $elemMatch: {
      $elemMatch: {
        id: 2
      }
    }
  }
},
{
  $set: {
    "loans.$.$[loan].acName": "<NEW VALUE>"
  }
},
{
  arrayFilters: [
    {
      "loan.id": 2
    }
  ]
})

Demo Solution 2 @ MongoPlayground


text:
Q: Show enter contents of JSON QUESTION ::
I know this is a redundant question, but I am finding little help in other similar questions...
I have a json file.
I can load the json fine, but when I try to output a specific element with this
div.innerHTML = jsonfromfile[element];

I only get this...
[object Object]

as my output...
How do I get the entire element to display instead of this [object Object]?
more code to get a feel for how it is being done up...
var activity;
function jsfr() {
    $.getJSON('myjson.json', function(response){
    jsonfromfile = response;
    })
}

.
.
.
SOLUTION :: from Francis Stalin's answer
I added a new function...
        var items;
    function outty(data) {

            $.each(data, function(key, val) {
                items=items+key+","+val+";";
            });
    }

and i set the depth on the json leaving me with an object which i send to outty...
    dpth = jsonfromfile["elementOne"]["elSubone"]["elsuboneSub"];
    outty(dpth);
    div.innerHTML=items;

here's the HTML that shows the div it all prints to...

this turns the object of your desired json depth into an ugly string that you can then format for display..
if you like html lists check out how Stalin did it, but be weary of his appendTo('div')... this will place your list in every div.  Try putting the name of the class of the div you want to print to with a period leading it, appendTo('.outputbox')

A: you can't append the json object directly into ur html. u have to parse and convert into string
$.getJSON('myjson.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('
' + val + '
');
});
$('
', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('div');
});

http://api.jquery.com/jQuery.getJSON/

A: Use JSON.stringify(yourjsonobjecthere)

A: Try div.innerHTML = JSON.stringify(jsonfromfile[element]);


text:
Q: How to stop the execution if "!stop" found in the discord channel? How to stop the execution of the script if the bot receives the "!stop" command from the channel?
I am just learning to create such bot, so my current code is:
bot = commands.Bot(command_prefix='!')
@bot.command(name='stop')
async def here(ctx):
        while True:
            print(2)
            time.sleep(15)

bot.run(TOKEN)

So I have 3 selenium drivers working on different machines and I want to set up communication through a discord channel (each machine will have its own bot). Currently, the machine which opens a specific URL first that machine will send a stop message to the channel and close the connection with the chat, while the other two machines should stop immediately after the message.
So, the ideas
page_opened = True
while page_opened = True:
     do something and listen
     if there is a message stop:
         page_opened = false

How should I handle this idea with discord bots? Any hints?

A: You can simply use an exit() or sys.exit() command whenever you want to stop the execution of any Python program. For example:
import sys

bot = commands.Bot(command_prefix='!')

@bot.command(name='stop')
async def here(ctx):
    sys.exit()  # Stops execution of the program

bot.run(TOKEN)


text:
Q: SQL Loader - Actual length exceeds maximum I tried loading data into table using sql loader.
The log shows actual length of the string is 101 where as 100 is maximum(Rejects the record).But when i checked ,I found the length is 99.
data type of the string is varchar2(100) in table
I didnt specify anything about length in control file
What would be the exact problem?

A: Your data value only has 99 characters, but it seems some are multibyte characters - from a comment at least one is the symbol ½.
There are two related way to see this behaviour, depending on how your table is defined and what is in your control file.
You're probably seeing the effect of character length semantics. Your column is defined as 100 bytes; you're trying to insert 99 characters, but as some characters require multiple bytes for storage, the total number of bytes required for your string is 101 - too many for the column definition.
You can see that effect here:
create table t42 (str varchar2(10 byte));

Then if I have a data file with one row that has a multibyte character:
This is 10
This is 9½

and a simple control file:
LOAD DATA
CHARACTERSET UTF8
TRUNCATE INTO TABLE T42
FIELDS TERMINATED BY ','
TRAILING NULLCOLS
(
  STR
)

Then trying to load that gets:
Record 2: Rejected - Error on table T42, column STR.
ORA-12899: value too large for column "MYSCHEMA"."T42"."STR" (actual: 11, maximum: 10)

Total logical records read:             2
Total logical records rejected:         1

If I recreate my table with character semantics:
drop table t42 purge;
create table t42 (str varchar2(10 char));
then loading with the same data and control file now gets no errors, and:
Total logical records read:             2
Total logical records rejected:         0

However, even when the table is defined with character semantics, you could still see this; if I remove the line CHARACTERSET UTF8 then my environment defaults (via NLS_LANG, which happens to set my character set to WE8ISO8859P1) leads to a character set mismatch and I again see:
Record 2: Rejected - Error on table T42, column STR.
ORA-12899: value too large for column "STACKOVERFLOW"."T42"."STR" (actual: 11, maximum: 10)

(Without that control file line, and with byte semantics for the column, the error reports actual length as 13 not 11).
So you need the table to be defined to hold the maximum number of characters you expect, and you need the control file to specify the character set if your NLS_LANG is defaulting it to something that doesn't match the database character set.

You can see the default semantics a new table will get by querying, for the database default and your current session default:
select value from nls_database_parameters where parameter = 'NLS_LENGTH_SEMANTICS';
select value from nls_session_parameters where parameter = 'NLS_LENGTH_SEMANTICS';

For an existing table you can check which was used by looking at the user_tab_columns.char_used column, which will be B for byte semantics and C for character semantics.


text:
Q: Joint convergence of measures and functions: when do integrals converge? Let $\mu_n$ be a sequence of Radon measures weak-$*$ converging to a measure $\mu$. Moreover assume that $\{f_n\}_{n\in\mathbb{N}}$ is a sequence of measurable (continuous, whatever regulartiy you wish) functions converging in some sense to $f$.
My question is: in which cases can we deduce that:
$$ \int f_nd\mu_n\to\int f d\mu$$
as $n\to\infty$, or at least for a subsequence?
It is really well known that if $f_n$ are continuous, and for istance $\mu_n$ are finite and uniformily bounded ($\lVert\mu_n\rVert\leq C$ for any $n$), or $f_n$ have compact support uniformily contained in a bounded open set, and converges uniformily to $f$ the claim follows easily:
$$\left\lvert\int f_nd\mu_n-\int fd\mu\right\rvert\leq\left\lvert\int f_nd\mu_n-\int fd\mu_n\right\rvert+\left\lvert\int fd\mu_n-\int fd\mu\right\rvert\\
\leq\int\lVert f_n-f\rVert d\mu_n+\left\lvert\int fd\mu_n-\int fd\mu\right\rvert\leq C\lVert f_n-f\rVert+\left\lvert\int fd\mu_n-\int fd\mu\right\rvert.$$
On the other hand, if we assume some more regularity on the measures the claim follows as well, for istance if we assume that $\mu_n(B_r(x))=h(r)$ for any $n$ and any $x\in supp(\mu)$ and $f_n$ is radially simmetric, uniformily integrable for $\mu_n$ and converges pointwise to  $f$ then the claim holds for a subsequence. I remark that this sentence may be inaccurate, but if you want to figure out what I am talking about, you can find references in Mattila's book, or De Lellis notes on rectifiability (since uniformily distributed measures naturally arise as blowups of measures with finite and non zero density).
Are there any other important cases (general enough) in which this holds?


text:
Q: Property [kodeSparepart] does not exist on this collection instance I want to get all of the data from sparepart database using all() function, then use foreach in view to access the data, but I keep get that error. It works fine when I use the same method for other view blade.
Controller
  public function LaporanSisaStok(Request $request) {

    if($request->kode == "")
    {
        $spareparts = Sparepart::all();
        return view('laporan/sisaStok')->with(['spareparts' => $spareparts]);
    }
    else {
        $query = DB::table("historisparepart")->select(DB::raw('EXTRACT(MONTH FROM tanggal) AS Bulan, SUM(jumlah) as Sisa'))
        ->where('kodeSparepart', $request->kode)
        ->groupBy(DB::raw('EXTRACT(MONTH FROM tanggal)'))
        ->get();
        return view('printPreview/sisaStok', ['data'=>$query]);
    }
}

View
<form method="POST" action="{{ route('laporan.sisaStok') }}" enctype="multipart/form-data">
@csrf

    Sparepart
    <select class="custom-select" id="kode" name="kode">
        <option value="">-Pilih Sparepart-</option>
        foreach($spareparts as $sparepart)
        {
            <option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
        }
    </select>

<button type="submit" class="btn btn-info"> Cari </button>

A: You aren't looping through anything.  You need to give the foreach() method a variable from your spareparts collection.  I think it might help you avoid confusion, to name the collection variables plural:
In your controller:
$spareparts = Sparepart::all();
return view('laporan/sisaStok', compact('spareparts'));

Then, most importantly, you need to tell foreach what it should produce.  In your view, change:
foreach($sparepart)

to
@foreach($spareparts as $sparepart)

Don't forget you are in blade, so use the @ before the foreach.  Then, assuming you actually have a property on the spareparts model called kodeSparepart, this should work fine.

A: You shoud use the plural of your dtb name to loop over the values so your 'sparepart' variable should change to 'spareparts'
$sparepart = Sparepart::all();
return view('laporan/sisaStok')->with(['spareparts' => $sparepart]);

In your view change your loop to the new variable and loop using your current variable, so your view shoul look like this:
View

    Sparepart
    <select class="custom-select" id="kode" name="kode">
        <option value="">-Pilih Sparepart-</option>
        @foreach($spareparts as $sparepart)
        {
            <option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
        }
        @endforeach

    </select>

A: This is not a looping syntax in the laravel view
  foreach($spareparts as $sparepart)
    {
        <option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
    }

It should be like this
@foreach($spareparts as $sparepart)
<option value="{{$sparepart->kodeSparepart}}"> {{$sparepart->namaSparepart}} </option>
 @endforeach

And another problem is  you are passing the data in wrong way. It should be like this
  return view('printPreview/sisaStok', ['spareparts'=>$query]);


text:
Q: Why not create github.io (github page) I have created github page.
0
URL : https://github.com/khkong/khkong.github.io
When I access my page, I get a 404 error. I can not find the site. (https://khkong.github.io)
There seems to be a limit to the creation. Help.

A: When I create a GitHub-page, the URL is https://adarkhero.github.io/PROJECTNAME/ - So, try adding the name of your project to the URL (Like https://khkong.github.io/testproject). You can also see the link to your GitHub-page in the settings of your repository.


text:
Q: Heroku: Failed to git push Hi I am attempting to git push my python app, but constantly obtain error messages. This is the best that I can do so far. Errors below:
remote:            gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DUSE__THREAD -I/usr/include/ffi -I/usr/include/libffi -I/app/.heroku/miniconda/include/python2.7 -c c/_cffi_backend.c -o build/temp.linux-x86_64-2.7/c/_cffi_backend.o
remote:            c/_cffi_backend.c:15:17: fatal error: ffi.h: No such file or directory
remote:             #include <ffi.h>
remote:                             ^
remote:            compilation terminated.
remote:            error: command 'gcc' failed with exit status 1
remote:
remote:            ----------------------------------------
remote: Command "/app/.heroku/miniconda/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-HrTCjj/cffi/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-VNanYj-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-HrTCjj/cffi/
remote: You are using pip version 8.1.1, however version 8.1.2 is available.
remote: You should consider upgrading via the 'pip install --upgrade pip' command.
remote:
remote:  !     Push rejected, failed to compile Python/Conda app
remote:
remote: Verifying deploy....
remote:
remote: !   Push rejected to newhapp.
remote:
To https://git.heroku.com/newhapp.git

$heroku logts --tail
Slug compilation failed: failed to compile Python/Conda app

A: I had a really similar error message to this when deploying from Windows OS to Heroku, while this may not help everyone for me it actually turned out to be a simple fix.
In requirements.txt I removed packages that are not necessary for linux.
In my case removing
winkerberos

which was pip installed for windows support alongside
requests-kerberos

which fixed the issue.
If you can try pip freeze on a linux machine I would recommend this instead, to avoid error messages for missing windows C .h header files.

A: Did you follow all the steps in the heroku tutorial (all of them) ?

A: I think I did, in my best knowledge. But did you see what would I have missed? I have a huge list of requirements.txt ( ~40 dependencies). Most of them are not used in my app. They are there because I pip freeze > requirements.txt
Would this huge list cause the problem?
Thank you.


text:
Q: Different values for jQuery.css('top-margin') with margin:auto based on browser Let me try to lay this out, my question is why don't all the browsers treat this the same way.
html

Css
body{
    height:100%;
    width:100%;
    position:relative;
}
.container{
    height:800px;
    width:800px;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin: auto;
}
.footer{
    position:absolute;
    left:0;
    right:0;
    margin:0 auto;
}

jQuery
var footertop = (parseFloat($('#container').css('margin-top'))+parseFloat($('#container').css('height')))+'px';
$('#footer').css('top',footertop);

I have a container div that is absolutely centered horizontally and vertically.  Then I am attempting to set the 'top' of the footer to be the height of container plus the top margin of container. (So that it ends up right underneath the container).  This method works on some browsers (Chrome,Opera,Safari,IE9+) but doesn't work on others (Firefox,IE8-).
I am assuming IE8 and earlier doesn't support this method, and that's fine, but in Firefox the value of footertop is always equal to $('#container').css('height')
If I do a console.log(parseFloat($('#container').css('margin-top'))) I get a positive integer depending on the height of my browser, but on Firefox it is always 0.
Please advise.

A: Turns out in firefox the computed value for margin-top, margin-bottom, margin-left and margin-right all end up as 0 and the top,bottom,left and right attributes have the values that you would expect to find in the margins.
here is my jquery that works on all browsers now:
if(parseFloat($('#container').css('margin-top')) == 0){
    var footertop = (parseFloat($('#container').css('top'))+parseFloat($('#container').css('height')))+'px'; //firefox fix
}else{
    var footertop = (parseFloat($('#container').css('margin-top'))+parseFloat($('#container').css('height')))+'px';
}
$('#footer').css('top',footertop);


text:
Q: Can I update Timber and or Twig? I took over a site using Twig 1.24.1 from 2016.
It also has some version of Timber baked into an old Sage theme. There is no Timber plugin.
If I update to PHP 8, I get a fatal error.
If I install the Timber plugin, I get a fatal error.
Is there some way to update Timber and Twig to work with PHP 8? I have found zero helpful info or docs about doing this here, at Github, at Upstatement, or in Google.
I also tried downloading Twig and swapping out some files and directories. That also failed hard. So I know how to break this site... but I'd really like to get it updated and stable.
Here's the error if it helps - which goes away in PHP 7.4.x

PHP Fatal error: Uncaught TypeError: array_key_exists(): Argument #2 ($array) must be of type array, Timber\Menu given in /nas/content/live/site/wp-content/themes/wobs-theme/vendor/twig/twig/lib/Twig/Template.php:533\nStack trace:\n#0 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/twig/twig/lib/Twig/Environment.php(403) : eval()'d code(23): Twig_Template->getAttribute(Object(Timber\Menu), 'get_items', Array)\n#1 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/twig/twig/lib/Twig/Template.php(387): __TwigTemplate_eada0446f028acb9eb859e593a68397ec9225f348f46a00ab74866dfa38d8f16->doDisplay(Array, Array)\n#2 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/twig/twig/lib/Twig/Template.php(355): Twig_Template->displayWithErrorHandling(Array, Array)\n#3 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/twig/twig/lib/Twig/Template.php(366): Twig_Template->display(Array)\n#4 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/twig/twig/lib/Twig/Environment.php(347): Twig_Template->render(Array)\n#5 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/timber/timber/lib/Loader.php(72): Twig_Environment->render('header.twig', Array)\n#6 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/timber/timber/lib/Timber.php(281): Timber\Loader->render('header.twig', Array, false, 'default')\n#7 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/timber/timber/lib/Timber.php(317): Timber\Timber::compile('header.twig', Array, false, 'default', true)\n#8 /nas/content/live/site/wp-content/themes/wobs-theme/vendor/timber/timber/lib/Timber.php(332): Timber\Timber::fetch('header.twig', Array, false, 'default')\n#9 /nas/content/live/site/wp-content/themes/wobs-theme/templates/header.php(37): Timber\Timber::render('header.twig', Array)\n#10 /nas/content/live/site/wp-includes/template.php(785): require('/nas/content/li...')\n#11 /nas/content/live/site/wp-includes/template.php(718): load_template('/nas/content/li...', false, Array)\n#12 /nas/content/live/site/wp-includes/general-template.php(204): locate_template(Array, true, false, Array)\n#13 /nas/content/live/site/wp-content/themes/wobs-theme/base-front-page.php(19): get_template_part('templates/heade...')\n#14 /nas/content/live/site/wp-includes/template-loader.php(106): include('/nas/content/li...')\n#15 /nas/content/live/site/wp-blog-header.php(19): require_once('/nas/content/li...')\n#16 /nas/content/live/site/index.php(17): require('/nas/content/li...')\n#17 {main}\n thrown in /nas/content/live/site/wp-content/themes/wobs-theme/vendor/twig/twig/lib/Twig/Template.php on line 533


text:
Q: Probability that a fair coin requires 4 tosses to get a heads In this situation a fair coin is tossed until a head is obtained. What is the probability that the coin was tossed at least 4 times?
This question comes directly out of the 5th edition Text discrete mathematics by Kenneth Ross.
My initial intuition is that this merely requires that you get the probability that tails is obtained $3$ flips in a row which I believe is equal to $\frac{1}{8}$. My second thought however is that you also have to factor in the probability that the fourth flip is a heads. this I believe is equal to $\frac{1}{16}$.
I'm not confident however that my method for achieving these numbers is correct which is $\frac{1}{2^3}$ and $\frac{1}{2^4}$ respectively.
Thanks in advance for any guidance.

A: Clearly, if the coin is tossed repeatedly until the first observation of heads, then in order to toss the coin at least four times, the first three observations must be tails.  This occurs with probability $1/8$, as you noted.
After the third tail, the fourth toss could be heads, in which the tossing stops, or it could be tails, in which case more trials are generated until heads is observed; but in either case, at least four coin tosses were made.
If we wanted the probability of tossing the coin exactly four times, this would be $1/16$, as there is a unique outcome that this event corresponds to:  $TTTH$.


text:
Q: Springfox - Schema for Interfaces Empty I am using springfox 3.0.0, and I have an interface that is used as a @RequestBody.
pom.xml
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-boot-starter</artifactId>
  <version>3.0.0</version>
</dependency>

SwaggerConfig.java
class SwaggerConfig {

  @Bean
  Docket api() {
    return new Docket(OAS_30)
      .select()
      .apis(RequestHandlerSelectors.basePackage(
          "org.springframework.boot").negate())
      .build();
    }
  }

Models
//assume Lombok or standard getter/setters/constructors
class Clazz implements StringInterface {
  String s;
  Integer i;
}

@JsonDeserialize(as = Clazz.class)
interface StringInterface {
  String getString();
}

In Springfox 2.9.* the schema for StringInterface was
{
  "title": "StringInterface",
   "type": "object",
   "properties": {
     "s": {
       "type": "String"
    }
  }
}

When I upgrade to 3.0.0, however, the schema is now empty.
{
  "title": "StringInterface",
  "type": "object"
}

Regular classes are displayed correctly. It seems to a problem only with interfaces.

A: I was able to make a workaround. Unfortunately, it requires some configuration for every interface involved.
@JsonDeserialize(as = Clazz.class)
interface StringInterface {
  static class Model {
    String getString();
  }
}

SwaggerConfig.java
class SwaggerConfig {
  @Bean
  Docket api() {
    return new Docket(OAS_30)
      .select()
      .apis(RequestHandlerSelectors.basePackage(
          "org.springframework.boot").negate())
      .directModelSubstitute(StringInterface.class, StringInterface.Model.class)
      .build();
  }

  @Component
  @Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER)
  static class ModelDeclaringClassName implements TypeNameProviderPlugin {
    boolean supports(DocumentationType delimiter) {
      return true;
  }

  String nameFor(type: Class<?>) {
    Class<?> actualClass = type.getSimpleName().equals("Model") ?
      type.getDeclaringClass() :
      type;

      return type.getSimpleName();
    }
  }
}

My application was actually in Kotlin, so the directModelSubstitute calls can be simplified like this:
private inline fun <reified T> Docket.substituteModel() =
    T::class.java.let {
        directModelSubstitute(
            it,
            it.declaredClasses.first { c ->
                c.simpleName == "Model"
            }
        )
    }

Usage like this:
.substituteModel<StringInterface>()

A: I would recommend switching to SpringDoc.
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-ui</artifactId>
</dependency>

The latest version as of now, 1.5.6 would give you the following schema for your interface
{
   "type": "object",
   "properties": {
     "string": {
       "type": "string"
    }
  }
}

You would also have to setup the config class a little differently & annotate your controllers with @RestController. I have not personally, ever seen usage of an interface as a RequestBody so, this case is a little strange.
However, if your set on using your dependency version then, its something to do with how swagger schema generation is interpreting your JsonDeserialization I would think.


text:
Q: Prove that if $n^6$ is a perfect square, $n^{50}$ is a perfect square. Can someone help me prove/disprove this?
I wrote $n^6$ as $l^2$, but I don't know how to convert $n^{50}$ into that format because $^{50}$ is too large.
$n$ ∈ ℤ

A: Both $n^6$ and $n^{50}$ are perfect squares, since $n^6=(n^3)^2$ and $n^{50}=(n^{25})^2$. What's the problem?


text:
Q: Session in Threads I have an application that uses a thread to execute a process that generates a XML file at the end. This process takes a lots of time, and because of this, I created a progress bar outside the thread for each 0,5 seconds read a session variable that is set inside the thread. But, when I execute the application, without using breakpoints the following error is generated:

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive.
Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

On other hand, when I execute the application with the breakpoints, it executes successfully.
I don't know how to make this work out without breakpoints.
The thread and the progress bar are in different .aspx files.
Thread Creation:
HttpContext ctx = HttpContext.Current;
Thread thread = new Thread(new ThreadStart(() =>
{
    HttpContext.Current = ctx;
    GerarArquivosXML(DtArquivos, diretorioArquivos);
}));
thread.Start();

During the execution of the method "GerarArquivosXML" I try to add a value to a session variable:
Session.Add("Count", Progress.Count);

For example, if I put a breakpoint on the first line on page load and run it line by line, it works out. Without breakpoints, the application throws the exception, and crashes.


text:
Q: How to search an inverted index implemented in SQL for multiple words? I'm attempting to make a search engine for an SQL database of commnets. I read online that one of the best ways of doing this would be to make a inverted index.
My tables for my inverted index are as below. Please let me know if this is incorrect and needs to be changed, that can be done easily.

You can find a single word fairly easily using this setup, as so:
SELECT comment_terms.term, comment_terms.frequency, comments.body FROM     comment_terms
INNER JOIN comments ON comment_terms.comment_name = comments.name
WHERE comment_terms.term = 'reddit'
ORDER BY frequency DESC

Which gives you this table:
term   | frequency | body
-------+-----------+-------
reddit |        24 | etc..

But I'm wondering how to search for multiple terms, so that the body of the returned result has to contain all the words you searched for. Please let me know if I need to regigg my tables to make this happen. Cheers.
Expected Output
I'm expecting something along the lines of this:
GET COMMENTS THAT HAVE 'pig', 'dog'

| comment      |
|--------------|
| that pig dog |
| ...pig...dog |

A: General approach:
Zero! your comment_terms table should have these fields (Id,CommentId, TermId)
First you have get all words of search query.
For example you have dog with id of 1 and pig with id of 2.
Second you search in comment_terms for comments where have both Id (1 and 2) and have also 2 records in comment_terms table(GROUP BY HAVING COUNT(commentId))


text:
Q: How to properly configure Netbeans to build openCMS core? I'm trying to set up a development environment to build openCMS 10.5 with Netbeans 8.2 under Linux(Linux Mint 32-Bit, but I would be flexible there).
Now I'm getting as far as cloning the openCMS core from git. But I have trouble with creating the Netbeans project(s) so the openCMS core can be build properly.
What I need to know is:
How many projects do I need to create in Netbeans? There are several src-folders, does it need to be one project for each folder?
What kind of project(s) do I need to create?
There are several types of project like Java Application or Enterprise Application,...
There is an Ant-build-script in the git-clone. Can I use this to create the Netbeans project(s)?

A: First of all, you don't need an IDE to build opencms. Just invoke gradle from the command line:
gradle bindist

If you want to use NetBeans, you don't need to create any project. NetBeans provides support for gradle projects via plugins. Install the "Gradle JavaEE Support" and "Gradle Support" plugins, and open the already cloned directory:

Admittedly, the current gradle project description doesn't make it easy to work with the code (every module have the same set of sources, rendering the project view quite cumbersome), but you can get used to it.


text:
Q: Get array of all photos in iOS Photo Gallery with faces in them I'm trying to go through every photo in an iOS Device's photo library including camera roll, albums, etc..
From there, I want to check if the photo has a face in it, using core image, and if so, add it to an array called detectedFaceArray.
I understand I have to use ALAssetsLibrary to enumerate through all the groups and then photos in the photo gallery, but I have no idea how to implement core image on each photo. The code I am using is the code being asked in this question here:
https://stackoverflow.com/questions/18658783/enumerategroupswithtypes-alassetsgroupall-retrieves-only-the-number-of-photos-i
OR
-(void)getAllPictures
{
self.galleryImages=[[NSMutableArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];
library = [[ALAssetsLibrary alloc] init];

void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop)
{

if(result != nil)
{
    if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
    {
        [assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];

        NSURL *url= (NSURL*) [[result defaultRepresentation]url];

        [library assetForURL:url
                 resultBlock:^(ALAsset *asset) {
                     [mutableArray addObject:asset];
                     if ([mutableArray count]==count)
                     {
                         self.galleryImages=[[NSMutableArray alloc] initWithArray:mutableArray];
                     }
                 }
                failureBlock:^(NSError *error){ NSLog(@"operation was not successfull!"); } ];
    }
}
};

NSMutableArray *assetGroups = [[NSMutableArray alloc] init];

void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
    if(group != nil) {
        [group enumerateAssetsUsingBlock:assetEnumerator];
        [assetGroups addObject:group];
        count=[group numberOfAssets];
    }
};

assetGroups = [[NSMutableArray alloc] init];

[library enumerateGroupsWithTypes: ALAssetsGroupAll
                       usingBlock:assetGroupEnumerator
                     failureBlock:^(NSError *error) {NSLog(@"There is an error");}];
}

I'm not even sure if this is the correct code to be using so any help would be appreciated. I have read through the ALAssetsLibrary and Core Image Documentation but still don't know how I could do it.
Any suggestions? Thank you!

A: I exactly don't know how to detect a face from image. But you can read this link & download OpenCV to do that

A: For those who still looking for a possible answer to the question. I am using this code to enumerate assets and save those that have faces on them.
[self.library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                [group setAssetsFilter:[ALAssetsFilter allPhotos]];
                [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                    if(result && self.galleryAssets.count <= 20) {
                       CIImage *ciImage = [CIImage imageWithCGImage:result.thumbnail];
                        NSNumber *orientation = [NSNumber numberWithInt:[[UIImage imageWithCIImage:ciImage] imageOrientation]+1];
                        NSDictionary *fOptions = [NSDictionary dictionaryWithObject:orientation forKey: CIDetectorImageOrientation];
                        NSArray *features = [detector featuresInImage:ciImage options:fOptions];

                        if(features.count != 0) {
                            [self.galleryAssets addObject:result];
                        }
                        *stop = NO;
                    } else {
                        *stop = YES; return;
                    }
                }];

                dispatch_async(dispatch_get_main_queue(), ^{
                    if(self.galleryAssets.count == 0) {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Photos" message:@"You have no photos in your gallery." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                        [alert show];
                    }
                });
            } failureBlock:nil];


text:
Q: How to prove the given equation? While studying Ramanujan's Notebooks I stumbled upon the following entry :
$\frac{1}{(x^3-x)} = \frac{1}{2(x+1)} + \frac{1}{2(x-1)} - \frac{1}{x}$
Now, I can prove this identity while working on the RHS. However, if I were to prove it by expanding the LHS, how can I do it?

A: Since the denominator is $x(x^2-1)=x(x-1)(x+1)$ the partial fraction decomposition will be of the form: $
\frac{1}{x^3-x} = \frac{a}{x}+\frac{b}{x-1}+\frac{c}{x+1} \;\;\iff\;\; 1 = a(x-1)(x+1)+bx(x+1)+cx(x-1)
\,$ where $a,b,c$ can be determined by identifying the coefficients, or for a shortcut:

*

*$x=0 \implies 1=-a \implies a = -1\,$

*$x=1 \implies 1 = 2b \implies b = \cfrac{1}{2}$

*$x=-1 \implies 1 = 2c \implies c = \cfrac{1}{2}$

A: Very easily, combine the common denominators of the first two terms, and add to get $x/(x^2-1)$. Next, subtract $1/x$ from that and create a common denominator to yield the desired result!

A: We can prove it for RHS as you did by taking the common denominator of all of the fractions
$$\frac{1}{2(x+1)} + \frac{1}{2(x-1)} - \frac{1}{x}$$
$$\frac{x^2-x}{2(x^3-x)} + \frac{x^2+x}{2(x^3-x)} - \frac{2x^2-2}{2(x^3-x)}$$
$$\frac{1}{x^3-x}$$
And there we have it. Proving it for the LHS can be done simply by taking the opposite steps.
$$\frac{1}{x^3-x}$$
$$\frac{x^2-x+x^2+x-(2x^2-2)}{2(x^3-x)}$$
$$\frac{x^2-x}{2(x^3-x)} + \frac{x^2+x}{2(x^3-x)} - \frac{2x^2-2}{2(x^3-x)}$$
$$\frac{1}{2(x+1)} + \frac{1}{2(x-1)} - \frac{1}{x}$$
And there we have it again.
Generally if you can prove something by manipulating one side, you can simply reverse the steps to get to prove it by manipulating the other side. A good way of proving some equalities is actually to manipulate each expression until you get the same one. Just make sure not to divide by 0 when doing so!


text:
Q: Accumulating atoms into a list without recursion Prolog I'm trying to write a Prolog program that takes user input and makes decisions based on the semantics of the input (basically a chatbot).
I had originally thought (being not a logic programmer) that I would check against multiple sets of words (i.e., interrogatives, family words, words with good/bad emotional content), then accumulate atoms that describe the types of words used into a list, and then check against that list to decide what to say.
Obviously, this doesn't work, so now I'm pretty much lost.  Is there a way to even do something like this in Prolog, or am I thinking about it all wrong?

A: Are you familiar with setof/3?
It lets you collect the set of your results in a list:
setof( Category, is_a(Word, Category), L),
say_something(Word, L),
....

A: Use findall
Say that you have:
a( 'how are you', 'good' ).
a( 'how are you', 'not bad' ).
findall( Answer, a( 'how are you', Answer ), Answers )
In this, answers will have a list of items (in this case, 'good' and 'not bad')

A: ELIZA, that's approaching 50 (!) birthdays, it's the most famous chatbot I know. You can google for 'ELIZA prolog source' and take the first answer, then adapt the database to your needs.

A: Ok my answer ended up going away from the idea of lists, and using predicates instead:
maleWords(  [he, him, his]).
femaleWords([she, her, hers]).
familyWords([mother, mom, father, dad, sister, brother]).
goodEmotes( [happy, ecstatic, great, good, yay, love, like, better, best]).
badEmotes(  [sad, bad, horrible, depressed, sucks, death, die, died, dead]).

chat:-writeln('What\'s on your mind?'), bot.
bot:-readln(A),
 maplist(downcase_atom, A, X),
 X \= [quit] ->
    maplist(checkAtom,X,Temp),
    sort(Temp,List),
    wrt(List),
    bot;
 writeln('Fine. Ruin your life then.').

checkAtom(A,X):-
 maleWords(Y),   member(A,Y)-> X = maleW;
 femaleWords(Y), member(A,Y)-> X = femaleW;
 familyWords(Y), member(A,Y)-> X = family;
 goodEmotes(Y),  member(A,Y)-> X = goodEm;
 badEmotes(Y),   member(A,Y)-> X = badEm;
 X = nothing.

wrt(List):-
 sublist([badEm,family,femaleW],List) -> writeln('Do you feel like she\'s causing your problems?');
 sublist([badEm,family,maleW],List) -> writeln('Do you feel like he\'s causing your problems?');
 sublist([family,femaleW,goodEm],List) -> writeln('Do you feel like she\'s helping you?');
 sublist([family,goodEm,maleW],List) -> writeln('Do you feel like he\'s helping you?');
 writeln('Hmm.*writes on clipboard*').

%%%%%%% Got this predicate from another SO question... %%%%%%%%%%
sublist( [], _ ).
sublist( [X|XS], [X|XSS] ) :- sublist( XS, XSS ).
sublist( [X|XS], [_|XSS] ) :- sublist( [X|XS], XSS ).


text:
Q: A native way to automate clicking a windows form button? (batch) I have a simple batch file that automates a task we do frequently. (End all internet explorer processes, open Control Panel>Internet Settings>Advanced>Reset IE). This is the code
@echo off
taskkill /F /IM iexplore.exe /T
timeout /t 2 /nobreak > NUL
rundll32.exe InetCpl.cpl,ResetIEtoDefaults

The problem is that this Windows function throws up a final approval window:

Is there a native way in the batch file to simulate pressing the Reset button, or bypassing this and just executing it? *No third party software download.

A: Just use SendKeys() from Windows Script Host to simulate keyboard navigation.  Generically, you could send Tab or Shift+Tab to move the focus to different window controls, or Spacebar to toggle a check box or activate a button.  Or if the controls you want to activate are already assigned hotkeys (usually labeled with one letter underlined), just send Alt + whatever letter is underlined.  In the case of this Internet Explorer dialog you're opening, Alt+P will toggle the check box, and Alt+R will activate the Reset button.  See Microsoft's SendKeys() documentation for more details.
Here's a Batch + JScript hybrid example:
@if (@CodeSection == @Batch) @then
@echo off & setlocal
2>NUL taskkill /F /IM iexplore.exe /T
timeout /t 2 /nobreak > NUL
start "" rundll32.exe InetCpl.cpl,ResetIEtoDefaults

cscript /nologo /e:Jscript "%~f0"
goto :EOF

@end // end Batch / begin JScript hybrid code
var sh = WSH.CreateObject('Wscript.Shell');

sh.AppActivate("Reset Internet Explorer Settings");
sh.SendKeys("%p%r");

Here's another example, this time calling PowerShell from a .bat script:
@echo off & setlocal
2>NUL taskkill /F /IM iexplore.exe /T
timeout /t 2 /nobreak > NUL
start "" rundll32.exe InetCpl.cpl,ResetIEtoDefaults

powershell "$sh=new-object -COM Wscript.Shell;$sh.AppActivate('Reset Internet Explorer Settings');$sh.SendKeys('%p%r')"

Of course if there's a chance your scripts will be running on a Windows installation in a different language, you'd probably need to focus the reset window by its HWND rather than its title.  That's a subject for another lesson, though.


text:
Q: how to get value from a field in table I have a field named 'parameter' in table with below format
utf8: "\xE2\x9C\x93"
id: "805265"
plan: initial
acc: "123456"
last: "1234"
doc: "1281468479"
validation: field
commit: Accept

how to query 'acc' value from the table?
database :sequelPro

A: > str = 'utf8..... your string here...'
> puts str
utf8: "\xE2\x9C\x93"
id: "805265"
plan: initial
acc: "123456"
last: "1234"
doc: "1281468479"
validation: field
commit: Accept
=> nil
> str.match(/^acc: "(\d+)"/).captures.first
=> "123456"

A: If I understood correctly, In  PostgreSQL use split_part
See this EXAMPLE
create table star (param text);
insert into star values ('utf8: "\xE2\x9C\x93"'),
                        ('id: "805265"'),
                        ('plan: initial'),
                        ('acc: "123456"'),
                        ('last: "1234"'),
                        ('doc: "1281468479"'),
                        ('validation: field'),
                        ('commit: Accept');

and use function split_part in SELECT query to get value of acc: like this
select col2
from (
      select split_part(param, ' ', 1) col1,
             split_part(param, ' ', 2) col2
      from star
     ) t where col1='acc:'

Note: if you want to split your field by : then use select split_part(param, ':', 1) and split_part(param, ':', 2) col2  so the WHERE clause should be where col1='acc'
sqlfiddle-demo


text:
Q: Strange behaviour trying to draw a pythagorean triangle I'm trying to draw a right triangle with sqares over its sides to illustrate Pythagoras' theorem. Here's my code
    \begin{tikzpicture}[scale=4]
\coordinate[label=200:$A$]  (A) at (0,0) ;
\coordinate[label=120:$B$]  (B) at (0,1)  ;
\coordinate[label=right:$C$] (C) at (1,0) ;
\draw (A) -- (B) -- (C) -- (A) ;
\draw (A) rectangle (0.08,0.08);
\draw[rotate=90] (A)    let
                        \p1=(B),
                        \p2=(A),
                        \n1={veclen(\x2-\x1,\y2-\y1)}
                    in
                        rectangle (\n1,\n1);
\draw[rotate=270] (A)   let
                        \p1=(C),
                        \p2=(A),
                        \n3={veclen(\x2-\x1,\y2-\y1)}
                    in
                        rectangle (\n3,\n3);
\draw[rotate=45] (C) let
                        \p2=(B),
                        \p1=(C),
                        \n2={veclen(\x2-\x1,\y2-\y1)}
                    in
                        rectangle (\n2,\n2);
\end{tikzpicture}

As far as I can see I'm doing nothing wrong. But the picture I get is the following:

Now there are more elegant solutions to this problem, for instance here; but I want to know why my code doesn't do what it is expected.
Thanks in advance!

A: Tray
    \begin{tikzpicture}[scale=4]
\coordinate[label=200:$A$]  (A) at (0,0) ;
\coordinate[label=120:$B$]  (B) at (0,1)  ;
\coordinate[label=right:$C$] (C) at (1,0) ;
\draw (A) -- (B) -- (C) -- cycle ;
\draw (A) rectangle (0.08,0.08);
\draw[red] (A)    let% <---
                        \p1=(B),
                        \p2=(A),
                        \n1={veclen(\x2-\x1,\y2-\y1)}
                    in
                        rectangle +(-\n1,\n1);% <---
\draw[blue] (A)   let% <---
                        \p1=(A),
                        \p2=(B),
                        \n2={veclen(\x2-\x1,\y2-\y1)}
                    in

                        rectangle +(\n2,-\n2);% <---
\draw[rotate=45] (C) let
                        \p2=(B),
                        \p1=(C),
                        \n3={veclen(\x2-\x1,\y2-\y1)}
                    in
                        rectangle + (\n3,\n3);% <---
\end{tikzpicture}

Differences to your MWE are designated by `% <---%. This code gives:

Note: angle for rotate third rectangle is `45 degrees˙only if the first and second are of the same size ...
Addadendum:
Your triangle have equal cathetus, so the \n2 is not necessary to calculate. Shorter code is:
\draw   let \p1=(A),
            \p2=(B),
            \n1={veclen(\x2-\x1,\y2-\y1)} in
            (A) rectangle +(-\n1,\n1)
            (A) rectangle +(\n1,-\n1);


text:
Q: Trouble with Selenium and java Locating Element I am trying to locate an element but it always defines as not found
Below is the HTML code for the section.
I have tried all the options provided by Selenium IDE, Firebug etc, and cannot get the button to click

                   Criação Clients

A: if you can;t find it by " all the options provided by Selenium IDE, Firebug etc"
I think this page section is in a frame or iframe. what you need to do is
to switch to this frame and then try to locate it


text:
Q: If $f(x)$ has $n$ distinct roots in $R$, then $f'(x)$ has $n-1$ distinct roots in $R$ Without Rolle's Theorem Prove that: If $f(x)$ has $n$ distinct roots in $R$, then $f'(x)$ has $n-1$ distinct roots in $R$ Without Rolle's Theorem.
I know in this topic, There is proof with Rolle's theorem. It uses that if we sort the roots such that $x_i < x_{i+1}$,then  $\exists c_i\in(x_i,x_{i+1}) ; f'(c_i) = \frac{f(x_{i+1}) - f(x_i)}{x_{i+1} - x_i} =0$ where $i = \{ 1 , 2 ,... , n-1\}$.
But I want to know is there any way to prove this without Rolle's theorem. Maybe using Intermediate value theorem.  if there isn't repetitive roots, I can prove that with intermediate value theorem. (i.e. the power of each term in factorization of $f(x)$ is $1$). In this solution, I find that $sgn( f'(x_1)) = (-1)^{n-1},~~ sgn(f'(x_2)) = (-1)^{n-2} , ...$ ($x_i$ are sorted) and I find distinct roots using IVT. But If the power of each root get higher than one, this method doesn't work. So Is there any way to prove that generally without Rolle's Theorem?
By IVT, I mean this: (link to wikipedia)

A: Let's prove that between any two consecutive roots of a polynomial lies a root of its derivative. We will use the fact that a polynomial as well as its derivative are continuous and satisfy intermediate value property.
Let $a, b$ with $a < b$ be two consecutive roots of a polynomial $p(x) $. Then we have $$p(x) =(x-a) ^m(x-b) ^nq(x) $$ where $m, n$ are positive integers and $q(x) $ is a polynomial having no roots in $[a, b] $. Then $$p'(x) =q'(x) (x-a) ^m(x-b) ^n+\{m(x-b)+n(x-a)\}(x-a)^{m-1}(x-b)^{n-1}q(x)$$ This can be further written as $$p'(x) =(x-a) ^{m-1}(x-b)^{n-1}r(x)$$ where $$r(x) =(x-a) (x-b) q'(x) +\{m(x-b) +n(x-a) \}q(x) $$ Then $r(x)$ is a polynomial such that $$r(a) r(b) =-mn(a-b) ^2q(a)q(b)<0$$ (note that $q$ maintains a constant sign in $[a, b] $ as it has no roots in $[a, b] $). It follows from IVT that $r(x) $ has a root $c\in(a, b) $ and since $r(x) $ is a factor of $p'(x) $ it follows that $p'(x) $ has a root $c\in(a, b) $.
Historical Note: The above result is exactly what Michael Rolle was trying to prove using some heuristic / geometrical arguments. It is a bit ironical that Rolle was highly critical of the methods of calculus and his proof for the case of polynomials was not rigorous and yet a key theorem in calculus is named after him.


text:
Q: Removing duplicates from CSV yet keeping column headers I have a working powershell script that removes duplicates in a csv file, but it sorts the column headers within the data, which I don't want, and cannot figure out a way to keep the column headers.
Get-Content C:\testdata.csv | ConvertFrom-Csv -Header "Column1", "Column2", "Column3", "Column4" | sort -Unique -Property Column1 | % {"{0},{1},{2},{3}" -f $_.Column1, $_.Column2, $_.Column3, $_.Column4} | set-content c:\output.csv

The test data csv is as follows:

Name,IDNumber,OtherNumber,UniqueCode
Tom,10,133,abcd
Tom,10,133,abcd
Bill,4,132,efgh
Bill,4,132,efgh
Bill,4,132,efgh
Lefty,3,122,ijkl
Lefty,3,122,ijkl
Lefty,3,122,ijkl
Lefty,3,122,ijkl

Is there a way to accomplish this with Powershell?

A: Using Import-Csv and Export-Csv makes this process much easier as they are built to deal with csv files and headers.
Import-Csv "C:\testdata.csv" | Sort-Object * -Unique | Export-Csv "c:\output.csv" -NoTypeInformation

A: Untested, but try this...
Import-Csv -Path 'C:\path\to\File.csv' |
  Select * -Unique |
  Export-Csv 'C:\path\to\NewFile.csv' -NoTypeInformation

A: You could use Select -Skip 1 to skip over the original header column:
Get-Content testdata.csv | Select -Skip 1 | ConvertFrom-Csv -Header "Column1","Column2","Column3","Column4" | sort -Unique -Property Column1 | % {"{0},{1},{2},{3}" -f $_.Column1, $_.Column2, $_.Column3, $_.Column4} | set-content output.csv


text:
Q: What are the generic type variables on the Typescript ThunkAction type in redux-thunk Could anyone help me understand this type -maybe with a simple example- and how to use it correctly since I don't understand what this go between the < >? I just need to make a request to an API.

A: ThunkAction is a generic type, meaning that the specific type of any individual ThunkAction depends on the variables inside of the <>.
This section of the docs explains the meaning of each variable:
/**
 * A "thunk" action (a callback function that can be dispatched to the Redux
 * store.)
 *
 * Also known as the "thunk inner function", when used with the typical pattern
 * of an action creator function that returns a thunk action.
 *
 * @template TReturnType The return type of the thunk's inner function
 * @template TState The redux state
 * @template TExtraThunkARg Optional extra argument passed to the inner function
 * (if specified when setting up the Thunk middleware)
 * @template TBasicAction The (non-thunk) actions that can be dispatched.
 */
export type ThunkAction<
  TReturnType,
  TState,
  TExtraThunkArg,
  TBasicAction extends Action
> = (
  dispatch: ThunkDispatch<TState, TExtraThunkArg, TBasicAction>,
  getState: () => TState,
  extraArgument: TExtraThunkArg,
) => TReturnType;

You shouldn't need to explicitly type all four of those variables.  In fact you should need to use ThunkAction at all.  It just defines a function with a particular signature. So when you create your own thunk functions, you just need to type your function arguments (dispatch, getState, extraArguments), and the rest will be inferred.
You can get the specific dispatch type for your store like this:
type MyDispatch = typeof store.dispatch;

But it defaults to Dispatch which should be fine for most cases.
function makeASandwichWithSecretSauce(forPerson: string ) {
  return function(dispatch: Dispatch) {
    return fetchSecretSauce().then(
      (sauce) => dispatch(makeASandwich(forPerson, sauce)),
      (error) => dispatch(apologize('The Sandwich Shop', forPerson, error)),
    );
  };
}