text:
Q: Proof OLS is Biased if a Regressor is Correlated with the error Consider the basic linear model:
$$y_i =\beta_0 +\beta_1 x_i +\varepsilon_i$$
I am aware that if $E[\varepsilon_i|x_i ]=0$ then $E[\hat{\beta_1}]=\beta_1$ (unbiasedness) and also that if $Cov(x_i,\varepsilon_i)=0$ then $plim \hat{\beta_1} = \beta_1$ (consistency).
I am hoping to prove that if $Cov(x_i,\varepsilon_i) \ne 0$ then $E[\hat{\beta_1}]\ne\beta_1$.
Can anyone help? My attempt begins below.
$$\hat{\beta_1}=\frac{\sum_{i=1}^n (x_i-\bar{x})(y_i-\bar{y})}{\sum_{i=1}^n (x_i-\bar{x})^2}$$
$$\hat{\beta_1}=\beta_1 + \frac{\sum_{i=1}^n (x_i-\bar{x})(\varepsilon_i-\bar{\varepsilon})}{\sum_{i=1}^n (x_i-\bar{x})^2}$$
$$E[\hat{\beta_1}]=\beta_1 + E\left[\frac{\sum_{i=1}^n (x_i-\bar{x})(\varepsilon_i-\bar{\varepsilon})}{\sum_{i=1}^n (x_i-\bar{x})^2}\right]$$
My goal is to show the expectation on the right must be non-zero as a result of $Cov(x,\varepsilon)\ne 0$. The difficulty is that the expectation operator can be separately applied to the numerator and denominator. The numerator is in expectation non-zero, but if the sample covariance of $x$ and $\varepsilon$ is not independent of the sample variance of $x$, I don't know how to proceed.
Thanks in advance!

A: You are almost there. Remember that $\bar{\epsilon}=0$, you get:
$$
\hat{\beta}_1=\beta+\frac{\sum_{i=1}^n(x_i-\bar{x})(\epsilon_i-\bar{\epsilon})}{\sum_{i=1}^n(x_i-\bar{x})^2}=\beta+\frac{\sum_{i=1}^n(x_i-\bar{x})\epsilon_i}{\sum_{i=1}^n(x_i-\bar{x})^2}
$$
Therefore
$$
E(\hat{\beta}_1 \vert x)=E\left(\left. \beta+\frac{\sum_{i=1}^n(x_i-\bar{x})\epsilon_i}{\sum_{i=1}^n(x_i-\bar{x})^2}\right|x\right)=\beta+\frac{\sum_{i=1}^n(x_i-\bar{x})E(\epsilon_i\vert x)}{\sum_{i=1}^n(x_i-\bar{x})^2}\neq \beta
$$
since $E(\epsilon_i \vert x)\neq 0$. Since, $E(\hat{\beta}_1 \vert x) \neq \beta$ it follows that $E(\hat{\beta}_1)=E(E(\hat{\beta}_1 \vert x))\neq \beta$.

A: Woolridge does a really great job of explaining the unbiasedness of OLS coefficients in his book Introductory Econometrics. In what follows, I use his notation and arguments.
The assumption that $E(u\vert x)=E(u) = 0$ is a central assumption on OLS.  This assumption means that the error $u$ and the covariate $x$ are independent.  If the error and covariate are not independent (hence correlated), then $E(u\vert x) \neq 0 $ and will in genereal depend on $x$.
The proof that $\hat{\beta}_1$ is an unbiased estimate of $\beta_1$ makes use of this assumption.  Following Woolrdige...
$$\hat{\beta}_{1}=\frac{\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right) y_{i}}{\operatorname{SST}_{x}}=\frac{\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)\left(\beta_{0}+\beta_{1} x_{i}+u_{i}\right)}{\operatorname{SST}_{x}}$$
Here $\mathrm{SST}_{x}=\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)^{2}$.  Some commitment to doing some algebra yields
$$ \hat{\beta}_{1}=\beta_{1}+\left(1 / \operatorname{SST}_{x}\right) \sum_{i=1}^{n} (x_i - \bar{x}) u_{i} $$
If we take expectations in the above expression for $\hat{\beta}_1$, we obtain
$$ E(\hat{\beta}_1) = \beta_1 + 1/(\operatorname{SST}_x)\sum_{i=1}^n (x_i - \bar{x})E(u_i) $$
Note that since the error and predictor are not independent, $E(u_i)$ depends on $x$ and is not 0 in general, this the sum is not 0 leading to a bias.


text:
Q: Navbar becomes sticky when scrolling up even 1px - I want it to appear only when scrolling more than 10px I'm working on a navbar that is always sticky on mobile and disappears when scrolling down but appears again when scrolling up on desktop.
Now it works perfectly well but I have one problem. On desktop, it becomes sticky when scrolling up right away. Even if I scroll just a little bit which can be annoying.

I want it to appear only when scrolling more than let's say 10px. So I'd need to add some threshold. I guess it could be done with JS but I'm a beginner.
Here's a fiddle with what I have now: https://jsfiddle.net/zsoltszilvai/zfqd901m/4/
I'd appreciate any help :)
var sticky = header.offsetTop;

var prevScrollpos = window.pageYOffset;

function myFunction(x) {
  if (x.matches) {

    window.onscroll = function() {
      var currentScrollPos = window.pageYOffset;
    }

  } else {
    window.onscroll = function() {
      var currentScrollPos = window.pageYOffset;
      if (prevScrollpos > currentScrollPos) {
        document.getElementById("navbar").style.top = "0";
        if (window.pageYOffset > sticky) {
          header.classList.add("sticky");
        }
      } else {
        document.getElementById("navbar").style.top = "-58px";
        if (window.pageYOffset < sticky) {
          header.classList.remove("sticky");
        }
      }
      prevScrollpos = currentScrollPos;
    }
  }
}

A: You need to change prevScrollpos > currentScrollPos to prevScrollpos - currentScrollPos > 10, only tricky part is to not update prevScrollpos if the difference is smaller than the threshold.
var prevScrollpos = window.pageYOffset;
var SCROLL_UP_THRESHOLD = 200

function myFunction(x) {
  window.onscroll = function() {
    var currentScrollPos = window.pageYOffset;
    console.log(prevScrollpos, currentScrollPos)
    if (prevScrollpos > currentScrollPos) {
      if (prevScrollpos - currentScrollPos < SCROLL_UP_THRESHOLD)
        return console.log("not opening")
      document.getElementById("navbar").style.top = "0";
      if (window.pageYOffset > sticky) {
        header.classList.add("sticky");
      }
      prevScrollpos = currentScrollPos;
    } else {
      document.getElementById("navbar").style.top = "-58px";
      if (window.pageYOffset < sticky) {
        header.classList.remove("sticky");
      }
      prevScrollpos = currentScrollPos;
    }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS: How can you stop live-streaming AVPlayer? I want to have an AVPlayer for playing live steam.
The audio playing works very well like that.
class CustomPlayer: ObservableObject {

    let audioSession = AVAudioSession.sharedInstance()
    var p: AVPlayer

    init (){
        let string = "https://..."
        let url: URL! = URL(string: string)
        p = AVPlayer(url: URL)
        p.play()
        try! self.audioSession.setCategory(AVAudioSession.Category.playback)
        try! self.audioSession.setActive(true)
    }

}

But as soon as I come to the point of pausing/stopping it, it becomes difficult.
The method p.pause() does work, but pauses the player so that it starts playing at the same point as it was paused. That is not helpful, because it should still play the live stream without delay of course.
So my thought was to only mute the player with p.isMuted = true. But then I've got the problem that the wrong playback state is presented in the NowPlayingInfoCenter in the control center because this inherits from the playback state of the AVPlayer. To change the playback state manually my app needs special permission/entitlements. https://developer.apple.com/documentation/mediaplayer/mpnowplayinginfocenter/2588243-playbackstate/
So that's why I am stuck with this issue and I hope someone can help me solve it.
Thanks a lot!

A: In addition to p.pause(), you can try this:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
    if avPlayer.player?.rate ?? 0 > 0 {
        avPlayer.contentOverlayView?.removeAllSubviews()
    }
}

And add the observer beforehand:
avPlayer.player?.addObserver(self, forKeyPath: "rate", options: .new, context: nil)

Note:
Here, avPlayer should be of type AVPlayerViewController()


text:
Q: Which approach is better when using Redis? I'm facing following problem:
I wan't to keep track of tasks given to users and I want to store this state in Redis.
I can do:
1) create list called "dispatched_tasks" holding many objects (username, task)
2) create many (potentialy thousands) lists called dispatched_tasks:username holding usually few objects (task)
Which approach is better? If I only thought of my comfort, I would choose the second one, as from time to time I will have to search for particular user tasks, and this second approach gives this for free.
But how about Redis? Which approach will be more performant?
Thanks for any help.

A: Redis supports different kinds of data structures as shown here. There are different approaches you can take:
Scenario 1:
Using a list data type, your list will contain all the task/user combination for your problem. However, accessing and deleting a task runs in O(n) time complexity (it has to traverse the list to get to the element). This can have an impact in performance if your user has a lot of tasks.
Using sets:
Similar to lists, but you can add/delete/check for existence in O(1) and sets elements are unique. So if you add another username/task that already exists, it won't add it.
Scenario 2:
The data types do not change. The only difference is that there will be a lot more keys in redis, which in can increase the memory footprint.
From the FAQ:

What is the maximum number of keys a single Redis instance can hold? and what the max number of elements in a Hash, List, Set, Sorted
  Set?
Redis can handle up to 232 keys, and was tested in practice to handle
  at least 250 million keys per instance.
Every hash, list, set, and sorted set, can hold 232 elements.
In other words your limit is likely the available memory in your
  system.
What's the Redis memory footprint?
To give you a few examples (all obtained using 64-bit instances):
An empty instance uses ~ 3MB of memory. 1 Million small Keys ->
  String Value pairs use ~ 85MB of memory. 1 Million Keys -> Hash
  value, representing an object with 5 fields, use ~ 160 MB of
  memory. To test your use case is trivial using the
  redis-benchmark utility to generate random data sets and check with
  the INFO memory command the space used.


text:
Q: HTML area shapes and mobile phones: is this a bug and is there a workaround? My website has a very precise "area shape" definition. It's pixel perfect.
Here's my website
Move your mouse over the departments on the left, you'll see the departements highlight on the right. If you move the mouse over the departments, you'll see that it's a pixel-perfect precision.
My big problem is about "Ile de France", which is the center of the France, almost 1/5 of the population lives here, so what follows is a huge problem to me.
Nota: before trying on your mobile phone (if you do so), just verify that what I'm saying is true: on your PC, go to the main page (link before), zoom in (ctrl + keyboard shortcut) and move your mouse over the department "Ile de France". You'll see that the precision is perfect: move out of the department, move in, you'll see by yourself the precision of the "detection".
On my Sony Ericsson Xperia Arc, the way "area shape" is handled is a huge problem.
Here's what it gives when I try to click on "Ile de France":

Getting closer (to show the problem):

Getting even closer:

And to show which departement is selected:

As you can see from the lastest picture, the map is very enlarged, but it still doesn't want to select "Ile de France", whereas I clearly click on the very middle of the region.
I mean I've been working for 3 days to get a map of France that precise, I wouldn't like to throw away that work and do a coarse work...
Is this a bug? Is this considered a normal behavior? Do "iPhone" mobiles have the same problem? Do you have a workaround?
-Edit-
According to Andrei G, it seems to work on GalaxyS2, but still need to enlarge the map...
-Edit-
I've got exactly the same problem on some Android tablets. I need to make a "mobile" version. This is soo stupid.

A: I see no problem with your map. The issue is that a human finger is not nearly as accurate as the mouse. If you enlarge your map enough, you'll be able to select the appropriate region.
I used GalaxyS2 to go to your site.
Also, the hover effect is not going to work with a phone, as the people don't drag their fingers on the screen when they want to click your area.

A: I had a similar problem with a map in a HTML email when viewed on my Android phone. I was using the map tag with both the name and id attributes. When I removed the name attribute and just used the id attribute instead I was able to accurately tap the hotspot on my phone.


text:
Q: How to use contains() and retain() with String? I'm trying to use the retain(...) method to filter out values from a vector. As it stands, my code thus far is
let results = get_data(); // Returns Result<Vec<MyData>, Box<Error>>

match results {
    Ok(mut my_data) => {

        // Make sure that `name` is not None
        myData.retain(|ref d| d.name.is_some());

        // Only keep data if 'name' is in this list
        let names = ["Alice", "Bob", "Claire"];
        my_data.retain(|ref d| names.contains(d.name.unwrap().as_str()));
    },
    Err(_) => {}
}

However, this yields the error
|
|     my_data.retain(|ref d| names.contains(d.name.unwrap().as_str()));
|                                           ^^^^^^^^^^^^^^^^^^^^^^^^ expected &str, found str
|
= note: expected type `&&str`
           found type `&str`

It seems like the compiler is telling me two separate things here, but in both cases it seems to want an additional reference. However, when I try to change the relevant line to &names.contains(d.name.unwrap().as_str()), the compiler throws the following error.
|
|     my_data.retain(|ref d| names.contains(&d.name.unwrap().as_str()));
|                                            ^ cannot move out of borrowed content

How can I check whether a borrowed String (I think that's what the type of name.unwrap() is anyway) is contained in the names vector?

A: Here is a MCVE of your problem (your original code has other, unrelated problems that are ignored here):
struct MyData {
    name: Option<String>,
}

fn main() {
    let mut my_data: Vec<MyData> = vec![];

    // Only keep data if 'name' is in this list
    let names = ["Alice", "Bob", "Claire"];
    my_data.retain(|ref d| names.contains(d.name.unwrap().as_str()));
}

error[E0308]: mismatched types
  --> src/main.rs:10:43
   |
10 |     my_data.retain(|ref d| names.contains(d.name.unwrap().as_str()));
   |                                           ^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found `str`
   |
   = note: expected reference `&&str`
              found reference `&str`

As the error message states, slice::contains requires a reference to the type of value contained in the slice:
pub fn contains(&self, x: &T) -> bool
where
    T: PartialEq<T>,

Since your slice contains string literals (of type &'static str), it needs a &&str to compare against. We will take a reference to the result of the as_str method:
my_data.retain(|ref d| names.contains(&d.name.unwrap().as_str()));
//                                    ^-- added

error[E0507]: cannot move out of `d.name` which is behind a shared reference
  --> src/main.rs:10:44
   |
10 |     my_data.retain(|ref d| names.contains(&d.name.unwrap().as_str()));
   |                                            ^^^^^^
   |                                            |
   |                                            move occurs because `d.name` has type `std::option::Option<std::string::String>`, which does not implement the `Copy` trait
   |                                            help: consider borrowing the `Option`'s content: `d.name.as_ref()`

This error is already thoroughly explained elsewhere on Stack Overflow:

*

*Cannot move out of value which is behind a shared reference when unwrapping

*Cannot move out of borrowed content / cannot move out of behind a shared reference

*Can't borrow File from &mut self (error msg: cannot move out of borrowed content)

*Matching String: cannot move out of borrowed content
TL;DR — you don't own d, so you cannot unwrap d.name, consuming the value in the process. The fix is to use Option::as_ref:
my_data.retain(|ref d| names.contains(&d.name.as_ref().unwrap().as_str()));
//                                           ^^^^^^^^^-- added

However, needing to unwrap is ugly and it's ideally avoided. You can combine the two retain calls into one and skip the unwrap by using Option::map_or:
my_data.retain(|d| {
    d.name.as_ref().map_or(false, |name| {
        let name = name.as_str();
        names.contains(&name)
    })
});

This removes a potential panic and improves the efficiency of the code.
Since Rust 1.40, this can be shortened with Option::as_deref:
my_data.retain(|d| {
    d.name
        .as_deref()
        .map_or(false, |name| names.contains(&name))
});

See also:

*

*Converting from Option<String> to Option<&str>


text:
Q: When was it decided that Willow would be gay? In the Buffy the Vampire Slayer episode Doppelgangland there is an evil Vampire-Willow doppelgänger, who comes on to the real Willow.

Willow:  (appalled) It's horrible! That's me as a vampire? I'm so evil and... skanky. (aside to Buffy, worried) And I think I'm kinda gay.
Buffy:  (reassuringly) Willow, just remember, a vampire's personality
  has nothing to do with the person it was.
Angel:  (without thinking) Well, actually... (gets a look from Buffy)
  That's a good point.

That made me wonder, when the decision was made, that Willow would be gay. While watching the series already knowing that that's what eventually will happen, I noticed dozens of those little "hints". But some of those probably came before the decision was made (when the above dialogue occurred she is still with Oz and has a little affair with Xander).
By which episode (or season) did the scriptwriters know of Willows orientation, and were able to actually foreshadow her coming out?

A: The show's senior staffers and the network seem to have been aware of Willow's sexuality and the relationship between her and Tara before the end of season 3, hence the inclusion of the (in hindsight) highly revealing line in Doppelgangland:

Willow: I mean, I'm so evil, and skanky, (softly, to Buffy) and I think I'm kind of gay.

The rest of the cast and crew were then advised at the start of season 4 when they started receiving advance copies of scripts.

Alysson Hannigan spoke about this in an interview with Cult Times in July 2000.

The 'provocative' stuff refers, of course, to the romance between
  Willow and fellow student Tara (Amber Benson), which culminates with
  Willow making an arguably controversial decision late in Season Four.
  But Willow's course of action is surprising only to those who watched
  last season with their eyes closed.
"I knew that I was going to have a friend and that we'd do witchcraft
  together and cast spells and I'd always asked if there was 'something
  more' to the relationship. Joss would always say, "Well, maybe there's
  some subtext there" and then Amber and I would see some of the spells
  and we'd be like, "Joss -- this is going way beyond "subtext"."
Eventually, after weeks of tiptoeing round the issue, everyone
  concerned admitted that all roads led to the fact that the girls were
  in love which resulted in huge sighs of relief all round. "Amber and I
  were sort of in the same position as Willow and Tara in that for the
  longest time we weren't sure what was going on ... Then finally it
  was, "Great! It's official. We're in luurrvvve."


text:
Q: Iterate and print all of the file paths of all pdf files in a specific directory using Directory.EnumerateFiles How can I iterate and print all of the file paths of all .pdf files in a specific directory when using Directory.EnumerateFiles?
The following code only returns the path of the first .pdf file in the specified directory.
        IEnumerable<string> files = Directory.EnumerateFiles(@"C:\MyFolder", "*.pdf*", SearchOption.AllDirectories);

        foreach (string file in files) {
            Console.WriteLine("File Path:{0}", file);
        }

       // Returns:
       // C:\MyFolder\firstPdfFile.pdf

Again, what I want is to be able to print all of the paths of all pdfs files in a specified directory. What am I missing?
EDIT: I'm not getting any errors, but the only thing I see in the console is the path of the first pdf found in the specified directory and I was expecting to see the path of all pdf files in that directory.

A: haven't used function you written, but suggest you to try out below
string[] filePaths = Directory.GetFiles(@"c:\MyFolder\", "*.pdf",
                                         SearchOption.AllDirectories);
// returns:
// "c:\MyFolder\fist.pdf"
// "c:\MyFolder\subdirectory\sss.pdf"


text:
Q: check a checkbox when another checkbox is checked in react I have three checkboxes, when one check box is checked, I want the second check box to be checked automatically. The below code is written in a modal. It will only set the state value, but the checkbox is not getting checked. The change will be reflected only when we close and open the modal again.
<Checkbox className="checkbox-wrapper" onChange={(e, data) => {
     if(data.checked){
       setAddAccessCheck( ...addAccessCheck,ga.groupId])
       setEditAccessCheck([...editAccessCheck,ga.groupId])
      }
      else{
       setAddAccessCheck(addAccessCheck.filter((add) => add !== ga.groupId))
       setEditAccessCheck(editAccessCheck.filter((del) => del !== ga.groupId))
     }
    }}
   value={addAccessCheck}
   defaultChecked={addSubmitAccessCheck.includes(ga.groupId) ? true : false}
 />```


text:
Q: TweenMax at function out - how to implement conditional? I'm using JS libraries: GSAP along with ScrollMagic.io by Jan Paepke.
Scrollmagic.io allows me to trigger some CSS changes on scrolling once certain trigger element is reached, the JS script looks like this:
var controller = new ScrollMagic.Controller();
                        var scene = new ScrollMagic.Scene({
                                triggerElement: "#trigger1"
                            })
                            .setTween(new TimelineMax().add([
                                TweenMax.to("header", 0.5, {backgroundColor: "rgba(40,80,01, 0.95)", height:"6%", width:"100%", top:"0", borderRadius:"0px"}),
                                TweenMax.to(".headernav", 0.5, {color:"white", fontSize:"1.5em", marginTop:"10px"}),
                                TweenMax.to(".circle", 0.5, {height:"35px", marginTop:"10px"}),
                                TweenMax.to("#logo", 0.5, {width:"70px", marginTop:"-10px", marginRight:"500px"})
                            ]))
                            .addTo(controller);

In general - it would change position, background-color and font color of my menu once it is scrolled over white area of website so that it will still be noticable and easy to read.
The problem is my a:hover within menu stopped working.
I've found a workaround by using this:
$("#verticalnav p").hover(over, out);

     function over(){
          TweenMax.to(this, 0.5, {color:"rgb(181, 171, 171)", scale:"1.1"})
     }

     function out(){
          TweenMax.to(this, 0.5, {color:"rgb(105, 105, 105)", scale:"1"})
     }

This makes it work fine, but there's still one thing to be worked out - while background of menu is "white", color:"dimgray" of font is well noticable/readable, but it will also remain "dimgray" on the green background after scrolling.
Here's screenshot explanation to show it more clearly:
Default menu state with no hovers:

On:hover using js - changes color using script shown above:

Here some properties of menu have changed along with font color to be more readable on green background:

And here's how it looks like when the mouse is OUT of the link, leaving it "dimgray" because the script makes it:

My question is - how may I implement a conditional into this script:
$("#verticalnav p").hover(over, out);

 function over(){
      TweenMax.to(this, 0.5, {color:"rgb(181, 171, 171)", scale:"1.1"})
 }

 function out(){
      TweenMax.to(this, 0.5, {color:"rgb(105, 105, 105)", scale:"1"})
 }

so that it would read the current color value and run TweenMax.to with specific color according to this value?
I'm fairly green with JS so any kind of advice would be highly appreciated.
Regards,
Damian.

A: Actually it seems that the longer I don't get answer, the more creative i become.
Already worker it out, pretty much basic JS/jQuery was needed, posting it so maybe somebody could have some use of it later on.
Here's working code of function hover:
                            $("#verticalnav p").hover(over, out);

                        function over(){
                          TweenMax.to(this, 0.5, {color:"rgb(181, 171, 171)", scale:"1.1"})
                        };

                        function out(){
                            var kolor = $("header").css("background-color");
                            if (kolor == "rgba(255, 255, 255, 0.901961)") {
                          TweenMax.to(this, 0.5, {color:"rgb(105, 105, 105)", scale:"1"})
                          }
                            else {
                              TweenMax.to(this, 0.5, {color:"white", scale:"1"})
                            }
                        };


text:
Q: Rails: link_to_remote prototype helper with :with option I am trying to grab the current value of a drop down list with Prototype and passing it along using :with like this
<%= link_to_remote "today", :update => "choices",
    :url => { :action => "check_availability" } ,
    :with => "'practitioner='+$F('practitioner')&'clinic='+$F('clinic')&'when=today'",
    :loading => "spinner.show(); $('submit').disable();",
    :complete   => "spinner.hide(); $('submit').enable();" %>

However, this is not working as expected. I am unable to access parameters in the controller as the link_to_remote helper is sending parameters like this:
Parameters: {"succ"=>"function () {\n    return this + 1;\n}", "action"=>"check_availability", "round"=>"function () {\n    return __method.apply(null, [this].concat($A(arguments)));\n}", "ceil"=>"function () {\n    return __method.apply(null, [this].concat($A(arguments)));\n}", "floor"=>"function () {\n    return __method.apply(null, [this].concat($A(arguments)));\n}", "times"=>"function (iterator, context) {\n    $R(0, this, true).each(iterator, context);\n    return this;\n}", "toPaddedString"=>"function (length, radix) {\n    var string = this.toString(radix || 10);\n    return \"0\".times(length - string.length) + string;\n}", "toColorPart"=>"function () {\n    return this.toPaddedString(2, 16);\n}", "abs"=>"function () {\n    return __method.apply(null, [this].concat($A(arguments)));\n}", "controller"=>"main"}

Where am I going wrong? Is there a better way to do this?

A: Try this
<%= link_to_remote "today", :update => "choices",
    :url => { :action => "check_availability" } ,
    :with => "'practitioner='+$F('practitioner')+&'clinic='+$F('clinic')+&'when=today'",
    :loading => "spinner.show(); $('submit').disable();",
    :complete   => "spinner.hide(); $('submit').enable();" %>

Here is the difference
:with => "'practitioner='+$F('practitioner')&'clinic='+$F('clinic')&'when=today'",

Should change to
:with => "'practitioner='+$F('practitioner')**+**&'clinic='+$F('clinic')**+**&'when=today'",

Ref: http://firstruby.wordpress.com/2008/11/03/remote_function-or-link_to_remote-with-multiple-parameters-in-ruby-on-rails/

A: Thank you, Salil.
The solution you suggested also have some problems (throwing Javascript syntax error). I guess it has the same quotes issue as mine, which I am unable to figure out. But the solution cleanly solves that problem and works smoothly:
:with => "$H({ practitioner: $F('practitioner'), clinic: $F('clinic'),
         when: 'today' }).toQueryString()"

Ref: http://www.spacevatican.org/2008/5/17/with-or-without-you-link_to_remote-s-mysterious-parameter

A: I suggest to do like this:
<%= link_to_remote "today", :update => "choices",
  :url => { :action => "check_availability" } ,
  :with => "'practitioner='+$('practitioner').value +'&clinic='+$('clinic').value+'&when=today'",
  :loading => "spinner.show(); $('submit').disable();",
  :complete   => "spinner.hide(); $('submit').enable();" %>


text:
Q: Control 4 wheeled raspberry robot with Simulink I am going to control 4 wh raspberry robot in Simulink. I found this one to control DC motor with simulink: https://www.mathworks.com/matlabcentral/fileexchange/41528-raspberry-pi-dc-motor-h-bridge-driver-block-sfunction?s_tid=srchtitle It is just for a one motor. My question: is it possible to build a simulink model for 4wheeled robot car by this model? I understood that, by changing to - or + value of block constant motor will drive anticlockwise or clockwise. How to be to turn left or right? It doesn't like Python or C programming, so it's stopped project. Especially for Simulink, any idea or suggestions would be greatly approtiated! Thank you so much in adwance!
I added images which i meant in comment. I am a newbie, so please, don't judge me quality)
enter image description here
enter image description here


text:
Q: C++ GCC Why this sfinae code can be compiled with GCC 4.7, but not with 4.8? I like to use local classes in template classes to perform constructions like "static if". But I've faced with the problem that gcc 4.8 does not want to compile my code. However 4.7 does.
This sample:
#include <type_traits>
#include <iostream>
#include <string>

using namespace std;

struct A {
    void printA() {
        cout << "I am A" << endl;
    }
};
struct B {
    void printB() {
        cout << "I am B" << endl;
    }
};

template <typename T>
struct Test {
    void print() {
        struct IfA {
            constexpr IfA(T &value) : value(value) {
            }
            T &value;
            void print() {
                value.printA();
            }
        };
        struct IfB {
            constexpr IfB(T &value) : value(value) {
            }
            T &value;
            void print() {
                value.printB();
            }
        };
        struct Else {
            constexpr Else(...) {}
            void print() {
            }
        };
        typename conditional<is_same<T, A>::value, IfA, Else>::type(value).print();
        typename conditional<is_same<T, B>::value, IfB, Else>::type(value).print();
    }
    T value;
};

int main() {
    Test<A>().print();
    Test<B>().print();
}

Options:
g++ --std=c++11 main.cc -o local-sfinae

Task:

*

*Given classes A and B with different interfaces for printing.

*Write a generic class Test that can print both A and B.

*Do not pollute either any namespace or class scope.

Description of the code:

*

*This is only a clean example.

*I use an approach like this, because I want to generalize the construction "static if". See, that I pass the arguments to IfA and IfB classes via their fields, not directly to the print() function.

*I use such constructions a lot.

*I've found that these constructions should not be in (pollute) class scope. I mean they should be placed in a method scope.

So the question.
This code can not be compiled with GCC 4.8. Because it checks ALL classes, even if they are never used. But it has not instantiate them in binary (I've commented the lines that cause errors and compiled it with gcc 4.8). Proof:
$ nm local-sfinae |c++filt |grep "::If.*print"
0000000000400724 W Test<A>::print()::IfA::print()
00000000004007fe W Test<B>::print()::IfB::print()

See, there is no Test::print()::IfB::print(). (See later: 'void Test::print()::IfB::print() [with T = A]')
The errors if I compile aforementioned code with gcc 4.8:
g++ --std=c++11 main.cc -o local-sfinae
main.cc: In instantiation of 'void Test<T>::print()::IfB::print() [with T = A]':
main.cc:36:9:   required from 'void Test<T>::print() [with T = A]'
main.cc:49:21:   required from here
main.cc:34:17: error: 'struct A' has no member named 'printB'
                 value.printB();
                 ^
main.cc: In instantiation of 'void Test<T>::print()::IfA::print() [with T = B]':
main.cc:28:9:   required from 'void Test<T>::print() [with T = B]'
main.cc:50:21:   required from here
main.cc:26:17: error: 'struct B' has no member named 'printA'
                 value.printA();
                 ^

*

*Is it a GCC 4.8 bug?

*Or is it GCC 4.7 bug? Maybe the code should not be compiled.

*Or it is a my bug, and I should not rely on the compiler behavior/should not use such approach to implement "static if".

Additional info:
This simple code compiles on 4.7, but not on 4.8. I shortened it.
struct A {
    void exist() {
    }
};

template <typename T>
struct Test {
    void print() {
        struct LocalClass {
            constexpr LocalClass(T &value) : value(value) {
            }
            T &value;
            void print() {
                value.notExist();
            }
        };
    }
    T value;
};

int main() {
    Test<A>().print();
}

Errors:
main.cc: In instantiation of 'void Test<T>::print()::LocalClass::print() [with T = A]':
main.cc:16:9:   required from 'void Test<T>::print() [with T = A]'
main.cc:22:21:   required from here
main.cc:14:17: error: 'struct A' has no member named 'notExist'
                 value.notExist();
                 ^

Have tested two GCC 4.8 versions: 2012.10 and 2013.02. Hope it is GCC 4.8 bug and it can be fixed.

A: LocalClass is not a template. The "not instantiated if not used" rule is only applicable to member functions of class templates.
That is, when Test::print() is instantiated, everything that is inside is brought to life, including the unused member of its local class.

A: There is no SFINAE in your code.
SFINAE applies during template argument deduction and argument substitution (the 'S' in SFINAE stands for substitution) but the only substitution in your program happens when substituting A for T in the template parameter list of Test, which doesn't fail.
You then call print() which instantiates Test<A>::print(), which doesn't involve any substitution, and you get an error because value.notExist(); is not valid.
SFINAE has to be used in substitution contexts, such as template argument deduction caused by a function call or when deducing template parameters with default arguments.


text:
Q: Performance issue using mediumtext causing slow page speed I've been analysing my website's performance using Google PageSpeed Insights, and the main issue it's reporting is slow server response times, which seem to average around 1.5 - 2 seconds. Google recommend trying to achieve 200ms, so I'm way off.
What I've established is that the queries to retrieve the data from the database are causing quite significant performance issues.  My website makes extensive use of caching to retrieve the sections of the website. The entire webpage can usually be generated from 5 database queries from the cache table.
When I hard-code my return value to this (note the 'This is a test' selection):
$sql = "SELECT 'This is a test'
        FROM cache
        WHERE url = ?
         AND language = ?
         AND currency = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_param('sss', $url, $language, $currency);
if (!$stmt->execute()) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_result($cache);
$stmt->fetch();
$stmt->close();

The server response speed drops to 0.5 seconds.  When I put it back to select the actual data column page_body, like this:
$sql = "SELECT page_body
        FROM cache_copy
        WHERE url = ?
         AND language = ?
         AND currency = ?";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_param('sss', $url, $language, $currency);
if (!$stmt->execute()) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_result($cache);
$stmt->fetch();
$stmt->close();

The the server response time jumps consistently to 1.5 - 2 seconds for the 5 queries the website makes to the cache table.
The cache table only contains 8,000 rows and I think I've correctly indexed it. The column page_body is a mediumtext - does anyone know of performance-related issues using mediumtext?  I just can't figure why it would add 1.5 seconds to the load time.
Here is the DDL for the cache table:
CREATE TABLE `cache` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(255) NOT NULL,
  `language` varchar(2) NOT NULL,
  `currency` varchar(3) NOT NULL,
  `page_body` mediumtext NOT NULL,
  `cached_time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `url, language, currency` (`url`,`language`,`currency`) USING BTREE,
  KEY `cached_time` (`cached_time`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Any ideas?
Many thanks

A: How many rows does it return?  If it returning only 1 row, it should be well under 200ms.
Oh!  Is see the problem.  You are using MyISAM.  Don't.  Switch to InnoDB.
If the real table is like cache, you will get virtually the same speed from it.  I suggest your get rid of the cache.


text:
Q: How to get the distribution name from a spicy.stats. frozen distribution? Access to a Frozen Distribution's Name
When creating a frozen distribution from the scipy.stats package, how can the distribution's name be accessed once the distribution instance is frozen?  Trying to access the .name attribute produces an error since it is no longer an attribute of the rv variable.
import scipy.stats as stats

# Get the name of the distribution
print 'gamma :', stats.norm.name

# Create frozen distribution
rv = stats.norm()

# Get the name of the frozen distribution
print 'rv    :', rv.name

gamma : norm
rv    :

 ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      9
     10 # Get the name of the frozen distribution
---> 11 print 'rv    :', rv.name

 AttributeError: 'rv_frozen' object has no attribute 'name'

A: The Frozen Distribution rv_frozen Class
The frozen distribution, or rv_frozen class creates an instance of the distribution during initialization and this is stored in the self.dist attribute. To access attributes of the original distribution, use rv.dist.{attribute}.
import scipy.stats as stats

# Get the name of the distribution
print 'gamma :', stats.norm.name

# Create frozen distribution
rv = stats.norm()

# Get the name of the frozen distribution
print 'rv    :', rv.dist.name

gamma : norm
rv    : norm


text:
Q: How to aggregate records in django based on multiple criteria Lets say, I have following models in my Django app.
class EventGroup
    name = models.CharField()

class Event(models.Model):
    name = models.CharField()
    group = models.ForeignKey(EventGroup)

class Severity(models.Model):
    name = models.CharField()
    group = models.ForeignKey(EventGroup)

class LogEntry(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    event = models.ForeignKey('Event')
    severity = models.ForeignKey('Severity')

What is the optimal way to find latest log entries of each severity for each event in a group? That is, if I have an event group with some severities and some events related to it, I would expect to get a list of latest log entries for each combination of severity and event.

A: The most straight forward way would be something along the lines of:
groups = EventGroup.objects.all()
for group in groups:
    for event in group.event_set.all():
        LogEntry.objects.filter(event = event).latest('timestamp')

This will hit the database multiple times.
Another way would be to start with the LogEntry model. This approach requires fewer queries.
groups = EventGroup.objects.all()
for group in groups:
    LogEntry.objects.select_related().filter(event__group = group).latest('timestamp')

Warning: I haven't tested this code. This is working for me.


text:
Q: CreationException intermittently with Struts2 application on JBoss7.1.1 I have an application developed in Struts2 and it is deployed on JBoss 7.1.1. We have used CDI for injecting the dependencies.
I have included below in Struts.xml: <constant name="struts.objectFactory.cdi.jndiKey" value="java:comp/some/weird/BeanManagerReference" />
Also included cdi-api-1.0-SP1.jar and struts2-cdi-plugin-2.3.4.1.jar jars along with other required jars for the application.
Intermittently I am getting the below exception and my server needs a restart to solve this.
Unable to instantiate Action, com.action.SearchAction,  defined for 'searchAction' in namespace '/'null
        com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:316)
        com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
        com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
        org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)

    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
        com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
        org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:553)
        org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
root cause
javax.enterprise.inject.CreationException
        sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        java.lang.Class.newInstance0(Class.java:355)
        java.lang.Class.newInstance(Class.java:308)
        org.jboss.weld.util.reflection.SecureReflections$16.work(SecureReflections.java:343)
        org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
        org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInstantiation(SecureReflectionAccess.java:173)
        org.jboss.weld.util.reflection.SecureReflections.newInstance(SecureReflections.java:340)
        org.jboss.weld.injection.Exceptions.rethrowException(Exceptions.java:33)
        org.jboss.weld.injection.Exceptions.rethrowException(Exceptions.java:45)
        org.jboss.weld.injection.Exceptions.rethrowException(Exceptions.java:85)
        org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:125)
        org.jboss.weld.bean.ManagedBean.createInstance(ManagedBean.java:333)
        org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.produce(ManagedBean.java:200)
        org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:289)
        org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:61)
        org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:616)
        org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:681)
        org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:118)
        org.jboss.weld.util.Beans.injectBoundFields(Beans.java:703)
        org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:712)
        org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:161)
        org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:48)
        org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:157)
        org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:131)
        org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:153)
        org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:290)
        org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:61)
        org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:616)
        org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:681)
        org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:118)
        org.jboss.weld.util.Beans.injectBoundFields(Beans.java:703)
        org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:712)
        org.jboss.weld.manager.SimpleInjectionTarget$1.proceed(SimpleInjectionTarget.java:106)
        org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:48)
        org.jboss.weld.manager.SimpleInjectionTarget.inject(SimpleInjectionTarget.java:102)
        org.apache.struts2.cdi.CdiObjectFactory.buildBean(CdiObjectFactory.java:163)
        com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
        com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:121)
        com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
        com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
        com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
        org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
        org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
        com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
        org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:553)
        org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)

Please let me know how to solve this.

A: The problem is that you're including app server provided JARs in your WAR file.  Do not include the API jars for CDI, etc.


text:
Q: How do I properly implement a binary search algorithm to guess a random BigInteger in Java? I am writing a program that is supposed to guess a randomly generated BigInteger from another program. The number class gives feedback on whether my guess was higher or lower than the number ("correct" if the answer is correct).  While my program works fine and correctly guesses the BigInteger, my binary search algorithm I implemented is performing less efficiently than I expected. I have been racking my brain and can't figure out why the number of guesses (after the bit is found) exceeds log(n) time.
I've been counting the number of guesses guesses and the first part of my code (that finds the proper bit of the big int) performs exceptionally well, usually only requiring a handful of guesses.
public static BigInteger guesser(Number n) {
    int guesses=0;

    String feedback = n.guess(BigInteger.ONE);
    guesses++;

    if (feedback.equals("correct")){
        return BigInteger.ONE;

    } else{
        BigInteger two = new BigInteger("2");
        BigInteger max = two;
        BigInteger min = max;
        BigInteger mid;

        if(n.guess(max).equals("correct")) {
            return max;
        }

        while (!feedback.equals("lower")) {
            min = max;
            max = max.pow(2);
            feedback=n.guess(max);
                    guesses++;
        }

        mid = min.add(max).divide(two);
        feedback = n.guess(mid);
            guesses++;

        while (!feedback.equals("correct")){
            if (feedback.equals("higher")){
                min=mid.add(BigInteger.ONE);
            } else if (feedback.equals("lower")){
                max=mid.subtract(BigInteger.ONE);
            }
            mid= min.add(max).divide(two);
            feedback = n.guess(mid);
                guesses++;
        }
        return mid;
    }

The binary search algorithm portion of the code racks up a huge number of guesses and I can't figure out why. For a 38119 bit BigInteger, it takes the program approximately twice that number of guesses. Am I doing something fundamentally wrong or is there a simple error here that I'm overlooking? Shouldn't the number of guesses be approximately equal to 2log(n)?

A: Problem is that you are going too high with exponential search. When the number is big enough the first number you find is a lot higher than it needs to be.
Let's say the number you want to guess is 43263289412904812894021841098214912804215324, looking for the upper range by applying pow(2) the first number you are gonna hit is 115792089237316195423570985008687907853269984665640564039457584007913129639936 - that is so much higher, it takes so much attempts just to return back to close proximity.
Now lets say you applied multiply(new BigInteger("25")) instead - the first number you hit is 43368086899420177360298112034797668457031250. Yes, it takes more attempts to get to that number, but it's worth it in the end, because the last pow(2) on such a huge number creates so big overkill that it's hard to come back. I used a small number here, but it gets worse and worse with bigger numbers.
In my opinion - you should find balance between applying pow and multiplication while finding the upper bound. Maybe if a number is big enough then stop exponentiation and start multiplication by some value and make this value higher as the bound gets higher.
I used a small value in my example above, but with 38119 bit BigInteger:

*

*pow(2) - upper bound 17 guesses - all guesses 65552

*multiply(new BigInteger("25")) - upper bound 8209 guesses - all guesses 46327

*multiply(new BigInteger("100")) - upper bound 5738 guesses - all guesses 43854

*multiply(new BigInteger("1000")) - upper bound 3826 guesses - all guesses 41946

*multiply(new BigInteger("10000")) - upper bound 2870 guesses - all guesses 40994

*multiply(new BigInteger("50000")) - upper bound 2443 guesses - all guesses 40562

*multiply(new BigInteger("100000")) - upper bound 2296 guesses - all guesses 40416

It takes a lot more guesses to get to the upper bound, but then we are a lot closer to the final value, so it's still worth it. Notice that it stops being worth at some point.


text:
Q: Flip Language content in Salesforce Email Template based on contact language preference We have a custom field on Contact > Language Preference.
Currently it holds English and French values.
We want to create a auto-response template that will show both English and French to the contact when say a Case is created.

Now the requirement is to show English content at top and French content at bottom if contact's language preference is English and show French content at top and English content at bottom if contact's language preference is French.

I could not find any other question on the same here in forum.
Please advise on if we can achieve that and how?
Thank you!


text: Q: SharePoint 2013 Apps to Apps Communication I am having the requirement that I have two apps[Client App Parts]. The user is trying to drag some items from App1 to App2, App2 do some action. This functionality is available in SP 2013. I have added two SP 2013 Document library apps. But SP 2013 not allowed to drag item from App1 to App2, but it is allowed to drag the item from App1 to App2[Which is listed in Recent Items]. I'm aware that App-2-App communication is not possible in SP 2013. Is it anyway to implement this scenario in SP 2013?


text:
Q: Typescript async and this scope I've set up a simple service to pull data from a db, the service works fine but when I try to take the data from the service and into a component via an aysnc function, I can't seem to pass the scope of the function through using "this".
Any ideas? I must be doing something obviously wrong as I'm new to development.
Here's the service code which works fine;
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class VenueserviceService {

  constructor(private http: HttpClient) { }

  httpGetFeatures() {
    console.log("inFeatures")
    this.http.post("http://******************",
  {
         "command": "get_feature",
         "classes":"F,G"
  })

  .subscribe(
         (val) => {
        console.log("inSubscribe")
        console.log(val)
          return(val)
          //this.parseFeatures(val)
         },
         response => {
         console.log("POST call in error", response);
         },
                 () => {
  });
  }

  parseFeatures (val: any) {
    console.log("in parse Features")
    console.log(val)
  }

}

and here is the component TS, the problem is "this" throws an error because  it's undefined as I believe the scope of this isn't being passed through. Its the final async function at the bottom.
import { Component, OnInit } from '@angular/core';
import * as data from "./testfile.json";
import * as catdata from "../categories/cattestfile.json";
import {VenueserviceService} from "../../services/venueservice.service"

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

  constructor(private venueService: VenueserviceService) { }

  panelOpenState = false;
  title = 'Cotswolds Destinations';

  venues: any = (data as any).default;

  categories: any = (catdata as any).default;

  formatLabel(value: number) {
    if (value >= 1000) {
      return Math.round(value / 1000) + 'm';
    }

    return value;
  }

  value = 'Clear me!';

  ngOnInit(): void {
    console.log("Homepage Start");
    console.log(this.categories);
    console.log(this.venues);
    console.log(data);
    console.log(this.venues.name);
    for(var i=0; i < this.venues.length; i++){
    console.log(this.venues[i]);
    }
    console.log("Homepage End");
    let categories = this.venueService.httpGetFeatures()

    console.log(categories)

  }
}

const getData =  async () => {
  const data  = await this.venueService.httpGetFeatures()
  console.log(data)
}

A: What I'd suggest is you do this
Service File
    httpGetFeatures() {
        console.log("inFeatures")
        return this.http.post("http://cotswoldsdestinations.co.uk:8443",
        {
            "command": "get_feature",
            "classes":"F,G"
        })
    }

Component File
fetchedData:any;
const getData =  async () => {
  this.venueService.httpGetFeatures()
    .subscribe( data => { this.fetchedData = data });
}

A: 1st, you haven't returned anything in VenueserviceService.httpGetFeatures, it's return type is void.
2nd, you are expecting a promise in your getData lambda function, as you are using asyc-await syntax. Either do this:
httpGetFeatures() {
  return this.http.post("http://cotswoldsdestinations.co.uk:8443",
  {
    "command": "get_feature",
    "classes":"F,G"
  }).toPromise();
}

Or just subscribe to returned observable without awaiting:
httpGetFeatures() {
  return this.http.post("http://cotswoldsdestinations.co.uk:8443",
  {
    "command": "get_feature",
    "classes":"F,G"
  });
}
const getData = () => {
  this.venueService.httpGetFeatures().subscribe(data =>
    console.log(data);
  );
}

This is all ok if you defined getData within some component that has venueService: VenueserviceService passed via DI in it's constructor.
For it to work properly, define getData as a member of Home page component's class, e.g.:
export component HomePageComponent {
  constructor(private venueService: VenueserviceService) {}

  getData() {
    this.venueService.httpGetFeatures().subscribe(data =>
      console.log(data);
    );
  }
}


text:
Q: If an antenna must be $\frac{1}{4}$ of the wavelength, how can car antennas be so small? If the transmission antenna has to be $\frac{1}{4}$ of the wavelength, how can the car antennas' size  be much less than that and properly receive the radio signal?

A: With a resonant antenna, the reactance (capacitive and inductive) should be zero.  Short antennas are usually capacitive so that capacitive reactance is offset using an inductor.  Often for an AM radio a loop inductance is included.  Also, some antennas are longer than they appear because the conductor is wrapped around the core of the antenna (sometimes you can see this).
And, note that a short antenna is an inefficient antenna but often AM signals are so strong that the poor efficiency is not an issue.  The antenna length is much closer to the 1/4 wavelength needs of the FM frequencies.
To get the full 411 on antenna design and matching issues, consider taking a look at the most recent ARRL Antenna Book.  I think the most recent is the 22nd edition.  You might find it in your local library or you can buy a copy from the ARRL store at http://www.arrl.org.

A: It doesn't really matter if you're talking about transmission or reception; the answer is basically the same. A quarter-wave antenna for the commercial AM band would be about 80 meters long, which would clearly be impractical for a receiving antenna. The gain is lower because it's not resonant, but that's OK, you just amplify. You can amplify a lot because although noise is also picked up, the antenna is equally insensitive to noise and signal, so the signal-to-noise ratio is still OK after amplification.

A: The idea behind the quarter wavelength antenna is that it is self-resonant: it is "tuned". You can however use an antenna of any size to pick off some electromagnetic energy - and you can tune the antenna by adding some inductance in series (or inductance and capacitance). The reason that you tune an antenna is simply this: you want it to have real impedance, which happens exactly at resonance. When this happens, then all the power that is incident on the antenna ends up going into the electronics; when the impedance is complex, the current either lags or leads the voltage, and this results in reflection of the power (and less power going into the amplifier).
You can't get around the fact that you are "capturing" energy from less area in space, so it will be less efficient. On the other hand having an antenna that is too long doesn't buy you anything as the signal from one part of the antenna would cancel the signal from another.
This is one of the beautiful things about the Yagi antenna: the multiple elements are spaced in such a way that they cause constructive interference along a particular axis, giving you both gain and directionality - in essence you are capturing energy from a larger volume of space.
Little anecdote: from wikipedia article on Yagi-Uda antenna

The Yagi was first widely used during World War II for airborne radar sets, because of its simplicity and directionality. Despite its being invented in Japan, many Japanese radar engineers were unaware of the design until very late in the war, partly due to rivalry between the Army and Navy. The Japanese military authorities first became aware of this technology after the Battle of Singapore when they captured the notes of a British radar technician that mentioned "yagi antenna". Japanese intelligence officers did not even recognise that Yagi was a Japanese name in this context. When questioned, the technician said it was an antenna named after a Japanese professor.

I have heard it said that the inventor was executed during WW-II by the Japanese because his invention "helped the enemy". I can't find a reference to support that. Apparently he wasn't even the inventor - it was Uda. But Yagi published it, patented it, and even sold the rights to Marconi (before the war). It would be karma if he ended up paying the ultimate price for stiffing the real inventor...  "No, it wasn't me! But Professor, your name is on the patent... off with his head." In fact it is apocryphal - a bit more searching reveals that he died in 1976.

A: Antennas don't have to be sized to the wavelength of the signal. It just happens, that if they are significantly smaller than a quarter wavelength, the sensitivity drops very quickly with antenna size. That, by the way, is also an enormous advantage for electronics design of switched mode power supplies. If the transmission efficiency wouldn't drop, our switched mode power supplies would need very expensive shielding to prevent them from being efficient transmitters. As it is, we can get away with very little, very cheap shielding because the circuit sizes are small fractions of the antenna size required at those frequencies.

A: Antennas don't have to be sized to the wavelength of the signal. It just happens, that if they are significantly smaller than a quarter wavelength, the sensitivity drops very quickly with antenna size. That, by the way, is also an enormous advantage for electronics design of switched mode power supplies. If the transmission efficiency wouldn't drop, our switched mode power supplies would need very expensive shielding to prevent them from being efficient transmitters. As it is, we can get away with very little, very cheap shielding because the circuit sizes are small fractions of the size that would be required of an efficient antenna at those frequencies.
There is, by the way, absolutely no difference between receiving and transmitting antennas. The efficiency hit is the same for both types.


text:
Q: PHP decreasing date('Y-m-d', strtotime(x days')) by (x-1) in while loop I'm trying to decrease a counter variable (x) within this date function:
date('Y-m-d', strtotime(x days'))

in a while loop like this:
$Today = date('Y-m-d', strtotime('-1 days'));

output thus far: 2015-06-25
$x = -1;

while ($row = mysql_fetch_array($result1)) {

$Today = date('Y-m-d', strtotime('$x days'));

...

$x = $x - 1;
}

desired output on next iteration of while loop: 2015-06-24 and so on ...

A: What you have already will work, except that it has to be done with a double quoted string to interpolate the variable, as in strtotime("$x days") –  @Michael Berkowski


text:
Q: Extracting relevant information from a long string of ffmpeg data I'm aware later versions of ffmpeg seem to present this information in a more accessible form, but my application is running on an old version for many reasons right now.
Is it possible to extract

*

*Format: flv (located after Input #0, )

*Duration: 00:05:23.20 (located after Duration: )

*Bitrate: N/A (located after bitrate: )

*Video: h264, yuv420p, 640x360 [PAR 1:1 DAR 16:9] (located after Video: )

*Audio: aac, 44100 Hz, mono, s16 (after Audio: )

In the knowledge that these figures/strings might change. It seems like a mammoth task in string searches to me, one I've often struggled with and eventually contemplated suicide. Is there a 'quick way'? or any widely applicable logic to getting this stuff.
... [flv @ 0xa3d3440]skipping flv packet: type 18, size 268, flags 0 Seems stream 0 codec frame rate differs from container frame rate: 50.00 (50/1) -> 25.00 (25/1) Input #0, flv, from '/var/www/vhosts/test/htdocs/5tester.flv': Duration: 00:05:23.20, start: 0.000000, bitrate: N/A Stream #0.0: Video: h264, yuv420p, 640x360 [PAR 1:1 DAR 16:9], 25 tbr, 1k tbn, 50 tbc Stream #0.1: Audio: aac, 44100 Hz, mono, s16 At least one o...

Thanks in advance for any help.

A: Use regular expressions and try to match your target strings... see preg_match_all
second way of achieving this is to use PHP's explode().


text:
Q: Trouble overlaying one div with another with JavaScript & CSS Here is my goal:

*

*When the user hovers a div of class "item" another div of class "menu" should appear overlaying the "item" div.

*The position of the "menu" div should be relative to the "item" div.

*When the user unhovers the item "div" the menu div should disappear.

*When the user mouses over the "menu" div the "menu" div the "menu" div should not disappear so that user can click a button in it.

I am looking for a JavaScript and CSS solution. If you can help but you can only post a JQuery solution I will still appreciate it but I will have to translate it to straight JavaScript.
So far I have tried:

*

*To make the "hover" div an absolutely positioned child of the document.body. This works for positioning, but hovering the "hover" div unhovers the "item" div and I don't know how to figure out that the new hovered div is the "hover" div.

*To make the "hover" div a absolutely or fixed positioned child of the "item" div. This places the "hover" div underneath the "item" div and style.top seems to have no effect on the "hover" div".

*To make the "hover" div a relatively positioned child of the "item" div. This places the "hover" div within the "item" div and increases the size of the "hover" div, which I don't want.

Thank you for your help with this!
Here is a JSFiddle that is a starting point for a solution https://jsfiddle.net/ypn5f1ng/
HTML

    content

item 1

item 2

    more content

CSS
body {  background:green; }

#content { z-index:100; width:500px; position:absolute; left:0px; right:0px; margin-left:auto; margin-right:auto; background:white; margin-top:10px;  background:lightblue; padding:5px; }

div.item { background:pink; margin:5px}

div.hover { background:yellow; height:15px; width:100px; z-index:101; position:fixed }

JavaScript
function getElem(event) {
    if (!event) {
        event = window.event;
    }

    var elem = null;
    if (event.target) {
        elem = event.target;
    } else if (event.srcElement) {
        elem = event.srcElement;
    }

    if (elem && elem.nodeType == 3) {
        elem = elem.parentNode;
    }

    return elem;
}

var hoverDiv = null;

function onItemMouseOver(event) {
    var elem = getElem(event);

    if (!hoverDiv) {
        hoverDiv = document.createElement('DIV');
        hoverDiv.className = "hover";
        document.body.appendChild(hoverDiv);
        //elem.appendChild(hoverDiv);
        hoverDiv.style.right=100;
        hoverDiv.style.top=-100;
    }
}

function onItemMouseOut(event) {
    if(hoverDiv) {
        hoverDiv.parentNode.removeChild(hoverDiv);
        hoverDiv = null;
    }
}

var items = document.getElementsByClassName("item");
for(var i = 0; i < items.length; ++i) {
   var item = items[i];
   item.onmouseover = onItemMouseOver;
   item.onmouseout = onItemMouseOut;
}

A: fiddle
HTML

        asfdwa

CSS
.a {
    position: relative;
    width: 300px;
    height: 300px;
    background: lightgray;
}

.b {
    position: absolute;
    top: 0;
    left: 0;
    width: 300px;
    height: 80px;
    background: pink;
    opacity: 0;
    transition: .2s opacity ease-in-out;
}

.b a {
    display: block;
    margin: 1rem;
}

.a:hover .b {
    opacity: 1;
}

A: The best approach is to use CSS only if possible (no JS).
In this situation, I would recommend to put the div you would like to display on hover into the div that is the trigger.

        ...

    ...

Than the CSS would look like this:
div.child {
    display: none;
}
div.parent:hover div.child {
    display: block;
}

With this technique you can position the child even to get outside the parent and it will not disappear if you get out of the parent if you are still on the child since the child is technically (not visually) in the parent. You just need to make sure that the parent at least touches the displayed child since the child will disappear if you travel over the gap between them with your cursor (the cursor won't be on the parent nor on the child)


text:
Q: Как получить URL пользователя vk, facebook куда он расшарил ссылку? Добрый день,
На сайте имеются кнопки поделиться для VK и facebook. Если пользователь решает поделиться, то как узнать URL его странички куда он добавил информацию о нашем сайте?

A: Никак.
Наличие подобной возможности являлось бы серьёзной уязвимостью, позволяющей сайту, на котором размещена ссылка на сторонний ресурс, иметь доступ к данным пользователя, авторизованном на этом ресурсе.


text:
Q: (R, dplyr) How to aggregate-window data where rows must be conditionally included? I've googled around, but have not found anything similar to this, but I'm hoping what I'm trying to do has already been done by someone else before.

*

*I have a set of data with timestamps.

*I need a running cumulative count of transactions per second - calculated as a true rolling second window.  Would be nice to just truncate / round off to nearest second but that wont be enough for my use case.

#Timestamp
Current TPS

00:00:00.1
1
................................................................................................

00:00:00.2
2

00:00:00.3
3

00:00:00.4
4

00:00:00.5
5

00:00:00.6
6

00:00:00.7
7

00:00:00.8
8

00:00:00.9
9

00:00:01.0
10
....................................10 TPS here............................................................

00:00:01.1
10

00:00:01.2
10
.................................... still 10 TPS here............................................................

00:00:01.4
9
............ only 9 here, because no event at 00:00:01.3

00:00:01.5
9

00:00:01.5
10

00:00:01.8
8

Initially, I was planning to calculate a time interval difference between rows, but that doesn't solve the question of how to determine which rows should be included or excluded in the aggregate window.
This morning, I thought about mutating a new column that is just the subsecond portion of time. Then, I use that new column as a substraction on the time column, and cumsum it inside a 2nd if_else mutate that does a look-back over last X number of rows?
Does that sound reasonable? Have I overlooked some other/better approach?

A: library(dplyr)

timestamps <- c("00:00:00.1", "00:00:00.2", "00:00:00.3", "00:00:00.4", "00:00:00.5", "00:00:00.6", "00:00:00.7", "00:00:00.8", "00:00:00.9", "00:00:01.0", "00:00:01.1", "00:00:01.2", "00:00:01.4", "00:00:01.5", "00:00:01.5", "00:00:01.8") %>%
  lubridate::hms %>%     # convert to a time period in hours minutes seconds
  as.numeric  # convert that to a number of seconds

slider::slide_index_dbl(timestamps,
            timestamps,
            ~length(.x),   # = how many timestamps are in the window
            .before = .99)  # Note: using 1 here gave me an incorrect result,
            # presumably due to floating point arithmetic errors
            # https://en.wikipedia.org/wiki/Floating-point_error_mitigation
[1]  1  2  3  4  5  6  7  8  9 10 10 10  9 10 10  8


text:
Q: How to log the correct timezone with log4j which is parsable by logstash I have problems logging the correct datetime in log4j and parse it with logstash.
I set up a tomcat with log4j (1.2.17) and a little application which just produces some logs.
I logged the time with %d{ISO8601}
The result was that the timezone was missing and logstash thought it was UTC, because i parsed it with.
date {
    type => "tomcat"
            match  => [ "orig_timestamp", "ISO8601"]
    }

After that I tried the following:
                <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="%d{ISO8601}%d{Z} %-5p %50.50c - %m%n" />
                </layout>

but that resulted in following error in logstash:
{:timestamp=>"2013-10-17T19:13:12.977000+0200", :message=>"Failed parsing date from field", :field=>"orig_timestamp", :value=>"2013-10-17 19:00:02,059+0200", :exception=>java.lang.IllegalArgumentException: Invalid format: "2013-10-17 19:00:02,059+0200" is malformed at " 19:00:02,059+0200", :level=>:warn}

I think the : are missing in the offset. But how can I do it without all that manual try and error? Cant I just say print iso8601 with timezone and parse ISO8601 with timezone?

A: Slight amendment to the above answer, I think the hours need to be HH instead of hh to make them support the 24 hour clock.
%d{yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ}

A: My solution was to use %d{yyyy-MM-dd'T'hh:mm:ss.SSSZZZZ}


text:
Q: How to remove # sign in input type in edittext in android Hi I had added android:inputType="number" in  Edittext. I want add "+" sign also.
I want nothing except "+" sign and "number" as a input.User willnot be able to add # sign.
Is there any way?

A: I would get the user halfway there by specifying
android:inputType="phone"
android:hint="+1235554444"

and then programmatically checking that their input follows your required template, since the phone input type does allow #.
//First ensure the input starts with "+"
if(!phoneString[0].equals("+"){
    //Error
}

for(i = 0; i < phoneString.length() ; i++){
    if(phoneString[i].equals("#"){
        //Error
}

Add any other error checks you can think of.


text:
Q: Can't connect to IBMMQ MQRC_NOT_UNAUTHORIZED I have installed IBMMQ 9.0 in windows running in virtualbox in my local and I have sample java code sending message to MQ.
here is the java code
 MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
 cf.setHostName(MY_IP);
 cf.setPort(1417);
 cf.setTransportType(WMQConstants.WMQ_CM_CLIENT);
 cf.setQueueManager("QM1_TEST");
 cf.setChannel("QM1_TEST.CH");
 MQQueueConnection connection = (MQQueueConnection)
 cf.createQueueConnection();
 MQQueueSession session = (MQQueueSession)
 connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
 MQQueue queue = (MQQueue) session.createQueue("queue:///QUEUE_TEST");
 MQQueueSender sender = (MQQueueSender) session.createSender(queue);
 String message = "Test Message";
 TextMessage textMessage = (TextMessage)
 session.createTextMessage(message);
 connection.start();
 sender.send(textMessage);

The program receives this error.
com.ibm.msg.client.jms.DetailedJMSSecurityException: JMSWMQ2013: The
security authentication was not valid that was supplied for QueueManager
'QM1_TEST' with connection mode 'Client' and host name '192.168.0.24(1417)'.
Please check if the supplied username and password are correct on the
QueueManager to which you are connecting. at
com.ibm.msg.client.wmq.common.internal.Reason.reasonToException(Reason.java:531)
at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:215)
at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:424)
at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createV7ProviderConnection(WMQConnectionFactory.java:8475)
at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createProviderConnection(WMQConnectionFactory.java:7815)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl._createConnection(JmsConnectionFactoryImpl.java:303)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.createConnection(JmsConnectionFactoryImpl.java:236)
at com.ibm.mq.jms.MQConnectionFactory.createCommonConnection(MQConnectionFactory.java:6016)
at com.ibm.mq.jms.MQQueueConnectionFactory.createQueueConnection(MQQueueConnectionFactory.java:111)
at com.cwt.bpg.cbr.demo.ibm.mq.client.SendMessage.main(SendMessage.java:24)
Caused by: com.ibm.mq.MQException: JMSCMQ0001: IBM MQ call failed with compcode '2' ('MQCC_FAILED') reason '2035' ('MQRC_NOT_AUTHORIZED').
at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:203)
... 8 more

Here is the log under my queue manager with significant details.
5/21/2018 16:42:46 - Process(4984.8) User(MUSR_MQADMIN) Program
(amqrmppa.exe) Host(MSEDGEWIN10) Installation(Installation1) VRMF(9.0.0.0)
QMgr(QM1_DEV) AMQ9776: Channel was blocked by userid
EXPLANATION:
The inbound channel 'QM1_DEV.CH' was blocked from address '10.xx.xx.xx'
because the active values of the channel were mapped to a userid which
should be blocked. The active values of the channel were 'MCAUSER(IEUser)
CLNTUSER(IEUser) ADDRESS(LWPHL1U012FXP)'

A: You are not providing a user and password, your are connecting with the default user identity.
QueueConnection createQueueConnection()
Creates a queue connection with default user identity.

You can either provide credentials:
QueueConnection createQueueConnection(String userid,String password)

By default the userid and password for any user in the mqm group on the MQ broker will have access to the queue managers.
The IBM MQ docs also have instructions for disabling security altogether.


text:
Q: Combine two generators and preserve send method I have a generator that I can send values to using the generator.send() method. I'd like to add to this generator after it has been made and continue using the same functions to iterate through it. I tried itertools.chain, but that returns an iterator and I get an AttributeError when I try to send values to it.
How can I combine two generators and preserve the ability to send values to them?

A: You can use yield from (refer to the docs and this answer for more details):
def multi_generator(*gens):
    for gen in gens:
        yield from gen


text:
Q: Execution of stored function using spring's SimpleJdbcCall not giving output I am trying to call a stored function using spring's SimpleJdbc call. I have written a simple function which takes two numbers as input and returns their sum. I am using Oracle 11.2g as the database. I am not getting any exceptions but at the same time not getting the result either. The function works well when called from an anonymous PL/SQL block through sql-plus. The code is as follows:
SimpleJdbcCall _simpleJdbcCall=new SimpleJdbcCall(this.jdbcTemplate);
_simpleJdbcCall.withCatalogName("BROADCASTSHEETMANAGEMENT");
_simpleJdbcCall.withSchemaName("PPV");
_simpleJdbcCall.withFunctionName("TEST");
_simpleJdbcCall.withoutProcedureColumnMetaDataAccess();

_simpleJdbcCall.declareParameters(new  SqlParameter("newChangeSequence",java.sql.Types.NUMERIC));
_simpleJdbcCall.declareParameters(new SqlParameter("number1",java.sql.Types.NUMERIC));
_simpleJdbcCall.declareParameters(new SqlParameter("number2",java.sql.Types.NUMERIC));

MapSqlParameterSource mapSqlParameterSource1=new MapSqlParameterSource();
mapSqlParameterSource1.addValue("newChangeSequence", Integer.valueOf(0));
mapSqlParameterSource1.addValue("number1", Integer.valueOf(10));
mapSqlParameterSource1.addValue("number2", Integer.valueOf(20));

    newChangeSequence = _simpleJdbcCall.executeFunction(Integer.class,mapSqlParameterSource1);

System.out.println("Returned changeSequence is: " + newChangeSequence);

The stack trace shows following information:
2013/12/19 18:52:53,604 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - Added declared parameter for [TEST]: newChangeSequence
2013/12/19 18:52:53,604 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - Added declared parameter for [TEST]: number1
2013/12/19 18:52:53,604 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - Added declared parameter for [TEST]: number2
2013/12/19 18:52:53,605 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - JdbcCall call not compiled before execution - invoking compile
2013/12/19 18:52:53,608 [main] - [] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
2013/12/19 18:52:53,609 [main] - [] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:oracle:thin:@localhost:1521:orcl]
2013/12/19 18:52:53,647 [main] - [] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Registering transaction synchronization for JDBC Connection
2013/12/19 18:52:53,649 [main] - [] DEBUG org.springframework.jdbc.core.metadata.CallMetaDataProviderFactory - Using org.springframework.jdbc.core.metadata.OracleCallMetaDataProvider
2013/12/19 18:52:53,649 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - Compiled stored procedure. Call string is [{? = call PPV.BROADCASTSHEETMANAGEMENT.TEST(?, ?)}]
2013/12/19 18:52:53,649 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - SqlCall for function [TEST] compiled
2013/12/19 18:52:53,651 [main] - [] DEBUG org.springframework.jdbc.core.metadata.CallMetaDataContext - Matching [number2, number1, newChangeSequence] with [number2, newChangeSequence, number1]
2013/12/19 18:52:53,651 [main] - [] DEBUG org.springframework.jdbc.core.metadata.CallMetaDataContext - Found match for [number2, number1, newChangeSequence]
2013/12/19 18:52:53,652 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - The following parameters are used for call {? = call PPV.BROADCASTSHEETMANAGEMENT.TEST(?, ?)} with: {number2=20, number1=10, newChangeSequence=0}
2013/12/19 18:52:53,652 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - 1: newChangeSequence SQL Type 2 Type Name null org.springframework.jdbc.core.SqlParameter
2013/12/19 18:52:53,652 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - 2: number1 SQL Type 2 Type Name null org.springframework.jdbc.core.SqlParameter
2013/12/19 18:52:53,652 [main] - [] DEBUG org.springframework.jdbc.core.simple.SimpleJdbcCall - 3: number2 SQL Type 2 Type Name null org.springframework.jdbc.core.SqlParameter
2013/12/19 18:52:53,653 [main] - [] DEBUG org.springframework.jdbc.core.JdbcTemplate - Calling stored procedure [{? = call PPV.BROADCASTSHEETMANAGEMENT.TEST(?, ?)}]
2013/12/19 18:52:53,655 [main] - [] DEBUG org.springframework.jdbc.core.JdbcTemplate - CallableStatement.execute() returned 'false'
2013/12/19 18:52:53,655 [main] - [] DEBUG org.springframework.jdbc.core.JdbcTemplate - CallableStatement.getUpdateCount() returned -1
Returned changeSequence is: null

The stored procedure code is:
function test(number1 number, number2 number) return number is
    newChangeSequence number(4);
begin
     newChangeSequence:= number1 + number2;
             return newChangeSequence;
end test;

A: you have to use SqlOutParameter like this:
_simpleJdbcCall.declareParameters.declareParameters(new SqlOutParameter("newChangeSequence",java.sql.Types.NUMERIC));

and please post your stored procedure code too.


text:
Q: Uninstall Visual Studio 2015 Community - Uninstall button disabled? Trying to remove Visual Studio 2015 Community edition (as I am now using 2017) on a Windows 10 desktop computer.
However, when I go the "Apps & Features" the Uninstall button is disabled!

How do you remove VS 2015 Community when this happens without clobbering 2017?
Unfortunately, I inherited this workstation and no one seems to know where the original install disks (if any) are!  I also found Visual Studio 2010 and 2013 exist on this workstation.  I suspect VS 2015 was simply downloaded and installed; hence no original disks per se.
Any suggestions are appreciated.

A: Press the Modify and it will give uninstall option.

A: Thanks for the quick replies -- shortly after I posted, I did manage to find the following (in case anyone else runs into this "feature"):
Uninstalling VS 2010
The following blog lead me to an uninstaller for VS2010:
https://blogs.msdn.microsoft.com/heaths/2010/08/23/visual-studio-2010-uninstall-utility/
The Uninstall archive (for VS2010) is available at:
https://aka.ms/vs2010uninstall
I then ran the command (as per the instructions):
VS2010_Uninstall-RTM.ENU.exe /full

Worked without any issues.
Uninstalling VS2013 and VS2015:
Download the uninstaller from:
https://github.com/Microsoft/VisualStudioUninstaller
Simply run the installer as per the directions given -- BUT BE PATIENT -- It took almost an hour to remove all the components (this may be because my particular system had so many earlier versions installed).
Once the above was done, I was then able to open the control panel and use the "Change" option.   A dialog then opens that includes an "Uninstall" button that was enabled.
I then ran the Visual Studio Installer (2017) and choose Update to make sure everything was up-to-date.
Rebooted -- so far, everything is working and the system dropped a few hundred stale MSIs!

A: You might have to use the software that comes with it if its a new install called visual studio installer. Alos have you tried the old uninstall in windows? You can access it via "Run => Control Panel => Programs => Programs and Features"?

A: At the end and after trying a lot of different things trying to fix my situation, I found out how to solve it.
I went into the VS2017 Installer and then I hit to modify the installation. I just clicked in the box for "asp.net and web development" and then hit again, and it looks like something needed to be downloaded and installed (among the options there was one of IIS Express and it was pre-selected).
After all the process finished, I was able to reopen the solution and the project was automatically loaded as before.


text:
Q: a simple regexp The regexp has to remove ,id or id, in read and unread.
GM_setValue('unreadids', unreadids.replace(new RegExp('('+id+',)|(,'+id+')', 'i'),''));
GM_setValue('readids', readids.replace(new RegExp('('+id+',)|(,'+id+')', 'i'), ''));

In RX Toolkit, (,1|1,) for a test, ,1 or ,1 is replaced with nothing.
In real life...
http://userscripts.org/scripts/show/73562
http://userscripts.org/scripts/review/
...id isn't replaced with nothing.
Why?

A: Your question is kind of hard to understand, I don't think it's clearly explaining what you need to do and what is wrong. I'm not sure if the links clarify as they are broken.
I think I see what you mean, but I may be wrong.
If you have a string like
var test = "(674,)|(,674)"

Where 674 is the "id", and you are trying to replace "674," and ",674" with "" to get "()|()"
Then your code should work fine excepting you need the "g" (global) flag as well to replace ALL instances.
Example:
                    var test = "(674,)|(,674)";
                    var id = "674";
                    var expr = new RegExp('(' + id + ',)|(,' + id + ')', 'gi');
                    var b = test.replace(expr, '');
                    alert(test);
                    alert(b);

You're using the same regular expression twice, so why not just save it?
If you're wondering why it doesn't replace instances of JUST "674" in addition to "674," or ",675"...well that's because you didn't write a regular expression to replace it! Yours only covers it with the commas.
If that IS what you are trying to do, replace ",674" and "674," and just plain "674" with null then here is a regex that will match all of those:
var expr = new RegExp(',?' + id + ',?', 'gi');

? matches the preceding character 0 or 1 times.
If you need to match only instances that occure withing ()|() it's pretty easy to adjust the preceding regex for that, I'll leave it as an exercise for the reader.


text:
Q: C asks an input array of string until it is within a specified length I'm trying to make a code in C where in I'm asking the user to input an array of string, and if their input exceeds the length of 10 then I'm gonna print an error, and then loop back and ask again until they input a string that's lower than 10
What I did was make an 11 digit array, and then an endless for loop, and then make an if statement stating that if the 11th digit is no longer == '/0' then I'll print "error" then made an else as break.
Code:
char x[11];

int main(void) {
    for (;;) {

        printf("Enter String X: ");
        scanf("%s", x);

        if (x[10] != '\0') {
            printf("ERROR\n");
        } else {

            break;
        }
    }

    return (EXIT_SUCCESS);
}

Which works for the most part if I enter equal to or less than 10 digits of strings it works, and if I enter more than 10 then it works as well prompting "ERROR" and asking to input the strings once more,
But the problem is that when I enter more than 10 to prompt the "ERROR", and then enter within the accepted length it will still give me "ERROR" unless i enter the exact length of 10 where it will work

A: It seems you are new to C, when getting string input, the array is assigned with the characters inputted until the length of the input, and following a NULL value ('\0').
You are checking if the last value is NULL, which is probably also the initial value of the array you allocated.
So once you have input "1234567890A", x[10] = 'A'.
Now let's enter "123", now: x = "123\0567890A", and still x[10] = 'A'.
You need to use C's standard strlen, strlen("123\0567890A") -> 3.


text:
Q: Uninstall Microsoft Windows KB3177467 Update How can I uninstall Microsoft Windows KB3177467 Update from Windows Server 2008. When I select this update to be removed, there are no uninstall button and won't even uninstall when I double-click on it.
Why I want to uninstall the update?
I updated the server 3 days ago and since then the clients has been complaining about how slow the website is. I thought it might be the problem with CPU, RAM or bad programming but it wasn't.

A: Servicing stack updates cannot be uninstalled.
As this update has nothing to do with IIS (only patching), it is likely not to blame.


text:
Q: Как ускорить разворачиваение бэкапа MySQL Имеется бэкап баз данных размером чуть более 2Gb. Бэкап сделан штатными средствами через mysqldump.
Разворачивается бэкап на новом сервере очень долго, более 2 часов.
Как можно более быстро развернуть бэкап MySQL? Или как создать более быстрый (для развертывания) бэкап?
PS по структуре этот бэкап состоит из 2000 маленьких баз данных и 1 большой БД (1 очень большая таблица).

A:
Как можно более быстро развернуть бэкап MySQL?

Можно на время развёртывания отключить индексы и внешние ключи, которые затем создать/установить на уже развёрнутых данных. Будет немножко быстрее.

как создать более быстрый (для развертывания) бэкап?

Самый быстрый вариант - использовать тупо файловую копию (Raw Data Backup). Впрочем, восстановление в этом случае не совсем тривиально, хотя и не чрезмерно сложно.
Не самое плохое - отдельный бэкап структуры и отдельный - данных (SELECT INTO OUTFILE + LOAD DATA INFILE). Но и тут отключение индексации способствует.
Ну и вообще неплохо бы внимательно проштудировать официальную документацию по резервному копированию и восстановлению. И не забыть раздел по репликации, там тоже кое-что есть интересного.


text:
Q: Assign new labels based on row condition, update when either of 2 new conditions present In the dataframe below, whenever the row equal to "close short, prior high violation" presents, I would like to repeat "No Trade" for as many rows as needed until either a next row appears with the label of either "open short" or "hold long".
pd.DataFrame({'intraday_action':['close long, upper bb violation',
                                 None,
                                 'open short',
                                'hold short',
                                'hold short',
                                'close short, prior high violation',
                                'hold short',
                                'hold short',
                                'hold short',
                                'hold short',
                                'close short, prior high violation',
                                'hold short',
                                'open short',
                                'open short',
                                'hold short',
                                'close short, lower bb violation',
                                None,
                                None,
                                None,
                                'hold long',
                                'hold long']})

Here is what the output should look like:
pd.DataFrame({'intraday_action':['close long, upper bb violation',
                                     None,
                                     'open short',
                                    'hold short',
                                    'hold short',
                                    'close short, prior high violation',
                                    'No Trade',
                                    'No Trade',
                                    'No Trade',
                                    'No Trade',
                                    'No Trade',
                                    'No Trade',
                                    'open short',
                                    'open short',
                                    'hold short',
                                    'close short, lower bb violation',
                                    None,
                                    None,
                                    None,
                                    'hold long',
                                    'hold long']})

I've tried various instances of str in, ffill(), and np.where statements, but unsure how to bring all together. It may involve creating multiple columns and leveraging the logic from those columns, but unsure.


text:
Q: BottomNavigationView not working with navigation I'm trying to make this BottomNavigationView work with navigation but is giving me head-aches.
I'll explain my setup :
this the fragment of my activity_home.xml
<fragment
        android:id="@+id/nav_host_fragment"
        android:layout_width="match_parent"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_height="match_parent"
        android:layout_marginBottom="?attr/actionBarSize"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />

Also I've tried with FragmentContainerView but is not working neither.
The error is on the navigation/nav_graph.xml as the error says :

Exception inflating package:navigation/nav_graph line 7

Where line 7 is :
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_graph"
    app:startDestination="@id/featureHomeNavGraph">

    <include //Line 7
        android:id="@+id/featureHomeNavGraph"
        app:graph="@navigation/feature_home_nav_graph"/>

    <include
        android:id="@+id/featureFavouritesNavGraph"
        app:graph="@navigation/feature_favourites_nav_graph" />

    ....
</navigation>

Then I've created different layouts for the navigations as :
feature_home_nav_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:startDestination="@id/homeFragment">
    <fragment
        android:id="@+id/homeFragment"
        android:name="package.HomeFragment"
        android:label="HomeFragment" />
</navigation>

And feature_favourites_nav_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:startDestination="@id/favouritesFragment">
    <fragment
        android:id="@+id/favouritesFragment"
        android:name="package.FavouritesFragment"
        android:label="FavouritesFragment" />
</navigation>

Then I think the problem also comes by the implementation on my HomeActivity.kt where I have to setup the navigation stuff... I'm doing it like this :
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
        setSupportActionBar(findViewById(R.id.toolbar))
        val navHostFragment = supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment?
        NavigationUI.setupWithNavController(
            bottomNavigation,
            navHostFragment!!.navController
        )
    }

Also I've tried the NavigationExtension followed on this tutorial but it did not work neither.
Note
I'm using the same id on my items of bottom_menu.xml than on the navigation graph id for the fragments.

A: I guess the feature_home_nav_graph doesn't have an id on the navigation tag?


text:
Q: Using javax.sound.sampled with openjdk-7 on Raspi I'm having big problems getting good sound out of my Raspi using Java.
I want to write an little AirPlay Client to a media server I wrote in Java. I started with using the Player Class from javazoom (http://www.javazoom.net/javalayer/docs/docs1.0/javazoom/jl/player/package-summary.html). Which gave me a not really choppy but somehow distorted and slower than normal playback of an mp3 file I streamed over to the Raspi.
My first idea was, that maybe the decoding of an mp3 was a bit too much for the Raspi, especially since overclocking helped a little.
So now I'm converting the mp3 to a wav file on the server and then stream it to the Raspi playing it with the javax.sound.sampled.* stuff. Yet, no improvement :|
Has anybody some experience with playing soundFiles from Java on an Raspi? Any advice helps!
Thanks, Stefan

A: I suggest you try using JavaFX instead. It is way better than support for media on the standard JDK. Besides, you are already using Java 7, so migrating will be easy. Here is how:
Media media = new Media(Utils.findURI(baseDirName, soundFileName).toString());
SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MediaPlayer mediaPlayer = new MediaPlayer(media);
                mediaPlayer.setCycleCount(1);
                mediaPlayer.play();
            }
        });
    }
});

the implementation of sound in OpenJDK has lots of bugs. One of them is that it abuses the sound system and monopolizes it. So on Linux you have better chances to get things working if you do as above.


text:
Q: MapStruct map fields to target only when target's fields are null I am trying to map this object
public class Source {
  private String value1;
  private String value2;
  private String value3;
}

Into this object
public class Target {
  private String targetValue1;
  private String targetValue2;
  private String targetValue3;
}

This is the Mapper definition.
@Mapper
public interface SourceMapper {
  void toTarget(Source source, @MappingTarget Target target);
}

What I am trying to achieve is only map fields in source into target only when the fields in target are null. For example, source.value1 only maps to target.targetValue1 when target.targetValue1 is null. If it is not null, the mapping for that field is ignored.
Is it possible with MapStruct without having to write custom code?
Edit
I changed the field names of Target to make it clear that the names of the Target may/may not match the names of the fields in Source.

A: I don't think that can be done with mapstruct. If you still want to use mapstruct, you can ignore the target variables that could be null with @Mapping (target =" propName ", ignore = true) and decide yourself with a @AfterMapping method when you set your target variables.

A: You can achieve that by doing the following trick:
first, you need to know that you can control the mapping behavior on 'source' nulls fields
using Mapping.nullValuePropertyMappingStrategy()
So the following should do the work:
Target target = new Target(); // the actual target, first grade values
Source source = new Source(); // the actual source, secund grade values
Target result = new Target(); // the result
SourceMapper.toTarget(source, result); // now you have secund grade value
SourceMapper.toTarget(target, result); /* now you overide the secund grade value only
if the first grade isn't null */

@Mapper
public interface SourceMapper {
@Mapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
void toTarget(Target source, @MappingTarget Target target);

void toTarget(Source source, @MappingTarget Target target);
}