text:
Q: Electric current and potential difference I have lots of doubts regarding electrical energy, electric current and voltage. I have tried to understand as much I can but every time I try to completely clear my concept, I encounter a dilemma! So here are they -

*

*First of all, voltage:-

The electric potential at any point in an electric field is the amount of work done by the external force in bringing unit positive charge from infinity (U = 0) to that point. In direction of electric field potential decreases. Now I have a battery having potential difference of 2V , Now how this potential difference is created, I mean there must be some constant (or not constant?) electric field, along/against which a charge had been moved so as to increase potential energy. So how this occurs? potential difference without field how ??
NEXT:-
Since a battery has potential difference of 2V i.e. electric field will go from higher to lower potential (2 to 0), so why not the mobile charge due to which potential energy is there in the battery, move and thus causing self depletion of electrical energy of the battery.

*Electric field due to battery

When we insert a battery into a circuit, due to potential difference it creates electric field going from high potential to low potential. Taking one terminal as high potential and other as low (which one is the one ?) , then electric field should go from one terminal to other terminal. So how electrons in the wire start moving due to field ?? How this field bends along with wire? Is this field constant (why) ? what happens to the field inside of the battery ??

*Potential drop and energy dissipation

How energy is supplied to electrical appliances in the circuit? In what from electrons carry energy? how electrons get energy? why this energy is not dissipated in the wire (since they are travelling against electric field)
If you got irritated by this, then please explain all the core concepts related.

A:
The electric potential at any point in an electric field is the amount
of work done by the external force in bringing unit positive charge
from infinity (U = 0) to that point. In direction of electric field
potential decreases.

While what you say is correct, this definition of electric potential at a point is not particularly useful in analyzing electric circuits where we are more interested in the potential difference or voltage between two points. The potential difference $V$ between two points is the work per unit charge required to move the charge between the two points.

Now I have a battery having potential difference of 2V , Now how this
potential difference is created...

Without getting into too much detail on how a battery works, the potential difference between the terminals of a battery is created by chemical reactions that separate positive and negative charge at the battery terminals. That creates an electric field between the terminals which, when connected to a circuit, moves charge in the circuit creating current.

NEXT:- Since a battery has potential difference of 2V i.e. electric
field will go from higher to lower potential (2 to 0)...

First of all, any point in a circuit can arbitrarily assigned a potential of zero. Frequently that point is the negative terminal of a battery as you indicated. But it doesn't have to be. In your example the negative terminal can be assigned any potential, as long as the potential at the positive terminal differs by +2 volts. So the potential could just as well be from 4 to 2.

..so why not the mobile charge due to which potential energy is there
in the battery, move and thus causing self depletion of electrical
energy of the battery.

It is a common misconception that the battery supplies the charge for the current in the circuit. It doesn't. It provides the electric field that does work to move the mobile charge carriers already in the circuit (e.g. the free electrons in a metal wire). But the work done by the battery to move the charge in the circuit comes from the conversion of chemical potential energy to electrical potential energy. It is the chemical energy that is eventually used up. When that happens, the battery can no longer provide a potential difference and do work.

*

*Electric field due to battery

So how electrons in the wire start moving due to field ??

As stated above, the electric field $E$ established by the battery almost instantaneously in the circuit exerts a force on the mobile charge carriers in the circuit causing them to immediately start moving. In so doing the field does work to move the charge.

How this field bends along with wire?

Basically, it's because when a wire is bent an imbalance of surface charge builds up on the surface of the wire causing the field to "bend". Check out the answer in the following link for more details.
https://www.quora.com/How-does-the-electric-field-therefore-the-electric-force-in-a-wire-remain-parallel-to-the-wire-even-if-it-is-randomly-curved-current-still-flows

Is this field constant (why) ? what happens to the field inside of the
battery ??

The strength of the field is basically constant. It's the voltage that is not constant. The electric field is the voltage gradient along the conductor.
Basically, the field in the battery is maintained by the conversion of chemical potential energy to electrical potential energy maintaining a potential difference between the terminals, until the chemicals are consumed.

How energy is supplied to electrical appliances in the circuit? In
what form electrons carry energy? how electrons get energy? why this
energy is not dissipated in the wire (since they are traveling against
electric field)

All these questions are somewhat repetitive of the previous ones. So, briefly

How energy is supplied to electrical appliances in the circuit?

By a voltage source (battery or ac) that supplies electrical potential energy to the charges which, in turn, convert that potential energy into heat and/or work.

In what from electrons carry energy?

I assume you mean "form" not "from".
It has already been explained the battery, or in the case of ac appliances, the ac voltage source, establishes an electric field that exerts a force doing work on the mobile charge carriers. That work gives the electrons kinetic energy. So the "form" of the energy carried by the electrons is kinetic energy.

how electrons get energy?

Asked and answered- by a voltage source doing work.

why this energy is not dissipated in the wire (since they are traveling against
electric field)

A portion of the energy is dissipated in the resistance that exists everywhere in the circuit, not just the interconnecting wires. In the case of resistance wire heating appliances, where heat is the desired product, most of the energy is dissipated as heat in the heater wire. For things like motor operated appliances, some energy is lost as heat but generally most of it is converted to mechanical energy.
In closing, the above explanations are not a substitute for a good basic textbook on electric circuits and circuit theory. I suggest you get hold of one.
Hope this helps.

A: I'll try to Adress all your individual question. There are many, and it could be fruitful to split the question into two. But here we go.

Now how this potential difference is created

The battery potential difference is created by the internal electrochemistry which forces electrons to one pole. With many electrons accumulated there, this pole will have a higher electric repulsion than the other pole against any additional electrons arriving.

I mean there must be some constant (or not constant?) electric field, along/against which a charge had been moved so as to increase potential energy. So how this occurs? potential difference without field how ??

Indeed, and that is in fact an internal electric field caused by the chemical potential within. This field causes an electric force that forces electrons to accumulate at one pole. At some point the accumulated repulsion balances out this internal force - and then the battery is fully charged. The internal chemistry is in your example designed to exactly provide up to a 2V potential difference.

so why not the mobile charge due to which potential energy is there in the battery, move and thus causing self depletion

Because the internal electric forces caused by the chemical potentials are stronger than (or exactly equal to) the accumulated electric force that tries to make the electrons move away from the pole. Also, they can't jump out into the air since the air is not conductive and thus resists them even more strongly. They are thus stuck on that pole until a conductive path is provided.

Taking one terminal as high potential and other as low (which one is the one ?)

By default we always refer directions and highs vs lows to how a positive charge would behave. With many electrons accumulated on one pole, making it negatively charged, then if a positive charge was placed nearby, it would want to move towards this negative pole. Since objects always want to move towards states of less stored energy, then the negative pole is thus the one with low potential and the other and comparatively positive pole is associated with high potential.
Note, though, this is only a default terminology. A book that specifies that it is concerned with the energies of electrons as charge-carriers might use the terms oppositely, since an electron will want to move away from the electron-full pole, thus associating that pole with a high potential from the electron perspective. So be clear on the context in various textbooks.

electric field should go from one terminal to other terminal. So how electrons in the wire start moving due to field ?? How this field bends along with wire?

They move because they "queue up". An electron at the negative pole wants to move as far away from the pole as possible due to the enormous repulsion. When the only conductive path is away from the pole, then that is the way it will move.
This electron would then theoretically be satisfied with its new location somewhere within the wire and would not want to move further. But then another electron arrives. And yet another. Etc. Each electron carries its own electric field with it, and when queuing up like this, their electric fields will again accumulate like on the pole. But the accumulate will be momentary since the first electron of course simply will move further in on the wire.
Eventually it will be pushed all the way through. Simply because it isn't alone in the circuit. And at any bends or corners in the wire, there will in the same way we a slight tendency for charge accumulation until a charge inevitably will find the new path to move along.

Is this field constant (why)

It might be, for typical batteries that aren't depleted, yes. The queuing up of electrons effective means that any push on one is passed on to its neighbour. In this way the push is eventually the same throughout all parts of a (series connected) wire.
As long as the battery can sustain the constant 2V at the pole, that is - the current flow away from that pole thus mustn't be quicker than the chemical activity that moves electrons to this pole. This is typically labeled on a battery as the possible maximum current that can be drawn from the battery.

what happens to the field inside of the battery

It is upheld for as long as the chemical potential exists. The mechanisms here are very technology dependent and could for instant depend on the ratio of acid molecules to the electrode surface atoms.

How energy is supplied to electrical appliances in the circuit? In what from electrons carry energy?

What we call electric energy is essentially kinetic energy of the charges. That is, kinetic energy at the sub-atomic scale from the violent fluctuations and vibrations which particles like electrons constsly undergo. When electrons are slowly pushed through the circuit, then suddenly they are pushed into, say, more dense materials like the filament of a light bulb. This is also a conductor but one with higher resistance, meaning the electrons will jump into the material atoms.
With a collision happens energy transfer. Kinetic energy of the electron is passed on to a material atom within the material lattice. Eventually many atoms have now gained kinetic energy and are thus moving in rapid vibration. This is what we defined as thermal energy and temperature, and this eventually might glow and thus send off photons - then electric energy is converted into light.

why this energy is not dissipated in the wire (since they are travelling against electric field)

The energy that electrons carry is to some extend dissipated in the wires via collisions with the wire atoms. Wires will indeed get warm as well. But they are typically optimised to be as little resistive as possible to avoid this energy loss.

I hope this helps. Please let me know in comments if something is unclear.


text:
Q: Kendo radio button checked dot not in center As shown in the following image:

The dot is not coming to the center of the circle when Kendo radio button is placed inside Kendo window or a fieldset.

Update:
After some testings I find that the Kendo radio button's circle becomes smaller when placed in Kendo window or some other elements, thus caused the issue.
I have tried to use css to resize the kendo radio button using the selector:
.k-radio or input[type=radio] { width:15px; height:15px}

Still can't change the size of the button.

A: I just ran across this same issue. I ended up adding this to the kendo.custom.css.
.k-radio-label:before {
  border-color: #c4c4c4;
  border-radius: 50%;
  background-color: #ffffff;
  border-width: 1px;
  box-sizing:unset; //This is part of the problem I had
  -webkit-box-sizing: unset;  //This is part of the problem I had
}

This solved my problem, I really hope it helps you out as well.

A: I had the same issue but for mine the following resolved it.
Before
After
.k-radio-label {
    left: -2px;
    line-height: 16px;
    padding-left: 23px;
}
.k-radio-label::after, .k-radio-label::before {
    box-sizing: content-box;
}
.k-radio-label:before {
    border-width: 1px;
    -webkit-box-sizing: unset;
}

A: Thanks to Steve's idea, the problem is now solved. The issue is caused because I added this css file for Kendo box sizing issue with Bootstrap:
.k-animation-container, .k-widget, .k-widget *, .k-animation-container *, .k-widget *:before, .k-animation-container *:after, .k-block .k-header, .k-list-container {
    box-sizing: inherit;
}

Here is the link to Kendo UI Box-sizing:
to fix the issue, I need to override the kendo-radio-label to:
.k-radio-label:before {
  box-sizing:content-box;
  -webkit-box-sizing:content-box;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML Links not working in hotmail I'm currently building a application which sends some url's to our users by email. Though it seems that Hotmail is blocking the urls resulting in a redirect to their Inbox. I can't find a solution. Url is looking like this:
http://www.example.com/example/32/Iew12

Does anybody know the solution?

A: The link looks fine so I would say it's more likely this is a security feature within hotmail.  Are the emails going to the users junk mail?  I don't think there's anything you can do other than make sure your recipients have your reply email address on their whitelist and they enable links to be clicked within the email.


text:
Q: How to hide Iframe if the same button is clicked again or other button is clicked? I can show my other webpage through iframe, but how can I make it invisible or terminate the web page when the same button is clicked again

<form name="search" id="search" method="get" action="../crime_map/map_crime_pending.php" target="carsearch">

<button type="submit" id="SearchCarButton" class="submitBtn" onclick="showIFrame()"/>  Search</button></form>
<button>Catcher</button>

A: try this code that check the display, and change it based in the current status;
   function showIFrame() {
      var iframe = document.getElementById("myiframe");
      var d = iframe.style.display;
      if(d=="block"){
         iframe.style.display = "none"
      }else{
        iframe.style.display = "block";
      }
}


text:
Q: Stopping Dell P2715Q monitor flickers with MacBook Retina 12" (2015) I have recently purchased both a Dell 4K display (P2715Q) and a new Macbook (Retina, 12", 2015).  According to Apple's website, the MacBook should be capable of driving the display at full resolution at 30 Hz, when connected over HDMI (via Apple's own USB-C to HDMI adapter), https://support.apple.com/en-us/HT202856.  While the display is detected correctly and I can select up to the full 3840 x 2160 (though it defaults to 1920 x 1080) pixel settings, the Dell display continually flickers, going blank for a fraction of second every few seconds.  This behavior persists regardless of the choice of scaling.
Has anyone else encountered this issue (or not) with this setup (or other 4K display)?  Any strategy to resolve this issue?
Things I've tried:

*

*Doing an NVRAM reset on the Mac (https://support.apple.com/en-us/HT204063, as suggested by Apple's help desk) and

*a Factory Reset in the Dell monitor menu options (the only suggestion from Dell's help desk)

both of these appear to reduce or sometimes stop the flickering for a few hours, but it returns by the end of the day (or if the Mac is left on over night).  Having to reset NVRAM every day isn't a great experience...
Edit the problem persists both while the laptop is in Clamshell mode (with the lid closed) or open as an additional monitor.

A: This may be good or bad news deepening on how you look at it, but it's the Dell 4K display, not your Mac. Both Dell model numbers 2715Q and 2815Q are notorious for this kind of flickering when used with MacBooks. If you search around on Amazon and other sites you will find similar complaints.
We purchased 4 of the Dell 4K P2715Q monitors where I work, and we returned ALL of them in the end because they exhibited this exact flickering behavior (as well as the inability to properly run at 60Hz).
It didn't matter if we connected different types of Macs, or used different connectors. If we tried to drive these monitors at full resolution we saw this problem.
Dell told us the same thing when we called support (and we have the good support where I work), and we still never succeeded in making them work.
If you do find a solution with your Mac that makes this monitor work properly I will be happy to learn about it.
EDIT: For the benefit of anyone coming to this answer and wondering about other's who've seen the same problem. Check out Apple's forum posts reporting the same problems with the P2715Q.


text:
Q: MediaPlayer + MediaRecorder for rtsp stream? Is it possible to use both MediaPlayer and MediaRecorder simultaneously to function with rtsp stream?
For example,I would use MediaPlayer to play live video stream
MediaPlayer.setDataSource("rtsp://link:port/parameters.sdp?");
and then set a button to use MediaRecorder to record the live stream and save it locally(or remotely if possible)
MediaRecorder.setOutputFile("/sdcard/liveRTSP.mp4");

A: As long as you do not need them to share the same underlying RTP connection you should be fine. Using both of these classes will result in two outstanding RTSP connections to the RTSP server. If it can handle that and you are not required to synchronize both of these connections (one of them may lag behind the other, but the delay would be small and is not guaranteed) then you are fine.


text:
Q: Programatically adding NSConstraints to existing views on storyboards i'm finding that constraints aren't implemented correcting when typed programatically to existing views on story boards. here's what i have:
class ViewController: UIViewController {

    @IBOutlet weak var textField2: UITextField! {
        didSet {
            textField2.delegate = self
        }
    }

    func viewDidLoad() {
        super.viewDidLoad()

        let superview = self.view

        let textField1 = UITextField()
        textField1.backgroundColor = UIColor.greenColor()
        textField1.placeholder = "test text field"
        view.addSubview(textField1)
        textField1.translatesAutoresizingMaskIntoConstraints = false
        superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: superview.frame.width * 0.50))
        superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: superview.frame.height * 0.05))
        superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .CenterX, relatedBy: .Equal, toItem: superview, attribute: .CenterX, multiplier: 1, constant: 0))
        superview.addConstraint(NSLayoutConstraint(item: textField1, attribute: .CenterY, relatedBy: .Equal, toItem: superview, attribute: .CenterY, multiplier: 1, constant: 0))

        textField2.translatesAutoresizingMaskIntoConstraints = false
        superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: superview.frame.width * 0.50))
        superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: superview.frame.height * 0.05))
        superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .CenterX, relatedBy: .Equal, toItem: superview, attribute: .CenterX, multiplier: 1, constant: 0))
        superview.addConstraint(NSLayoutConstraint(item: textField2, attribute: .CenterY, relatedBy: .Equal, toItem: superview, attribute: .CenterY, multiplier: 1, constant: 0))

    }
}

textField1 works perfectly. it is add to the centre of the view. however, textField2, which i dragged and dropped onto the storyboard, is offset from the centre. why is this happening?
thanks

A: The problem is that if a view comes from the storyboard, like your textField2, it already has constraints. Saying textField2.translatesAutoresizingMaskIntoConstraints = false does not magically solve that problem. You would also need to get hold of those constraints, somehow, and remove them before applying your own constraints in code. That can be tricky to do, and you are not doing it, which is why your view is misbehaving. It is better, at this stage, for you to follow these simple rules:

*

*if a view comes from the storyboard, set its constraints only in the storyboard

*but if a view is made in code, now you can say translatesAutoresizingMaskIntoConstraints = false and set its constraints in code


text:
Q: Is it possible to distcp files (comma separated) using distcp between 2 Hdfs directories (separate clusters)? I have the need to only distcp x number of files.
Couldn't find a way to do it.

*

*One idea is to copy it over a temporary directory and then distcp that directory. Once complete I can delete that temp directory.

*Individual distcp commands (for each file). This could be painful.
Not sure if comma separation is allowed.
Any ideas?
Thanks in advance.

A: You can either pass all the files as sources to the DistCp command
hadoop distcp hdfs://src_nn/var/log/spark/appHistory/<appId_1>/ \
              hdfs://src_nn/var/log/spark/appHistory/<appId_2>/ \
              ....
              hdfs://src_nn/var/log/spark/appHistory/<appId_n>/ \
              hdfs://dest_nn/target/

Or, Create a file containing the list of sources and pass it to the command as source with -f option
hadoop distcp -f hdfs://src_nn/list_of_files hdfs://dest_nn/target/


text:
Q: Unwanted space between divs I am trying to get three images to connect for my content box but for some reason there is some space between the second and the third. Any help would be appreciated.
here is the site: http://hyvhuynh.com/hyperbolical-blog
<?php get_header(); ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<div <?php post_class();?> id="post-<?php the_ID();?>">

<a href="<?php the_permalink() ?>" rel="bookmark" title="Post <?php the_ID(); ?> - permanent link"><?php the_title(); ?>

<?php the_time('F j, Y'); ?>

<?php the_content(the_title('', '', false)." - continue reading"); ?>

<?php if('open' == $post->comment_status) : ?>
<?php comments_popup_link('Comment on '.$post->post_title, '1 Comment on '.$post->post_title, '% Comments on '.$post->post_title,'postcomment','Comments are off for '.$post->post_title); ?>
<?php endif;?>

<?php if(get_the_tag_list()) :?>

Tags: <?php the_tags('

',',

','

');?>

<?php endif;?>

<?php endwhile; ?>

<?php next_posts_link('« Older Posts'); ?>

<?php previous_posts_link('Newer Posts »');?>

<?php endif; ?>

<?php get_footer(); ?>

---------css---------------
#mid {
    background-image:url('http://hyvhuynh.com/wp-content/themes/zenlite/images/bodymiddle.png');
    width:806px;
}

#bottom {
    background-image:url('http://hyvhuynh.com/wp-content/themes/zenlite/images/bodybottom.png');
    width:806px;
    height:27px;

}

#header {
width:800px;
float:right;
margin:0 0 50px 0;
}

/*
Navigation Bar Time!
*/

#jsddm
{   margin: 20px 0 0 0;
    padding: 0;
    font-weight:bold;
    text-shadow: #000000;

}

    #jsddm li
    {   float: left;
        list-style: none;
        font: bold 12px Tahoma, Arial}

    #jsddm li a
    {   display: block;
        background: #E7E7EF;
        padding: 5px 12px;
        text-decoration: none;
        border: 1px solid #555555;
        width: 70px;
        color:#000000;
        white-space: nowrap}

    #jsddm li a:hover
    {   background: #1A4473}

        #jsddm li ul
        {   margin: 0;
            padding: 0;
            position: absolute;
            visibility: hidden;
            }

        #jsddm li ul li
        {   float: none;
            display: inline}

        #jsddm li ul li a
        {   width: auto;
            background: #E7E7EF}

        #jsddm li ul li a:hover
        {   background: #1A4473}

/*
End Navigation Time!
*/

.logo {
    float:right;
}

#content .post {
    float:left;
    width:800px;
}

#content .page,#content .attachment,.postcontent {

    width:800px;
    text-decoration:none;

}

.photo {
    width: 250px;
    height:700px;
    background-color:#000000;
    margin:0 0 0 880px;
}

.slideshow { height: 232px; width: 232px; margin:0 0 0 880px;  }
.slideshow img {  border: 5px solid #000;  }

.post-title {
    margin:0;
    padding:0;
    text-align:center;
}
.post-title a {
    text-decoration:none;
    color:#000000;
}
.post-title a:hover,.post-title a:active,.post-title a:focus {
    text-decoration:underline;
    color:#5F625F;
}
#content .meta li,#content .prevnext li,#content .gallery li {
    list-style-image:none;
    list-style:none;
}
.meta {
    margin:5px 0 0;
    padding:0;
    font-size:.85em;
}
.meta ul,.meta li {
    margin:0;
    padding:0;
}
.meta ul {
    display:inline;
}
.meta li li {
    display:inline;
    padding-right:.3em;
}
.postfoot {
    clear:both;

    padding-bottom:10px;
    line-height:1.2em;
}
.author .posts-by {
    padding-top:10px;
}

.clearfix {
display: inline-block; }

.clearfix:after {
content: " ";
display: block;
height: 0;
clear: both;
visibility: hidden;
}

#footer {
    clear:both;
    margin:0 auto;
    padding:0 0 5px;
    text-align:center;
    font-size:.8em;
    border: 0;
    width:800px;
    height:200px;

}
#footer ul {
    clear:both;
    margin:0;
    padding:0;
}
#footer li {
    display:inline;
    margin:0;
    padding:0 5px;
}
#footer li.rss {
    position:relative;
    top:3px;
}

.copyright {

}

.copyright a
{

}

.copyright a:hover
{

}

.postcontent p {
    text-decoration:none;
    border:0;
    border-style:none;
    }

    .postcontent p a:hover {
        color:#fff;

    }

A: The space is from the margin on your unordered list.  Add this to your stylesheet
ul.prevnext {margin: 0px;}

And it'll correct it.  I'm not sure what you're doing with it though, so you may want to just scrap it for now because once you add any items, it will pop up again.  Or move it to a different position as mltsteeves mentioned.

A:
 is causing the space between the two divs, try putting it inside the previous div.

A: You have nesting errors in your markup.  I would sort them out first, from what I can see in Firebug, it might already sort it out.

end tag for "div" omitted, but OMITTAG NO was specified
end tag for "ul" which is not finished

A: The block below:

is not contained inside the proper
 tag, it is between your mid and bottom divs.


text:
Q: Why my code of lifetime function call is ok or fail?
*

*I'm new to Rust lang and wonder what difference between two blocks in fn main(), can anyone explain in words of lifetime.

*Are .as_str() calls change the lifetime of x and y?

*Whose lifetime does -> &a' str refer to? a,b,c at lifetime() returning position or z to receive the result?

I consider the variables x and y have the same lifetime scopes in both blocks. And that of z covers the x's and y's.
If (x: &'a str, y: &'a str, z: &'a str) demands same lifetime scope of x,y,z, both blocks should fail.
fn main()
{
    let mut z = "123abc";

    {////    CAN ONLY SUCCEED WHEN REMOVE THE BRACES OF THIS BLOCK
        let x = String::from("ajoisd");
        let y = String::from("aso");
        z = lifetime(x.as_str(), y.as_str(), z);
    }

    {////    GOES WELL WITH/WITHOUT BRACES
        let x = "ajoisd";
        let y = "aso";
        z = lifetime(x, y, z);
    }

    println!("{}", z);
}

fn lifetime<'a>(a: &'a str, b: &'a str, c: &'a str) -> &'a str
{
    if a.len() > b.len()          {a}
    else if a.len() < b.len()     {b}
    else                          {c}
}

A: Strings "ajoisd" and "aso" have the 'static lifetime. They outlive any variable in the program. Variables x and y in the first block live only in this block which is less than the lifetime of z.


text:
Q: CSS media queries interpret resolution rather than viewport I made an HTML page and a CSS file. I created media queries to display this page correctly on different devices.
Everything is fine except on a Samsung A51 (android). This mobile interpret the CSS media query for resolution > 1000 pixels rather than interpret the media query for resolution = 414px.
As you can see on this website, Samsung A51 have a resolution 1080x2400 and 405PPI: https://phonesdata.com/fr/smartphones/samsung/galaxy-a51-5458463/#techspec
I don't understand why. However i clearly indicate the meta tag:
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />

Here is the CSS interpreted:
h3 {
    max-width: 70%;
    text-align: center;
    font-weight: 800;
    color: #13A538;
    margin: 5rem auto 1rem;
    font-size: 2.5rem;
    margin-bottom: 30px;
}

Here is the media querie that should be interpreted:
@media screen and (min-width: 414px) {
            h3{
                font-weight: 500;
                /* color: #13A538; */
                color: pink;
                margin: 2rem auto 1rem;
                font-size: 1.5rem;
            }

EDIT: My break points:
@media screen and (max-width: 360px)
@media screen and (min-width: 414px)
@media (min-width: 576px)
@media (min-width: 768px)
@media (min-width: 992px)
@media (min-width: 1200px)

@Greg-- you think it's necessary to add you media querie ?

A: Samsung A51 has viewport size 412x915px, change you media querie to:
@media screen and (min-width:320px) {
        h3{
            font-weight: 500;
            /* color: #13A538; */
            color: pink;
            margin: 2rem auto 1rem;
            font-size: 1.5rem;
        }
}

320px - is min almost all devices, but better use max-width
How can you calculate viewport:
Samsung A51 resolution: 1080x2400px
Density: 2.625 (resolution 405px/inch to viewport 154px/inch)
viewport:

*

*width: 1080/2.625=411,4px

*height: 2400/2.625 = 914.2px

UPD

This Samsung stil display this media queries: @media (min-width:
1200px)

Please check and check on your Samsung
Please try to check on different mobile browsers (Samsung browser and Chrome) - does it have same issue?
For detect mobile device you can use:

*

*@media only screen and (hover: none) and (pointer: coarse) - for detect touch sreens link;

*orientation: portrait - link;


text:
Q: Eureke- connection refused - registration failed New to microservices and have checked serveral other posts but i keep getting this error, my applications.yaml already contains:

    server:
      port: 8761

    spring:
      application:
        name: Eureka-server

    eureka:
      client:
        fetch-registry: false
        register-with-eureka: false

and i have @EnableEurekeServer already done in main.
Eureka hasn't successfully launched for me even once thus far and am looking for a solution to this issue but unable to find/troubleshoot one.
Any help would be appreciated! The error messagese are below
2022-03-09 11:53:38.814  WARN 23686 --- [freshExecutor-0] c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: java.net.ConnectException: Connection refused
2022-03-09 11:53:38.814  INFO 23686 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_UNKNOWN/taruns-mbp.ht.home - was unable to refresh its cache! This periodic background refresh will be retried in 30 seconds. status = Cannot execute request on any known server stacktrace = com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
    at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:112)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$6.execute(EurekaHttpClientDecorator.java:137)
    at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134)
    at com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry(DiscoveryClient.java:1101)
    at com.netflix.discovery.DiscoveryClient.fetchRegistry(DiscoveryClient.java:1014)
    at com.netflix.discovery.DiscoveryClient.refreshRegistry(DiscoveryClient.java:1531)
    at com.netflix.discovery.DiscoveryClient$CacheRefreshThread.run(DiscoveryClient.java:1498)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:833)

2022-03-09 11:53:38.862  INFO 23686 --- [tbeatExecutor-0] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://localhost:8761/eureka/}, exception=java.net.ConnectException: Connection refused stacktrace=com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused
    at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:187)
    at com.sun.jersey.api.client.filter.GZIPContentEncodingFilter.handle(GZIPContentEncodingFilter.java:123)
    at com.netflix.discovery.EurekaIdentityHeaderFilter.handle(EurekaIdentityHeaderFilter.java:27)
    at com.sun.jersey.api.client.Client.handle(Client.java:652)
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:682)
    at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
    at com.sun.jersey.api.client.WebResource$Builder.put(WebResource.java:529)
    at com.netflix.discovery.shared.transport.jersey.AbstractJerseyEurekaHttpClient.sendHeartBeat(AbstractJerseyEurekaHttpClient.java:103)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92)
    at com.netflix.discovery.shared.transport.decorator.MetricsCollectingEurekaHttpClient.execute(MetricsCollectingEurekaHttpClient.java:73)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92)
    at com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient.executeOnNewServer(RedirectingEurekaHttpClient.java:121)
    at com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient.execute(RedirectingEurekaHttpClient.java:80)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92)
    at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:120)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92)
    at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77)
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89)
    at com.netflix.discovery.DiscoveryClient.renew(DiscoveryClient.java:893)
    at com.netflix.discovery.DiscoveryClient$HeartbeatThread.run(DiscoveryClient.java:1457)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.net.ConnectException: Connection refused
    at java.base/sun.nio.ch.Net.pollConnect(Native Method)
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672)
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549)
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
    at java.base/java.net.Socket.connect(Socket.java:633)
    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:144)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:134)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:605)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:440)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:118)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:173)
    ... 27 more

2022-03-09 11:53:38.863  WARN 23686 --- [tbeatExecutor-0] c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: java.net.ConnectException: Connection refused
2022-03-09 11:53:38.863 ERROR 23686 --- [tbeatExecutor-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_UNKNOWN/taruns-mbp.ht.home - was unable to send heartbeat!

com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
    at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:112) ~[eureka-client-1.10.17.jar:1.10.17]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89) ~[eureka-client-1.10.17.jar:1.10.17]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92) ~[eureka-client-1.10.17.jar:1.10.17]
    at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77) ~[eureka-client-1.10.17.jar:1.10.17]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89) ~[eureka-client-1.10.17.jar:1.10.17]
    at com.netflix.discovery.DiscoveryClient.renew(DiscoveryClient.java:893) ~[eureka-client-1.10.17.jar:1.10.17]
    at com.netflix.discovery.DiscoveryClient$HeartbeatThread.run(DiscoveryClient.java:1457) ~[eureka-client-1.10.17.jar:1.10.17]
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) ~[na:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]


text:
Q: AWS Toolkit for Visual Studio Code using the AWS Serverless Application Model AWS SAM I follow the steps described at Create a Serverless Application with the AWS Toolkit for Visual Studio Code:
https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/create-sam.html
This is step by step building a lambda function with AWS SAM model.
When I execute the function locally, I got following error message:
File "/usr/local/Cellar/aws-sam-cli/0.15.0/libexec/lib/python3.7/site-packages/botocore/regions.py", line 135, in _endpoint_for_partition
    raise NoRegionError()
botocore.exceptions.NoRegionError: You must specify a region.
I have the AWS Toolkit for Visual Studio Code extension installed and I can connect to any region using AWS Explorer
Any help appretiated!

A: I realized that I have not configured aws for access keys and default region
On Terminal screen, you can execute
aws configure

command and provide information requested


text:
Q: Old backup data not shown in GAE sql instance How to restore from an google cloud sql instance backup data which was 90 days old. As for now, GAE clould sql instance page shows only the last 7 backups not the full list of backups. Is there any way to get the old backup to restore?

I want the backup made on July 10.

A: Backups are only kept for 7 days.


text:
Q: Magento 2.3.5-p2 with Stripe Plugin 3.0.0: New order emails being sent twice Checking out with Stripe plugin for magento (ver 3.0.0) on Magento 2.3.5-p2 sends out 2 "New order confirmation" emails with the same order number, no invoice email gets sent.
Tried checking out with another payment method like "Purchase order" and "Bank Transfer" and only 1 "New order confirmation" gets sent.
Tried with Stripe Magento Plugin 2.8.4 and only 1 "New order confirmation" email gets sent, so it appears that this is an issue with Stripe Magento Plugin 3.0.0
Stores > Configuration > Sales > Sales Email > "Sales" and "Invoice" are set to enabled and "Send Invoice Email Copy Method" is set to Bcc.
The Stripe payments settings are as follows.

The order notes shows the following order status flow.

The Stripe payment timeline is as follows

The Stripe webhooks log shows the following
[2022-04-02 14:41:01] webhooks.INFO: Received stripe_payments_webhook_payment_intent_succeeded [] []
[2022-04-02 14:41:01] webhooks.INFO: 200 OK [] []
[2022-04-02 14:41:02] webhooks.INFO: Received stripe_payments_webhook_charge_succeeded [] []
[2022-04-02 14:41:06] webhooks.INFO: 200 OK [] []

I've tried toggling between "authorize only" and "authorize and capture" with the same result, also no "invoice" email gets sent, only a "new order confirmation" email.
Tried to disable and enable "async sending" with the same result.
I can't seem to figure out the "New order confirmation" is being sent twice for the same order and the invoice email isn't sent with the successful capture of the payment.
Any help with this would be great, thanks.

A: This issue is now solved with the 3.1.1 update https://github.com/stripe/stripe-magento2-releases/blob/master/CHANGELOG.md

A: Update from Stripe

Hello,
This is a quick update to let you know that the problem has been fixed, and will be included in the next release of the module. We anticipate the next release to be publicly available within 1 week.
You can keep an eye for new releases is via one of the following 2 pages:

*

*The Magento Marketplace changelog.

*Stripe's changelog on
Github.


text:
Q: Consecutive Days bug/glitch Up until a few hours ago (at least I presume that's the case!), I had somewhere around the mid to late 90s in "consecutive days" showing, but as of just now Stackoverflow is showing:

Is this a (temporary, hopefully!!) side-effect of the outage earlier, or has something gone really quite horribly wrong? Has anyone else experienced this?

A: This is probably due to yesterday's SO Outage which required the database to be restored, rebuilt and merged. I am assuming that this would have reset the consecutive days on some accounts.

A: The team appear to have resolved this as I received the "Fanatic" badge 12 minutes ago on so.


text:
Q: Remove all except one file in bash on mac bash on mac, installed by brew
λ  brew list | grep bash
bash

λ  which bash
/usr/local/bin/bash

λ  rm !("shorturl.api")
-bash: !: event not found

λ  ls -1 | grep -v shorturl.api | xargs rm
rm: cannot remove ''$'\033''[0m'$'\033''[01;32mapi'$'\033''[0m': No such file or directory
rm: cannot remove ''$'\033''[01;34metc'$'\033''[0m': No such file or directory
rm: cannot remove ''$'\033''[01;34minternal'$'\033''[0m': No such file or directory
rm: cannot remove ''$'\033''[00mshorturl.go'$'\033''[0m': No such file or directory

A: The !(pattern-list) globbing pattern only works when extended globbing is enabled.  See the extglob section in glob - Greg's Wiki.  In this case you need:
shopt -s extglob
rm -- !(shorturl.api)

*

*The -- with rm is to prevent files whose names begin with - being treated as options.

One way to do it without extended globbing is:
find . -maxdepth 1 -type f ! -name shorturl.api -delete

The ls -1 | grep -v shorturl.api | xargs rm attempt in the question is broken in several ways, including:

*

*The output of ls is intended for reading by humans.  It is not suitable for automatic processing.  See Why you shouldn't parse the output of ls(1).

*The grep -v shorturl.api will exclude files other than the intended one.  For instance, old-shorturl.api would be excluded.

*xargs by default uses spaces and newlines to split its input into arguments.  xargs rm won't delete files that have such characters in their names.

A: thanks @GordonDavisson.
use ls --color before pipeline to xargs
ls -1 --color=never | grep -v shorturl.api | xargs rm -rf


text:
Q: Programmatically blur background view behind Pop Over I have a view controller(PopOverViewController) being instantiated by another view controller(ListViewController).
Within ListViewController, PopOverViewController is modally presented:
popOverVC = self.storyboard?.instantiateViewController(withIdentifier: "sbPopUpID") as! PopUpViewController

popOverVC.modalPresentationStyle = .fullScreen

Within PopOverViewController, the PopOverViewController is animated in/out with CGAfflineTransformation:
    func showAnimate()
{
    self.shadowView.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
    self.view.alpha = 0.0;
    UIView.animate(withDuration: 0.3, animations: {
        self.view.alpha = 1.0
        self.shadowView.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
    });
}

func removeAnimate()
{
    UIView.animate(withDuration: 0.3, animations: {
        self.shadowView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        self.view.alpha = 0.0;
    }, completion:{(finished: Bool) in
        if (finished)
        {
            self.view.removeFromSuperview()
        }
    });
}

In the viewDidLoad of the PopOverViewController, the background color is turned down:
self.view.backgroundColor = UIColor(white: 0, alpha: 0.7)

My Question:
When the PopOver is presented, the background is still visible due to the alpha of the PopOver. I would like to blur this background when the PopOver is being presented, and have the blur disappear when the PopOver is closed.
I am stumped on how to do this.
Thank you!
Swift 3

A: private func makeEffectView() {
        let effect: UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
        effectView = UIVisualEffectView(effect: effect)
        effectView.frame = CGRect(x:0, y:0, width:UIScreen.main.bounds.size.width, height:UIScreen.main.bounds.size.height)
        self.window?.addSubview(effectView)
    }

private func removeEffectView() {
        if effectView != nil {
            self.effectView.removeFromSuperview()
        }
    }


text:
Q: How to view version of a ppt file? In my computer MS office 2013 is installed. I have a set of ppt files, I would like to see the version(2002, 2003 . . 2007,2010) of the PPT file. Please help me with the solution.

A: If you want to know the version of PowerPoint that created the file (or perhaps that last saved it?) tack .ZIP onto the end of the filename (ie, myfile.pptx.zip) and open it in Windows Explorer or any ZIP utility you like.
In the \docProps folder, you'll find app.xml and near the end of this file you'll find xx.0000
XX will be 14 for PPT 2010, 15 for PPT 2013, 16 for PPT 2016

A: Office 2013
- See link below
http://www.indezine.com/products/powerpoint/learn/interface/2013/determine-service-pack-1-office-2013.html
PowerPoint 2010
- Open the ppt file
- Click one File
- Select Help
- You will see the version on your right hand side.


text:
Q: Information flow in ES6 modules without using globals Say I have a website with a file structure like this:
index.html
main.js
modules/my-module.js

index.html contains (along with a lot of HTML):
<button id='my-btn'>My Button</button>
<script type='module' src='./main.js'></script>

main.js contains:
import { myBtn } from "./modules/my-module.js";

and modules/my-module.js contains:
const myBtn = document.querySelector("#my-btn");
myBtn.addEventListener("click", function(){
    alert("Hallo from My Button");
});
export { myBtn };

Now if I click on the button I get an alert as expected.
The problem I am having is that I have some information (ie variables with values such as strings, arrays etc) in other script tags on the index.html page which I need in modules/my-module.js
I do not want to use a global variable for this
I thought of creating an element(s) on the index.html page with data set attributes as keys and assign values to them. The element could then be accessed from modules/my-module.js and its data set attributes would be readable. This does work when I try it but it seems a long winded way of getting access to information available on the index.html page.
Is there any other approach which would be more direct?
I would prefer an answer to the question rather than being told I am an idiot or marking the page as a duplicate and pointing to a page that is not a duplicate. Just because I mention the word global does not mean this is a question about how to create a global to the kind editor who directed me to a page on how to make a global.


text:
Q: Get the Domain that an Ajax Request is coming from I have a set of JSONP Web Service created on my J2EE application, which will be used by a website under a different domain. The web services have been created using the Jersey framework.
What I want to know is, is there a way I can tell in my Web Service code, what domain the request came from?  What I'm hoping is that there is a value in the HttpHeader which would have this value.
Also would it be possible for the user making the Ajax call, to fake this value, or to put in another value before they send the call?
What I'm hoping to use this for is to restrict the domains that can call my web service.  I need to use JSONP, but i don't want my web service to be available to anybody who reverse engineers my JavaScript code.
Or does anybody know another way of doing this?

A: You can use HTTP_REFERER as already mentioned
Some code example:
talker.php

    <title>HTTP Referer example</title>

observer.php
<?php
    echo $_SERVER['HTTP_REFERER'];
?>

The result looks like this:
http://localhost/talker.php

A: One way to achieve this would be to authenticate the users on the distant domain which is supposed to send the request. So for example the server on the distant domain could emit some encrypted value to authenticated users. Then when sending the JSONP request you would send this token to the web service which would decrypt it. The idea is that both servers should share some common secret to encrypt/decrypt this token. This way you can ensure that the request came from the other server.

A: Your RESTful services are hosted on a web server and with REST you're limited to the standard stuff that comes as part of HTTP. For example, you could get the host IP that sent the request, but be aware that this can be spoofed.
One option open to you would be to require the web service requests to be digitally signed. This basically means that the caller creates and adds a Message Authentication Code to the request. The MAC is generated using a secret key that only an authorised user of your service knows. You can (and should) also add a user ID to the web service request, allowing you to give each user their own secret key.
Remember that if your services are being called by javascript (eg using AJAX) then the calls will come from the client computer. This means they are completely open to reverse engineering. If you rely on javascript to digitally sign the request then the javascript would need to know the secret key, therefore exposing it to any attacker.


text:
Q: How to get FormControlName of the field which value changed in Angular reactive forms I have a reactive form with over 10 form controls and using subscription on valueChanges observable to detect changes. It works perfectly but output is always the entire form value object(meaning all the form controls and their values). Is there a way to simply get the form control name of the field that changed?
this.form = this.fb.group({
    field1: ['', Validators.required],
    field2: ['', Validators.required],
    field3: ['', Validators.required],
    field4: ['', Validators.required],
    field5: ['', Validators.required],
    field6: ['', Validators.required],
    field7: ['', Validators.required],
    field8: ['', Validators.required],
    field9: ['', Validators.required],
    field10: ['', Validators.required],
    field11: ['', Validators.required],
    field12: ['', Validators.required],
    field13: [{ value: '', disabled: true }, Validators.required]
});

this.form.valueChanges.subscribe(
    result => this.calculateParams(result)
);

calculateParams(result) {
    console.log(result); // giving the entire form.value object
}

A: It's a work-around but if store the old values you can do some like
this.old={...this.myForm.value}
this.myForm.valueChanges.subscribe(res=>{
  const key=Object.keys(res).find(k=>res[k]!=this.old[k])
  this.old={...this.myForm.value}
})

A: The rxjs way of Eliseo's answer
this.form.valueChanges.pipe(
    startWith(this.form.value),
    pairwise(),
    map(([oldValues, newValues]) => {
        return Object.keys(newValues).find(k => newValues[k] != oldValues[k]);
    }),
).subscribe(key => {
    console.log( key )
});

A: You can isolate the formcontrol from the formgroup by using the get method and the access the valueChanges method on it.
this.form.get('formcontrolName').valueChanges().
Note: form.get returns you the AbstractControl, which also has the valueChanges method on it.

A: Haven't fully tested the code but the idea is to pair the controls and their key then listen to valueChanges on each control simultaneously and return object key instead of value (and of course you can map both value and key to the output)
const fields={
    field1: ['', Validators.required],
    field2: ['', Validators.required],
    field3: ['', Validators.required],
    field4: ['', Validators.required],
    field5: ['', Validators.required],
    field6: ['', Validators.required],
}

zip(
 from(Object.values(fb.group(fields).controls)),
 from(Object.keys(fields))
).pipe(mergeMap([control,key])=>control.valueChanges.pipe(mapTo(key)))

A: You could subscribe to each change individually.
for (const controlProperty in this.myForm.controls) {
    if (this.myForm.controls.hasOwnProperty(controlProperty)) {
      this.myForm.controls[controlProperty].valueChanges.pipe(untilDestroyed(this)).subscribe(result => {
        console.log(controlProperty + " is now ", result);
      });
    }
}

This just felt more angular-y to me.

A: Use valueChanges for each control after adding control dynamically to FormGroup.
const ct = {key: 'myControl'};
this.myForm.addControl(ct.key, new FormControl('', Validators.required))
this.myForm.controls[ct.key].valueChanges
.subscribe(d => {
    // here ct will be available as closure , so that we can access every form control here and do operation accordingly
    console.log(d, ct.key);
})

Here ct object will be available inside subscribe as a closure.

A: The method from @alex-walker (https://stackoverflow.com/a/64830665/134120) seems to be the best, but it only works well on flat forms, with simple key-value pairs. If you have nested forms, with FormArrays of FormGroups, the key property in that method will only return the top-level key of the form, which is not very useful if you want e.g. to indicate to the user the particular input field that triggered the event.
So I combined this method with a deep object diff method described here: https://stackoverflow.com/a/50278133/134120
To get something like this:
this.form.valueChanges
    .pipe(
        startWith(this.form.value),
        pairwise(),
        map(([oldValues, newValues]) => {
            return bdiff(oldValues, newValues);
        })
    )
    .subscribe(keys => {
        console.log(keys);
    });

bdiff(a: Record<string, any>, b: Record<string, any>): string[] {
    return _reduce(
        a,
        (res, val, key) =>
            res.concat(
                (_isPlainObject(val) || Array.isArray(val)) && b
                    ? this.bdiff(val, b[key]).map(x => key + (key.trim ? '' : ']') + (x.search(/^\d/) ? '.' : '[') + x)
                    : !b || val !== b[key]
                    ? [key + (key.trim ? '' : ']')]
                    : []
            ),
        []
    );
}

Which will return an array of nested keys such as keys = ['fieldgroup2.fieldArray[3].myNestedField'] which you should easily access and set as invalid with form.get(keys[0]).valid.


text:
Q: Which instance will receive the notification if there are two instances of same controller? I'm firing a notification from the same controller and receiving it in the same controller.
I'm using a common controller whose one instance is created first and then pushed into the stack and then the other one.
So what I was expecting is that I should be receiving the notification in both instances but in this case I'm only receiving the notification in second instance which is lower down the stack. But when there is only one instance then I'm receiving the notification in the same controller just like it should be.
Can anybody explain me the reason why this is happening?


text:
Q: How to draw incircle (inscribed circle)? First Question
\documentclass[pstricks,12pt,border=12pt]{standalone}
\usepackage{pst-eucl}
\begin{document}
\begin{pspicture}[showgrid](-3,-2)(2,2)
\psset{PointSymbol=none,CodeFig,CodeFigColor=red}
\pstTriangle(1,1){A}(-2,1){C}(-1,-1){B}
\pstProjection{A}{B}{C}[I]
\pstProjection{A}{C}{B}[J]
\pstProjection{C}{B}{A}[K]
\end{pspicture}
\end{document}

How to modify the size of right angle mark?
Second Question
In  TikZ, we can draw both excircle (escribed circle) and incircle (inscribed circle) of a triangle ABC by passing circum and in, respectively  as follows.
\tkzDrawCircle[circum](A,B,C)
\tkzDrawCircle[in](A,B,C)

In PSTricks, what options do I have to pass to \pstCircleABC[<options>]{A}{B}{C}{O} to draw an incircle (of the triangle) ABC?  I know that we can use \pstBissectBAC, \pstProjection and \pstCircleOA but it is too long.
Third Question
For the following macros,
\pstLineAB[Options]{A}{B}
\pstCircleOA[Options]{O}{A}
\pstCircleAB[Options]{O}{A}
\pstDistAB[Options]{A}{B}
\pstDistVal[Options]{x}
\pstInterFF[Options]{f}{g}{x0}{M}
\pstInterFL[Options]{f}{A}{B}{x0}{M}
\pstInterFC[Options]{f}{O}{A}{x0}{M}
\psGetDistanceAB[Options](x1,y1)(x2,y2){<name>}
\psGetAngleABC[Options](x1,y1)(x2,y2)(x3,y3){<symbol>}

what are all possible optional arguments?

A: Please provide always complete examples!
1.
\documentclass[pstricks]{standalone}
\usepackage{pst-eucl}
\begin{document}

\begin{pspicture}[showgrid](-3,-2)(2,2)
\psset{PointSymbol=none,CodeFig,CodeFigColor=red,RightAngleSize=0.2}
\pstTriangle(1,1){A}(-2,1){C}(-1,-1){B}
\pstProjection{A}{B}{C}[I]
\pstProjection{A}{C}{B}[J]
\pstProjection{C}{B}{A}[K]
\end{pspicture}

\end{document}

2.Write an own macro \pstInnerCircle, which isn't too complicated
\documentclass[pstricks]{standalone}
\usepackage{pst-eucl}
\makeatletter
\def\pstTriangleIC{\pst@object{pstTriangleIC}}
\def\pstTriangleIC@i#1#2#3{%
  \begingroup
  \psset{PointSymbol=none,PointName=none,linestyle=none}
  \pstBissectBAC{#3}{#1}{#2}{IC_BC}
  \pstBissectBAC{#2}{#3}{#1}{IC_AB}
  \pstInterLL{#3}{IC_AB}{#1}{IC_BC}{IC_M}
  \pstProjection[CodeFig=false]{A}{B}{IC_M}[IC_MAB]
  \endgroup
  \begingroup
  \use@par
  \pstCircleOA{IC_M}{IC_MAB}
  \endgroup
}
\makeatother
\begin{document}

\begin{pspicture}[showgrid](-3,-2)(2,2)
\psset{PointSymbol=none,CodeFig,CodeFigColor=red,RightAngleSize=0.2}
\pstTriangle(1,1){A}(-2,1){C}(-1,-1){B}
\pstProjection{A}{B}{C}[I]
\pstProjection{A}{C}{B}[J]
\pstProjection{C}{B}{A}[K]
\pstTriangleIC[linestyle=dashed,linecolor=blue]{A}{B}{C}
\end{pspicture}

\end{document}

3.Read the documentation


text:
Q: Use associative array to merge two objects based on ID So I have the following method $data = Twitter::get_profile_tweets() which outputs the following response:
object(stdClass)#1597 (3) {
  ["data"]=>
  array(5) {
    [0]=>
    object(stdClass)#1612 (4) {
      ["text"]=>
      string(231) "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
      ["id"]=>
      string(19) "1487953501825163264"
      ["author_id"]=>
      string(19) "1487104761291849728"
    }
    [1]=>
    object(stdClass)#1586 (5) {
      ["attachments"]=>
      object(stdClass)#1606 (1) {
        ["media_keys"]=>
        array(1) {
          [0]=>
          string(22) "16_1487594952561467393"
        }
      }
      ["text"]=>
      string(56) "Telling myself how I really feel"
      ["id"]=>
      string(19) "1487594959125549059"
      ["author_id"]=>
      string(19) "1487104761291849728"
    }
  }
  ["includes"]=>
  object(stdClass)#1604 (2) {
    ["users"]=>
    array(1) {
      [0]=>
      object(stdClass)#1591 (9) {
        ["profile_image_url"]=>
        string(78) "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"
        ["id"]=>
        string(19) "1487104761291849728"
        ["name"]=>
        string(14) "FHTechServices"
      }
    }
  }
}

The API response makes no sense, but I guess you have to match the data tweets return to the corresponding user.

Here is what I'm attempting to do:
Let's say this would be the ideal return:
object(stdClass)#1597 (3) {
  array(2) {
    [0] => {
        [0] => {
            object(stdClass)#1612 (4) {
              ["text"]=>
              string(231) "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
              ["id"]=>
              string(19) "1487953501825163264"
              ["author_id"]=>
              string(19) "1487104761291849728"
            }
        [1] =>
            object(stdClass)#1591 (9) {
              ["profile_image_url"]=>
              string(78) "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"
              ["id"]=>
              string(19) "1487104761291849728"
              ["name"]=>
              string(14) "FHTechServices"
            }
        }
    }
    [1] => {
        [0] => {
            object(stdClass)#1612 (4) {
              ["text"]=>
              string(231) "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
              ["id"]=>
              string(19) "1487953501825163264"
              ["author_id"]=>
              string(19) "1487104761291849728"
            }
        }
        [1] => {
            object(stdClass)#1591 (9) {
              ["profile_image_url"]=>
              string(78) "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"
              ["id"]=>
              string(19) "1487104761291849728"
              ["name"]=>
              string(14) "FHTechServices"
            }
        }
    }
  }
}

We looked at ["data"] in the first index and grabbed the Author ID and then looked at the ID inside ["includes"]["users"] and if it matches, merge its own array of object.
Unsure about the below, since there might be key collisions:
What if we can just merge it all into one single array or object, so then I don't have to do [0] for the tweet keys and [1] for the user keys, I can just loop and grab the keys such as:
[0] => {
    [0] => {
        object(stdClass)#1612 (4) {
          ["text"]=>
          string(231) "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
          ["id"]=>
          string(19) "1487953501825163264"
          ["author_id"]=>
          string(19) "1487104761291849728"
          ["profile_image_url"]=>
          string(78) "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"
          ["id"]=>
          string(19) "1487104761291849728"
          ["name"]=>
          string(14) "FHTechServices"
        }
    }
}

This sounds extremely confusing, so all help will be really appreciated!

A: Your requested output contains 2 ID fields and really just needs ID and author_id.
On the combined object we need to map the ID field on the user to the author ID field on the tweet!
So first we make a lookup table (array) with our users that lets us map the author_id on a tweet to the id field on the user.
Then when we loop through our tweets we can add the user details as needed.
<?php

$twitter_data = (object) [
    'data' => [
        (object) [
            'text' => "Follow DataTongue on twitter",
            'id' => "1487953501825163264",
            'author_id' => "14871047612917656543",
        ],

        (object) [
            'text' => "My name is Keith Ismael",
            'id' => "1487953501825112346",
            'author_id' => "14871047612918412345",
        ],

        (object) [
            'text' => "My name is Paul Malvino",
            'id' => "1487953501825198765",
            'author_id' => "14871047612918469875",
        ],
    ],

    'includes' => (object) [
        'users' => [
            (object) [
                'profile_image_url' => "https://example.com",
                'id' => "14871047612918469875",
                'name' => "Paul Malvino",
            ],
            (object) [
                'profile_image_url' => "https://example.com",
                'id' => "14871047612918412345",
                'name' => "Keith Ismael",
            ],
            (object) [
                'profile_image_url' => "https://example.com",
                'id' => "14871047612917656543",
                'name' => "Sally Pemdas",
            ],
        ],
    ]
];

function mergeTweetsWithUsers ($merge_me) {
    $users_lookup = [];
    $combined_output = [];

    foreach ($merge_me->includes->users as $key => $user) {
        $users_lookup[$user->id] = $user;
    }

    foreach ($merge_me->data as $tweet) {
        $merged_tweet = $tweet;
        $merged_tweet->author_name = $users_lookup[$tweet->author_id]->name;
        $merged_tweet->author_profile_image_url = $users_lookup[$tweet->author_id]->profile_image_url;

        $combined_output[] = $merged_tweet;
    }

    return $combined_output;
}

mergeTweetsWithUsers($twitter_data);

/*
array(3) {
  [0]=>
  object(stdClass)#1 (5) {
    ["text"]=>
    string(28) "Follow DataTongue on twitter"
    ["id"]=>
    string(19) "1487953501825163264"
    ["author_id"]=>
    string(20) "14871047612917656543"
    ["author_name"]=>
    string(12) "Sally Pemdas"
    ["author_profile_image_url"]=>
    string(19) "https://example.com"
  }
  [1]=>
  object(stdClass)#2 (5) {
    ["text"]=>
    string(23) "My name is Keith Ismael"
    ["id"]=>
    string(19) "1487953501825112346"
    ["author_id"]=>
    string(20) "14871047612918412345"
    ["author_name"]=>
    string(12) "Keith Ismael"
    ["author_profile_image_url"]=>
    string(19) "https://example.com"
  }
  [2]=>
  object(stdClass)#3 (5) {
    ["text"]=>
    string(23) "My name is Paul Malvino"
    ["id"]=>
    string(19) "1487953501825198765"
    ["author_id"]=>
    string(20) "14871047612918469875"
    ["author_name"]=>
    string(12) "Paul Malvino"
    ["author_profile_image_url"]=>
    string(19) "https://example.com"
  }
}

*/


text:
Q: accuracy of tf.metrics.mean_squared_error For the study needs, I want to check the accuracy of tf.Metrics.mean_squared_error. To my surprise, they are much different. I am seeking for explanations. Here is my experiement brief followed by my sample code:
1) evaluate the trained toy model with the whole training data by tf.Metrics.mean_squared_error; and
2) evaluate again immediately after the step 1, by first collecting the prediction given all "Xs" (or images) of the same whole training data, and then computing the mean squared error with all the ground truth (or labels) of the training data and the prediction.
I have two unproved explanations: (1) float precision loss accumulates and (2) tf.Metrics.mean_square_error applies seemingly moving average in its implementation that brings about inaccuracy.
Any relavent ideas are greatly appreciated! Thanks!

import tensorflow as tf
from numpy import genfromtxt

tf.logging.set_verbosity(tf.logging.INFO)
# (hyper)parameters
batch_size = 200
num_epochs = 1000
steps = 1000
# prepare data
with tf.Session() as sess:
    training_x = sess.run(tf.random_normal([2048, 16], mean=-1, stddev=4, dtype=tf.float64))
    training_y = norm = sess.run(tf.random_normal([2048, 1], mean=-1, stddev=4, dtype=tf.float64))
# input function
_input_fn = lambda _input_path: genfromtxt(_input_path, delimiter=',')
input_training = tf.contrib.learn.io.numpy_input_fn({"input": training_x}, training_y,
                                              batch_size=batch_size, num_epochs=num_epochs)
input_evaluate_train_data = tf.contrib.learn.io.numpy_input_fn({"input": training_x}, training_y)

# remember to give the same column name as used in _input_fn
features = [tf.contrib.layers.real_valued_column('input', dimension=16)]
regressor = tf.contrib.learn.DNNRegressor(feature_columns=features,
                                          hidden_units=[32, 8],
                                          dropout=0.1,
                                          model_dir="testDNNR/result",
                                          optimizer=tf.train.AdamOptimizer(learning_rate=0.008),
                                          activation_fn=tf.nn.elu)

# training
regressor.fit(input_fn=input_training, steps=steps)
# testing with training data
eval_metric_ops = {
    "mse": lambda targets, predictions: tf.metrics.mean_squared_error(tf.cast(targets, tf.float64), predictions)
}
ev = regressor.evaluate(input_fn=input_evaluate_train_data, steps=1, metrics=eval_metric_ops)
pred = regressor.predict(input_fn=input_evaluate_train_data, as_iterable=False)
# using my MSE
mse = ((training_y - pred) ** 2).mean()

print ("evaluation result given training data using my MSE: " + str(mse))
print ("evaluation result given training data using the library built-in MSE: " + str(ev))

A: The mismatch comes from how tf.contrib.learn.io.numpy_input_fn works. After some wrapping this function is implemented by https://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/python/estimator/inputs/numpy_io.py#L45
As you can see, by default, each time it is called it returns a batch of 128 values. When you use it in a call to regressor.evaluate you get a different set of 128 values than what you get in when you use it in regressor.predict.
There are other related issues. The implementation linked above has shuffle=True which means it will pick random 128 elements from your data.
Also, when you do training_y - pred the sizes are very different and the tensors get broadcasted resulting in many more terms than what you expect.


text:
Q: Fast way to find if IPv6 belongs to network range I've created a simple script to detect if an IP is in a fixed number of networks (if IP is part of CIDR IP range). Unfortunately the performance goal was not met. 50 checks(for loop) if an IPv6 belongs to one one of 250 networks takes 55ms, which is way slower than what is expected. I supply a short version of the program and code in hope of finding a more performant solution. I used https://github.com/lduchosal/ipnetwork library because I didn't know how to perform bitwise shifts on 128 bits of data needed to store IPv6.
I don't include a large block of IPv4s, because IPv4 lookups are 3x faster. IPv6 were duplicated a few times to simulate large block.
Thats how you call it:
 using System;
 using System.Globalization;
 using System.Net;

 namespace CIDR_lookup
 {
  internal class Program

  {
    public static void Main(string[] args){

      // initilizes static cache by triggering a call to static constructor. i and jk arrays are not used
      IPNetwork[] i = CidrLookup.subnetCache;
      IPNetwork[] jk = CidrLookup.subnetCache6;
      Console.WriteLine(jk.Length);

      var watch = System.Diagnostics.Stopwatch.StartNew();
      bool IsIn = false;
      for (int j = 0; j < 50; j++){
        IsIn= CidrLookup.IpInRange(IPAddress.Parse("2a03:2880::1").GetAddressBytes());
      }

      watch.Stop();
      var elapsedMs = watch.ElapsedMilliseconds;
      Console.WriteLine("Elapsed: "+ elapsedMs);
   }
 }
}

This is the class code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Numerics;

namespace CIDR_lookup
{
  public partial class CidrLookup
  {
    public static IPNetwork[] subnetCache;
    public static IPNetwork[] subnetCache6;

    static CidrLookup(){
      subnetCache = CidrLookup.CreateSubnets(_ipRanges);
      subnetCache6 = CidrLookup.CreateSubnets(_ipRanges6);
    }

    public static bool IpInRange(byte[] ipBytes){

      IPAddress ip = new IPAddress(ipBytes);

        if (ip.AddressFamily  == AddressFamily.InterNetwork){
          foreach (var subnet in subnetCache){
            bool isIn = subnet.Contains(ip);
            if (isIn){
              return true;
            }
          }
        }
        else{
          foreach (var subnet in subnetCache6){
            bool isIn = subnet.Contains(ip);
            if (isIn){
              return true;
            }
          }
        }

      return false;
    }

    public static IPNetwork[] CreateSubnets(string ipRanges){
      string[] ipRangesArray = ipRanges.Split('\n');
      IPNetwork[] table = new IPNetwork[ipRangesArray.Length];

      for (int i = 0; i < ipRangesArray.Length; i++){
        table[i] = IPNetwork.Parse(ipRangesArray[i]);
      }

      return table;
    }

    public static string IpRanges
    {
      get { return _ipRanges; }
      set { _ipRanges = value; }
    }

    public static string IpRanges6
    {
      get { return _ipRanges6; }
      set { _ipRanges6 = value; }
    }

    private static string _ipRanges6 = @"2604:ca00:f001::/48
    2604:ca00:f004::/48
    2402:9800:8001:0:0:0:0:0/48
    2604:ca00:f009::/48
    2604:ca00:9::/48
    2604:ca00:f008::/48
    2604:ca00:8::/48
    2604:ca00:1a0::/43
    2604:ca00:f::/48
    2604:ca00:d000::/48
    2604:ca00:f000::/48
    2605:ef80:240::/42
    2605:ef80:300::/40
    2605:ef80:400::/42
    2605:ef80:600::/40
    2605:ef80:900::/40
    2607:f8b0:4000::/48
    2a00:79e1:abc::/46
    2a03:ace0:100::/40
    2a03:ace0:200::/40
    2a03:ace0:300::/40
    2605:ef80::/32
    2a03:ace0::/32
    2605:ef80::/42
    2605:ef80:100::/42
    2605:ef80:140::/42
    2605:ef80:180::/42
    2605:ef80:1c0::/42
    2605:ef80:40::/42
    2605:ef80:80::/42
    2605:ef80:c0::/42
    2605:59C0::/32
    2604:ca00::/32
    2604:ca00:f001::/48
    2604:ca00:f004::/48
    2402:9800:8001:0:0:0:0:0/48
    2604:ca00:f009::/48
    2604:ca00:9::/48
    2604:ca00:f008::/48
    2604:ca00:8::/48
    2604:ca00:1a0::/43
    2604:ca00:f::/48
    2604:ca00:d000::/48
    2604:ca00:f000::/48
    2605:ef80:240::/42
    2605:ef80:300::/40
    2605:ef80:400::/42
    2605:ef80:600::/40
    2605:ef80:900::/40
    2607:f8b0:4000::/48
    2a00:79e1:abc::/46
    2a03:ace0:100::/40
    2a03:ace0:200::/40
    2a03:ace0:300::/40
    2605:ef80::/32
    2a03:ace0::/32
    2605:ef80::/42
    2605:ef80:100::/42
    2605:ef80:140::/42
    2605:ef80:180::/42
    2605:ef80:1c0::/42
    2605:ef80:40::/42
    2605:ef80:80::/42
    2605:ef80:c0::/42
    2605:59C0::/32
    2604:ca00::/32
    2604:ca00:f001::/48
    2604:ca00:f004::/48
    2402:9800:8001:0:0:0:0:0/48
    2604:ca00:f009::/48
    2604:ca00:9::/48
    2604:ca00:f008::/48
    2604:ca00:8::/48
    2604:ca00:1a0::/43
    2604:ca00:f::/48
    2604:ca00:d000::/48
    2604:ca00:f000::/48
    2605:ef80:240::/42
    2605:ef80:300::/40
    2605:ef80:400::/42
    2605:ef80:600::/40
    2605:ef80:900::/40
    2607:f8b0:4000::/48
    2a00:79e1:abc::/46
    2a03:ace0:100::/40
    2a03:ace0:200::/40
    2a03:ace0:300::/40
    2605:ef80::/32
    2a03:ace0::/32
    2605:ef80::/42
    2605:ef80:100::/42
    2605:ef80:140::/42
    2605:ef80:180::/42
    2605:ef80:1c0::/42
    2605:ef80:40::/42
    2605:ef80:80::/42
    2605:ef80:c0::/42
    2605:59C0::/32
    2604:ca00::/32
    2604:ca00:f001::/48
    2604:ca00:f004::/48
    2402:9800:8001:0:0:0:0:0/48
    2604:ca00:f009::/48
    2604:ca00:9::/48
    2604:ca00:f008::/48
    2604:ca00:8::/48
    2604:ca00:1a0::/43
    2604:ca00:f::/48
    2604:ca00:d000::/48
    2604:ca00:f000::/48
    2605:ef80:240::/42
    2605:ef80:300::/40
    2605:ef80:400::/42
    2605:ef80:600::/40
    2605:ef80:900::/40
    2607:f8b0:4000::/48
    2a00:79e1:abc::/46
    2a03:ace0:100::/40
    2a03:ace0:200::/40
    2a03:ace0:300::/40
    2605:ef80::/32
    2a03:ace0::/32
    2605:ef80::/42
    2605:ef80:100::/42
    2605:ef80:140::/42
    2605:ef80:180::/42
    2605:ef80:1c0::/42
    2605:ef80:40::/42
    2605:ef80:80::/42
    2605:ef80:c0::/42
    2605:59C0::/32
    2604:ca00::/32
    2604:ca00:f001::/48
    2604:ca00:f004::/48
    2402:9800:8001:0:0:0:0:0/48
    2604:ca00:f009::/48
    2604:ca00:9::/48
    2604:ca00:f008::/48
    2604:ca00:8::/48
    2604:ca00:1a0::/43
    2604:ca00:f::/48
    2604:ca00:d000::/48
    2604:ca00:f000::/48
    2605:ef80:240::/42
    2605:ef80:300::/40
    2605:ef80:400::/42
    2605:ef80:600::/40
    2605:ef80:900::/40
    2607:f8b0:4000::/48
    2a00:79e1:abc::/46
    2a03:ace0:100::/40
    2a03:ace0:200::/40
    2a03:ace0:300::/40
    2605:ef80::/32
    2a03:ace0::/32
    2605:ef80::/42
    2605:ef80:100::/42
    2605:ef80:140::/42
    2605:ef80:180::/42
    2605:ef80:1c0::/42
    2605:ef80:40::/42
    2605:ef80:80::/42
    2605:ef80:c0::/42
    2605:59C0::/32
    2604:ca00::/32
    2604:ca00:f001::/48
    2604:ca00:f004::/48
    2402:9800:8001:0:0:0:0:0/48
    2604:ca00:f009::/48
    2604:ca00:9::/48
    2604:ca00:f008::/48
    2604:ca00:8::/48
    2604:ca00:1a0::/43
    2604:ca00:f::/48
    2604:ca00:d000::/48
    2604:ca00:f000::/48
    2605:ef80:240::/42
    2605:ef80:300::/40
    2605:ef80:400::/42
    2605:ef80:600::/40
    2605:ef80:900::/40
    2607:f8b0:4000::/48
    2a00:79e1:abc::/46
    2a03:ace0:100::/40
    2a03:ace0:200::/40
    2a03:ace0:300::/40
    2605:ef80::/32
    2a03:ace0::/32
    2605:ef80::/42
    2605:ef80:100::/42
    2605:ef80:140::/42
    2605:ef80:180::/42
    2605:ef80:1c0::/42
    2605:ef80:40::/42
    2605:ef80:80::/42
    2605:ef80:c0::/42
    2605:59C0::/32
    2604:ca00::/32
    2604:ca00:f001::/48
    2604:ca00:f004::/48
    2402:9800:8001:0:0:0:0:0/48
    2604:ca00:f009::/48
    2604:ca00:9::/48
    2604:ca00:f008::/48
    2604:ca00:8::/48
    2604:ca00:1a0::/43
    2604:ca00:f::/48
    2604:ca00:d000::/48
    2604:ca00:f000::/48
    2605:ef80:240::/42
    2605:ef80:300::/40
    2605:ef80:400::/42
    2605:ef80:600::/40
    2605:ef80:900::/40
    2607:f8b0:4000::/48
    2a00:79e1:abc::/46
    2a03:ace0:100::/40
    2a03:ace0:200::/40
    2a03:ace0:300::/40
    2605:ef80::/32
    2a03:ace0::/32
    2605:ef80::/42
    2605:ef80:100::/42
    2605:ef80:140::/42
    2605:ef80:180::/42
    2605:ef80:1c0::/42
    2605:ef80:40::/42
    2605:ef80:80::/42
    2605:ef80:c0::/42
    2605:59C0::/32";

    private static string _ipRanges = @"1.1.1.1
2.2.2.2
3.3.3.3";
  }
}

A: Subnetting in IPv6 is typically no smaller than a /64. You can use two longs as network and mask respectively to check. If you do want to permit longer subnets, you could use a 128-bit integer library or use two sets of longs for the high and low bits.


text:
Q: How to flip a moving image horizontally when it reaches a certain point on the screen Overview
For my school project I have to create an animation in HTML, CSS and Javascript. I have just started to learn how to code and so am new to these kinds of projects. I have been able to make an image of mario move across the screen and then move back, but I want the image to flip when it reaches the start and end of the container. I have no idea how to do this and would be so grateful if someone could help me.

var objX = 0;
var change = 10;

function moveBlock() {
  var obj = document.getElementById("object");
  if ((objX + 251) > 1100) {
    change = -10;

  } else if (objX == 0) {
    change = 10;
  }
  objX = objX + change;
  obj.style.left = objX + "px";
}
.rotate {
  animation: rotation 8s infinite linear;
}

@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(359deg);
  }
}

#grass {
  width: 1100px;
  height: 100px;
  margin-top: 0px;
  position: relative;
  background-color: green;
}

#container {
  width: 1100px;
  height: 320px;
  margin-top: 0px;
  position: relative;
  background-color: white;
}

#object {
  width: 251px;
  height: 320px;
  margin-top: 0px;
  position: absolute;
  background-image: url("https://i.stack.imgur.com/e7Hib.png")
}

Layers and animation

<button onclick="setInterval(moveBlock, 25)">Click Me</button>

https://i.stack.imgur.com/e7Hib.png

A: I hope the following snippet can be of help, please do not hesitate to ask if there is any doubt.

const img = document.getElementById('img');
const container = img.parentElement;

let left = 0;
let sign = 1;

let ticking = false;

img.style.left = `${left}px`;
img.style.transform = `scaleX(${sign})`;

function translate() {
  // YOU CAN CHANGE THE SPEED BY CHANGING THIS.
  left += sign * 10;

  if (left + img.offsetWidth >= container.clientWidth) {
    // CASE: RIGHT LIMIT.
    left = container.clientWidth - img.offsetWidth;
    sign *= -1;
  } else if (left <= 0) {
    // CASE: LEFT LIMIT.
    left = 0;
    sign *= -1;
  }

  if (ticking) {
    return;
  }

  // THIS WILL RUN THE CALLBACK WHEN THE BROWSER IS READY TO DO A REPAINT. (JUST A PERFORMANCE IMPROVEMENT)
  requestAnimationFrame(() => {
    img.style.left = `${left}px`;
    img.style.transform = `scaleX(${sign})`;

    ticking = false;
  });

  ticking = true;
}

setInterval(translate, 10);
#img {
  height: 100px;
  width: 100px;
  position: absolute;
  top: 0;
  left: 0;
  transition: transform 0.5s linear;
}


text:
Q: Performing expression evaluation/reduction in Visual Studio 2008 Is it possible to get Visual Studio to do mathematical expression evaluation/reduction?
For example if I type '-0.005 + -0.345' how do I get Visual Studio to reduce that (i.e. replace it with the reduction)?  Do I have to write a macro?  If so, are there any pre-existing macros to do this type of expression reduction?
Just to be clear,  I want to be able to highlight an expression and have it replaced with the reduced result.  Many are suggesting the immediate window but I fail to see how that will suffice?
Edit I should point out that this is while editing not running or debugging.  The immediate window is of little to no use.  I also consider this a language neutral question.  I would certainly be interested in seeing alternative macros to the one I had posted.
Edit Going Once... Going Twice... (i.e. any other suggestions before I consider accepting my own answer?)

A: Thank you for the above answers.
There probably are better ways, but here's a quick and dirty macro that does what I need.
References to the System.Data and System.XML namespaces need to be added.
Highlight the expression you want to evaluate and run the macro (it uses the calculated column in the DataTable to evaluate the expression.)  It will replace the expression with the reduced result.
Edit - Updated code below.  It worked extremely well for reducing a large number of expressions. As pointed out by others there is the immediate window but this will not work for editing purposes.  This macro is a language independent solution for basic expressions "(), +, -, *, /".

Sub Eval()
  Dim ts As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
  Using dt As New DataTable()
    dt.Columns.Add("Expression", GetType(Double), ts.Text)
    dt.Rows.Add(dt.NewRow)
    ts.Text = CDbl(dt.Rows(0).Item("Expression"))
  End Using
End Sub

A: Visual Studio by default will not do any mathematical expression evaluation / reduction.  I'm not sure if you can get support for that via items like ReSharper, but if it is available it will be in an add-in.
Also, it would be helpful to know the language you are working in?
Some languages may be helpful in this area.  F# for instance makes it easy to evaluate expressions in the IDE via the interactive window and will display out the result.  This could easily be added back into your code but it doesn't appear to be exactly what you're looking for.

A: Here's an answer:  Yes, it is possible using the following steps.  (While technically performing what you're asking for, I'm not sure it will be extremely useful.  :-)

*

*Set a breakpoint in your program that's likely to get hit when you debug the program.

*Then, run your program under the Visual Studio debugger.

*When the breakpoint is hit, open the Watch window.

*In the Watch window, add a new watch by clicking in the Name column.

*Enter your expression '-0.005 + -0.345' (without the quotes) then hit [Enter].
... You should see the Value column get populated with -0.35.

Of course, that isn't in the context of the editor window ... which is, presumably, where you'd want to perform the reduction.  So again, not very useful, I imagine.  An add-in is the likely way to do that in the editor window.

A: You could just go to the immediate window and type "?<yourExpression>"


text:
Q: powershell get-service is not showing all services defined
I'm running in powershell (as administrator):

get-service

and I'm looking for the 'Remote Desktop Services' but it is not written out by the command
The relevant part of the output is (the R's):

Status   Name               DisplayName
...
Stopped  RemoteAccess       Routing and Remote Access
Running  RemoteRegistry     Remote Registry
Running  RpcEptMapper       RPC Endpoint Mapper
Stopped  RpcLocator         Remote Procedure Call (RPC) Locator
Running  RpcSs              Remote Procedure Call (RPC)
Stopped  RSoPProv           Resultant Set of Policy Provider
...

However in services.msc there is:

Remote Desktop Services                                       Running
Remote Desktop Services UserMode Port Redirector              Running

Can someone please tell me why get-services is not returning 'Remote Desktop Services' and 'Remote Desktop Services UserMode Port Redirector' services?

A: By default, Get-Service orders the output by the 'Name' of the service and Services.msc uses the 'DisplayName'.
Remote Desktop Services has a 'Name' of TermService and Remote Desktop Services UserMode Port Redirector has a 'Name' of UmRdpService.  So neither of these would appear in the R section of your output, which is why you're not seeing them there.
Sort by DisplayName and you'll see them listed together:
Get-Service | Sort-Object DisplayName | Format-Table -AutoSize

...
Stopped RasAuto        Remote Access Auto Connection Manager
Running RasMan         Remote Access Connection Manager
Stopped SessionEnv     Remote Desktop Configuration
Stopped TermService    Remote Desktop Services
Stopped UmRdpService   Remote Desktop Services UserMode Port Redirector
Running RpcSs          Remote Procedure Call (RPC)
Stopped RpcLocator     Remote Procedure Call (RPC) Locator
Stopped RemoteRegistry Remote Registry
...


text:
Q: In rails4 having many models, using cancancan gem, grant access to specific user to a specific model only? I have 5 models in my rails 4 application, and using cancancan gem I want to give access to specific users to a specific model only.
This means:

*

*user1 is allowed to access 1,2 model

*user 2 is allowed to access 3,4 model

*user 3 is allowed to access all models.
Please guide me.

A: You should use rolify with cancan to accomplish that. You can assign a certain role with rolify to represent your "user 1" or "user 2" like this:
user = User.find(1)
user.add_role :limited_user_1

and your "user 3" that has access to everything can be an admin
user = User.find(3)
user.add_role :admin

Then with cancan it's as simple as checking if the user has the specified role. In this case :manage means the user has access to all actions, such as :read, :create, :update, :destroy.
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
    elsif user.limited_user_1?
      can :manage, :model_1
      can :manage, :model_2
    elsif user.limited_user_2?
      can :manage, :model_3
      can :manage, :model_4
    end
  end
end

A: A simpler version of Mike's answer would be as follows:
#app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    case user.role_id
      when 1
         can :read, Model
         can :read, Model2
      when 2
         can :read, Model3
         can :read, Model4
      when 3
         can, :manage, :all
    end
  end
end

You'll have to add a way to define whether a User is 1,2,3 etc, which is why Mike suggested rolify.


text:
Q: In Django Todo App how can each user have a distinct set of tasks? I am making a todo app using Django. Currently, the problem I am facing is that no matter which user logs in, the same set of tasks appears, i.e. if a user adds some task for himself, they appear in every other user's todo list. How can I modify my code so that each user can have a distinct set of tasks?
Here's some of my code:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User

class To_DO_Fun(models.Model):
    Task_Name = models.CharField(max_length=20, default='')
    Task_Text = models.TextField(max_length=450, default='')
    Task_Done = models.BooleanField(default=False)

    def __str__(self):
        return self.Task_Name + '  --- is ---  ' + str(self.Task_Done)

class user_TODO(models.Model):
    User_Name = models.ForeignKey(To_DO_Fun , User, on_delete=models.CASCADE)

from __future__ import unicode_literals
from django.shortcuts import render, redirect
from .models import To_DO_Fun, user_TODO #Class Name
from .forms import Form_todo, Form_Task #Form Name
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

def HomeFun(request): #To view contents of the home page
    return render(request, "ToDo_Files/HomePage.html")

@login_required(login_url='Login-Page')
def Display_Page(request, User_Name_id):

    if request.method == "POST":

        form = Form_todo(request.POST or None)

        if form.is_valid():
            all_items = To_DO_Fun.objects.get(pk=User_Name_id)
            form.save()
            messages.success(request, ("Good Luck"))
            return render(request , 'ToDo_Files/Display_Page.html' , {'all_items': all_items} )

    else:
        form = Form_todo(request.POST or None)
        all_items = To_DO_Fun.objects.get(pk=User_Name_id)
        return render(request,'ToDo_Files/Display_Page.html',{'all_items': all_items} )

@login_required(login_url='Login-Page')
def remove(request, To_DO_Fun_id):
    item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
    item.delete()
    messages.success(request, ('Congratulations!!! You finished your task'))
    return redirect('Display-Page')

@login_required(login_url='Login-Page')
def data(request, To_DO_Fun_id):

        if request.method == "POST":
            item_all = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
            form = Form_Task(request.POST, instance= item_all)

            if form.is_valid():
                form.save()
                urlstr = 'ToDo_Files/details/'
                messages.success(request, ("Item Updated"))
                return redirect('Display-Page')

        else:
            item_all = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
            return render(request, 'ToDo_Files/details.html', {'item_all' : item_all})

        return redirect('Display-Page')

@login_required(login_url='Login-Page')
def Done_status(request, To_DO_Fun_id):
    item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
    item.Task_Done = True
    item.save()
    return redirect('Display-Page')

@login_required
def Pen_status(request, To_DO_Fun_id):
    item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
    item.Task_Done = False
    item.save()
    return redirect('Display-Page')

def Reg_Fun(request):
    if request.method == "POST":
        UserReg_Form = UserCreationForm(request.POST)

        if UserReg_Form.is_valid():
            UserReg_Form.save()
            messages.success(request, ("Welcome"))
            return redirect('Login-Page')
    else:
        UserReg_Form = UserCreationForm(request.POST)
        return render(request, "ToDo_Files/reg.html", {'UserReg_Form':UserReg_Form})

        return redirect('Login-Page')

A: Add a many-to-one-relationship from your tasks model to the User model.
in your models.py
class To_DO_Fun(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    Task_Name = models.CharField(max_length=20, default='')
    Task_Text = models.TextField(max_length=450, default='')
    Task_Done = models.BooleanField(default=False)

then in your views.py you can retrieve all the tasks that belong to the user that is currently logged in using a filter.
tasks = To_DO_Fun.objects.filter(owner=request.user)
context = {'tasks': tasks}
return(request, "yourpage.html", context)

I suggest you take a look at Django's coding style following the coding style will improve your code consistency and readability.


text:
Q: How can i change mobile menu one scroll to multiple pages? I have one page scroll menu,but i've changed that in multiple page.These kind of menu is working on desktop,but is not working on mobile version.How can I change code css or html because in mobile version when i click on menu and close it anywhere i clicked redirectg me to another page.

.mobile-menu {
 display: block;
     width: 18%;
    right: -20%;
    height: 100%;
    background: rgba(1, 16, 25, 0.67);
    position: fixed;
    z-index: 9998;
    transition: 0.6s ease;
    top: 0;
    opacity: 0;
}

.mobile-menu ul {
 position: relative;
    top: 20%;
    padding: 0;
}

.mobile-menu ul li {
 list-style: none;
    margin-bottom: 2em;
 display: block;
}
.mobile-menu ul li a {
 width: 100%;
    margin: 0 auto;
    display: block;
    text-align: center;
    text-decoration: none;
    color: #fff;
    font-size: 1em;
    font-weight: bold;
    overflow: hidden;
    position: relative;
    padding: 1em 0;
    text-transform: uppercase;
    letter-spacing: 3px;
}
.open > ul.dropdown-menu.agile_short_dropdown{
    display: block;
    transform: none !important;
    min-width: 65%;
    border: none;
    box-shadow: none;
    border-radius: 0;
    left: 18%;
}
.open > ul.dropdown-menu.agile_short_dropdown li{
 margin:0 !important;
}
ul.dropdown-menu.agile_short_dropdown > li > a:hover{
    background: none;
}
.mobile-menu ul li a:after {
 content: '';
    background: #191143;
 width: 100%;
 height: 100%;
 position: absolute;
 right: -100%;
 top: 0;
 z-index: -1;
 transition: 0.4s ease;
}

.mobile-menu ul li a:hover,.mobile-menu ul li.active a {
 color: #fff;
}

.mobile-menu ul li a:hover:after,.mobile-menu ul li.active a:after {
 right: 0;
}
li.dropdown.act a.w3_icons_act {
    background: #0e0e0e;
 color: #fff;
}
.mobile-menu img {
 position: absolute;
 width: 150px;
 display: block;
 left: 50%;
 top: 3rem;
 transform: translatex(-50%);
 -webkit-transform: translatex(-50%);
 -moz-transform: translatex(-50%);
 -o-transform: translatex(-50%);
 -ms-transform: translatex(-50%);
 padding: 0;
 text-align: center;
}

.mobile-menu--open {
 opacity: 1;
 right:0%;
}
.dropdown.active.open a  ul.dropdown-menu.agile_short_dropdown li a.w3_icon_1:after{
 background:none !important;

Despre mine

Repertoriu

Discografie

Evenimente

Foto

Video

Contact

Can anyone help me?