text:
Q: Where do shakespeare splices look for their files I'm trying to get Shakespeare templates up and running; in particular Text.Hamlet.  I have $(shamletFile "HTML/index.hamlet") (See notes) and when I compile the file I get an error telling me the file does not exist. So I have tried various combinations of file paths trying to guess at what working directory is being used by the splice, but without success.
Where do shakespeare splices look for their files?  Is this documented somewhere?

NOTES

*

*This path is relative to the source file using the template.

*I am not using the full Yesod framework, just the template engine.

A: shamletFile takes a standard FilePath as an argument, and therefore is evaluated against "current local directory". "Current" during Template Haskell evaluation - i.e. compilation phase. As @arrowd pointed out, this is usually main project directory.
Note that if you were using Yesod this would no longer be true, as during the build yesod-bin adds templates/ prefix to each Shakespearean file (and it's hardcoded there).


text:
Q: Are there any problems with this Haskell function for strictly timing a computation? Recently I was trying to determine the time needed to calculate a waveform using the vector storage type.
I wanted to do so without requiring to print the length or something like that.  Finally I came up with the following two definitions.  It seems simple enough, and from what I can tell it prints a non-zero computation time as expected the first time I run the function, but I'm wondering if there are any laziness caveats here that I've missed.
import System.IO
import System.CPUTime
import qualified Data.Vector.Storable as V

timerIO f = do
  start <- getCPUTime
  x <- f
  let !y = x
  end <- getCPUTime
  let diff = (fromIntegral (end - start)) / (10^12)
  print $ "Computation time: " ++ show diff ++ " sec\n"

timer f = timerIO $ do return f

main :: IO ()
main = do
  let sr = 1000.0
      time = V.map (/ sr) $ V.enumFromN 0 120000 :: V.Vector Float
      wave = V.map (\x -> sin $ x * 2 * pi * 10) time :: V.Vector Float

  timer wave
  timer wave

prints,
Computation time: 0.16001 sec
Computation time: 0.0 sec

Are there any hidden bugs here?  I'm really not sure that the let with strictness flag is really the best way to go here.  Is there a more concise way to write this?  Are there any standard functions that already do this that I should know about?
Edit: I should mention that I had read about criterion but in this case I was not looking for a robust way to calculate average timing for profiling-only purposes; rather I was looking for a simple / low-overhead way to integrate single timers into my program for tracing the timing of some computations during normal running of the application.  Criterion is cool, but this was a slightly different use case.

A: If evaluating to weak head normal form is enough - for strict Vectors or UArrays it is -, then your timing code works well¹, however, instead of the bang pattern in the let-binding, you could put a bang on the monadic bind,
start <- getCPUTime
!x <- f
end <- getCPUTime

which to me looks nicer, or you could use Control.Exception.evaluate
start <- getCPUTime
evaluate f
end <- getCPUTime

which has the advantage of (supposed) portability, whereas bang patterns are a GHC extension. If WHNF is not enough, you would need to force full evaluation, for example using rnf or deepseq, like
start <- getCPUTime
!x <- rnf `fmap` f
end <- getCPUTime

However, repeatedly timing the same computation with that is hairy. If, as in your example, you give the thing a name, and call it
timer wave
timer wave

the compiler shares the computation, so it's only done once and all but the first timer calls return zero (or very close to zero) times. If you call it with code instead of a name,
timer (V.map (\x -> sin $ x * 2 * pi * 10) time :: V.Vector Float)
timer (V.map (\x -> sin $ x * 2 * pi * 10) time :: V.Vector Float)

the compiler can still share the computation, if it does common subexpression elimination. And although GHC doesn't do much CSE, it does some and I'm rather confident it would spot and share this (when compiling with optimisations). To reliably make the compiler repeat the computations, you need to hide the fact that they are the same from it (or use some low-level internals), which is not easy to do without influencing the time needed for the computation.
¹ It works well if the computation takes a significant amount of time. If it takes only a short time, the jitter introduced by outside influences (CPU load, scheduling, ...) will make single timings far too unreliable. Then you should do multiple measurements, and for that, as has been mentioned elsewhere, the criterion library is an excellent way to relieve you of the burden of writing robust timing code.

A: Are you familiar with the deepseq package? It's used by the criterion package for pretty much the purpose you describe.
Speaking of which, you may want to consider whether criterion itself does what you need anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does it shows error while running ConnectedThresholdImageFilter example? I am trying to run ConnectedThresholdImageFilter example in ITK mentioned "https://itk.org/Doxygen45/html/Segmentation_2ConnectedThresholdImageFilter_8cxx-example.html" here.
But it is showing the following error.

itk::ImageFileWriterException (0x24cb740)
Location: "void itk::ImageFileWriter::Write() [with
  TInputImage = itk::Image]"  File:
  /usr/local/include/ITK-4.13/itkImageFileWriter.hxx Line: 151
  Description:  Could not create IO object for writing file output
  Tried to create one of the following:
      BMPImageIO
      BioRadImageIO
      Bruker2dseqImageIO
      GDCMImageIO
      GE4ImageIO
      GE5ImageIO
      GiplImageIO
      HDF5ImageIO
      JPEGImageIO
      LSMImageIO
      MINCImageIO
      MRCImageIO
      MetaImageIO
      NiftiImageIO
      NrrdImageIO
      PNGImageIO
      StimulateImageIO
      TIFFImageIO
      VTKImageIO   You probably failed to set a file suffix, or
      set the suffix to an unsupported type

I didn't do any changes in code. And I am trying to use dicom image as an input.

A: It is either

*

*You set the output file name with an unsupported extension.

*There is something wrong about how you compiled/linked ITK or how you are linking your example to ITK.


text:
Q: MediaElement buffering twice I'm using a MediaElement to play a video and using the BufferingProgressChanged event to update a progress bar when buffering occurs. However, when the BufferingProgress property of the MediaElement reaches 1 it resets back to 0 and then buffesr to 1 again. As a result the progress shows twice, which looks strange to the user.
Any idea why this happens and how to prevent it?
I've seen others ask this question, but no answers so far. I guess it's a non trivial problem, hope one of you experts can help!
P.S if you don't know the answer, can you vote for this question so it gets brought to the attention of more people? Thanks...

A: This seems to be a problem with the encoding of the video.
Encoding using Expression Encoder resolved the problem.


text:
Q: Include root in django rest framework responses I have a ready Django project that serves JSON via the rest_framework and its viewsets. Now I would like to write the client using Ember. Here is my setup:

*

*Django 1.6.5

*Ember 1.6.1

*Ember-Data 1.0.0-beta.8.2a68c63a

*jQuery 2.1.1

My Django server runs on the default port 8000 under localhost. I test my Ember application by opening index.html in the browser. Therefore, I customised the ApplicationAdapter like so
App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://localhost:8000',
});

I try to fetch a list of artists from http://localhost:8000/artists. The specified route is
App.ArtistsRoute = Ember.Route.extend({
    model: function() {
        this.store.find('artists');
    }
});

And the response I get back from the server when I open the mentioned url in the browser is
[
    {
        "id": 1,
        "name": "Kollegah",
        "origin": "Germany",
        "genre": "German Rap"
    },
    {
        "id": 2,
        "name": "Peter Fox",
        "origin": "Germany",
        "genre": "Hip-Hop"
    },
    {
        "id": 3,
        "name": "Farid Bang",
        "origin": "Germany",
        "genre": "German Rap"
    },
    {
        "id": 4,
        "name": "Eko Fresh",
        "origin": "Germany",
        "genre": "German Rap"
    }
]

When fetching the data I these two Ember errors:
-Error while processing route: artists No model was found for 'artists' Error: No model was found for 'artists'
-No model was found for 'artists' Error: No model was found for 'artists'
The problem is that I have specified a model already
var attr = DS.attr;
App.Artist = DS.Model.extend({
    name: attr,
    origin: attr,
    genre: attr,
});

I suppose the problem is the missing root element at the beginning of each JSON response. I suggest it should look like this example from the Ember Guides:
{
  "post": {
    "id": 1,
    "title": "Rails is omakase",
    "comments": ["1", "2"],
    "user" : "dhh"
  },

  "comments": [{
    "id": "1",
    "body": "Rails is unagi"
  }, {
    "id": "2",
    "body": "Omakase O_o"
  }]
}

After searching a short while I found a similar problems with Rails. I tried out the solution for Django mentioned in another Stackoverflow question but I got the same errors.
Does anybody know a server-side solution for this problem? The Ember Data Django Adapter could be one for the client side. Unfortunately, it is designed as a node plugin and at the moment I don't use it for my project.

A: The Ember Data Django Adapter is the most simple way of solving your problem, and if you pay attention to the docs, there are instructions for using it without ember-cli.


text:
Q: Union not reinterpreting values? Consider this program:
#include <stdio.h>

union myUnion
{
    int x;
    long double y;
};

int main()
{
    union myUnion a;
    a.x = 5;
    a.y = 3.2;
    printf("%d\n%.2Lf", a.x, a.y);
    return 0;
}

Output:
-858993459
3.20

This is fine, as the int member gets interpreted using some of the bits of the long double member. However, the reverse doesn't really apply:
#include <stdio.h>

union myUnion
{
    int x;
    long double y;
};

int main()
{
    union myUnion a;
    a.y = 3.2;
    a.x = 5;
    printf("%d\n%.2Lf", a.x, a.y);
    return 0;
}

Output:
5
3.20

The question is why the long double doesn't get reinterpreted as some garbage value (since 4 of its bytes should represent the integer)? It is not a coincidence, the program outputs 3.20 for all values of a.x, not just 5.

A:
However, the reverse doesn't really apply

On a little endian system (least significant byte of a multi-byte value is at the lowest address), the int will correspond to the least significant bits of the mantissa of the long double. You have to print that long double with a great deal of precision to see the effect of that int on those insignificant digits.
On a big endian system, like a Power PC box, things would be different: the int part would line up with the most significant part of the long double, overlapping with the sign bit, exponent and most significant mantissa bits. Thus changes in x would have drastic effects on the observed floating-point value, even if only a few significant digits are printed. However, for small values of x, the value appears to be zero.
On a PPC64 system, the following version of the program:
int main(void)
{
    union myUnion a;
    a.y = 3.2;
    int i;
    for (i = 0; i < 1000; i++) {
      a.x = i;
      printf("%d -- %.2Lf\n", a.x, a.y);
    }
    return 0;
}

prints nothing but
1 -- 0.0
2 -- 0.0
[...]
999 - 0.0

This is because we're creating an exponent field with all zeros, giving rise to values close to zero. However, the initial value 3.2 is completely clobbered; it doesn't just have its least significant bits ruffled.

A: The size of long double is very large. To see the effect of modifying the x field on implementations where x lines up with the LSBs of the mantissa of y and other bits of union are not effected when modifying via x, you need to print the value with much higher precision.

A: This is only affecting the last half of the mantissa. It won't make any noticeable difference with the amount of digits you're printing. However, the difference can be seen when you print 64 digits.
This program will show the difference:
#include <stdio.h>
#include <string.h>
#include <ctype.h>

union myUnion
{
    int x;
    long double y;
};

int main()
{
    union myUnion a;
    a.y = 3.2;
    a.x = 5;
    printf("%d\n%.64Lf\n", a.x, a.y);
    a.y = 3.2;
    printf("%.64Lf\n", a.y);
    return 0;
}

My output:
5
3.1999999992549419413918193599855044340074528008699417114257812500
3.2000000000000001776356839400250464677810668945312500000000000000

Based on my knowledge of the 80-bit long double format, this overwrites half of the mantissa, which doesn't skew the result much, so this prints somewhat accurate results.
If you had done this in my program:
a.x = 0;

the result would've been:
0
3.1999999992549419403076171875000000000000000000000000000000000000
3.2000000000000001776356839400250464677810668945312500000000000000

which is only slightly different.

A: Answers posted by Mohit Jain, Kaz and JL2210 provide good insight to explain your observations and investigate further, but be aware that the C Standard does not guarantee this behavior:

6.2.6 Representations of types
6.2.6.1 General
6   When a value is stored in an object of structure or union type, including in a member object, the bytes of the object representation that correspond to any padding bytes take unspecified values. The value of a structure or union object is never a trap representation, even though the value of a member of the structure or union object may be a trap representation.
7   When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values.

As a consequence, the behavior described in the answers is not guaranteed as all the bytes of the long double y member could be modified by setting the int x member, including the bytes that are not part of the int. These bytes can take any value and the contents of y could even be a trap value, causing undefined behavior.
As commented by Kaz, gcc is more precise than the C Standard: the documentation notes it as a common practice: The practice of reading from a different union member than the one most recently written to (called type-punning) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. This practice is actually condoned in the C Standard since C11, as documented in this answer: https://stackoverflow.com/a/11996970/4593267 . Yet in my reading of this footnote there is still no guarantee about the bytes of y not part of x.


text:
Q: How to access a repository from another computer using Tortoise svn? I was install tortoise SVN in my system and i want to give a checkout to my friend so he needs to access my repository like 192.168.10.24/reponame/ so how he can checkout.
The repository is not accessible.

A: To share your repository with another person you need to set up a Subversion server. TortoiseSVN is not a server, it's only a client. Your server will need to be accessible to your friend via network, so unless he's on the same network as you are, you'll need to open a port on your firewall, forward the traffic through, and pay attention to all the security concerns that come with operating a server on the Internet.
Or you could try Git, create a repository on Github, tell him where to find it, and have him send you pull requests when he wants to integrate his work with yours. Or try Bitbucket (with Mercurial or Git) - pretty much the same principle, difference being that Bitbucket is free private repositories and Github charges for private repos. You won't have to worry about the networking, server operation, backups, security or anything else related.


text:
Q: Lost code but I have xcarchive how do I extract my code from it My mac crashed, lost all my code but I have an old xcarchive how do I extract my code from it?

A: sorry but you want get back source code that way
the archive only contains compiled code and while you could decompile it in THEORY it won't work in practice.

A: You all all correct there is no way of doing it, I will have to re-write.
Thank you.


text:
Q: Slave DNS not acessible from outside network: Bind9 misconfiguration or firewall issue? I'm not sure why I can't access my Slave DNS from outside my network.
I've probably done something wrong while configuring it, but I just can't figure out what.
Can someone give me a little help?
Thank you already.
pfSense (10.1.1.1):
Interface: WAN
Protocol: UDP
Source Addr: *
Source Ports: *
Dest. Address: WAN Address
Dest. Ports: 53
NAT IP: 10.1.1.15
NAT Ports: 53
I can't see anything in my log and my ISP has already opened all UDP ports.
Slave DNS (10.1.1.15):
/etc/named.conf:
options {
        listen-on port 53 { 127.0.0.1; 10.1.1.15; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        allow-query     { any; };
        recursion yes;
        allow-recursion { 127.0.0.1; 10.1.1.0/24; };
        allow-recursion-on { 127.0.0.1; 10.1.1.0/24; };

        dnssec-enable yes;
        dnssec-validation yes;
        dnssec-lookaside auto;

        /* Path to ISC DLV key */
        bindkeys-file "/etc/named.iscdlv.key";
        managed-keys-directory "/var/named/dynamic";

         pid-file "/run/named/named.pid";
        session-keyfile "/run/named/session.key";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};
zone "." IN {
        type forward;
#        forward only;
forwarders { 213.186.33.99; 8.8.8.8; 8.8.4.4; };
};

zone "domain1.com.br" IN {
        type slave;
        file "bak.domain1.com.br";
        masterfile-format text;
        masters { masterdnsip; };
};

zone "domain2.com.br" IN {
        type slave;
 file "bak.domain2.com.br";
        masterfile-format text;
        masters { masterdnsip; };
};
zone "domain3.com.br" IN {
        type slave;
        file "bak.domain3.com.br";
        masterfile-format text;
        masters { masterdnsip; };
};

zone "re.ver.se.ip.in-addr.arpa" IN {
        type slave;
        file "bak.domain1.com.br-reverso";
        masterfile-format text;
        masters { masterdnsip; };
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

A: If your WAN address really is 10.1.1.1 which is in a private address range then I really don't see how your nameserver can be reached from the internet unless your ISP provided you with public IP which they MAP to that address (or at least map DNS port 53 from there to you).

A: Try doing packet captures, either with tcpdump on the pfSense machine and DNS server or by using SPAN ports on your switches and using Wireshark. That way you can see the packets before and after the firewall and verify your NAT rules are working fine. Next, if the traffic also correctly enters your DNS server, you can start checking the configuration of that server.
If you're able to make some packet captures, please share that information with us as well. It will help us analyze the problem as we currently have too little information to work with.


text:
Q: How to solve Optimization problems in calculus. In my math class we are currently studying calculus. We just came to the Optimization section and my teacher said that it's very tricky. I don't quite understand so I was hoping for some guidance on a problem so that hopefully I can use it to work on other problems. (Would I be able to use the way I do one problem for a different problem? Based on the questions we did in class, it seemed different which makes me very confused.).
This is a problem in our textbook as an example.
A manufacturer needs to construct a box having a square base and holding 100 cubic inches.
a) Let each side of the square base be $x$ inches. Write an expression for the height, $h$, of the box in terms of $x$.
So, I know the volume is base multiplied by width multiplied by height. Does that have any relevance for this part of the problem?
b) Let A(x) be the outside surface area of the box. Show that $A(x) = 2x^2 + 400/x$.
To be completely honest, I really don't know where to even begin on this part of the question.
c) Find $A'(x)$.
Would this be $4x + -400/x$?
d) Find the height of the box that will minimize the outside surface area.
Basically, I need some help getting a grasp on the concept of Optimization problems. I don't really have a clue where to begin with them. This question is an example of the types of problems I'm working with in class. Are there are tips / tricks you could show me to help me get through this unit?

A: You know that $V(x,h) = x^2h$ and also that $V(x,h) = 100$. In particular, this means you can determine $h$ using $h= {100 \over x^2}$.
The area is given by $2x^2+4xh$ (counting all 6 sides), so using the previous
relation we have
$A(x) = 2x^2 + 4 x {100 \over x^2} = 2x^2 + {400 \over x}$.
Note that there is an implicit constraint that $x > 0$.
If we plot $A$ for $x>0$ we see that it has a $\min$ somewhere, to find the
$\min$ we look for points where the slope $A'(x)$ is zero.
Since $A'(x) = 4x -{400 \over x^2}$, we see that the slope is zero when
$x = \sqrt[3]{100}$.
This gives the $x$ value, to get $h$ we use the formula from the first
paragraph to get $h = {100 \over \sqrt[3]{10000}} = \sqrt[3]{100}$.

A: a) Consider the equation for the volume of a box with a square base of area x^2, Volume = x^2 * height. From here you can solve for the height of the box in terms of x.
b) After you find an equation for height in terms of x, to find the surface area, you just need to find the sum of each face's area.
c)No. You forgot to subtract 1 from the exponent.
d)Look at the 0s of the derivative.
Now, considering optimization problems in a first year calculus course, I believe you can approach most similarly. Consider what function you are trying to optimize. In your case, the surface area formula. Then you should figure out how to reduce this formula to only 1 variable, in this case, x, using constraints that are given to you. Then take the derivative of the function you are trying to optimize and solve for 0. Once you figure out what this variable is, go back and plug it into your given constrains. You'll likely find that you can solve for a different variable explicitly.

A: The square base has sides $x$ and the height is $h$, so the volume $V=x^2h$. We know $V=100$, so we get that $100=x^2h$, or, as we want it, $h=\frac{100}{x^2}$.
b) Draw a cuboid with the required dimensions and find its surface area. Then use that $h=\frac{100}{x^2}$.
c) It's good practice to write the original as $A(x)=2x^2+400x^{-1}$, that way you can see the normal power rules more easily.
d) This is the optimisation bit of the question, and its simpler than it seems. $A(x)$ is the surface area of the cuboid when its base is $x$. If we wish to minimise it, we want where:
$$A'(x)=0 \text{ and } A''(x)>0$$
The first derivative being $0$ means we have a turning point, the second derivative being positive means that the turning point is a trough rather than a peak. You can calculate the two derivatives quite easily, then solve $A'(x)=0$ and check each solution in $A''(x)$ to see if that's positive too. Don't forget that $x>0$, it's a length!
Lastly, once you've found your value of $x$, the question asks for $h$, so find that via $h=\frac{100}{x^2}$
Good luck!


text:
Q: Evaluate with numbers from list This code works:
x=2
y/.Solve[y==x^2]
Out[138]= 2
Out[139]= {4}

So above I put number in variable x and getting the result of corresponding y
Now I want to give list with several values in list in variable x and get evaluated values of corresponding y's. How can I do that?
I tried this but it does not works:
x={1,2,3,4}
y/.Solve[y==x^2]
Out[140]= {1,2,3,4}
Out[141]= y

Expected output is:
{1,4,9,16}

A: Maybe you can use the following codes:
x = {1, 2, 3, 4};Solve[y == z^2] /. z -> x

The final result is:
{{y -> {1, 4, 9, 16}}}

A: Why not bypass Solve, and apply the square directly:
x={1, 2, 3, 4};

y = x^2

{1, 4, 9, 16}

More complicated operations:
y= somethingComplicated[#]&/@x


text:
Q: Gesture blocking buttons in ZStack I have a gesture added to a Rectangle inside a ZStack.  I have a VStack which is a view or menu of buttons.  When I add the gesture to the Rectangle (because I need to detect a tap on that view behind the menu buttons), then the buttons can not receive interaction from the user on device.  I have the Rectangle behind the buttons and they do show above the Rectangle. On the simulator it worked just fine but on device it does not. Any help would be greatly appreciated from the community.  Thanks!
var body: some View {
        ZStack {
            Rectangle()
                .foregroundColor(Color.black.opacity(0.01))
                .gesture(DragGesture(minimumDistance: 0)
                    .onChanged({ (value) in
                    self.store.tapped = true
                }))
            VStack(alignment: .leading, spacing: 0) {
                //menu buttons
                HStack(alignment: .center, spacing: 18.5) {
                    someView()
                        .environmentObject(self.anotherStore)
                        .frame(width: 145, height: 22)
                    self.otherSubviews()
                }
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 37, alignment: .leading)
                .padding(EdgeInsets(top: 0, leading: 6, bottom: 0, trailing: 6))
                //menu detail view
                self.detailView()
                }
            .padding(EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 12))
        }
    }

I have tried changing the .zIndex for both to -1 for the Rectangle to something higher for the menu view.  It does not change anything
I would like for the Rectangle to receive interaction (taps) from the user and also that the VStack of buttons will also receive interaction from the user.

A: Figured out that with a view in the background that has a gesture you need to make sure that your other views have .contentShape(Specify A Shape).
In the Apple documentation it states
    /// Returns a new view that defines the content shape for
    /// hit-testing `self` as `shape`.

I added .contentShape(Rectangle()) to the VStack and it allowed taps for the menu view of buttons as well as allowing taps to the Rectangle view in the background.
Updated code with answer
var body: some View {
        ZStack {
            Rectangle()
                .foregroundColor(Color.black.opacity(0.01))
                .gesture(DragGesture(minimumDistance: 0)
                    .onChanged({ (value) in
                    self.store.tapped = true
                }))
            VStack(alignment: .leading, spacing: 0) {
                //menu buttons
                HStack(alignment: .center, spacing: 18.5) {
                    someView()
                        .environmentObject(self.anotherStore)
                        .frame(width: 145, height: 22)
                    self.otherSubviews()
                }
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 37, alignment: .leading)
                .padding(EdgeInsets(top: 0, leading: 6, bottom: 0, trailing: 6))
                //menu detail view
                self.detailView()
                }.contentShape(Rectangle()) //Define a tappable area
            .padding(EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 12))
        }
    }


text:
Q: Some definitions: parskip, baselineskip, topskip I am a bit confused about what characteristics of the page are controlled by: \parskip, \baselineskip, \topskip.`
\parskip` controls the space between paragraphs but is it the same value all across the document? It seems, for example, to have a different value in a paragraph between title and subtitle that in one between subtitle and text. Is this right?
Are there simple ways to control all different "parskips" in the .tex file?
Some examples about those three will be welcome.

A: \parskip adds some "glue" between each paragraph. As I understand it, "glue" in LaTeX means, that it is not something fixed but it can adapt a bit according to what fills the space on a page best. This vertical empty space is inserted between every paragraph but not before the first or after the last one on a page. But it does influence the spacing between eg. a section heading and the beginning of the text.
There is a package called parskip which should be used if you want to use spacing between paragraphs instead of indentation in the standard classes like article.
\baselineskip influences the spaceing between two lines. But if you want to change the linespreading you should instead use the package setspace because that changes the linespacing for text but excludes captions, footnotes etc. from the setting which is normally wanted.
\topskip specifies the vertical spacing of the first line of a page in relation to the default.
\parindent  by default LaTeX indents every paragraph except from the first one after a new heading. The indentation of the other paragraphs can be changed with this command.

For comparison lets look at a default \documentclass{article} in LaTeX (with the package showframe to visualise the separation at the top)

and one where we set
\topskip=40pt
\parskip=10pt
\parindent=0pt
\baselineskip=15pt


text:
Q: C# How to add placement variable into a resource string This should be easy, but can't find anything to explain it.
Say I am writing something out on console.writeln like:
console.writeln("Jim is a  {0} ", xmlscript);
Say I wanted to convert string `"Jim is.." to a resource string in a global resource.resx. It would be:
jimstring jim is a {0}
and I would refer to it in code as
console.writeln(Resources.jimstring)
How to I put the placement variable (xmlscript) (is this what they are called?) into the resource string in console.writeln?
Thanks,
Bob

A: Console.WriteLine(Resources.jimstring, xmlscript);

Console.WriteLine takes additional formatting arguments that will replace the {0} in your Resources.jimstring string.
More info here: http://msdn.microsoft.com/en-us/library/828t9b9h.aspx

A: As Jeff Johnson mentioned in his answer, it basically the exact same thing as the original Console.WriteLine().  The resource string is just a string.  So you reference the resource file and do the format.
If you need it for something other than the Console you can use the String.Format():
  var newString = String.Format(resources.jimstring, xmlscript);


text:
Q: How to use multiple vpn clients with wireguard on windows? I have multiple connections to the same vpn server. One connection is a wireguard with access to the Internet, the other is an openvpn connection with access only to the local network of the remote server. But when I connect to wireguard all other connections don't work. How to add other routes when connected to wireguard vpn? It seems that when wireguard connected, it blocks all other routes.

A: Make sure your WireGuard connection profile does not list 0.0.0.0/0 or ::/0 as its AllowedIPs, because this causes the Windows client to automatically activate the "Block untunnelled traffic (kill-switch)" feature – it inserts hidden firewall rules preventing packets from going through any other interface regardless of routes.
To avoid this, change the profile to:
AllowedIPs = 0.0.0.0/1, 128.0.0.0/1, ::/1, 8000::/1

These prefixes still combine to 0.0.0.0/0 and ::/0 and have the same effect as a "default route", but it won't trigger the block rules as long as it doesn't literally say "0.0.0.0/0" in the profile.
Disabling the "Block untunnelled traffic" checkbox will do this automatically.


text:
Q: How to avoid destroy deleting earlier related object If the user already has a favorite model after log in, then I want the products that were added to their anonymous bookmarks to be overwritten in the favorite that is attached to their user object.
I find session_favorite (anonymous favorite), @favorite, which belongs to the user. I am rewriting line_item.favorite with the ID of session_favorite to the user's ID favorite. I reset the session and destroy that anonymous favorite, which in theory has become empty, since now line_items has the user's favorite ID.
But, for some reason, when destroying a session_favorite, line_items are also deleted. Why?
module CurrentFavorite
  def set_favorite
    if user_signed_in?
      set_user_favorite
    else
      if session[:favorite]
        @favorite = Favorite.find(session[:favorite])
      else
        @favorite = Favorite.create
        session[:favorite] = @favorite.id
      end
    end
  end
  def set_user_favorite
    if session[:favorite]
      if current_user.favorite.nil?
        @favorite = Favorite.find(session[:favorite])
        session[:favorite] = nil
        @favorite.update(user: current_user)
      else
        #block with error
        session_favorite = Favorite.find(session[:favorite])
        @favorite = Favorite.find_by(user: current_user)
        session_favorite.line_items.each do |line_item|
          line_item.update(favorite: @favorite)
        end
        session[:favorite] = nil
        session_favorite.destroy
        @favorite
      end
    else
      if current_user.favorite.nil?
        @favorite = current_user.build_favorite
        @favorite.save
      else
        @favorite = Favorite.find_by(user: current_user)
      end
    end
  end
end

LineItem Update (0.7ms)  UPDATE "line_items" SET "favorite_id" = ?, "updated_at" = ? WHERE "line_items"."id" = ?  [["favorite_id", 1], ["updated_at", "2020-06-07 05:19:54.653064"], ["id", 13]]
  ↳ app/models/concerns/current_favorite.rb:31
   (12.9ms)  commit transaction
  ↳ app/models/concerns/current_favorite.rb:31
   (0.0ms)  begin transaction
  ↳ app/models/concerns/current_favorite.rb:31
  Movie Load (0.1ms)  SELECT  "movies".* FROM "movies" WHERE "movies"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  ↳ app/models/concerns/current_favorite.rb:31
  LineItem Update (0.7ms)  UPDATE "line_items" SET "favorite_id" = ?, "updated_at" = ? WHERE "line_items"."id" = ?  [["favorite_id", 1], ["updated_at", "2020-06-07 05:19:54.674229"], ["id", 14]]
  ↳ app/models/concerns/current_favorite.rb:31
   (3.6ms)  commit transaction
  ↳ app/models/concerns/current_favorite.rb:31
   (0.0ms)  begin transaction
  ↳ app/models/concerns/current_favorite.rb:34
  LineItem Destroy (0.5ms)  DELETE FROM "line_items" WHERE "line_items"."id" = ?  [["id", 13]]
  ↳ app/models/concerns/current_favorite.rb:34
  LineItem Destroy (0.1ms)  DELETE FROM "line_items" WHERE "line_items"."id" = ?  [["id", 14]]
  ↳ app/models/concerns/current_favorite.rb:34
  Favorite Destroy (0.2ms)  DELETE FROM "favorites" WHERE "favorites"."id" = ?  [["id", 10]]
  ↳ app/models/concerns/current_favorite.rb:34

A: session_favorite still has the set of line_items associated with it.  For performance reasons, Rails does not automatically reload the line_items before destroying the session_favorite so it doesn't recognize that the line_items are now associated with a different favorite.
To prevent the line_items being destroyed, refresh the association before doing the destroy:
session_favorite.line_items.reload
session_favorite.destroy


text:
Q: Scraping a table I am trying to extract the properties of a house and the corresponding values. I am interested in getting {key:{Property type: Commercial property, Purchase price: CHF 475,000, etc. }
I was able to extract the values one by one but not as a loop that is updating my dictionary.

            Property type

Commercial property

            Purchase price

CHF 475,000

            Floor space

114 m²

            Floor

1. floor

            Year of construction

1989

            Balcony/ies

            Indoor parking

            Outdoor parking

            Lift

            Cable TV

            Public transport stop

150 m

            Motorway

500 m

            Shops

300 m

A: Considering the html text provided by you, which is stored as a string in table_text.
from bs4 import BeautifulSoup
soup = BeautifulSoup(table_text,"lxml")
temp_dict = {}
for d in soup.find_all("div",{"class":"column"}):
    temp_dict[d.find("dt").text.strip()] = d.find("dd").text.strip()
print(temp_dict)

I am guessing the html text you provided was for only one row of the table, if you want this for all the rows, loop over them and keep a parent dictionary where you update row as a key and temp_dict as a value in each iteration. This will give you the structure you wanted.


text:
Q: mysql order with many criterias on two tables I'm trying to sort a visitor list after some different criteria and got stuck, as I can't figure out, how to do this.
I have a queue of people who check in first, and out of that the list is generated. The client is marked as showedUp, if he comes to the door (after called with his number on the list). If someone comes late, he must be at the end of the list. Another thing is, the list starts everytime with a different number.
Day 1 -> List from 1 to 160
Day 2 -> List from 33 to 160, 1 to 32
Day 3 -> List from 65 to 160, 1 to 64

If someone comes late, meaning the number after him is already called, he should be added to the end of the list, like 1 to 160, 10 was late, as 20 was already called, it should be 1 to 160, 10. If there is another starting number it should be 33 to 160, 1 to 32, 10. The criteria here is: if a placeNr after your number is already called (showedUp), than you be at the end of the list.
Tables
clients (id, name, placeNr)
visits (id, pid, checkInTime, showedUp, showedUpTime)

Select
SELECT clients.id AS id, visits.id AS visitId, clients.placeNr AS placeNr, clients.name AS name
FROM clients, visits
WHERE clients.id = visits.pid AND visits.checkInTime >= '1447286401' AND visits.checkInTime <= '1447372799'
ORDER BY clients.placeNr < '1', if(visits.showedUpTime < visits.checkInTime, clients.placeNr, 1), ttc.placeNr

So how do I get the late showers at the end of my list?
Thank you very much in advance!

A: If I follow your logic, you need to specify whether or not someone is late.  The following is the structure that you want for this type of query.  I think I've captured the rules in your question:
select v.id, v.id AS visitId, c.placeNr, c.name,
       (case when v.showedUpTime >
                  (select min(v.checkInTime)
                   from visits v2 join
                        clients c2
                        on v2.pid = c2.id
                   where date(v2.showedUpTime) = date(v.showedUpTime) and
                         c2.placeNr > c.placeNr
                  )
             then 1 else 0 end) as IsLate
from clients c join
     visits v
     on c.id = v.pid
order by date(v.showedUpTime),
         isLate,
         c.placeNr;


text:
Q: Python unit test gives AttributeError: 'TestCalculator' object has no attribute 'calculator' I am attempting some unit testing in python for the first time for a simple calculator. I have the calculator file as Calculator_steps.py
class Calculator:

def addNumbers(self, numberlist):
    total = 0
    if numberlist == "":
        numberlist = "0"
        numbers = numberlist.split(",")
    if len(numbers) > 3:
        raise TypeError("Only three variables are accepted")
    for i in range(len(numbers)):
        if int(numbers[i]) > 100:
            raise TypeError("Only values less than 100 is accepted")
        try:
            total = total+int(numbers[i])
        except ValueError:
            raise TypeError("Only integers values are allowed")
    return total

I have written a test file as test_calculator.py
There i have 4 test functions to test addition with one integer, two integers, three integers and one to check for only whole numbers
import unittest

import Calculator_steps as CalculatorClass

class TestCalculator(unittest.TestCase):

    def _init_(self):
        self.calculator = CalculatorClass.Calculator()

    def test_oneIntegers(self):
        self.assertEqual(self.calculator.addNumbers('6'),6)

    def test_twoIntegers(self):
        self.assertEqual(self.calculator.addNumbers('5,6'),11)

    def test_threeIntegers(self):
    self.assertEqual(self.calculator.addNumbers('100,6,7'),113)

    def test_DecimalValues(self):
        with self.assertRaises(Exception):
            self.calculator.addNumbers('5.66,3.44')

When i try to run this i get AttributeError: 'TestCalculator' object has no attribute 'calculator' for the first three functions. I'm confused as to what the issue is. Can some one explain to me why it is giving this error to the first three and not the fourth.

A: You import the file calculator_steps.py in the test_calculator.py not the class Calculator.
Replace import Calculator_steps as CalculatorClass with from calculator_steps import Calculator as CalculatorClass.


text:
Q: how to get php connect to mysql? i've tried everything to make my site connect to the database but i always get his error:  Could not connect to Master Database
i have 2 files
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','root');
define('DBNAME','test');
define('dbslave','test');
define('dbsiteid','1');
define('dbprefix','_blog');

and connect.php
error_reporting(0);
$connect = mysql_connect("$DBHOST", "$DBUSER", "$DBPASS");
if ( ! $connect) {
    die('Could not connect to Database server');
}
$siteid  = "$dbsiteid";
$prefix  = "$dbprefix";
$dbmast  = "$DBNAME";
$dbslave = "$dbslave";
$cmast   = mysql_select_db("$DBNAME");
if ( ! $cmast) {
    die('Could not connect to Master Database');
}
$cslave = mysql_select_db("$dbslave");
if ( ! $cslave) {
    die('Could not connect to Slave Database');
}

how do i solve this error with connection or what i did wrong ?

A: You do not put constants in quotes, they do not start with $, and by convention are all uppercase.
 define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','root');
define('DBNAME','test');
define('DBSLAVE','test');
define('DBSITEID','1');
define('DBPREFIX','_blog');

$connect = mysql_connect(DBHOST, DBUSER, DBPASS);
if (!$connect) {die('Could not connect to Database server');}
$cmast = mysql_select_db(DBNAME);
if (!$cmast) {die('Could not connect to Master Database');}
$cslave = mysql_select_db(DBSLAVE);
if (!$cslave) {die('Could not connect to Slave Database');}

Also, defining constants only to assign them to variables is silly and a waste of resources. And don't turn off error reporting when developing as it hides your errors. You want to do the opposite and them them on.


text:
Q: Shortcut for conditional formatting in Excel 2011 in OS X How do I create a keyboard shortcut for conditional formatting for Excel 2011 in OS X? I am unable to find any such shortcut.

A: press Alt + O + D and In the New Formatting Rule dialogue box, select the option 'Use a formula to determine which cells to format'. Set the format that you want to apply to the cells that are blank or have errors.

A: You could use the build in Recorder in Excel 2011. It is called Macro recorder.
Under Tools select New Macro recording. It will record your actions that you can call up with a keyboard short cut that you have chosen.

The result would be something like this pending what you did, and you can recall that any time with your assigned keyboard shortcut.


text:
Q: jQuery running extremely slow on iPad I've got some jQuery I'm running on a test case we're looking into, and it runs extremely slowly on our iPad 2's.
It's snappy and responsive on our desktops and laptops, though. I've tried removing all the selectors (where possible) and instead using stored references, which didn't help much.
Before that change it was http://jsfiddle.net/EEGgv/5/ while after it was http://jsfiddle.net/EEGgv/6/
Here is the current jQuery code:
$().ready(function () {
    var $varSelected = 'undefined';
    var $this = 'undefined';
    var varPrev = '';
    var varNew = '';

    $('.btn').click(function () {
        $this = $(this);

        if ($varSelected !== 'undefined') {
            // Get previous value
            varPrev = $varSelected.text();

            // Find value we're trying to add
            varAdding = $this.attr('value');

            if (varAdding == 'Clr') {
                varNew = '';
            } else {
                varNew = varPrev + varAdding;
            }

            // Write new value
            $varSelected.text(varNew);
        }
    });

    $('.qtyBox').click(function () {
        $this = $(this);

        // Check if we've previously had a selected box
        if ($varSelected === 'undefined') {
            // Didn't have one before -- nothing special
        } else {
            // Had one selected. We need to unselect it.
            $varSelected.removeClass('Selected');
        }

        // Select the one we have now
        $varSelected = $this;

        // Add formatting
        $this.addClass('Selected');

        // Clear value
        varNew = '';
        $this.text(varNew);
    });
});

I have the /5/ version (pre-references) uploaded to http://test.projectdavis.com/test.html while the /6/ versoin (references) uploaded to http://test.projectdavis.com/test2.html.
Anyone have any insight?
Thanks

A: I was able to test your page on my iPad 2. The input lag seems to be the mobile click event delay where  click events are fired after 0.3 seconds on mobile browsers(https://developers.google.com/mobile/articles/fast_buttons?hl=de-DE.). This delay is so that the browser can listen for a double tap. There are four additional event handlers that mobile browser provide, the one you are probably interested in is clickend. The clickend event is fired when the user lifts their finger from the screen.
The code below is from MDN
https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Touch_events
var el = document.getElementsById("MyButtonID");
el.addEventListener("touchend", handleEnd, false);


text:
Q: Server, Database or Code Issue? Magento backend rewrites itself with a index.php which doesnt work I will be honest and admit my cross posting in magento.stackexchange.com but the reason is that I believe it is a server fault, and now I am looking for proof to present to my dreaded hosting providers, GoDaddy...
My magento was working a dream, all of a sudden, when logining into
mysite.com/mixitup/

after the login, it changes to
mysite.com/index.php/mixitup/dashboard/index/key/812b0641da.... etc,

however if I change the path to
mysite.com/mixitup/dashboard/index/key/812b0641da... etc

then it shows the dasboard, but upon clicking anything such as catalogue > manage products the index.php is inserted again, leaving
mysite.com/index.php/mixitup/catalog_product/index/key/f0e2d249eca781e... etc

Strangly, this has suddenly taken affect on 2 independent magento sites on one server. They share a .htaccess file on the route, however this hasn't changed to cause the problem. It's a godaddy shared server so my options here are limited.
Any thoughts on what may have changed this? or how to fix it?
Here is a copy of my .htaccess file (sorry to dump)
############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi

#    Action php5-cgi /cgi-bin/php5-cgi
#    AddHandler php5-cgi .php

############################################
## GoDaddy specific options

Options -MultiViews

## you might also need to add this line to php.ini
##     cgi.fix_pathinfo = 1
## if it still doesn't work, rename php.ini to php5.ini

############################################
## this line is specific for 1and1 hosting

#AddType x-mapp-php5 .php
#AddHandler x-mapp-php5 .php

############################################
## default index file

DirectoryIndex index.php index.html

<IfModule mod_php5.c>

############################################
## adjust memory limit

#    php_value memory_limit 64M
php_value memory_limit 128M
php_value max_execution_time 18000

############################################
## disable magic quotes for php request vars

php_flag magic_quotes_gpc off

############################################
## disable automatic session start
## before autoload was initialized

php_flag session.auto_start off

############################################
## enable resulting html compression

#php_flag zlib.output_compression on

###########################################
# disable user agent verification to not break multiple image upload

php_flag suhosin.session.cryptua off

###########################################
# turn off compatibility with PHP4 when dealing with objects

php_flag zend.ze1_compatibility_mode Off

</IfModule>

<IfModule mod_security.c>
###########################################
# disable POST processing to not break multiple image upload

SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>

<IfModule mod_deflate.c>

############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

# Insert filter on all content
###SetOutputFilter DEFLATE
# Insert filter on selected content types only
#AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript

# Netscape 4.x has some problems...
#BrowserMatch ^Mozilla/4 gzip-only-text/html

# Netscape 4.06-4.08 have some more problems
#BrowserMatch ^Mozilla/4\.0[678] no-gzip

# MSIE masquerades as Netscape, but it is fine
#BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

# Don't compress images
#SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

# Make sure proxies don't deliver the wrong content
#Header append Vary User-Agent env=!dont-vary

</IfModule>

<IfModule mod_ssl.c>

############################################
## make HTTPS env vars available for CGI mode

SSLOptions StdEnvVars

</IfModule>

<IfModule mod_rewrite.c>

############################################
## enable rewrites

Options +FollowSymLinks
RewriteEngine on

############################################
## you can put here your magento root folder
## path relative to web root

RewriteBase /

############################################
## workaround for HTTP authorization
## in CGI environment

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

############################################
## always send 404 on missing files in these folders

RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

RewriteRule .* index.php [L]

</IfModule>

############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead

AddDefaultCharset Off
#AddDefaultCharset UTF-8

<IfModule mod_expires.c>

############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires

ExpiresDefault "access plus 1 year"

</IfModule>

############################################
## By default allow all access

Order allow,deny
Allow from all

############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags

#FileETag none

WHAT I'VE ALSO TRIED
I just tried restoring last Mondays backup, of both database and data and no such luck... can I therefore presume that it's a server config change? The way its handling URL Rewrites? Mod_Rewrites? or the .htaccess file itself?
Henry

A: From your .htaccess file:
## never rewrite for URI beginning with admin
RewriteCond %{REQUEST_URI} !^/mixitup.*

that may be the error. try to change /mixitup to /admin to prevent rewrites from the admin URL.
maybe this rules should also be changed to /admin instead of /mixitup
## externally rewrite index.php/mixitup to mixitup
RewriteCond %{REQUEST_URI} ^/index.php/mixitup.*$
RewriteRule ^index.php/mixitup(.*) /mixitup$1 [R]

A: Solved the same issue with this extension: http://www.magentocommerce.com/magento-connect/clockworkgeek/extension/3692/clockworkgeek_adminrewrites


text:
Q: How to get environment variable in shopify public app using react js? I can not get the environment variable by this process in Shopify public app with react js
const { SHOPIFY_API_KEY } = process.env;

OR
const SHOPIFY_API_KEY = process.env.SHOPIFY_API_KEY;

I consoled the SHOPIFY_API_KEY parameter and it gives undefined output.


text:
Q: Pitfalls in doing GLMM or interpreting GLMM results I know this is a general question, but it would benefit CVers to learn about
common pitfalls, things to consider and caveats on how to do rigorous GLMM modeling.
Could those with experience on GLMMs share any insights they might have?

A: I came across this link which addresses many issues in running GLMM models.


text:
Q: How to click button using JSOUP? I have a a problem here
I have a website which I must parse, but here's button

My Tasks (0)

This button makes site to open table, and this table is most interesting for me
Please help me to click it using JSOUP.

A: JSoup is not a browser. It will not interpret and execute JavaScript. Therefore your approach will not work. However, you could analyse the network traffic of that AJAX call taht dynamically fills the table in question and mimic these requests directly. Or you could use tools like selenium webdriver for android to access the page within a real browser.


text:
Q: Catching error that is thrown within the catch of a promise I am trying to catch an error that may be thrown within the catch of another promise. (sorry if that is confusing...)
async function throwingError () {
  throw new Error('this error needs to be caught'); // I don't know if I need to return, throw or something else. This function may or may not have an error
};

async function mainFunction () {
  promiseFunction()
    .catch(error => {
      throwingError();
      // I've tried throw throwingError() and return Promise.reject(throwingError());
    });
};

mainFunction().catch(error => `caught: ${console.error}`);

Right now, it doesn't catch the error.
From what I know, this doesn't work because the promises finish at different times, but I'm not sure.

A: Your mainFunction needs to return a Promise. What you're missing is the return statement. You also need to return throwingError() in the catch block.
Without the return statement, the value returned by your mainFunction is a Promise that always resolves to undefined
async function mainFunction () {
  return promiseFunction()
    .catch(error => {
      return throwingError();
    });
};

A: You need to return promise.

function throwingError () {
  throw new Error('this error needs to be caught');
}
function mainFunction () {
  return new Promise((resolve, reject) => {
    reject(throwingError())
  })
};

mainFunction().catch(error => console.log(`caught: ${error}`));


text:
Q: Viber api and php web application? So, I've a list of around 900 phone numbers of a clinic that I'm working on. I need to send a photo to those all numbers if they have viber account. Doing so for individual numbers is a pain and time consuming as well. I was wondering if I could do a simple web application that would take a list of numbers and then send the picture to those numbers through Viber
Is there any similar or simple way to do so?


text:
Q: Transform time in JSON into actual time played PHP Im working on a app, and I requested the time played for a whole game, from when they bought it, till now for a particular user, and this is the result I got in JSON.
{
  "TotalTimePlayed": "PT48M26.4570633S"
}

I need to transform that into: Month, Day, Hours, Minutes, Seconds
In my view, this is how my variable is displayed:
{{ $TotalTimePlayed }}

How would I transform that into readable time?
/********** EDIT ****************/
I inserted prettyDate function from helpers file, but that show wrong time though
{{ prettyDate($TotalTimePlayed) }}

In helper.php file:
function prettyDate($date) {
    return date("d h, I", strtotime($date));
}

/***** EDIT ******/
I would want it to like like this for eaxample:
1M, 22D, 6H, 45M, 56S

A: That duration format is in ISO 8601 format.
You could proceed like this:
1. Using DateInterval
The given format is almost the one expected by PHP's DateInterval class, except that it does not allow fractional numbers.
So, we could first remove that fractional part, and then make use of this class to generate the output:
$json = '{
  "TotalTimePlayed": "PT48M26.4570633S"
}';

// Interpret JSON
$obj = json_decode($json);

// Get value, and strip fractional part (not supported by DateInterval)
$value = preg_replace("/\.\d+/", "", $obj->TotalTimePlayed);

// Turn this into a DateInterval instance
$interval = new DateInterval($value);

// Use format method to get the desired output
echo $interval->format('%m months, %d days, %h hours, %i minutes, %s seconds');

Output for the example data would be:

0 months, 0 days, 0 hours, 48 minutes, 26 seconds

2. Extracting the numbers with preg_match_all
This alternative does not make use of DateInterval, and thus can deal with the fractional seconds:
// Sample data:
$json = '{
  "TotalTimePlayed": "PT48M26.4570633S"
}';

// Interpret JSON
$obj = json_decode($json);

// Extract all numbers in that "PT" format into an array
preg_match_all("/[\d.]+/", $obj->TotalTimePlayed, $parts);

// Convert string representations to numbers
$parts = array_map('floatval', $parts[0]);

// Pad the array on the left in order to get 5 elements (months, days, hours, minutes, seconds)
$parts = array_pad($parts, -5, 0);

// Output (just for checking)
echo json_encode($parts);

Outputs:

[0,0,0,48,26.4570633]

If you don't want the fractional part of the seconds, then replace 'floatval' by 'intval' in the above code:
$parts = array_map('intval', $parts[0]);

Then the example will have as output:

[0,0,0,48,26]

Then you could do something like this:
$playtime = $parts[0] . " months, " .
            $parts[1] . " days, " .
            $parts[2] . " hours, " .
            $parts[3] . " minutes, and " .
            $parts[4] . " seconds";


text:
Q: Magento 2.3 reindex design_config_grid stucks on processing design_config_grid and customer_grid stuck on processing when I use bin/magento indexer:reindex. Even after bin/magento indexer:reset and changing status to Invalid, when I reindex again, they stuck on processing and I get this message: State for the same view already exists.

A: Can you please used this if you stuck
    php -dmemory_limit=6G bin/magento indexer:reset
    php -dmemory_limit=6G bin/magento indexer:reindex design_config_grid customer_grid
    php -dmemory_limit=6G bin/magento indexer:reindex catalog_category_product
    php -dmemory_limit=6G bin/magento indexer:reindex catalog_product_category
    php -dmemory_limit=6G bin/magento indexer:reindex catalog_product_price
    php -dmemory_limit=6G bin/magento indexer:reindex catalog_product_attribute
    php -dmemory_limit=6G bin/magento indexer:reindex catalogsearch_fulltext
    php -dmemory_limit=6G bin/magento indexer:reindex cataloginventory_stock
    php -dmemory_limit=6G bin/magento indexer:reindex catalogrule_rule
    php -dmemory_limit=6G bin/magento indexer:reindex catalogrule_product

Thank you

A: I bumped into the same problem this week. Was able to fix it using the database. Don't know if all steps are necessary:

*

*Disable all cron's

*run bin/magento indexer:reindex

*Go to tabel mview_state in your db. Check for duplicate view_id entries (mine where: design_config_dummy & customer_dummy) and remove them.

*Run bin/magento setup:upgrade (pretty sure you can run bin/magento indexer:reindex as well)

*Enable all cron's


text:
Q: Applying !important to whole CSS layout I want to apply !important to all div,p,pre, and span elements, overwriting all properties which are currently written inline. For example:
.contpost p,pre,span,div{
    color:#4c4c4c !important;
}

Does this color now apply to the whole page and specifically to that div?

A: Perhaps you mean this? It's a bit vague without more information.
.contpost p,
.contpost pre,
.contpost span,
.contpost div{
    color:#4c4c4c!important;
}

A: You could add an id to the body tag, say
<body id="container">

and then use
#container div{color:value !important;}
#container p{color:value !important;}
#container pre{color:value !important;}
#container span{color:value !important;}

OR just combine them into one:
 #container div, #container p, #container pre, #container span{color:value !important;}


text:
Q: Application of binomial formula Let $0<p<1$ and $n$ integer. Then
$$
\sum_{d=0}^{n-1}\binom{n-1}{d} p^d (1-p)^{n-1-d}=(n-1)p
$$

Proof: By the binomial formula
$$
(p+q)^{n-1}=\sum_{d=0}^{n-1}\binom{n-1}{d}p^d q^{n-1-d}
$$
Differentiating both sides with respect to $p$ and replacing $q=1-p$ we get
$$
(n-1)(p+1-p)^{n-2}=\frac{1}{p}\sum_{d=0}^{n-1}\binom{n-1}{d}p^d (1-p)^{n-1-d}
$$
and the result follows.

Question: let's consider the example with $n=3$, $p=0.3$. Then
$$
\sum_{d=0}^{n-1}\binom{n-1}{d} p^d (1-p)^{n-1-d}= 0.7^2+(2*0.3*0.7)+(0.3^2)=1
$$
and
$$
(n-1)p=2*0.3=0.6
$$

What am I doing wrong?

A: You differentiated wrong.  If you differentiate $p^d$ with respect to $p$ you should get $d\; p^{d-1}$, not just $p^{d-1}$.
The binomial theorem should give you
$$ \sum_{d=0}^{n-1} {n-1 \choose d} p^d (1-p)^{n-1-d} = 1$$
not $(n-1)p$.  Perhaps you meant
$$ \sum_{d=0}^{n-1} {n-1 \choose d} d \; p^d (1-p)^{n-1-d} = (n-1) p $$


text:
Q: Find the distribution of the supremum of the Brownian motion Let $A(t)$, $t \in [0,1]$ be a Gaussian process with zero mean and co-variance kernel $\mathrm{Cov}(A(t_1),A(t_2))= \min (t_1,t_2),\, \forall t_1,t_2 \in [0,1]$. Find $$P\left[\sup_{t \in [0,1]}|A(t)|>c\right]$$ where $c= 0.1,0.5,1$.
Under the same set up, find
$$P\left[\int_0^1 A(t)^2\, dt >c\right]$$
where $c= 0.1,0.5,1$.
I don't know how to solve this kind problem. I know the definition of Gaussian process only. I am stuck at the first step. Please help.

A: Part one of the question:
If this is indeed a Brownian process, $B(t)$, then we can use the following:
$$Pr(\sup |B(t)|> x = 1- \frac{4}{\pi} \sum_{k=0}^{\infty} \exp \left( \frac{-\pi^2(2k+1)^2}{8y^2} \right)$$
and we can calculate this with e.g.
probSupBr <- function(x){
        k <- c(0L, seq.int(1e4))
        1 - (4 / pi) * (sum(((( - 1)^k) / (2 * k + 1)) *
             exp(-(((pi^2) * (2 * k + 1)^2) / (8 * x^2)))))
}

The use of 1e4 in place of $\infty$ allows for a practical numeric approximation; larger values do not appear to improve this beyond $4$ significant digits.
As to your example values:
> sapply(c(0.1, 0.5, 1), probSupBr)
[1] 1.0000000 0.9908430 0.6292226

I believe the equation was first is attributed to Billingsley (much of this is on Google books.
As to part two, I would be interested to hear if you have managed to solve this with a more precise method than those given below.
As I understand it, the approach used depends on your need for accuracy:

*

*We can use the values of the asymptomtic limits of the distribution, given by Csaki (Springer, paywall) for 'large' or 'small' values of $c$ ($=y$ below): $$ P[B(t)^2 > y] = \frac{4 \sqrt{2}}{\pi^2 \sqrt{y}} \exp \left( -\frac{\pi^2 y}{8} \right) \quad \mathrm{as} \quad y \rightarrow \infty $$
which is:
probSqGr <- function(y){
  min(1,
      (4 * sqrt(2)) / ((pi^2) * sqrt(y)) * (exp(-(pi^2) * y / 8))
      )
}
giving:
sapply(c(0.1, 0.5, 1), probSqGr)
[1] 1.0000000 0.4374169 0.1669114
Note that $y \leq 0.2 \rightarrow P=1$ and so for such small values the lower tail should probably be used instead (same source):
$$ P[B(t)^2 < x] = \frac{4 \sqrt{x}}{\sqrt{\pi}} \exp \left( -\frac{1}{8x} \right) \quad \mathrm{as} \quad x \rightarrow 0 $$

*For values closer to the center of the distribution, we can simulate values of the distribution as per @ThePawn's answer here. As this involves random sampling, this will produce slightly different results each time, even when a very large distribution is generated. Using the suggested cdfW function this poster suggests, with $1 \mathrm{e}^5$ Markov chains and $\mathrm{d}t = 1\mathrm{e}^{-4}$ we have:
1 - sapply(c(0.1, 0.5, 1), cdfW)
[1] 0.83834 0.32298 0.13506
which is not far from the values above.

*There is an exact method for this, but I'm having trouble turning the equation into code; it can be found on the link above or here: Erdos On certain limit theorems of the theory of probability.


text:
Q: css property value in percentage not working in safari using jquery I am trying to get css property top value for particular element using Jquery like below:
var topvl1 = $("#top1").css( "top" );

if I set css property top value as pixels , then I can get value.
if I set css property top as percentage , then I can't get value there so value as 0.
how can i get css percentage value in jquery, please solve this issue
i have change my code link and here not working please check:
http://jsfiddle.net/ZnGks/4/
advance thanks


text:
Q: Android Style Drag Resizable Menu Fiddle (Along with snippet at bottom of post): http://jsfiddle.net/6pp0Lg6v/8/
On iOS you can drag to reveal a menu from the top to view your notifications. You can do the same on Android as well.
I'm working on a web designer where I'll be using this type of effect and I been trying to do this in jQuery and am having trouble getting it to only change the element's size (that'd be .reveal).

$('strong').click(function() {
  $('.reveal').animate({ 'height': 'toggle' }, 100)
});

// Handles FunctionBar
$(".functionbar").draggable({
  axis: "y",
  handle: ".handlesbar",
  disabled: false
});

$(".revealbar").draggable({
  axis: "y",
  //containment: "parent",
  helper: "clone",
  drag: function (event, ui) {
    var height = ui.offset.top;
    $(this).prev().height(height);
    $(".revealbar.ui-draggable-dragging").addClass("hide").css({
      "height": "0",
      "overflow": "hidden"
    });
  }
});
body {
  background:  #aaa;
}

/* FunctionBar */
.functionbar {
  overflow: hidden;
}

.handlesbar {
  margin: auto;
  width: 90%;
  padding: 6px 0;
  border-radius: 10px 10px 0 0;
  font: 24px arial;
  text-align: center;
  background: hsla(180, 0%, 0%, .75);
  word-spacing: 12px;
}

a {
  text-decoration: none;
  color: hsl(180, 0%, 90%);
}

.active {
  color: #9cf;
}

.hide {
  display: none;
}

/* Drag to Reveal Elements */
.reveal {
  margin: auto;
  width: 90%;
  background: #fff;
  overflow: visible!important;
  display:none;
}
.reveal, .revealcontent {
  z-index: 0;
  overflow: auto;
}
.revealbar {
  cursor: default;
  text-align: center;
  background: #666;
  color: #1c1c1c;
  z-index: 1;
  overflow: hidden;
}
.reveal h1 {
  margin: 0;
  padding: 16px 0;
}
<!DOCTYPE html>

    <title>Android Style Drag Menu Reveal/Hide</title>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=9" />
    <link type="text/css" rel="stylesheet" href="http://necolas.github.io/normalize.css/3.0.1/normalize.css"/>
    <link type="text/css" rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.css"/>
    <link type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" />

            ...

            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A: Remove the "containment" param:
$(".revealbar").draggable({
axis: "y",
//containment: "parent",
helper: "clone",
drag: function (event, ui) {
    var height = ui.offset.top;
    $(this).prev().height(height);
    $(".revealbar.ui-draggable-dragging").addClass("hide").css({
        "height": "0",
        "overflow": "hidden"
    });
}
});

FIDDLE

A: Please try adding below code in css.
/* Drag to Reveal Elements */
.reveal {
margin: auto;
width: 90%;
background: #fff;
overflow: visible!important;
display:none;
}

and following script in js file
$('strong').click(function() {
    $('.reveal').animate({ 'height': 'toggle' }, 100)
});

Updated jsFiddle link http://jsfiddle.net/6pp0Lg6v/3/


text:
Q: C++ lambda type conversion? I'm new to C++. I was messing around with lambdas and gcc compiler threw an error. Can someone kindly explain why it's happening?
Compilable code:
int main() {
    int abc= 456;
    int* abc_ptr= &abc;
    auto lambda= [abc_ptr]() { *abc_ptr= 123; };    // Works fine
    lambda();
}

This does not work however:
int main() {
    int abc= 456;
    int* abc_ptr= &abc;
    void (*lambda)()= [abc_ptr]() { *abc_ptr= 123; };    // error: cannot convert 'main()::<lambda()>' to 'void (*)()' in initializationx86-64 gcc 11.2 #1
    lambda();
}


text:
Q: AvalonDock FloatingWindow Fill Content I am using the AvalonDock component for my application. I have defined the views for my view models in xaml like this via data templates:
            <xcad:DockingManager.Resources>
            <DataTemplate DataType="{x:Type vm:ImageViewModel}">
                <v:ImageView />
            </DataTemplate>
        </xcad:DockingManager.Resources>

The views show up as expected and the views are currently implemented as WPF user controls. The user controls are resizable and the content will resize accordingly. This works fine when the view is docked in the application. When I undock a view so that it becomes a floating window, the content (e.g. my user control) does not resize with the window. Is there a special setting which I have to apply in order to resize the content as well?


text:
Q: Client and Admin not receiving Sales Email Notifications I've configured notifications in System -> Configuration -> Sales Emails
But still, I'm not receiving any email notification.

A: Make sure your cron is set up, else the email queue will not be processed.
I would recommend using AOE Scheduler Module: http://www.magentocommerce.com/magento-connect/aoe-scheduler.html
If you have your cron configured, make sure it actually runs. This may be of help: Cron.php do not start the cronjobs


text:
Q: Why aren't my checkboxes updating using Redux? I am working on a React-Native mobile app using Redux to manage the state. I have filter to manage the data displayed.
I am using Redux to manage all the data in the filters.
It's quite simple: I click on the checkbox, it gets clicked. I click on the checkbox again (guess what), it gets unclicked. When there is a box with the value "allInclusive", all boxes are unchecked except the "allInclusive" one.
Here's the code for the reducer and the code for the Checkbox thing.
var comparators = {...state.comparators};
      if (!comparators[action.payload.comparator]) {
        comparators[action.payload.comparator] = {};
        comparators[action.payload.comparator][action.payload.name] = [action.payload.value];
      } else {
        if (!comparators[action.payload.comparator][action.payload.name]) {
          comparators[action.payload.comparator][action.payload.name] = [action.payload.value];
        } else {
          if (comparators[action.payload.comparator][action.payload.name].includes(action.payload.value)) {
            comparators[action.payload.comparator][action.payload.name] = comparators[action.payload.comparator][action.payload.name].filter(value => value !== action.payload.value);
          } else {
            comparators[action.payload.comparator][action.payload.name].push(action.payload.value);
          }
        }
      }
      return Object.assign({}, state, {
        comparators,
      });

import React, {Component} from 'react';
import {View, StyleSheet} from 'react-native';
import colors from '../res/colors/index';
import {CheckBox} from 'react-native-elements';
import PropTypes from 'prop-types';
import {Text} from '.';
import {style} from 'd3';
import i18n from '../i18n/i18n';
import {connect} from 'react-redux';
import * as actions from '../actions';

export class ComparatorCheckboxesContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {checked: false};
  }

  checked(value) {
    if (this.props.filter.includes('allInclusive')) {
      return value === 'allInclusive';
    }
    alert(JSON.stringify(this.props.filter));
    return this.props.filter.includes(value);
  }

  render() {
    return (
      <View style={styles.checkboxesContainer}>
        <Text style={styles.checkboxesTitle}>
          {this.props.title + JSON.stringify(this.props.filter)}
        </Text>
        {this.props.options.map(option => (
          <CheckBox
            checkedIcon="check-square-o"
            uncheckedIcon="square-o"
            checkedColor={colors.principal}
            checked={this.checked(option.value)}
            onPress={() =>
              this.props.checkboxFilterChange(
                this.props.type,
                this.props.name,
                option.value,
              )
            }
            title={i18n.t(option.title)}
            containerStyle={styles.containerStyle}
            textStyle={style.textStyle}
            fontStyle={style.textStyle}
          />
        ))}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  checkboxesContainer: {
    width: '100%',
    marginLeft: 'auto',
    marginRight: 'auto',
    marginTop: 14,
  },
  checkboxesTitle: {
    fontSize: 10,
    color: colors.darkGray,
  },
  checkboxLine: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
  },
  checkboxLineText: {
    fontSize: 16,
    color: colors.darkGray,
  },
  containerStyle: {
    backgroundColor: 'transparent',
    borderWidth: 0,
    marginBottom: 0,
    marginTop: 0,
    padding: 10,
  },
  textStyle: {
    marginLeft: 2,
    color: colors.darkGray,
  },
});

const mapStateToProps = ({comparators}, ownProps) => {
  if (comparators.comparators[ownProps.type] && comparators.comparators[ownProps.type][ownProps.name]) {
    return {
      filter: comparators.comparators[ownProps.type][ownProps.name],
    };
  } else {
    return {
      filter: [],
    }
  }
};

export default connect(
  mapStateToProps,
  actions,
)(ComparatorCheckboxesContainer);

A: You're mutating the state in your reducer, because you're only copying the top level object and then mutating the contents nested inside of that.  Immutable updates always require copying every level of nesting, for both objects and arrays.
The number one rule of writing Redux logic is: Don't mutate state.
You should switch to using our official Redux Toolkit package.  Not only would it have caught these accidental mutations and warned you, the createSlice API lets you actually write "mutating" code that is turned into safe, correct immutable updates.
You should also take the time to read through the Redux docs page on "Immutable Update Patterns", and Dave Ceddia's post on The Complete Guide to Immutability in React and Redux.

A: Here is the reducer re-written to be immutable:
 const { comparators } = state;
  const { comparator, name, value } = action.payload;

  if (!comparators[comparator]) {
    return {
      ...state,
      comparators: {
        [comparator]: {
          [name]: value
        }
      }
    };
  } else {
    return !comparators[comparator][name]
      ? {
          ...state,
          comparators: {
            [comparator]: {
              [name]: value
            }
          }
        }
      : comparators[comparator][name].includes([value])
      ? {
          ...state,
          comparators: {
            [name]: comparators[comparator][name].filter(val2 => val2 !== value)
          }
        }
      : {
          ...state,
          comparators: {
            [comparator]: {
              [name]: [...comparators.comparator.name, value]
            }
          }
        };
  }


text:
Q: Angular 5 authenticate with web api i try to post my login credentials to my asp.net core web api. but every time i do this i get this message.
OPTIONS XHR
http://localhost:64989/api/auth/login [HTTP/1.1 415 Unsupported Media Type 16ms]
ERROR Object { headers: Object, status: 0, statusText: "Unknown Error", url: null, ok: false, name: "HttpErrorResponse", message: "Http failure response for (unknown …", error: error }
my code looks like this on Angular side:
login( email:string, password:string ) :Observable<boolean>{

  return this.http.post('http://localhost:64989/api/auth/login', {email, password}, {headers: new HttpHeaders().set('Content-Type', 'application/json')})
   .map(data => {
     let userAuth = data;
     if(userAuth){
       localStorage.setItem('currentUser', JSON.stringify(userAuth));
       return true;
     }else{
       return false;
     }
   });
}

On server side i've got a web api which should check the login credentials. this works with postman but not with angular. The Web Api is made with Asp.net core 2.
 [AllowAnonymous]
    [HttpPost("CreateToken")]
    [Route("login")]
    public async Task<IActionResult> Login([FromBody] LoginDTO model)
    {
        try
        {
            var user = await _userManager.FindByNameAsync(model.Email);
            if (user == null)
            {
                return Unauthorized();
            }

            var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);

            if (signInResult.Succeeded)
            {
                var userClaims = await _userManager.GetClaimsAsync(user);

                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Email, user.Email)
                }.Union(userClaims);

                var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtToken:Key"]));
                var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);

                var jwtSecurityToken = new JwtSecurityToken(
                    issuer: _configuration["JwtToken:Issuer"],
                    audience: _configuration["JwtToken:Audience"],
                    claims: claims,
                    expires: DateTime.UtcNow.AddMinutes(60),
                    signingCredentials: signingCredentials
                    );
                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
                    expiration = jwtSecurityToken.ValidTo
                });
            }
            return Unauthorized();
        }
        catch (Exception ex)
        {
            _logger.LogError($"error while creating token: {ex}");
            return StatusCode((int)HttpStatusCode.InternalServerError, "error while creating token");
        }
    }

A: I think i found a way how it works for me in development. not production.
The problem was on the Web API. if you come from a different source to your web api it won't awnser. in my case if i try to call my web api from client side app on http://localhost:4200/ and my web api is running on http://localhost:64989 i will come to this issue i had. if your client side app and server side app is under the same domain you won't have any problem. I will have it in the same domain in production. So i still need a workaround for dev.
in my ASP.NET core app i can add CORS(Cross Origin resource sharing) to Startup.
  public void ConfigureServices(IServiceCollection services)
  {
        services.AddCors();
        //add cors bevor mvc
        services.AddMvc();
  }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

        loggerFactory.AddConsole();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            app.UseCors(builder =>
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader());
        }

        app.UseAuthentication();

        app.UseMvc();
    }

define use cors in IsDevelopment. here you can define which origin is allow and which isn't. i allow any for dev because i won't have this issue in production.


text:
Q: why inline styling &:hover will not have any effect in react js I'm trying to add hover effect to a span element as shown below.

*

*Hover effect doesn't work when added inside
style prop.

*But, If it is written in separate css file it will work

I just want to know, Why it is So?

https://codesandbox.io/s/happy-resonance-stqbf9?file=/src/App.js
App.js
import "./styles.css";

export default function App() {
  return (

        Element

      Element 2

  );
}

styles.css
.App {
  font-family: sans-serif;
  text-align: center;
}

.ele {
  font-size: 4em;
  color: blue;
}

.ele:hover {
  font-size: 6em;
  color: green;
}

A: That because we can't specify the inline styles for pseudo elements and pseudo classes. You can use it with the,

*

*Internal - by using a


text:
Q: Rails Form_For/Select with Jquery and Images I've been struggling with finding the best approach to this issue for over a week now (yes, I'm a newbie). In my app, users create projects and then build relationships ("pfollow") with their choice of plant objects in my database.
I've been using a collection_select styled with a dropdown Jquery select plugin called "listselect" up till now (and it works fine), but I now want to be able to feature the plant choices as images--not in a dropdown menu of any sort, but rather as a grid or in a circle of images with certain Jquery-UI effects upon click. The collection_select currently looks like this:
    <%= form_for @project.prelationships.build(:pfollowed_id =>
                                       @project_id) do |f| %>
      <%= collection_select :prelationship, :pfollower_id, Plant.all, :id,
                            :group, {},:multiple => true,
                            :class => "listselect" %>
      <%= hidden_field_tag :project_id, @project.id %>
    <div class="actions">
      <%= f.submit "Pfollow" %>
    </div>
   <% end %>

What I can't figure out now is: what's the best way to feature these plant images on my page and pass the selected plants on to the controller? I've been toying with four different approaches:
a) Build off a Jquery-UI Plugin like the 'Simple Photo Manager' or 'Selectable-Display as Grid' and then try to capture the li class of "ui.selected." But if I do this, I have no idea how to pass the class of the selected object back into the collection_select, and I haven't found a good solution online.
b) Use the html options block in collection_select to create an image select with some added Jquery <-- is that even possible? I can't find any documentation on doing this or a good plugin.
c) Feature each plant image as a unique object on the select page without collection_select and make each plant image its own "form_for image_tag" that creates the appropriate relationship instantly upon click with Ajax <-- again, I'm not sure if this is possible
d) Similar to (c), make each plant image its own unique object and then when clicked, capture the ui.selected and pass it to form_for helper like this one:
    <%= form_for @project.prelationships.build(:pfollowed_id =>
                                       @project_id) do |f| %>

but, again, I can't figure out how I can pass the selected image into a :pfollowed_id that the form_for helper could use to pass to the controller.
Thanks in advance!
In the end, my code actually looked like this. Still have to play with the CSS and Jquery:
   <%= form_for @project.prelationships.build(:pfollowed_id =>
                                       @project_id) do |f| %>
     <%  Plant.all.each do |plant| %>
       <%= label_tag "prelationship[pfollower_id][]", plant.name %>
       <%= check_box_tag "prelationship[pfollower_id][]", plant.id %>
     <% end %>
   <%= hidden_field_tag :project_id, @project.id %>
   <%= f.submit "Pfollow" %>
   <% end %>

A: There may be a lot of UI-magic you could possibly implement using Jquery etc, but I'll suggest a simple way to replace drop downs with check-boxes -
<%= form_for(prelationship) do |f| %>
  <%  Plant.all.each do |plant| %>
    <%= label_tag plant.name %>
    <%= check_box_tag "prelationship[pfollower_ids]" %>
  <% end %>
<%= end %>

This code creates a checkbox and a corresponding label for each of the plants, and when the form is posted, params[:prelationship][:pfollower_ids] contains a list of all the pfollower_ids
To enhance the UI further, you can replace the label with an image_tag, and add some Js to check/uncheck the corresponding checkboxes every-time the image label is clicked. Then, maybe if you want to remove checkboxes, you can hide them with css, or use hidden_field_tag to remove them entirely.


text:
Q: Trying to use crystalreportviewer to display .rpt's using vb.net I've been trying to build a simple vb.net app that basically displays already built .rpt reports in a crystalreportviewer.  No matter how many times I try to code it, I run into problems.  Some reports have worked, others have thrown errors such as load report failed, invalid path, etc..  All of the reports work when I run them in crystal.
Ideally, I'm looking to just have a menu with report names, and a crystalreportviewer where the user can click a report, and the app prompts them for parameter values.
I'm currently working with crystal 9 I believe, and vs.net 2003, or I have access to 2005 as well.
Can someone help me with this, or explain why I'm running into problems?  Nothing has been consistent - I'm at a loss right now.
Help is highly appreciated!! thanks in advance

A: You need to get them all working in the development environment, then on the client side, make sure the dependent files are installed and the network drive names are mapped consistently if your code's dependent on it.
Here's an example in VB.NET 2005:
Public Class frmCrystal
    Public Sub _init(ByVal windowTitle As String, ByVal rptPath As String)
        Dim rptDoc As CrystalDecisions.CrystalReports.Engine.ReportDocument
        Dim ConInfo As CrystalDecisions.Shared.TableLogOnInfo
        Dim crTables As CrystalDecisions.CrystalReports.Engine.Tables
        Dim crTable As CrystalDecisions.CrystalReports.Engine.Table

        Me.Text = windowTitle
        rptDoc = New CrystalDecisions.CrystalReports.Engine.ReportDocument
        rptDoc.Load(rptPath)
        ConInfo = New CrystalDecisions.Shared.TableLogOnInfo
        crTables = rptDoc.Database.Tables
        For Each crTable In crTables
            With ConInfo.ConnectionInfo
                .ServerName = "dhsdev10069\dsd"
                .DatabaseName = "DSDWorkPlanTracking"
                .IntegratedSecurity = True
            End With
            ConInfo.ReportName = rptPath
            crTable.ApplyLogOnInfo(ConInfo)
        Next

        rptCrystal.ReportSource = rptDoc
    End Sub

the form frmCrystal contains one CrystalReportViewer control:
Private Sub InitializeComponent()
        Me.rptCrystal = New CrystalDecisions.Windows.Forms.CrystalReportViewer
        Me.SuspendLayout()
        '
        'rptCrystal
        '
        Me.rptCrystal.ActiveViewIndex = -1
        Me.rptCrystal.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.rptCrystal.DisplayGroupTree = False
        Me.rptCrystal.Dock = System.Windows.Forms.DockStyle.Fill
        Me.rptCrystal.Location = New System.Drawing.Point(0, 0)
        Me.rptCrystal.Name = "rptCrystal"
        Me.rptCrystal.Size = New System.Drawing.Size(292, 273)
        Me.rptCrystal.TabIndex = 0
        '
        'frmCrystal
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.rptCrystal)
        Me.Name = "frmCrystal"
        Me.Text = "DSD Report"
        Me.ResumeLayout(False)

    End Sub
End Class

Then to call the form, you need something like:
Private _crystal As frmCrystal

    _crystal = New frmCrystal
    _crystal.MdiParent = Me
    _crystal._init(windowTitle, rptpath)
    _crystal.WindowState = FormWindowState.Maximized
    _crystal.Show()


text:
Q: ActionBar menu item background using xml drawable? I was searching for a way to style the menu buttons in my ActionBar, I would like to use a .xml drawable with rounded corners as a background for my menu items (the item is basically a counter with numbers, which I update dynamically).
There is no documentation about adding a background drawable to menu items on the action bar. Can this be achieved??
Thanks!

A: Please see in ActionProvider side


text:
Q: Rendering is displayed twice in Codesandbox I'm used to using Codesandbox,
but for the first time like I said in the title the rendering is displayed two times and I don't understand how to fix that.
For a simple example, the Contact component is very simple but the title and the button are displayed twice, you can see also them in my codesanbox link if you want.
Maybe I do something wrong with Vue because I'm learning it?
https://codesandbox.io/s/vue-router-with-rick-and-morty-api-qdfe12?file=/src/views/Contact.vue
<template>

Contact

  <button @click="home()">Home</button>
</template>

A: You should remove <router-view></router-view> from the Navbar component :
<template>

      <router-link to="/">Home</router-link>

      <router-link to="/about">About</router-link>

      <router-link to="/contact">Contact</router-link>

</template>


text:
Q: How can I merge two Pcollections(various sizes/data) with a common "key"(Street) via a side input? I have two PCollections: one that pulls info from Pub/Sub, and one that pulls data from a CSV file. After some various transforms in each pipeline, I'd like to merge the two on a common key they both share, "STREET". I'm including the second PCollection as a side input. However, I'm getting an error on attempt to run.
I've attempted to utilize CoGroupByKey, but I kept receiving errors regarding the difference in types of data in the Pcollections. I tried refactoring the outputs, and setting the attribute of the PCollection via the __setattr__ to force the types to be equal, but it reported "mixed values" regardless. After further research, it seems like it's better to utilize side inputs, especially when there's disparity in data size between elements. Even with side inputs, I'm still unable to get past the current error:
from_runner_api raise ValueError('No producer for %s' % id)
ValueError: No producer for ref_PCollection_PCollection_6

My application logic is as follows:
def merge_accidents(element, pcoll):
    print(element)
    print(pcoll)
    "some code that will append to existing data"

accident_pl = beam.Pipeline()
accident_data = (accident_pl |
                        'Read' >> beam.io.ReadFromText('/modified_Excel_Crashes_Chicago.csv')
                        | 'Map Accidents' >> beam.ParDo(AccidentstoDict())
                        | 'Count Accidents' >> Count.PerKey())

chi_traf_pl = beam.Pipeline(options=pipeline_options)
chi_traffic = (chi_traf_pl | 'ReadPubSub' >> beam.io.ReadFromPubSub(subscription=subscription_name, with_attributes=True)
                           | 'GeoEnrich&Trim' >> beam.Map(loc_trim_enhance)
                           | 'TimeDelayEnrich' >> beam.Map(timedelay)
                           | 'TrafficRatingEnrich' >> beam.Map(traffic_rating)
                           | 'MergeAccidents' >> beam.Map(merge_accidents, pcoll=AsDict(accident_data))
                           | 'Temp Write'>> beam.io.WriteToText('testtime', file_name_suffix='.txt'))

accident_pl.run()
chi_result = chi_traf_pl.run()
chi_result.wait_until_finish()```

**Pcoll 1:**
[{'segment_id': '1', 'street': 'Western Ave', 'direction': 'EB', 'length': '0.5', 'cur_traffic': '24', 'county': 'Cook County', 'neighborhood': 'West Elsdon', 'zip_code': '60629', 'evnt_timestamp': '2019-04-01 20:50:20.0', 'traffic_rating': 'Heavy', 'time_delay': '0.15'}]
**Pcoll 2:**
('MILWAUKEE AVE', 1)
('CENTRAL AVE', 2)
('WESTERN AVE', 6)

**Expected:**
[{'segment_id': '1', 'street': 'Western Ave', 'direction': 'EB', 'length': '0.5', 'cur_traffic': '24', 'county': 'Cook County', 'neighborhood': 'West Elsdon', 'zip_code': '60629', 'evnt_timestamp': '2019-04-01 20:50:20.0', 'traffic_rating': 'Heavy', 'time_delay': '0.15', 'accident_count': '6'}]

**Actual Results:**
"from_runner_api raise ValueError('No producer for %s' % id)ValueError: No producer for ref_PCollection_PCollection_6

A: So I figured out the problem. After looking through pipeline.py and the unittest source for side inputs, I realized that there's a check against the Pipeline object created.
I'm new to this and so I originally believed that you needed to create two separate Pipeline objects(streaming vs batch) so I could pass different options to both; i.e.streaming: True. That being said, I don't believe that is needed.
After consolidating them to a single object like below, the error went away and I was able to accept side inputs into the function:
'''
pipeline = beam.Pipeline(options=pipeline_options)
accident_data = (pipeline
                 | 'Read' >> beam.io.ReadFromText('modified_Excel_Crashes_Chicago.csv')
                 | 'Map Accidents' >> beam.ParDo(AccidentstoDict())
                 | 'Count Accidents' >> Count.PerKey())

chi_traffic = (pipeline
               | 'ReadPubSub' >> beam.io.ReadFromPubSub(subscription=subscription_name, with_attributes=True)
               | 'GeoEnrich&Trim' >> beam.Map(loc_trim_enhance)
               | 'TimeDelayEnrich' >> beam.Map(timedelay)
               | 'TrafficRatingEnrich' >> beam.Map(traffic_rating)
               | 'MergeAccidents' >> beam.Map(merge_accidents, pcoll=pvalue.AsDict(accident_data))
               | 'Temp Write' >> beam.io.WriteToText('testtime',
                                                     file_name_suffix='.txt'))

chi_result = pipeline.run()
chi_result.wait_until_finish()

'''