text:
Q: Proxying window object to detect changes Can I proxy the window object to detect changes? I tried the following without any luck:

var handler = {
  get: function(target, property) {
    console.log("getting " + property + " for " + target);
    return target[property];
  },
  set: function(target, property, value, receiver) {
    console.log("setting " + property + " for " + target + " with value " + value);
    target[property] = value;
    return true;
  },
};
var p = new Proxy(window, handler);
setTimeout(() => {
  window.a = 10; // expecting a log, but nothing...
}, 3000);
setTimeout(() => {
  window.c = 20; // expecting a log, but nothing...
}, 4000);

A: You have to reference the Proxy instance in your lower code, not the window:

var handler = {
  get: function(target, property) {
    console.log("getting " + property + " for " + target);
    return target[property];
  },
  set: function(target, property, value, receiver) {
    console.log("setting " + property + " for " + target + " with value " + value);
    target[property] = value;
    return true;
  },
};
var p = new Proxy(window, handler);

setTimeout(() => {
  p.a = 10;    // <------------
}, 300);
setTimeout(() => {
  p.c = 20;    // <------------
}, 400);

If you can't change the code that references the window, you could also name the proxy window (and save a reference to the true window in another variable), but the code for that would look confusing.
If it's in a standalone script file, the above trick won't work, and you won't be able to use a Proxy - you can't redefine the window object, after all. If you're looking for a change for a specific property on window, you could use defineProperty and have the setter overwrite the property descriptor with the new value when it gets assigned to:

Object.defineProperty(window, 'a', {
  configurable: true,
  set(value) {
    console.log("setting with value " + value);
    Object.defineProperty(window, 'a', { value });
  }
});

setTimeout(() => {
  window.a = 10;
  console.log(window.a);
}, 300);


text:
Q: plot gmdistribution.fit together with data I have a histogram of data (x,y) which is a mixed of two Gaussians (simple case i.e in one dimension). To get a fit to it, i use
obj= gmdistribution.fit(data,2)
that gives me the
obj =
Gaussian mixture distribution with 2 components in 1 dimensions
Component 1:
Mixing proportion: 0.499387
Mean:    -0.4789
Component 2:
Mixing proportion: 0.500613
Mean:    -0.4786
Now, how can I plot this together with the original histogram? I am aware of these 2 links but they dont help me so much:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/317868
http://www.mathworks.de/de/help/stats/gmdistribution.fit.html
Any clear help is highly appreciated!

A: I guess this might be a bit late, but its been updated on matlabs site. Just in case
MU1 = [1 2];
SIGMA1 = [2 0; 0 .5];
MU2 = [-3 -5];
SIGMA2 = [1 0; 0 1];
X = [mvnrnd(MU1,SIGMA1,1000);mvnrnd(MU2,SIGMA2,1000)];

scatter(X(:,1),X(:,2),10,'.')
hold on

options = statset('Display','final');
obj = gmdistribution.fit(X,2,'Options',options);
10 iterations, log-likelihood = -7046.78

h = ezcontour(@(x,y)pdf(obj,[x y]),[-8 6],[-8 6]);

You could do the same for 3d using scatter3.

redpajama_set_name: RedPajamaStackExchange


text:
Q: php operator without spaces I have this shopkeeper running in Wordpress. And I want to change the colon to parentheses but it gets weird , I don't want spaces between it just like this " (€5,50).
I've been trying to fix this problem for almost a day.
really hope to see any answers.
here is the html : gyazo.com/f05c00f01d2522aa962d90f5c0fcc5ea
method function :
function wc_cart_totals_shipping_method_label( $method ) {
    $label = $method->label;

    if ( $method->cost > 0 ) {
        if ( WC()->cart->tax_display_cart == 'excl' ) {
            $label .= ': ' . wc_price( $method->cost );
            if ( $method->get_shipping_tax() > 0 && WC()->cart->prices_include_tax ) {
                $label .= ' ' . WC()->countries->ex_tax_or_vat() . '';
            }
        } else {
            $label .= '(' . wc_price( $method->cost + $method->get_shipping_tax() ).')';
            if ( $method->get_shipping_tax() > 0 && ! WC()->cart->prices_include_tax ) {
                $label .= ' ' . WC()->countries->inc_tax_or_vat() . '';
            }
        }
    } elseif ( $method->id !== 'free_shipping' ) {
        $label .= ' (' . __( 'Free', 'woocommerce' ) . ')';
    }

    return apply_filters( 'woocommerce_cart_shipping_method_full_label', $label, $method );
}

code where I print :
            <select name="shipping_method[<?php echo $index; ?>]" data-index="<?php echo $index; ?>" id="shipping_method_<?php echo $index; ?>" class="shipping_method">
                <?php foreach ( $available_methods as $method ) : ?>
                    <option value="<?php echo esc_attr( $method->id ); ?>" <?php selected( $method->id, $chosen_method ); ?>><?php echo wp_kses_post( wc_cart_totals_shipping_method_label( $method ) ); ?></option>
                <?php endforeach; ?>
            </select>

A: Before the result try to add this:
$label = '(€'.preg_replace("/\([\s]+?/", "", str_replace(array('€', ' '), '', $label));

First use str_replace to remove html entities, seconds use a regex to remove all whitespaces after the ( and finally append at the start of the string "(€"


text:
Q: GWT Create a sub-process in server side Every RPC in GWT is limited with 1 minute timeout, and this is not configurable.
I am consuming a SYNC METHOD from a third party provider which calls a WEBSERVICE.
Sometimes this METHOD (webservice) hangs for more than 1 minute, and crashes my RPC. The problem is that I cant catch this exception on the server side, which I need to rollback some flags (its a more complicated process this is just for a example)
try {

...my code goes here...

MYTHIRDPARTYWS ws = new MYTHIRDPARTYWS()
String RESULT = ws.run;

...my code needs to take action depending of the result...

} catch (Exception e) {

...my code needs to take action depending of the exception...

}

I need something like this:
try {

...my code goes here...

Process p = new Process() {
MYTHIRDPARTYWS ws = new MYTHIRDPARTYWS()
String RESULT = ws.run;

};

p.setTimeOut(40000);
p.run;

...my code needs to take action depending of the result...

} catch (Exception e) {

...my code needs to take action depending of the exception...

}

Any idea?

A: Use method ExecutorService.execute() to spawn some task in a background thread.
Steps to follow:

*

*Read some init parameters from web.xml in servlet init() method such as timeout and threadpoolsize

*

*timeout parameter is used to set the timeout of Async thread

*threadpoolsize is used to create a pool of Async threads

*Get AsyncContext by calling HTTP request.startAsync() in doGet() or doPost() method

*Set timeout of AsyncContext

*Attach listener to respond to lifecycle events of this AsyncContext such as onComplete(), onTimeout(), onError(), onStartAsync()

*Call ExecutorService.execute() to spawn some task in a background thread

I have already posted the code here Asynchronous servlet not acting asynchronously
Please have look and let me know if there is any confusion. It really works.
You have full control on each life cycle method of sub-process to handle any type of exception.


text:
Q: Displaying click results in a side panel I am trying to do something similar to the interactive choropleth map (http://leafletjs.com/examples/choropleth.html) on leaflet's website.
In my case I want to use a click instead of a hover and want to show the results in a side panel (i.e. separate div).
Can someone point me to an example or suggest how I can do this?
UPDATE:
Based on Bronco's reply:
That part I understand. It is this snippet that I need to change but I don't know how:
var info = L.control();

info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
this.update();
return this._div;
};

// method that we will use to update the control based on feature properties passed
info.update = function (props) {
this._div.innerHTML = 'US Population Density' + (props ? '' + props.name + '
' + props.density + ' people / mi2'
: 'Hover over a state');
};
info.addTo(map);

A: You just need to change the code a little bit.  Look at this function that adds the listeners:
function onEachFeature(feature, layer) {
    layer.on({
        mouseover: highlightFeature, //you need to change this
        mouseout: resetHighlight,
        click: zoomToFeature
    });
}

geojson = L.geoJson(statesData, {
    style: style,
    onEachFeature: onEachFeature
}).addTo(map);

Where I marked the change, you can change it from mouseover to click and that should fire the highlightFeature function.  Of course, you would want to change the current click event zoomToFeature to something different probably.
I didn't look through the code enough to see if the highlightFeature function posts the data into a separate div, but you should be able to adjust the code accordingly to put the information wherever you'd like it to go.

A: Just came across this while looking for clues to a further task. For doing this quickly, follow what Branco suggested : change mouseover: to click: and comment out the mouseout: and click: lines.
The example you're working on is a step further than what you seek: It creates a div in the map itself for use as an info panel. If you're looking for populating another element entirely that you've defined outside of the map, then you actually don't need even the whole info control. You can just as easily do what you need in the onEachFeature >> layer.on >> click part too.
function onEachFeature(feature, layer) {
    layer.on({
        click: function populate() {
            document.getElementById('externaldiv').innerHTML = "BLAH BLAH BLAH " + feature.properties.name + "
" + feature.properties.description;
        }
    });
}

In your html body, you just have to make sure your
 or whatever is placed where you want it.
This demo populates an external
 when the user clicks on a map feature : http://labs.easyblog.it/maps/leaflet-geojson-list/


text:
Q: Why my stateless session bean works as stateful? I've wrote stateful session bean:
@Stateful
public class SessionBean {
List<Integer> list = new ArrayList<>();
public void addItem(int s) {
    list.add(s);
}
public int getItemsCount() {
    return list.size();
}
}

and use it in my servlet:
@WebServlet("/add")
public class AddServlet extends HttpServlet {
@Inject
SessionBean sessionBean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int i = sessionBean.getItemsCount();
    resp.getWriter().write(i + " ");
    sessionBean.addItem(i + 1);
}
}

It works as expected, list saves the state and I can use it in next request.
But if I'd change @Stateful on @Stateless I expected not to store state of the bean, and get in each request clean list, but it always save the state of previous request and shows new number. So what is the difference between stateless and stateful? How to see it? As I see, they work the same.
I want to see example that will show something like - here we use stateful and it saves the state, and here we change on stateless and it works differently and not save the state. Please show me the differences.

A:
But if I'd change @Stateful on @Stateless I expected not to store state of the bean, and get in each request clean list, but it always save the state of previous request and shows new number.

The Stateful vs. Stateless distinction is foremost declarative, not functional.  If you declare a session bean to be stateless, then it is your responsibility to ensure that it does not actually retain any state between method invocations.

So what is the difference between stateless and stateful? How to see it? As I see, they work the same.

One of the more important differences is that if you declare a bean stateless then you afford the container the option of serving different requests with different bean instances.  If it opted to do so then that could make a declared-stateless bean that in fact retains state appear not to retain state after all, at least to a limited extent.  But the container is not required to do that, so if your stateless bean violates its contract by retaining state, then that will probably be visible to clients sooner or later.
There is more (rather a lot more, in fact -- read the specifications), but the most important thing is what I led off with.  To put it another way, the correct declaration of a session bean as stateless vs. stateful is part of its developer's contract with the container in which it is deployed.  A bean does not behave differently than its code demands just for being declared stateless.

A: Stateless session beans are not expected to carry any form of state, e.g. instance variables. Therefore, containers often maintain a pool of stateless beans so they can be reused by different clients.
The Oracle doc mentions the following about session beans: http://docs.oracle.com/javaee/5/tutorial/doc/bnbly.html

Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean.

This phenomenon is what you might be experiencing and why the list not empty.


text:
Q: Custom [Authorize] filter for Ajax Jquery requests I have derived from AuthorizeAttribute class and made my own CustomAuthorize
  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.HttpContext.Response.StatusCode = 401;
            filterContext.Result = new JsonResult
            {

                Data = new DataSourceResult { Errors = new { error = "NotAuthorized" } }
                ,JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
          // this is a standard request, let parent filter to handle it
           base.HandleUnauthorizedRequest(filterContext);
        }
    }

There are so many places where I am using Ajax Jquery call and it does not look practical to check response in each one of those and then do
window.location.href='/Auth/login';

I am just wondering , Can we redirect to login page from HandleUnauthorizedRequest method?

A: Create a base controller on which you place your custom authorize attribute.
Something like:
[YourAuthorizeAttribute]
public class BaseAuthorizeController : BaseController
{
    public BaseAuthorizeController() {}
}

The above will be applied to all of your actions, not just the ajax actions.
You could expand the attribute by passing it a boolean of false for actions that do not need the new logic;
public class ClaimsAuthorizeAttribute : ActionFilterAttribute
{
    private readonly bool authorize = true;public YourAuthorizeAttribute(bool authorize = true)
    {
        this.authorize = authorize;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!authorize)
        {
            return;
        }

        // Your custom authentication logic
    }


text:
Q: Potential difference of resistors in parallel linked systems Before the question I want to explain somethings to see if I understand anything wrong please tell me if im wrong: When there is a Potential difference on a system then the electrical charge will move from high voltage to low voltage and the amount of charge flows at one point is called the Current. In parallel linked resistors total current of each resistors is equal to current of the generator's but the voltage of the resistors are same and equal to voltage of the generator's,
So my question is how is the voltage of the different resistor's with different currents are equal to each other? in my logic if there are more charge flowing from a resistor then the voltage must be bigger but how is this working and what is the defination of the potential difference of a resistor, isn't it same with difference between two generator's potentials? and please don't make the classical explanation(potential difference is the difference between two point bla bla) I've read this 1000 times and it just doesn't make sense to me because if I gave x voltage to a system then I have to get x voltage out I can't get 2x because with this logic if parallel resistors have equal voltage then x+x=2x voltage but my generator has x voltage and how did I get 2x voltage with x voltage? Anyway hope you get it and can help me to end my complexity right now xd

A: Start with one resistor resistance $R$ and connect it to a power supply so that the potential difference across the resistor is $V$.
The current in the resistor is $I= \frac VR$.
Now set up the same circuit with a resistor with the same resistance $R$ as before with the same potential difference across it $V$ generated by a different power supply.
The current through this resistor is $I= \frac VR$, the same as before.
Now connect up the positive terminals of the two power supplies together and also the negative terminals.
The potential difference across each of the resistors is still $V$ and the current through each of the resistors is still $I$.
The total current is $2I$.
Keeping the resistors connected to one power supply remove the other power supply.
The potential difference across each of the resistors is still $V$ and the current through each of the resistors is still $I$.
The total current is still $2I$.
You can do a similar analysis with any number of resistors and varying sizes of resistance.
In each case the potential difference across the parallel resistors will still be $V$ but the total current will vary.

A: At some stage you will need to get to grips with "the classical explanation [that you've read] a thousand times". I'll just tackle one misconception that you have: "if parallel resistors have equal voltage then x+x=2x voltage". This is confused because there is only one voltage… If you have two resistors, R1 and R2, in parallel and connect a voltmeter first across R1 and then across R2, you're reading the same voltage twice, because the ends of R1 are connected to the ends of R2. So there is no sense in adding the two voltage readings together.
It's just like this… Two staircases go between the same two floors of a building. Each staircase takes you through a vertical distance of 2.5 m. I can't think of any circumstances when it is useful to add the two 2.5 m together.
Now suppose that there is a burst water pipe on the upper of the two floors, and water is cascading down both staircases. If the rates of flow are 2 litre per second down one staircase and 3 litre per second down the other, then it does make sense to add the two flow rates together to deduce that water is descending at a rate of 5 litres per second. In the same way, it makes sense to add together the electric currents through two resistors in parallel.
Electrical potential difference ('voltage'), then, is analogous to height difference. Electric current (rate of flow of charge) is analogous to (volumetric) rate of flow of water. These analogies mustn't be taken too far, but many people find them useful.


text:
Q: Work around rate limit for extracting large list of user information using twitteR package in R I am attempting to download all of the followers and their information (location, date of creation, etc.) from the Haaretz Twitter feed (@haaretzcom) using the twitteR package in R. The Twitter feed has over 90,000 followers  I was able to download the full list of followers no problem using the code below.
require(twitteR)
require(ROAuth)
#Loading the Twitter OAuthorization
load("~/Dropbox/Twitter/my_oauth")

#Confirming the OAuth
registerTwitterOAuth(my_oauth)

# opening list to download
haaretz_followers<-getUser("haaretzcom")$getFollowerIDs(retryOnRateLimit=9999999)

However, when I try to extract their information using the lookupUsers function, I run into the rate limit. The trick of using retryOnRateLimit does not seem to work here:)
 #Extracting user information for each of Haaretz followers
 haaretz_followers_info<-lookupUsers(haaretz_followers)

 haaretz_followers_full<-twListToDF(haaretz_followers_info)

 #Export data to csv
 write.table(haaretz_followers_full, file = "haaretz_twitter_followers.csv",  sep=",")

I believe I need to write a for loop and subsample over the list of followers (haaretz_followers) to avoid the rate limit. In this loop, I need to include some kind of rest/pause like Keep downloading tweets within the limits using twitteR package. The twitteR package is a bit opaque on how to go about this and  I am bit of a novice writing for loops in R. Finally, I know that depending on how you write your loops in R, greatly affects the run time. Any help you could give would be much appreciated!

A: Something like this will likely get the job done:
for (follower in haaretz_followers){
  Sys.sleep(5)
  haaretz_followers_info<-lookupUsers(haaretz_followers)

  haaretz_followers_full<-twListToDF(haaretz_followers_info)

  #Export data to csv
  write.table(haaretz_followers_full, file = "haaretz_twitter_followers.csv",  sep=",")
}

Here you're sleeping for 5 seconds between each call. I don't know what you're rate limit is -- you may need more or less to comply with Twitter's policies.
You're correct that the way you structure loops in R will affect performance, but in this case, you're intentionally inserting a pause which will be orders of magnitude longer than any wasted CPU time from a poorly-designed loop, so you don't really need to worry about that.


text:
Q: How to change MenuItem background on item clicked Android What is correct way to  to change my toolbar MenuItem background when menu item selected. I would like to change it to signalize that MenuItem is selected I tried other answers , but no help. Any solution please?
Here is my menu xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="left"
android:textDirection="ltr"
app:itemBackground="@drawable/drawer_list_selector">

    <item
        android:id="@+id/informacije"
        android:layout_gravity="left|start"
        android:checked="true"
        android:textDirection="ltr"
        android:title="O aplikaciji"
        app:showAsAction="never" />
    <item
        android:id="@+id/podesavanja"
        android:layout_gravity="left|start"
        android:textDirection="ltr"
        android:title="Podešavanja"
        app:showAsAction="never" />

And styles.xml:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:listDivider">@color/status</item>
    <item name="android:itemBackground">#333333</item>.
    <item name="android:itemTextAppearance">@style/myCustomMenuTextApearance</item>
    <item name="dropDownListViewStyle">@style/PopupMenuListView</item>
    <item name="android:activatedBackgroundIndicator">@drawable/drawer_list_selector</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

<style name="AppTheme.CustomTheme" >
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowCloseOnTouchOutside">true</item>
</style>

<style name="NavigationViewStyle">
    <item name="android:activatedBackgroundIndicator">@drawable/drawer_list_selector</item>
    <item name="android:textSize">14sp</item> <!-- menu item text size-->
    <item name="android:listPreferredItemHeightSmall">40dp</item><!-- menu item height-->
</style>

<style name="myCustomMenuTextApearance" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:textSize">14sp</item>
    <item name="android:listPreferredItemHeightSmall">40dp</item>
    <item name="android:activatedBackgroundIndicator">@drawable/drawer_list_selector</item>
</style>

<style name="PopupMenuListView" parent="@style/Widget.AppCompat.Light.ListView.DropDown">
    <item name="android:divider">#FFFF</item>
    <item name="android:dividerHeight">1dp</item>
    <item name="android:showDividers"></item>
    <item name="android:textDirection">ltr</item>
    <item name="android:activatedBackgroundIndicator">@drawable/drawer_list_selector</item>
</style>

In Activity:
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.podesavanja) {

        startActivity(new Intent(this, Podesavanja.class));
        return true;
    }

    if (id == R.id.informacije) {

        startActivity(new Intent(this, OAplikacij.class));
        return true;
    }

    return super.onOptionsItemSelected(item);
}

enter code here

A: You should make list selector for that popup menu. This answer below should work both on pre and post-lollipop devices
https://stackoverflow.com/a/35749206/5577679


text:
Q: Open source project has `No Scheme` in Xcode I have uploaded an open source project called SuperCrack! to Github.  I made it with Xcode 8.3.3.  It's quite a large project with lots of pods.  I asked a friend to download and build it but he complains that there is No Scheme:

He tried the solutions here but said they didn't help.
If anybody could tell me where I went wrong and fix this problem I'd be grateful.

A: I had the same problem when trying to run this app turns out I just had to run 'pod install'

A: YOUR_PROJECT_NAME.pbxproj is missing. seems like something went wrong when pushing your project to the server...


text:
Q: Optical devices for micro meter photons? Are there all the common optical devices like beam splitters, mirrors, polarizers, fibers, etc for photons with a wavelenght in the range of micro meters?
If so, how broad can the bandwidth be for the optical devices to work properly?
Consider for example a photon with a mean frequency of $10^{12}\,\text{Hz}$ (i.e. a wavelength of $300\,\mu\text{m}$). Will problems occur if the bandwidth of the photon is also in the range of $10^{11}\,\text{Hz}$ or $10^{12}\,\text{Hz}$?

A: This falls into the "terahertz band" which has been getting a lot of attention recently.  I'm not an expert in that area, but I can suggest you search "terahertz optics".  I note that Newport Corporation has a line of terahertz components, along with some notes on their use.  And there are many more vendors.


text:
Q: How to test for an empty directory, no matter what its size, in Python? Suppose I have a directory C:/Test that is either empty or contains more than 2000000 files, all with the same extension (e.g. *.txt).
How can I use Python to determine if the directory is empty WITHOUT the enumeration of files?

A: I realise this is quite an old question but I found this as I was looking to do a similar thing and I found os.scandir to be useful in combination with any(). scandir() will return an iterator of entries in a directory rather than a list. any() can evaluate if the iterator is non-empty.
for _ in os.scandir(path):
 print('not empty')
 break

or
if any(os.scandir(path)):
   print('not empty')

A: Is this what you're looking for?
import os
if not os.listdir('C:/Test'):
    print "empty"

edit:
test run
for x in range(0, 3000000):
    open(str(x), 'a').close()

print not os.listdir('.')

output: False


text:
Q: jQuery Tools Tooltip hover not detected after link click Using the tooltip plugin from the jQuery Tools I successfully generate a tooltip with the following code.
$(".link_prijskaart").tooltip({
    tip: "#tooltip_prijskaart",
    position: "bottom center",
    delay: 1200,
    events: {
        def: 'click,mouseout',
        tooltip: 'mouseenter,mouseleave'
    },
    offset: [0, 90]
});

The tooltip itself is a simple HTML with anchor links in it, these links link to PDF files. When clicked, the PDF gets streamed and downloaded. After this process, the tooltip does not detect an hover anymore. When the target is clicked the tooltip opens, but the leaving the target closes the tooltip; the tooltip hover event does not seem to trigger (tested in Firefox 3.6 and IE8).
Does anyone have an idea why after clicking in a link the tooltip the mouseenter and mouseleave events as defined do not register anymore?

A: Apparently your events are destroyed. Maybe they were attached to HTML tags that were deleted and recreated. Instead of adding the events inside a parameter, you could download the file via AJAX, so your Javascript events will not break and will trigger successfully even afterwards.


text:
Q: Who is your favorite VPS Provider? Who is your favorite virtual hosting provider? I'm looking for your thoughts on SliceHost, Dreamhost VPS, Linode, 1and1 VPS, etc and why you like the particular provider you named.
Thanks!

A: I vote for RootBSD, a very reliable FreeBSD hosting provider.

A: I like Gandi (but they are in France which may not be the best option for you).
I really like their flexible architecture that let's you add server parts hourly to increase your processing power.

A: I've been using TekTonic for several years, and they have been extremely reliable. Inexpensive, responsive customer service, and a stable environment.

A: I would have to say Linode. Linode is built on Xen and has a great management AJAXy interface.
You can partition your hard drive directly on the web and install a different OS on each partition, boot one or the other. Of course, re-install whenever you want without filing a ticket.
They also provide a serial console that you can access through SSH or through-the-web (hence the AJAXy part).
They provide DNS service, in case you need it.
Their support is quite good and they have forums and an IRC chat where you can often get good answers.
Or if you can speak German host-europe.

A: I like Slicehost a lot.  Although their prices aren't the best for what you get, they aren't bad, and the service is wonderful.  There is nothing worse than going with a discount-bin host, and then having a problem, and finding their service staff is unresponsive.

A: I've just started a VPS with A2 Hosting.  Don't know how things will be long-term, but support has been great so far.

A: VPS.NET is a new cloud based VPS provider. It has been fantastic for us so far. Their staff are very helpful and competent. These are the guys behind the uk2group that owns many other service providers.
And you get a bunch of perks: Free DNS management that hooks up with Softlayer's anycast system. Free SSL certs. Free ISPmanager Pro for those that want a simple control panel.

A: I've been a happy customer of Memset for about 3-4 years.  Their support staff know their stuff, their VPS are quite well priced for what you get, and they run on Xen which is extremely stable.  My current VPS with them had an uptime record of 100% throughout 2009.
Oh, and they do Windows VPSs too if that's your thing.

A: I like a small startup called LayeredTech.  I have been with them for over 3 years since they first got rolling and they have been superior in every way.
For VPS they call their solutions "The Grid Layer", and have very aggresive pricing.

A: I have had really good luck with Media Temple's VPS solution called (dv) Dedicated-Virtual.

A: I have been very happy with Linode. Their web interface is a breeze and includes lots of great features such as the web-based serial console, a very clean DNS configuration editor, and snazzy performance graphs. Their prices are low and their uptime high.

A: I currently manage over two dozen servers at linode and slicehost. they are both excellent. You will get more for your money at Linode and the support at both companies is superb. I wouldn't trust my data to any other vps provider. (except maybe amazon ec2)

A: Havent Used them but Joyent seem to have very good plans. HEAPS of bandwidth. if you can deal with opensolaris they look pretty decent. Anybody has experience?

A: I'm using ContextShift. They are based in Amsterdam, and have a nice friendly support system.

A: Without a doubt my current VPS provider of choice is Ultima Hosts.
They offer both Hyper-V and Parrallels Virtuozzo hosting at a very good price, their support is awesome and during setup they even loaded Windows Server 2008 R2 for me. I had my sites moved and running within 24 hours.
I highly recommend them to anyone looking for an affordable and stable VPS host.

A: I've been using BudgetDedicated for the last three and a half years; they're a low cost, no frills, VPS provider.  They've been rock solid (I've seen no unscheduled downtime in that period [*]), I've not had a whole lot of reason to get in touch with them, but when I have, I've had my queries answered quickly by the founder, Erik de Bruijn, or his brother.  They run a low carbon footprint server array, and are a fairly small operation.  Erik is pretty active in the open source and open innovation scenes; BudgetDedicated hosts the Wine .debs, and Erik is involved in the RepRap 3d printing project.
As a general point, if you are in Europe, the Netherlands is a good place to run a web server, because it is close to the main internet line running across to the US.
[*] I should note that the Wine project have seen some outages in that period, four that I know of.  AFAICT, they were all sysadmin issues.

A: Performance
This VPS performance comparison by Uggedal compares linode and several other and is worth reading


text:
Q: How to pass value from cshtml file to the JS Hello I need to pass one param to the my JS function after pressing button.
Here is my button:
<button type="button" class="btn btn-default" id="UserClick" onclick="foo(@HttpContext.Current.User.Identity.Name)">Click here to add me as a user</button>

as You can see I try to send @HttpContext.Current.User.Identity.Name to the function foo.
Here my Foo function:
    function foo(value) {
         alert(value);
    };

I tried sollutions from those topics:
One
Two
But all I get get is this error:
Uncaught SyntaxError: Unexpected token ILLEGAL

How to bypass this?
@update
All files included:
<script src="/Scripts/CreateDevice.js"></script>
<script src="/Scripts/jquery-ui.js"></script>
<script src="/Scripts/jquery-1.10.2.js"></script>

full JS file:
$(document).ready(function () {

function foo(value) {
    alert(value);
};
})

I can access to the js file from page-source.

A: First of all change you sequence of file to
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery-ui.js"></script>
<script src="/Scripts/CreateDevice.js"></script>

Declare your function outside document-ready handler. Like
$(document).ready(function () {
});

function foo(value) {
    alert(value);
};

Pass your parameter in quotes
onclick="foo('@HttpContext.Current.User.Identity.Name');"

Additionally, You can bind event using .on()  and pass parameter using attributes
JS
$(document).ready(function () {
    //Bind Event
    $(document).on('click', '#UserClick', function(){
        alert($(this).data('user-name'))
    });
});

HTML
<button type="button"
    class="btn btn-default"
    id="UserClick"
    data-user-name="@HttpContext.Current.User.Identity.Name"
    >Click here to add me as a user</button>

A: onclick="foo('@HttpContext.Current.User.Identity.Name');"

$(document).ready(function () {

window.foo = function(value) {
    alert(value);
};
})

this will work...
You should consider removing the 'onclick' attribute in the html though, and binding the function to the button using jquery's  .on() function.


text:
Q: Access Top N Query where N changes by group I am trying to write a top n value query in Microsoft Access where n may change by group.  For example, one group may be top 3 records, another may be top 2 records, and another may be top 4 records.  I have a table with the field "TopN" where I store how many values to show for that group.
Sample of Top 3 query that works, I am trying to replace Top 3 with Top N where N is a DLookup or something that uses the value in TopN field:
SELECT Payout.GDate, Payout.[Game Type], Payout.Denom, Payout.Segment, Payout.Manufacturer_Description, Payout.Stand, Payout.Payout
  FROM Payout, PayoutShowSegment
  WHERE (((Payout.Payout) IN (SELECT TOP 3 [Payout]
                                FROM [Payout]
                                WHERE [Payout].[Segment]=[PayoutShowSegment].[Segment])))
  ORDER BY Payout.[Game Type], Payout.Denom, Payout.Payout DESC;

A: I had a similar problem a couple of months ago.
Working with your query, something like this should work:
SELECT      T1.GDate,
            T1.[Game Type],
            T1.Denom,
            T1.Segment,
            T1.Manufacturer_Description,
            T1.Stand,
            T1.Payout
FROM        Payout T1 INNER JOIN Payout T2 ON
                T1.[Game Type] = T2.[Game Type] AND
                T1.Denom = T2.Denom AND
                T1.Segment = T2.Segment AND
                T1.Manufacturer_Description = T2.Manufacturer_Description AND
                T1.Stand = T2.Stand AND
                T1.Payout = T2.Payout AND
                T1.GDate >= T2.GDate
GROUP BY    T1.GDate,
            T1.[Game Type],
            T1.Denom,
            T1.Segment,
            T1.Manufacturer_Description,
            T1.Stand,
            T1.Payout
HAVING      COUNT(*) <= (
                         SELECT TopN
                         FROM   MyOtherTable
                         WHERE  MyOtherTable.IDField = T1.IDField
                        )
ORDER BY    T1.GDate

Note - the join can probably be reduced to the PK in the Payout table.
For more info check this site:  http://www.sql-ex.com/help/select16.php


text:
Q: attempting to reference a deleted function error when create a class inheriting from QGraphicsPixmapItem in QT I would like to insert a picture in my scene, and do something when picture position change is detected. To realize it, I create a class BackgroundPic inheriting from QGraphicsPixmapItem. However, it arises C2280 error: 'BackgroundPic::BackgroundPic(const BackgroundPic &)': attempting to reference a deleted function (compiling source file mainwindow.cpp)     when I try to compile it. Does anyone knows what's the issue in my code?
#include <qstring.h>
#include <qgraphicsproxywidget.h>

class BackgroundPic: public QGraphicsPixmapItem
{
public:
    BackgroundPic()
    {
        show_flag = true;
        moveable_flag = true;
    }

    //QString name;
    float x_original;       //physical
    float y_original;
    float x;        //physical
    float y;
    QString pic_address;
    bool show_flag;
    bool moveable_flag;

    QVariant itemChange(GraphicsItemChange change, const QVariant &value)
    {
        if (change == ItemPositionChange)
        {
            x = x_original + value.toPointF().x();
            y = y_original + value.toPointF().y();
        }
        return QGraphicsItem::itemChange(change, value);
    }
};

A: The problem seems to be clear and it is not located in the code that you posted. In the file mainwindow.cpp there is a place where you call a copy constructor (this BackgroundPic::BackgroundPic(const BackgroundPic &)), but this function is not available.
Normaly copy constructor is defined automatically (you can read about rule of zero and rule of five), but in your case it is not. It happens because you inherit from a class that does not have a copy constructor. This means that your class is also not copyable.


text:
Q: Expected Value Function My text-book defines expected value as
$$E(X) = \mu_x = \sum_{x \in D} ~x  \cdot p(x)$$
And so, if I was to find the expected value of a random variable $X$, where $X = 1,2,3$, then it would resemble this:
$$E(X)= \sum_{x=1}^3~ x \cdot p(x)= 1\cdot p(1) + 2\cdot p(2) + 3 \cdot p(3)$$
Furthermore, if I wanted to calculate $E(X^2)$, it would be $E(X^2) = 1^2 \cdot P(1) + 2^2 \cdot p(2) + 3^2 \cdot p(3)$. My question is, why don't we square the x-values in the probability function $p(x)$?
Also, is computing the expected value a way of calculating the average of the random variable? It seems a little odd to calculate it that way.
PS: If any use of notation, or vocabulary, is incorrect, please inform me.

A: Let $Y=X^2$. Then $Y$ takes on the values $1$, $4$, and $9$ respectively when $X$ takes on the values $1$, $2$, and $3$.
Thus $p_Y(1)=p_X(1)$, $p_Y(4)=p_X(2)$, and $p_Y(9)=p_X(3)$.
Now for calculating $E(Y)$ we just use the formula the post started with, namely
$$E(Y)=\sum_y yp_Y(y).$$
In our case, we get $1\cdot p_Y(1)+4\cdot p_Y(4)+9\cdot p_Y(9)$. Equivalently, $E(Y)=  1\cdot p_X(1)+4\cdot p_X(2)+9\cdot p_X(3)$.
To answer your question more explicitly, we do not use $1^2(p_X(1))^2+2^2(p_X(2))^2+3^2(p_X(3))^2$ because, for example, $\Pr(X^2=3^2)$ is not  $(\Pr(X=3))^2$. In fact, $\Pr(X^2=3^2)=\Pr(X=3)$.
As to your question about average, yes, the mean is a very important measure of average value. The only serious competitor is the median.
Mean and median can be quite different. For example, imagine a population in which a small minority is insanely rich, while the vast majority of the population is struggling. Then the mean income of the population may be substantially higher than the median income. Is either one a "better" measure of average wealth? I would argue that in this case the median is ordinarily of greater relevance. But for certain planning purposes, such as level of tax revenues, the mean may be more useful.
The mathematics of the mean is substantially simpler than the mathematics of the median. For example, the mean of a sum of two random variables is the sum of the means. The median of a sum is a far more complicated object.

A: There were two questions. The first question: Why don't we square the $x$ values in the calculation for the expected value of $X^2$.
Suppose $Y = g(X)$.
\begin{equation}
\begin{aligned}
E(Y) & \stackrel{\text{(a)}}{=} \sum_{y\in{S_Y}}yP_Y(y)\\
& \stackrel{\text{(b)}}{=} \sum_{y\in{S_Y}}y\sum_{x:g(x) = y}P_X(x)\\
& \stackrel{\text{(c)}}{=} \sum_{y\in{S_Y}}\sum_{x:g(x) = y}yP_X(x)\\
& \stackrel{\text{(d)}}{=} \sum_{y\in{S_Y}}\sum_{x:g(x) = y}g(x)P_X(x)\\
& \stackrel{\text{(e)}}{=} \sum_{x\in{S_X}}g(x)P_X(x)\\
\end{aligned}
\end{equation}
(a): The definition of expected value of a discrete random variable, as you have supplied.
(b): Because the probability of random variable $Y$ taking on a value $g(x)$ is equal to the sum of the probability of all the values of $x$ which will map to $g(x)$.
(c): Interchanging the summation.
(d): Because of the condition in the summation, we can replace $y$ by $g(x)$.
(e): Because enumerating across all $y$, then enumerating across all $x$ such that $g(x) = y$, is equivalent to enumerating across all $x$ since every $x$ must map to exactly one $y$. (Multiple $x$ could map to the same $y$).
So, in your instance, set $g(x) = x^2$ to obtain the result.
The second question: Why is expected value defined the way it is defined?
Expected value can be thought of as the center of mass, if we set $P_X(x)$ to be the mass located at a distance $x$ from the origin. It corresponds exactly with the arithmetic average when the distribution of $X$ is uniform.

A: For computing $E[X^2]$, the probability is still taken over $X$ and not $X^2$. Otherwise, if you make $Y=X^2$ the random variable and then compute $E[Y]$, the only operation that you effectively did is to relabel the random variables (well, although only considering positive values): all the values taken by $|X|$ will also be taken by $Y$, so for positive values of $X$, computing $E[X^2]$ would be exactly like computing $E[X]$. But computing $E[X^2]$ gives you more information!
The expected value is the weighted average. "Normally" (in daily life), when you take an average, all the values have the same weight. The average salary of your family members, for instance. But say you wanted the average salary in your country, then it's nice to work with, say, the probability of a certain salary being had. Making this latter problem more concrete, you could approximate the average national salary by taking every integer multiple of $1000, and finding out the proportion of people with this salary. Then the weighted average gives you the true national average salary.


text:
Q: syntax issue with bash function in alias I can't figure out why my syntax is wrong here:
alias lookup='function lookup(){ echo "Unqiue ID: $1"; ldapsearch -x -h domain -b 'ou=people,dc=domain,dc=com' uid='$1'}'

A: You don't need an alias here at all; just define the function:
lookup () {
    echo "Unqiue ID: $1"
    ldapsearch -x -h domain -b 'ou=people,dc=domain,dc=com' uid="$1"
}

Be sure to use double quotes, not single quotes, to allow $1 to expand.
The only reason to use an alias as well would be if you wanted to give the function a long name for self-documenting purposes, then define a more user-friendly alias, say, alias lu=lookup.


text:
Q: Can't change swing window location dynamically I want to change scala-swing window location.
I found setting location works correctly when initialization but can't change location dynamically
import java.awt.Point

import scala.swing._
import scala.swing.event.ButtonClicked

object TestWindow extends SimpleSwingApplication {
  def top = new MainFrame {
    contents = new BoxPanel(Orientation.Vertical) {
      contents += new Button("Change location") {
        reactions += {
          case e: ButtonClicked => {
            println("change location")
            top.location = new Point(200, 100)//doesn't work
            println("change location end")
          }
        }
      }
    }
    location = new Point(100, 50) //works correctly
  }
}

How can I do it?

A: It can be achieved using following statement:
this.peer.getRootPane.getParent.setLocation(new Point(200, 100))

here this.peer is reference to java JButton, getRootPane gives you placeholder of the button, then in this particular case getParent gets your MainFrame object (may need to use more than one getParent if hierachy is bigger). I think by using top.location you are trying to create a new MainFrame which is likely to be prohibited by API.


text:
Q: Can you sort by subclass? Is there a way to list through subclass value? I'd like 'by' variable to be the first one and sort entire list by .number subclass.
class Abcd:
    def __init__(self, name, number):
        self.name = name
        self.number = number

ax = Abcd("a", 20)
by = Abcd("b", 1)

lst = [ax, by]

print lst[0]
list.sort(lst)
print lst[0]

A: This should do. All I am doing is adding a key to the sort function and some stuff to make printing look better but those really aren't necessary.
class Abcd:
    def __init__(self, name, number):
        self.name = name
        self.number = number

    def __str__(self):
        return "{} and {}".format(self.name, self.number)

    def __repr__(self):
        return self.__str__()

ax = Abcd("a", 20)
by = Abcd("b", 1)

lst = [ax, by]

print str(lst)
list.sort(lst, key=lambda x: x.number)
print str(lst)


text:
Q: Localizing MVC 3 client side validation messages I'm working on an ASP.Net MVC 3 project, which needs localized error messages from its validation rules.
Is there any way to do this client side ?
I can live with english serverside validation messages, as the client side ones should always be triggered (I've no fear my users will disable javascript, as it's an Intranet site)
Whilst I can use DataAnnotations for stuff such as [Required] and [StringLength], there is no such option (it seems) for data type validation.
If for instance I have int Portions in my view model, it's automatically validate input to ensure it's an int. Fair enough, but the validation message is always in english :-(
Suppose my model looks like this:
public class RecipeModel
{

[Display(Name = "Navn")]
[Required(ErrorMessage = "Skal udfyldes")]
public string Name { get; set; }

[Display(Name = "Portioner")]
public int Portions { get; set; }

}

As you can see I have a custom errormessage for "Name", however if I try to enter text into the EditorFor(Portions), it'll show my this errormessage:
"The field Portioner must be a number."
And that's the errormessage I want to localize. Unfortunately there's no DataAnnotation for that built-in validator (checking that it's an int).
I even tried using a DataType annotation of type Custom, to no avail :-(

A: You can create your own validation messages using data annotations with your model. If you want to support multiple languages you can create a resource file for each language and link from the data annotation to the Id of the message in your resource file.


text:
Q: How get default ReCaptcha key programmatically on Frontend?
I want to used this key in my Custom Module so how to get this this key using block.
I create a form on frontend which has a Recaptcha V2. How to used default keys for this Form.
And I also need to check is enable for Frontend (Backend) or not.
Thanks

A: Try with the below code in your block and let me know.
<?php
namespace Vendor\ModuleName\Block;
class TestClassName extends \Magento\Framework\View\Element\Template
{

    const XML_PATH_ENABLED_FRONTEND = 'msp_securitysuite_recaptcha/frontend/enabled';
    const XML_PATH_PUBLIC_KEY       = 'msp_securitysuite_recaptcha/general/public_key';

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    public function getFrontendCaptchaEnabled()
    {
        return $this->scopeConfig->getValue(
            self::XML_PATH_ENABLED_FRONTEND,
            ScopeInterface::SCOPE_STORE
        );
    }

    public function getSecurityCaptchaKey()
    {
        return $this->scopeConfig->getValue(
            self::XML_PATH_PUBLIC_KEY,
            ScopeInterface::SCOPE_STORE
        );
    }
}

if you would like to call the above method in your template file use this syntax

$block->getSecurityCaptchaKey();


text:
Q: debugging apollo, docker and typescript on VS code I am trying to make the debugger work on VS code using node but without any success as breakpoints are not hitting.
I tried to set the launch.json in many different configs but with no luck.
"type": "node",
"request": "attach",
"name": "Attach",
"port": 9229,
"skipFiles": [
    "<node_internals>/**"
]
},

{
    "type": "node",
    "request": "launch",
    "name": "Server",
    "runtimeExecutable": "nodemon",
    "program": "${workspaceRoot}/src/index.ts",
    "console": "integratedTerminal"
},

I am using a graphql running on node apollo and typescript on my machine with Visual Studio Code


text:
Q: Shifting from EXPO ..Your Android App Bundle is signed with the wrong key My old android app was deployed by expo and new one is by flutter.. How I can get the old keystore file.
It was managed by expo and now I cant download it.
When I try 'expo fetch:android:keystore'
I get
'There is no valid Keystore defined for this app'


text:
Q: Will a tomcat request connection also time out when a server side process is taking too long to send a response? I have a spring boot application with an embedded tomcat server. To limit the impact of DOS attacks i've set the property server.tomcat.connection-timeout to 3 seconds. A connectionTimeout is the limit of time after which the server will automatically close the connection with the client.
So if in my case the client takes more then 3 seconds to finish the request the connection will automatically time out. However, its not yet clear to me what exactly happens when instead it is a process on the server side that is causing a delay.
To give an example, My web application is using a hikari connection pool that manages connections to the database. It can have a maximum of 10 database connections. If all 10 are in use any incoming request will have to wait for one of the database connections to become available. If this wait takes more then 3 seconds, will the tomcat connection time out? Or will the connection remain available since the delay isn't caused by the client?
Thank you

A: According to the Tomcat 9.0 documentation, the connection-timeout is:

The number of milliseconds this Connector will wait, after accepting a connection, for the request URI line to be presented. [...] Unless disableUploadTimeout is set to false, this timeout will also be used when reading the request body (if any).

That is a time taken for the client to send the request.  This is unrelated to the time that the server takes to respond to the request.
So ...

If this wait takes more then 3 seconds, will the tomcat connection time out?

No, it won't1.  In fact, it appears that Tomcat doesn't have any limits on how long a (synchronous) request may take to complete.
Of course, the client could timeout a request if the server takes too long.  It is unlikely that the server will notice this so that it can abandon the request.

1 - Assuming that the documentation is accurate.  However, that config option has been present for a number of Tomcat versions, with the same description.  If the documentation was wrong, this would surely have been noticed, reported and fixed.


text:
Q: What does @defer.inlineCallbacks mean when I don't need yield return a value? At scrapy.core.engine
ExecutionEngine method start

@defer.inlineCallbacks
def start(self):
    """Start the execution engine"""
    assert not self.running, "Engine already running"
    self.start_time = time()
    yield self.signals.send_catch_log_deferred(signal=signals.engine_started)
    self.running = True
    self._closewait = defer.Deferred()
    yield self._closewait

Why don't use self.signals.send_catch_log_deferred(signal=signals.engine_started) directly but instead of a yield ?

A:
Why don't use self.signals.send_catch_log_deferred(signal=signals.engine_started) directly but instead of a yield ?

Because send_catch_log_deferred returns a Deferred object. If you want to avoid a yield there, then you should use send_catch_log but the point of using send_catch_log_deferred is to allow listeners to return Deferred objects.
The signals that use send_catch_log are not able to return Deferred objects, hence they do not allow to perform asynchronous operations.
Edit: For a good introduction to inlineCallbacks see: http://krondo.com/?p=2441

A: @defer.inlineCallbacks expects the decorated function to be a generator function and calling a generator function inside decorated function (even returning one) doesn't make the function, a generator function. An investigation:
def gen():
    yield 1

def func(): return gen

import dis

dis.dis(gen)
  2           0 LOAD_CONST               1 (1)
              3 YIELD_VALUE
              4 POP_TOP
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE

dis.dis(func)
  1           0 LOAD_GLOBAL              0 (gen)
              3 RETURN_VALUE

import inspect

inspect.isgeneratorfunction(gen)
True

inspect.isgeneratorfunction(func)
False

So only way to satisfy @defer.inlineCallbacks is either yield a deferred from self.signals.send_catch_log_deferred(signal=signals.engine_started) or from somewhere else.


text:
Q: How to say "I understand how to do something conceptually, but not concretely?" As a programmer a situation comes up frequently, where I 'conceptually' know what I need to do, and I can explain the thing from a 'high level' - but I don't know exactly what to do.
Like, I know that "I need to inject a configuration into a project" but I don't know what files to change to make that configuration inject.
I haven't figured out a way to nicely express this notion, so I often find myself stumbling around saying things that don't make sense: "I know what to do, but I don't know exactly what to do". "So, you don't know?", "No, I know how kind of, but not exactly".

A: This is the difference between theory, which are the conceptual steps you need to take, and practice, which is the actual implementation of those steps.
If someone asks if you know how to solve a problem, you could respond, "I understand the solution in theory, but don't know how to implement it in practice."
For example, you might understand all the equations and pseudocode needed to implement an algorithm (the theory), but if you're working in a new programming language/environment, you might be unable to write a program that would actually run (the practice).

A: You could use the phrase "in principle" about which Lexico (Oxford Dictionaries) says

in principle
  PHRASE
1 As a general idea or plan, although the details are not yet established.
The plan was accepted in principle but the details for it were not.
1.1 Used to indicate that although something is theoretically possible, in reality it may not actually happen.
This all seemed a great idea in principle but of course the numbers don't work.

So you can say

I understand how to do this in principle but I have yet to work out the detail.


text:
Q: How to display dynamic ImageView from URL in infoWindow I'm trying to download an image and show it as an ImageView in my infoWindow , working with InfoWindowsAdapter , i put all the necessary code in the getInfoContents() method, but i can't get the image , in fact i can get it but still can't show it .
As i read in the documentation,i have to recall the treatment to set the downloaded image , i have to use showInfoWindow() method because it's the only way to do it . I tried to use it in getInfoContents() just before the return  but , it blocks my app , need help !
This is my getInfoContents() :
  public View getInfoContents(Marker marker) {
  // set the view
  View v = (View) getLayoutInflater().inflate(R.layout.info_window,null);

  //assign values to the view field

   ImageView imagePlace =(ImageView) v.findViewById(R.id.imageview1);
   TextView tvLocality = (TextView) v.findViewById(R.id.tv_place);

  //setting values with the parameter

  Picasso.with(getApplicationContext()).load(url_image_place).into(imagePlace);
  tvLocality.setText(marker.getTitle());

 //marker.showInfoWindow();
 return v;

}

This my downloadIcon() :
 private Bitmap downloadIcon(String iconURL) {
    Bitmap bmImg = null;
    try {
        URL url = new URL(iconURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        bmImg = BitmapFactory.decodeStream(is);
    } catch (IOException e) {
        e.printStackTrace();
        bmImg = null;
    }

    return bmImg;
}

EDIT :
I used picasso to download my image , but the image is shown only after the second click , and any marker's infowindow that use the same image get the image in the first time , it means that the image have to be downloaded first !! i edited my getInfoContents() and i'm not using downloadIcon() anymore !

A: Using Picasso, this is extremely easy. Simply write:
String url = ...;//Your url
ImageView imageView; //Your ImageView
Picasso.with(context).load(url).into(imageView);

Or, If you want to do it yourself, you can implement an AsyncTask:
Definition:
private class ImageDownloader extends AsyncTask {

        @Override
        protected Bitmap doInBackground(String... param) {
            return downloadIcon(param[0]);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            //Handle your result, i.e. your bitmap
        }
}

Execution:
new ImageDownloader().execute(iconURL);

A: You should not dowmload image by using main UI thread, so you need another thread to do it, something like:
public void setImage(final ImageView img, final String iconURL)
{

  Thread thread = new Thread(new Runnable() {

     @Override
     public void run()
     {
        Bitmap bmImg;

        try {

              URL url = new URL(iconURL);
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              conn.setDoInput(true);
              conn.connect();
              InputStream is = conn.getInputStream();
              bmImg = BitmapFactory.decodeStream(is);

        }
        catch (IOException e) {
             e.printStackTrace();
             bmImg = null;
        }

        //after downloading, then talk to main ui
        runOnUiThread(new Runnable()
        {
              @Override
              public void run()
              {
                   img.setImageBitmap(bmImg);

              }
        }

     }}).start();

 }

Hope this help!


text:
Q: Loop and modify xml nodes SQL Server I want to loop through xml nodes in SQL Server, and create a copy of each node containing ','.
For example, for the following xml :
 declare @answerXML xml = '<answers><answer part="1">answer,test0</answer><answer part="1">answer,test1</answer></answers>'

I want to be modified to become the following :
declare @answerXML xml = '<answers><answer part="1">answer,test0</answer><answer part="1">answer, test0</answer><answer part="1">answer,test1</answer><answer part="1">answer, test1</answer></answers>'

(Each node is duplicated, and in the added node, a space is added after the comma).
I was planing in using something like this :
SELECT
    T.ref.value('.', 'varchar(256)') AS Answer
FROM
    (SELECT
         [Xml] = @answerXML.query('for $i in data(/answers/answer)
                                   return element temp { $i }')
    ) A
CROSS APPLY
    A.Xml.nodes('/temp') T(ref)

But no use, it seems it's too complicated.
Can anyone help in how to loop and update XML in T-SQL?
Thank you in advance,

A: You can try to shred the XML and rebuild it from scratch:
declare @answerXML xml=
'<answers>
  <answer part="1">answer,test0</answer>
  <answer part="1">answer,test1</answer>
</answers>';

SELECT a.value(N'@part',N'int') AS [answer/@part]
      ,a.value(N'text()[1]',N'nvarchar(max)') AS [answer]
      ,''
      ,a.value(N'@part',N'int') AS [answer/@part]
      ,REPLACE(a.value(N'text()[1]',N'nvarchar(max)'),',',', ') AS [answer]
FROM @answerXML.nodes(N'/answers/answer') AS A(a)
FOR XML PATH(''),ROOT('answers')

The result
<answers>
  <answer part="1">answer,test0</answer>
  <answer part="1">answer, test0</answer>
  <answer part="1">answer,test1</answer>
  <answer part="1">answer, test1</answer>
</answers>


text:
Q: How to generate gradle run configs in intellij? How to generate runClient and runServer?
I downloaded sources of TheQuarkMod for 1.16.5 from GitHub and I don't know how can I generate run configs in IntelliJ.
Using Windows 10 and Java 8 (for this project - I have Installed Java 15 [or maybe Java 14 or Java 16])?

A: Add apply plugin: 'idea' under apply plugin: 'eclipse' in the build.gradle.
Then you can use gradlew genIntellijRuns to generate the runs, gradlew idea to create an Intellij project and gradlew openIdea to open it.
Use ./gradlew if you are using a UNIX-based System.


text:
Q: Bind data and display datatable on aspx page using Jquery in asp.net on tbody Here is my HTML table:

            Check Box
            Category Name
            Category Details
            Status
            Action

            Other browsers
            All others
            yes
            for
            Ummm

I have already bound the HTML table using jQuery. Here is my jQuery code:
$(document).ready(function() {
    debugger
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "WebForm5.aspx/BindDatatable",
        data: "{}",
        dataType: "json",
        success: function (dt) {
            for (var i = 0; i < dt.d.length; i++) {
                $("#example1").append("
 <input type='checkbox' />	" + dt.d[i].CategoryID + "	" + dt.d[i].Name + "	" + dt.d[i].description + "	 <button type='submit'>Submit</button>
");
            }
        },
        error: function (result) {
            alert("Error");
        }
    });
});

My problem is that the table is binding at
 not at
 thats why
jQuery paging, searching, sorting is not working. I Want to bind at
. What is wrong with my code? Can anyone help me out?

A: You have to define the child what you want. There is different alternative
You should replace your element $("#example1") by this :
$("#example1 tbody")

Or you can do this too :
$("#example1 > tbody")

You can define an ID to your tbody

And get it with jQuery :
$("#myBody")

Then you can do this :
$("#example1 > tbody").append("
 <input type='checkbox' />	" + dt.d[i].CategoryID + "	" + dt.d[i].Name + "	" + dt.d[i].description + "	 <button type='submit'>Submit</button>
");


text:
Q: product of two uniformly continuous functions is uniformly continuous Suppose that $f$ and $g$ are uniformly continuous functions defined on $(a,b)$. Prove that $fg$ is also uniformly continuous on $(a,b)$.
My attempt: Since $f$ is uniformly continuous on $(a,b)$, for all $\epsilon>0$, we have $\delta_f(\epsilon)>0$ such that for all $x,y \in (a,b)$, $|x-y|<\delta_f$, $|f(x)-f(y)|<\epsilon$
Since $g$ is uniformly continuous on $(a,b)$, for all $\epsilon>0$, we have $\delta_g(\epsilon)>0$ such that for all $x,y \in (a,b)$, $|x-y|<\delta_g$, $|g(x)-g(y)|<\epsilon$
Notice that $$|f(x)g(x)-f(y)g(y)|=|f(x)g(x)-f(x)g(y)+f(x)g(y)-f(y)g(y)| \leq |f(x)||g(x)-g(y)| + |g(y)||f(x)-f(y)|$$
Here I don't know how to bound $|f(x)|$ and $|g(y)|$. I have proven that uniformly continuous functions preserve boundedness of an interval , i.e. $f$ is bounded on $(a,b)$. Can anyone help me?

A: Let $f$ and $g$ be bounded functions. Hence there are $c,d\in\mathbf{R}$ such that $c,d>0$, $\vert f(x) \vert < c$ and $\vert g(y) \vert < d$ for every $x,y\in(a,b)$. Let $\epsilon>0$.
Since $f$ is uniformly continuous on $(a,b)$, $\exists\delta_f(\epsilon)>0$ such that for all $x,y \in (a,b)$, $|x-y|<\delta_f$, $|f(x)-f(y)|<\epsilon/2d$.
Since $g$ is uniformly continuous on $(a,b)$, $\exists\delta_g(\epsilon)>0$ such that for all $x,y \in (a,b)$, $|x-y|<\delta_g$, $|g(x)-g(y)|<\epsilon/2c$.
Let $\delta = min\{\delta_f,\delta_g\}$. Hence, for all $x,y\in(a,b), \vert x-y \vert<\delta \Rightarrow |g(x)-g(y)|<\frac{\epsilon}{2c}$ and $|f(x)-f(y)|<\frac{\epsilon}{2d}$. Since $\vert f(x) \vert < c$ and $\vert g(y) \vert < d$ for every $x,y\in(a,b)$, it also implies that
$$|f(x)g(x)-f(y)g(y)|=|f(x)g(x)-f(x)g(y)+f(x)g(y)-f(y)g(y)| \leq |f(x)||g(x)-g(y)| + |g(y)||f(x)-f(y)| < c.\frac{\epsilon}{2c} + d.\frac{\epsilon}{2d} = \epsilon$$
Finally we have $|f(x)g(x)-f(y)g(y)| < \epsilon$ and $f.g$ is uniformly continuous if $f$ and $g$ are bounded functions.

A: $f$ and $g$ are continuous on $[a,b]$ hence bounded
try to show :$\lim_{x\rightarrow a+} f(x)$ and $\lim_{x\rightarrow b-} f(x) $ exist as finite limits.

A: $f$ uniform continuous on $(a,b)$ implies $\exists \varepsilon > 0$ such that $|f(x)-f(y)|< 1$ whenever $|x - y| < \varepsilon$. Pick a $N \in \mathbb{N}$ such that $\frac{b-a}{N} < \varepsilon$, we then have:
$$ \min_{i=1 \ldots N-1} f(a + \frac{i}{N})- 1 < f(x) < \max_{i=1 \ldots N-1} f(a + \frac{i}{N}) +1$$
because every $x \in (a,b)$ is at a distance $< \varepsilon$ from one of the $a + \frac{i}{N}, i=1 \ldots N-1$.

A: For the product of two uniformly continuous functions to be uniformly continuous, the two functions need to be bounded.

A: There is a nice way:
Hint: Try to show that if f, g are Uniformly continuous, so are $f \pm g$ and $f^2$. Then observe that $fg = 0.5((f+g)^2 - f^2 -g^2)$. Hope this helps.

A: the product of two uniformly continuous functions is not necessarily uniformly continuous for example $f(x)=x$ and $g(x)= \sin x$ are uniformly continuous on $(0,1)$ but $f\cdot g is not.

A: Multiplication of two uniformly continuous function is not uniformly continuous function.
Let f (x)=x ,g (x)=sinx
They are both uniformly continuous function on (0,x). But f(x).g(x) is not uniformly continuous function on (0,x) ,for all x\in \Bbb R^+


text:
Q: Modify and customize the wxColourDialog box I need a dialog box where I can  choose colour, font format, font style, and font size. I mean using wxWidgets (need a dialog with wxColourDialog and wxFontDialog in a same dialog box).

A: Notice that under Windows the native font selection dialog already allows you to select the font colour too. This is not the case under the other platforms however, so you would need to use the non-native, and hence ugly, wxGenericFontDialog there if you really need to select both at once.


text:
Q: Deciphering a message using given algorithm The following code produces a text file with an encoded message derived from a different, readable textfile.
   #include <stdio.h>
   #include <time.h>
   #include <stdlib.h>

   main()
   {
     FILE *f, *f_enc;
     char c, c_enc;
     int ind, a[26], r_val;

     srandom(time(NULL));
     for (ind=0; ind<26; ind++) a[ind]=-1;
     for (ind=0; ind<26; ind++){
       do
         r_val=random()%26;
       while (a[r_val]!=-1);
       a[r_val]=ind;
     }

     f=fopen("plain.txt","r");
     f_enc=fopen("cipher.txt","w");
     while (!feof(f)) {
       c=fgetc(f);
       if ((c>='A' && c<='Z')||(c>='a' && c<='z')) {
         if (c>='A' && c<='Z') c = c + 'a' - 'A';
         c=a[c-'a']+'a';
       }
       fputc(c,f_enc);
     }
     fclose(f);
     fclose(f_enc);
   }

What I am unclear of is the overal algorithm the code is implementing to encode a message.

*

*Is it subtracting an ASCII value ('a - 'A) from the character to produce an encoded character?

An example output is given below:
xohq xpu ouuf yubliu spieqxkhq, hzj hcc xpilnap xpu plnqu
tln slncj puhi ku yuhxeza xpu slkmnxui oexp xpu klnqu.
xpu jeqf ohq pnza nm ez xpu jeqf jieru oexp shiu,
hzj, zuujcuqq xl qht, e zuhict mnccuj lnx kt phei.

e ahru nm bli xphx zeapx, alx iuhjt bli yuj,
hzj olzjuiuj, "qplncj e gnqx ynt shijq ezqxuhj?"
khkh hzj jhjjt phj gnqx pex xpu pht,
ql e xlcj xpuk allj zeapx, hzj ouzx lz kt oht.

I'm going to try to reverse engineer this to see if I can get ahold of what's going on.
Any speculation is welcomed!

A: This is a simple substitution, such as is used in a cryptogram puzzle. It can be solved with letter frequency analysis.
There exist automated solvers. The original text for the example is:

twas the week before christmas, and all through the house you could
  hear me beating the computer with the mouse. the disk was hung up in
  the disk drive with care, and, needless to say, i nearly pulled out my
  hair.  i gave up for that night, got ready for bed, and wondered,
  'should i just buy cards instead?' mama and daddy had just hit the
  hay, so i told them good night, and went on my way.


text:
Q: Play framework. Session becomes null after redirection from google sign in page I am trying to incorporate google analytics graph at web app to show user statistics of their app usages. This is the local url http://192.168.100.10:9000/ i login to dashboard (web app) i have a google sign in button. So far here i maintain the session of the user after when he logs in.
And when user click on the sign in button. It triggers callback method. When callback is triggered first time then it has session maintained. I mean session("user") isn't null here.
public Result callback() {
    JsonNode jsonNode = Json.parse(session("user"));
    UserDTO userDTO = Json.fromJson(jsonNode, UserDTO.class);

    if (userDTO.getRole().getType().equals(RoleDTO.EnRoleType.ADMIN.toString()))
        return redirect(com.softoven.ultron.controllers.routes.AccountCTRL.index());
    if (request().queryString().get("code") != null && request().queryString().get("state") != null && request().queryString().get("state")[0].equals(session("state"))) { // Check if he/she is authorized
        session().remove("state");
        Analytics analytics = setAnalytics(userDTO, request());
        session("analytics", Json.toJson(analytics).toString());
        return redirect(com.softoven.ultron.controllers.routes.AccountCTRL.index());
    } else {  // Create Authorization URL
        String url = helper.buildLoginUrl();
        session("state", helper.getStateToken());
        return redirect(url);
    }
}

This is the url when user clicks on the sign in button
https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=784122128025-cvq0fn1e23f24dia4soavsd9v1ovesub.apps.googleusercontent.com&redirect_uri=http://localhost:9000/callback&response_type=code&scope=https://www.googleapis.com/auth/analytics.readonly%20https://www.googleapis.com/auth/analytics.manage.users%20https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/analytics.edit%20https://www.googleapis.com/auth/analytics.manage.users.readonly%20https://www.googleapis.com/auth/analytics.provision&state=google-35808300 And when user click on the allow button on the permission page of the google sign in then control goes back to callback()

but this time session("user") is null. which shouldn't be null because i had set the session when user logged in. I don't know why is it happening and how to fix this.
And this is the end url after the redirect from google permission page.
http://localhost:9000/callback?state=google-35808300&code=4/g-FkJ3GGS01jbeXLHK0o95ks-K-drGK7bxgzvi3cELU#

A:
This is the local url http://192.168.100.10:9000/ ...
... &redirect_uri=http://localhost:9000/ ...
And this is the end url after the redirect from google permission page http://localhost:9000/ ...

The starting URL is different from the ending URL. This is not correct.
Normally, the HTTP session in server side is tied to a session cookie. Cookies are in turn tied to a specific hostname (IP or domain). Webbrowsers are very strict in sending cookies to the specific hostname. Even though the IP would DNS-resolve to the correct domain, webbrowsers may refuse sending the cookie created on an IP address along with a request on the domain name. Basically, the webserver won't retrieve the originally created session cookie and hence creates a new one.
Then there exist webbrowsers who reject cookies whose hostname is explicitly set to "localhost", such as Google Chrome: Chrome doesn't create cookie for domain=localhost in broken https. Browsers may also choose to reject cookies whose hostname is explicitly set to an IP address because this may cause security trouble when client uses a dynamic IP.
It's therefore strongly recommended to use a real domain name such as example.com instead of an IP address or "localhost". Without buying one, you can fake one by simply editing the hosts file. The format of each line is like below, first the IP addres and thereafter the desired domains space separated.
127.0.0.1 localhost example.com anotherexample.com

Then consistently use exactly that domain throughout the process. Start at http://example.com:9000/..., use &redirect_uri=http://example.com:9000/... etc.
I don't do Play Framework, but if you're familiar with Servlet API, you may better understand the working of the HTTP session after reading this related Q&A: How do servlets work? Instantiation, sessions, shared variables and multithreading.


text:
Q: SSE copy data to variables I'm optimizing a piece of code that moves particles on the screen around gravity fields. For this we're told to use SSE. Now after rewriting this little bit of code, I was wondering if there is an easier/smaller way of storing the values back in the array of particles.
Here's the code before:
for (unsigned int i = 0; i < PARTICLES; i++) {
    m_Particle[i]->x += m_Particle[i]->vx;
    m_Particle[i]->y += m_Particle[i]->vy;
}

And here's the code after:
for (unsigned int i = 0; i < PARTICLES; i += 4) {
    // Particle position/velocity x & y
    __m128 ppx4 = _mm_set_ps(m_Particle[i]->x, m_Particle[i+1]->x,
                             m_Particle[i+2]->x, m_Particle[i+3]->x);
    __m128 ppy4 = _mm_set_ps(m_Particle[i]->y, m_Particle[i+1]->y,
                             m_Particle[i+2]->y, m_Particle[i+3]->y);
    __m128 pvx4 = _mm_set_ps(m_Particle[i]->vx, m_Particle[i+1]->vx,
                             m_Particle[i+2]->vx, m_Particle[i+3]->vx);
    __m128 pvy4 = _mm_set_ps(m_Particle[i]->vy, m_Particle[i+1]->vy,
                             m_Particle[i+2]->vy, m_Particle[i+3]->vy);

    union { float newx[4]; __m128 pnx4; };
    union { float newy[4]; __m128 pny4; };
    pnx4 = _mm_add_ps(ppx4, pvx4);
    pny4 = _mm_add_ps(ppy4, pvy4);

    m_Particle[i+0]->x = newx[3]; // Particle i + 0
    m_Particle[i+0]->y = newy[3];
    m_Particle[i+1]->x = newx[2]; // Particle i + 1
    m_Particle[i+1]->y = newy[2];
    m_Particle[i+2]->x = newx[1]; // Particle i + 2
    m_Particle[i+2]->y = newy[1];
    m_Particle[i+3]->x = newx[0]; // Particle i + 3
    m_Particle[i+3]->y = newy[0];
}

It works, but it looks way too large for something as simple as adding a value to another value. Is there a shorter way of doing this without changing the m_Particle structure?

A: There's no reason why you couldn't put x and y side by side in one __m128, shortening the code somewhat:
for (unsigned int i = 0; i < PARTICLES; i += 2) {
    // Particle position/velocity x & y
    __m128 pos = _mm_set_ps(m_Particle[i]->x, m_Particle[i+1]->x,
                            m_Particle[i]->y, m_Particle[i+1]->y);
    __m128 vel = _mm_set_ps(m_Particle[i]->vx, m_Particle[i+1]->vx,
                            m_Particle[i]->vy, m_Particle[i+1]->vy);

    union { float pnew[4]; __m128 pnew4; };
    pnew4 = _mm_add_ps(pos, vel);

    m_Particle[i+0]->x = pnew[0]; // Particle i + 0
    m_Particle[i+0]->y = pnew[2];
    m_Particle[i+1]->x = pnew[1]; // Particle i + 1
    m_Particle[i+1]->y = pnew[3];
}

But really, you've encountered the "Array of structs" vs. "Struct of arrays" issue.  SSE code works better with a "Struct of arrays" like:
struct Particles
{
    float x[PARTICLES];
    float y[PARTICLES];
    float xv[PARTICLES];
    float yv[PARTICLES];
};

Another option is a hybrid approach:
struct Particles4
{
    __m128 x;
    __m128 y;
    __m128 xv;
    __m128 yv;
};

Particles4 particles[PARTICLES / 4];

Either way will give simpler and faster code than your example.

A: I went a slightly different route to simplify: process 2 elements per iteration and pack them as (x,y,x,y) instead of (x,x,x,x) and (y,y,y,y) as you did.
If in your particle class x and y are contiguous floats and you align fields on 32 bits, a single operation loading a x as a double will in fact load the two floats x and y.
for (unsigned int i = 0; i < PARTICLES; i += 2) {
    __m128 pos = _mm_set1_pd(0); // zero vector
    // I assume x and y are contiguous in memory
    // so loading a double at x loads 2 floats: x and the following y.
           pos = _mm_loadl_pd(pos, (double*)&m_Particle[i  ]->x);
    // a register can contain 4 floats so 2 positions
           pos = _mm_loadh_pd(pos, (double*)&m_Particle[i+1]->x);

    // same for velocities
    __m128 vel = _mm_set1_pd(0);
           vel = _mm_loadl_pd(pos, (double*)&m_Particle[i  ]->vx);
           vel = _mm_loadh_pd(pos, (double*)&m_Particle[i+1]->vy);

    pos = _mm_add_ps(pos, vel); // do the math

    // store the same way as load
    _mm_storel_pd(&m_Particle[i  ]->x, pos);
    _mm_storeh_pd(&m_Particle[i+1]->x, pos);
}

Also, since you mention particle, do you intend to draw them with OpenGL / DirectX ? If so, you could perform this kind of permutation on the GPU faster while also avoiding data transfers from main memory to GPU, so it's a gain on all fronts.
If that's not the case and you intend to stay on the CPU, using an SSE friendly layout like one array for positions and one for velocities could be a solution:
struct particle_data {
    std::vector<float> xys, vxvys;
};

But it would have the drawback of either breaking your architecture or requiring a copy from your current array of structs to a temporary struct of arrays. The compute would be faster but the additional copy might outweigh that. Only benchmarking can show...
A last option is to sacrifice a little performance and load your data as it is, and use SSE shuffle instructions to rearrange the data locally at each iteration. But arguably this would make the code even harder to maintain.

A: For the design of performance you should avoid handling array of structure but you should work with structure of array.


text:
Q: is it possible to change layout content in laravel through ajax request? This the controller file, which setup layout of view.
class DashboardController extends BaseController{

    public  function __construct(){
        $this->layout='expert-dashboard::layouts.default';
    }

    public function index(){
        $action=Input::get('action');
        if($action=="dashboard"){
            $this->layout->content=View::make(Config::get('expert-dashboard::dashboard'));
            return ;

        }else{
            $this->layout->content=View::make(Config::get('expert-dashboard::activity'));
            return;

        }

    }
}

The js code which calls the action to replace with different content dynamically.The result shows, the the layout content has changed but not rendered. what will be the cause,else how to render the change.
$scope.changeContent=function(){
        $http({
            method: 'GET',
            url: './dashboard',
            params:{
                "action":"dashboard"
            },
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}

        }).
            success(function(response) {

            }).
            error(function(response) {
            });
    };


text:
Q: Angular 8 to Angular 9 migration issues I have migrated from angular 8 to angular 9 then i got the below issues For this i have removed the node_modules many times and installed freshly but still i am getting the below issues:
An unhandled exception occurred: Cannot find module 'webpack/lib/ParserHelpers'
Require stack:
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\worker-plugin\dist\worker-plugin.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular-devkit\build-angular\src\angular-cli-files\models\webpack-configs\worker.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular-devkit\build-angular\src\angular-cli-files\models\webpack-configs\index.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular-devkit\build-angular\src\browser\index.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular-devkit\build-angular\src\dev-server\index.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\node_modules\@angular-devkit\architect\node\index.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\models\architect-command.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\commands\serve-impl.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular-devkit\schematics\tools\export-ref.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular-devkit\schematics\tools\index.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\utilities\json-schema.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\models\command-runner.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\lib\cli\index.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\lib\init.js
- E:\ng9\Fxt\Web\src\main\ui\material\node_modules\@angular\cli\bin\ng
See "C:\Users\ADMIN\AppData\Local\Temp\ng-MOOMPS\angular-errors.log" for further details.
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file C:\WINDOWS\system32\cmd.exe
npm ERR! errno ENOENT
npm ERR! material@3.0.0 start: `ng serve --proxy-config proxy.config.json`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the material@3.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ADMIN\AppData\Roaming\npm-cache\_logs\2020-11-17T16_17_33_897Z-debug.log

A: uninstall webpack and then again install it globally.

npm uninstall -g webpack
npm install webpack -g

uninstall cli and then again install it globally.

npm uninstall -g @angular/cli
npm install -g @angular/cli

And now try to install node modules again.

rm node_modules -r -force
rm package-lock.json
npm cache verify
npm install


text:
Q: Elevator system schematic diagram in Latex I am working on a project related to elevator group control systems, and I am writing a paper right now, but I need to show a diagram that depicts an elevator system diagram in the paper, the example is shown below.
Could someone please tell me from where to start in order to obtain the shown results? I already have experience in using Tikz library and PGFPlots, but I only used them to create simple plots.

Edit: this is the code I have tried, but the results are far from what I wanted.
\documentclass[border=2mm]{standalone}
\usepackage{pgfgantt}
\begin{document}

\begin{ganttchart}[vgrid]{1}{5}
\gantttitle{Title}{5} \\
\ganttbar{}{1}{1} \\
\ganttbar{}{2}{2} \\
\ganttbar{}{3}{3} \\
\ganttbar{}{4}{4} \\
\ganttbar{}{5}{5} \\
\end{ganttchart}

\end{document}

A: Pure
\documentclass[tikz]{standalone}
\tikzset{elevator/.style={fill=black,inner sep=0pt,minimum height=0.7cm,minimum width=0.2cm}}
\begin{document}
\begin{tikzpicture}[x=2cm,>=latex]
\foreach \i/\elev/\mione/\mitwo in {
    1/7/8/9,
    4/1/3/6
} {
    \draw (\i,0) -- (\i,9);
    \foreach \j in {0,...,9} \draw (\i-.1,\j) -- (\i+.1,\j);
    \node at (\i,10) {Shaft \i};
    \path (\i-.1,\elev) node[left=.3333em,elevator] {};
    \path (\i-.1,\mione) node[left] {$-$};
    \path (\i-.1,\mitwo) node[left] {$-$};
}
\foreach \i/\elev/\mione/\mitwo in {2/6/0/4,3/8/0/0} {
    \draw (\i,0) -- (\i,9);
    \foreach \j in {0,...,9} \draw (\i-.1,\j) -- (\i+.1,\j);
    \node at (\i,10) {Shaft \i};
    \path (\i+.1,\elev) node[right=.3333em,elevator] {};
    \path (\i+.1,\mione) node[right] {$-$};
    \path (\i+.1,\mitwo) node[right] {$-$};
}
\draw (5,0) -- (5,9);
\foreach \i in {0,...,9} \draw (4.9,\i) -- (5.1,\i);
\node at (5,10) {Buttons};
\foreach \i in {2,3} \path (5.1,\i) node[right] {$+$};
\foreach \i in {5,8} \path (4.9,\i) node[left] {$+$};
\path (4.9,0) node[left] (up) {up};
\path (5.1,9) node[right] (dn) {dn};
\draw[->] (up) -- ++ (0,2);
\draw[->] (dn) -- ++ (0,-2);
\end{tikzpicture}
\end{document}


text:
Q: How can I identify the packages with conflicting dependencies? When performing sudo apt upgrade I get the following error message:
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libcurl4 : Conflicts: libcurl3 but 7.60.0-1 is to be installed
E: Broken packages

I understand this to mean:

*

*You have previously installed package X, which relies on libcurl4 (so libcurl4 is already installed).

*Your upgrade includes a package Y with a new dependency on libcurl3 (version 7.60.0-1).

*libcurl3 cannot be installed because it conflicts with libcurl4.

I used GNOME Packages to look at the lists of packages that require libcurl3 and libcurl4, but the lists are very long and can't be narrowed down (specifically, they don't indicate which packages are already installed or which are about to be installed).
I tried apt debugging but it doesn't seem to add any information:
$ sudo apt -o Debug::pkgProblemResolver=yes upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Entering ResolveByKeep 10%
  Dependencies are not satisfied for libcurl4:amd64 < 7.60.0-2 @ii mK Ib >
Keeping package libcurl4:amd64
  Dependencies are not satisfied for libcurl4:amd64 < 7.60.0-2 @ii mK Ib >
Package libcurl4:amd64 libcurl4:amd64 Conflicts on libcurl3:amd64 < none -> 7.60.0-1 @un uN >
  Dependencies are not satisfied for libcurl4:amd64 < 7.60.0-2 @ii mK Ib >
  Dependencies are not satisfied for libcurl4:amd64 < 7.60.0-2 @ii mK Ib >
  Dependencies are not satisfied for libcurl4:amd64 < 7.60.0-2 @ii mK Ib >
Calculating upgrade... Done
<repeats previous error message>

How can I identify package X (the existing package) and package Y (the new package, or an existing package with a new dependency)?

A: To identify packages causing conflicts (or other issues) during a package upgrade, I find the most helpful approach is to enable the resolver's debugging mode:
apt -o Debug::pkgProblemResolver=yes upgrade

This will show you all the problems the resolver runs into, along with the packages which caused it to consider the problematic dependencies.

A: Another take to add to @StephenKitt excelent answer is installing and using aptitude.
aptitude is usually a bit smarter managing packages and specially helping and suggesting alternatives when there are conflicts.
The usage is also very similar to apt as in using, aptitude install, aptitude update and aptitude upgrade. If you call aptitude without arguments, it will invoke a text menu interface.
From man aptitude

aptitude - high-level interface to the package manager
aptitude is a text-based interface to the Debian GNU/Linux package
  system.
It allows the user to view the list of packages and to perform package
  management tasks such as installing, upgrading, and removing packages.
  Actions may be performed from a visual interface or from the
  command-line.

For more details see aptitude - Command-line reference


text:
Q: MySql CREATE EVENT Error
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END$$ DELIMITER' at line 4

CREATE EVENT event_1 ON SCHEDULE EVERY 1 WEEK STARTS CURRENT_DATE + INTERVAL 6 - WEEKDAY(CURRENT_DATE) DAY DO BEGIN
UPDATE
    sonice_User
SET
    update_chance = "1"; END

A: use below code:
 Delimiter $$
 CREATE EVENT event_1 ON SCHEDULE EVERY 1 WEEK
     STARTS CURRENT_DATE + INTERVAL 6 - WEEKDAY(CURRENT_DATE) DAY
     DO
     BEGIN
     UPDATE   sonice_User
     SET update_chance = "1";
     END $$
 Delimiter ;

A:      CREATE EVENT event_1 ON SCHEDULE EVERY 1 WEEK
     STARTS CURRENT_DATE + INTERVAL 6 - WEEKDAY(CURRENT_DATE) DAY
     DO
     UPDATE   sonice_User
     SET update_chance = "1";


text:
Q: How to set landscape orientation mode for flutter app? I was looking for code which can set orientation of my flutter app landscape forcefully.

A: import 'package:flutter/services.dart';

void main()  {
   WidgetsFlutterBinding.ensureInitialized();
   SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft])
   .then((_) {
    runApp(new MyApp());
  });
}

A: SystemChrome.setPreferredOrientations is applicable for Flutter part of the app, but it's not a full solution. Because when you launching the app - Flutter are not created yet. So you should also setup orientation in the native parts.
Here the article with detailed instructions https://medium.com/@greymag/flutter-orientation-lock-portrait-only-c98910ebd769

A: Enable forcefully
Import package: import 'package:flutter/services.dart'; in main.dart file
1. Landscape mode:
// Set landscape orientation
SystemChrome.setPreferredOrientations([
  DeviceOrientation.landscapeLeft,
  DeviceOrientation.landscapeRight,
]);

2. Portrait mode:
// Set portrait orientation
SystemChrome.setPreferredOrientations([
   DeviceOrientation.portraitDown,
   DeviceOrientation.portraitUp,
]);