text:
Q: Suppose $f$ is in $C([0,1])$ and $f(0)=f(1)=0$. Show that $f$ is the uniform limit of a sequence of polynomials with $p_n(0) =p_n(1) = 0$ for all $n$. I am stuck on how to start. My idea is the following but I am not sure how it will lead to anything:

*

*We know that because $f$ is continuous function on real interval $[a,b]$, then for all $\epsilon$, there is polynomial $p$ such that for all $x\in[a,b]$, we have that $\left | f(x)-p(x) \right |< \epsilon $ by Weierstrass' Theorem.

*Construct Taylor series for $f(x)$, call it $p(x)$.

*So $f(x)-p(x) =0 $ so it will clearly be less than any choice of $\epsilon$.
But, how do the conditions on $f$, that $f(0)=f(1)=0$ come into play? Am I even on right track?

A: Here it is a trick: since $f(x)$ is continuous on $[0,1]$, we have $|f(x)|\leq M$ for any $x\in[0,1]$.
Let $g(x)=\frac{1}{\sqrt{2M}}\sqrt{f(x)+2M}$, which is also a continuous function. By the Weierstrass approximation theorem there is some polynomial $g_n(x)$ such that $\left|g(x)-g_n(x)\right|\leq \frac{1}{n}$ for any $x\in[0,1]$.
$$ h_n(x) = g_n(x)+(1-g_n(0))(1-x)+(1-g_n(1))x $$
is a polynomial such that $h_n(0)=h_n(1)=1$ and $|g(x)-h_n(x)|\leq \frac{2}{n}$ for any $x\in[0,1]$.
$$ f_n(x) = 2M h_n(x)^2 - 2M $$
is a polynomial such that $f_n(0)=f_n(1)=0$ and $|f(x)-f_n(x)|\leq\frac{5M}{n}$ for any $x\in[0,1]$.

If $f(x)$ is differentiable at $0$ and $1$ we may simply approximate $\frac{f(x)}{x(1-x)}$ through polynomials $p_n(x)$, then consider $f_n(x)=x(1-x)p_n(x)$. Of course this approach does not work if $f(x)=\sqrt{x(1-x)}$, for instance. And in general not every continuous function agrees with its Taylor series at some point.

A: Let $|f(x)-p(x)|<\epsilon$ for all $x$. Let $q(x)=p(x)-p(0)-x(p(1)-p(0)$. The $q$ is polynomial with $q(0)=0$ and $q(1)=0$. Also $|f(x)-q(x)|<|f(x)-p(x)|+|p(0)|+|p(1)-p(0)| \leq  \ 4\epsilon $. ($ |p(0)| \leq |f(0)-p(0)|+|f(0)| <\epsilon$ etc).


text:
Q: Simplifying the modification of strings from a dynamic list? I want to change a list of strings from one format to another.
An example of a full list can be found here: https://gist.github.com/ProGamerGov/1d728e7ca4cc52abf398277642e4ee78
Some examples of what I am trying to do:
Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))

To:
(2): Conv2d(3 -> 64, 3x3, 1,1, 1,1)

And this:
Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))

To this:
(8): Conv2d(64 -> 128, 3x3, 1,1, 1,1)

My current code setup looks like this:
def modify_text(text, new):
    return text.replace(", ","*", 1).replace(", ", new, 1)

for i, layer in enumerate(net):
        if "Conv2d" in str(layer):
           layer = str(layer).replace(","," ->", 1)
           layer = modify_text(layer, "x").replace("kernel_size=(", "").replace("stride=(", "").replace("padding=(", "").replace(")","", 3)
           layer = modify_text(modify_text(layer, ","), ",").replace("*",", ")
           print("  (" + str(i+1) + "): " + layer)

But I feel like I there could be a better looking/simpler way to do this?
Edit, I've simplified my setup down to this:
regx_map = r'(2d).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*'
regx_pool = r'(2d).*?(\d+).*?(\d+).*?(\d+).*'
for i, layer in enumerate(net):
     if "Conv2d" in str(layer):
          print("  (" + str(i+1) + "): " + re.sub(regx_map, r'\1(\2 -> \3, \4x\5, \6,\7, \8,\9)', str(layer)))
     elif "MaxPool2d" in str(layer) or "AvgPool2d" in str(layer):
          print("  (" + str(i+1) + "): " + re.sub(regx_pool, r'\1(\2x\2, \3,\3)', str(layer)))
     else:
          print("  (" + str(i+1) + "): " + "nn." + str(layer).split("(", 1)[0])

A: You could  use a regular expression to match:
import re
s = 'Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))'
regx = r'(Conv2d).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*'

print(re.sub(regx, r'\1(\2 -> \3, \4x\5, \6,\7,\8,\9)', s))

Output:
Conv2d(3 -> 64, 3x3, 1,1,1,1)

If you wanted to make the regex slightly more robust at the cost of it being quite long:
(Conv2d)\((\d+),\s(\d+),\skernel_size=\((\d+),\s(\d+)\),\sstride=\((\d+),\s(\d+)\),\spadding=\((\d+),\s(\d+)\)\)

Try it out here

A: You can use regex to parse the signatures of the functions in the strings, convert the parameters to the desired syntax, and then and then use re.sub to add the new signatures:
import re
import itertools
def signature(header):
  s = re.findall('(?<=\()[\w\W]+(?=\)$)', header)
  return re.split(',\s(?=\w\w)', s[0]) if s else ''

def combine_args(d):
   if '=' in d:
      return '{}x{}'.format(*re.findall('\d+', d)) if 'kernel_size' in d and len(re.findall('\d+', d)) == 2 else '{},{}'.format(*re.findall('\d+', d)) if len(re.findall('\d+', d)) == 2 else d
   return d

def combine_header(d):
  vals = [[a, list(b)] for a, b in itertools.groupby(d, key=lambda x:x.isdigit())]
  return list(itertools.chain(*[[' -> '.join(b)] if a else [combine_args(i) for i in b] for a, b in vals]))

lines = ['TVLoss()', 'Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())', 'Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)', 'Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())', 'Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)', 'Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())', 'Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)', 'Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())', 'Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'ContentLoss((crit): MSELoss())', 'Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)', 'Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())']
final_lines = [re.sub('(?<=\()[\w\W]+(?=\)$)', ', '.join(combine_header(c)), a) for a, c in zip(lines, map(signature, lines))]

Output:
['TVLoss()', 'Conv2d(3 -> 64, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())', 'Conv2d(64 -> 64, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)', 'Conv2d(64 -> 128, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())', 'Conv2d(128 -> 128, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)', 'Conv2d(128 -> 256, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())', 'Conv2d(256 -> 256, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'Conv2d(256 -> 256, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'Conv2d(256 -> 256, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)', 'Conv2d(256 -> 512, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())', 'Conv2d(512 -> 512, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'ContentLoss((crit): MSELoss())', 'Conv2d(512 -> 512, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'Conv2d(512 -> 512, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)', 'Conv2d(512 -> 512, 3x3, 1,1, 1,1)', 'ReLU(inplace)', 'StyleLoss((gram): GramMatrix()(crit): MSELoss())']

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenStreeMaps with ASP MVC .NET I would like to develop a project using OpenStreeMaps and ASP MVC. I have been googling but have not found any example, I found a library called thinkgeo but we can't afford to pay for it. Does anyone know an example of OpenStreetMaps with ASP MVC?

A: It doesn't clear what do you want to use ASP.net. Routing, for POI-s, searching?
If you want to embed an OSM map and show some places or routes on it, see OpenLayers:
http://www.openlayers.org/

A: All of the map rendering stuff happens on the client side (so the ASP MVC portion of this is moot insofar as rendering the map) - you need to find yourself a good javascript map client. The one I've done this with before is leaflets:
LefletJS Quickstart Guide
you add the relevant JS to your ASP MVC project and setup the view.cshtml to create a map. Unless the controller is telling the map where to render, JS/HTML should be all you need. If you give this a go and run into issues, please elaborate in your question above.


text:
Q: Customizing jQuery Mobile Rangeslider Widget I am using jquery mobile rangeslider for accepting a time range in a hybrid app. Can I customize the events/ properties of Rangeslider Widget so that my Widget will be like

If not possible, can anyone suggest an alternate control/widget for this?

A: The jQM rangeslider does not support time ranges out-of-the-box. However, you can add some script, CSS, and a couple of type="time" inputs to accomplish your goal.

Working DEMO

For the HTML, I have created a table with 1 row and 3 columns. The rangeslider goes in the middle column while the low and high time inputs go in the 1st and 3rd columns respectively. The middle column automatically stretches with the page width.

            <input data-mini="true" class="timeInp" type="time" id="t1" value="06:30" data-timeinputid="range-1a" />

                <input type="range" name="range-1a" id="range-1a" min="0" max="1439" value="0" data-timeinputid="t1" class="timeRange" />

                <input type="range" name="range-1b" id="range-1b" min="0" max="1439" value="1" data-timeinputid="t2" class="timeRange" />

            <input data-mini="true" class="timeInp" type="time" id="t2" value="16:00" data-timeinputid="range-1b" />

I have assigned the class timeInp to the 2 type="time" inputs and the class timeRange to the 2 type="range" inputs for convenience when attaching events. I have also used data-attributes to associate the each time input with its range input (e.g. data-timeinputid="t1").
The CSS makes sure the table stretches to the page width. It hides the default number inputs and it removes the default margins:
#theTimeRange {
    width: 100%;
}
#theTimeRange tr > td:first-child, #theTimeRange tr > td:last-child {
    width: 110px;
}
#theTimeRange input[type='number'] {
    display: none;
}
#theTimeRange .ui-rangeslider-sliders {
    margin: 0;
}

Finally, I put script in the pagecreate event of the jQM page. This script initializes the rangeslider to match the times in the time inputs. Then there are change handlers on both the time inputs and the range inputs that convert between time and integer minutes to sync in both directions. The user can update either the time inputs, or drag the slider.
$(document).on("pagecreate", "#page1", function(){

    $(".timeRange").on("change", function(e){
        var val = $(this).val();
        var timeid = $(this).jqmData("timeinputid");
        var d = MinutesToTime(val);
        $("#" + timeid).val(d);
    });

    $(".timeInp").on("change", function(e){
        var val = $(this).val();
        console.log(val);
        var timeid = $(this).jqmData("timeinputid");
        var d = TimeToMinutes(val);
        console.log(d);
        $("#" + timeid).val(d)
        $('#theTimeRange [data-role="rangeslider"]').rangeslider("refresh");
    });

    //sync rangeslider to inputs at page create
    $(".timeInp").each(function(idx){
        var val = $(this).val();
        var timeid = $(this).jqmData("timeinputid");
        var d = TimeToMinutes(val);
        $("#" + timeid).val(d)
    });
    $('#theTimeRange [data-role="rangeslider"]').rangeslider("refresh");

});

function MinutesToTime(val){
    var hours = parseInt( val / 60 );
    var min = val - (hours * 60);
    var time = (hours < 10 ? '0' + hours: hours) + ':' + (min < 10 ? '0' + min : min);
    return time;
}

function TimeToMinutes(val){
    var res = val.split(":");
    var h = parseInt(res[0]);
    var m = parseInt(res[1]);
    return (h * 60) + m;
}

Another link to the DEMO


text:
Q: Is it possible to use a c++ library from an older c++ version? So I'm trying to use JSON as a file format for my c++ project. But I cant find a library for C++17. There are a few(nlohmann/json,RapidJSON) for older versions, such as C++11 but I don't know if it's possible to use an older one. Can I do this?

A: C++ versions are largely backwards compatible with prior versions. Any incompatibility are (usually) done for a specific purpose and with some degree of deprecation or the like.
So broadly speaking, a C++11 library (header-only or compiled) will compile under a C++17 compiler. There are times when this will fail, but they're usually around specific library types (like std::auto_ptr or somesuch).
For compiled libraries, ABI can be an issue (which means you may need to recompile them, which requires the source code). But for header-only libraries, this isn't a problem, since you're always compiling them.


text:
Q: How do I access Redux items using selectors after I've normalized my store? I'm a bit confused on how I'm supposed to use selectors after I've normalized my Redux store.
I have the following setup for my store:
const DEFAULT_STATE = {
  allId: [],
  locations: {}
};

With the following for my reducer:
handleActions({
  ['UPDATE']: (state, action) => {
    let newID = state.allId.length;

    const allId = [...state.allId, newID];
    const locations = {
      ...state.locations,
      [newID]: action.payload
    };
    return {allId, locations};
  }
}),
...

I figured I would want something like this for my component:
function mapStateToProps(state) {
  return {
    share: callMySelector(state)
  };
}

But I don't see how my selector would do anything except return the location associated with the most recent ID. I'm thinking that normalizing is also not that great here - because I wouldn't end up searching by ID in a regular case.

A: The power of selectors is that it moves filtering logic away from the component consuming the data, and away from the actions/reducer into reusable functions. You mentioned getting the most recent location. From the update logic in the reducer, we'd just make a selector that grabs the last item.
function selectLatestLocation(state) {
  const latestId = state.allIds[state.allIds.length - 1];

  return state.locations[latestId];
}

This assumes the location data is structured with the location id as the key.
 {
   1: { id: 1, name: "USA" },
   2: { id: 2, name: "Europe" }
 }

In this case, normalizing the data isn't doing much. But let's say requirements change, and now we only want Europe locations. We could have another state property called europeIds that contains all Europe location ids.
function selectEuropeLocations(state) {
   return state.europeIds.map(id => state.locations[id]);
}

Using selectors with normalized Redux state make it really easy to change how data is filtered. Now like you said, some cases might not need to be normalized. It is really up to the project, and what is being accomplished. But, it's definitely worth it for data that needs to be memoized, or filtered in different ways!


text:
Q: Can the diode be ignored in this Op amp circuit?
Consider the circuit below:

The diode is ideal and \$R=1000\Omega\$.
What is \$v_o\$ when \$v_{in}=3V\$?
What is \$v_o\$ when \$v_{in}=-3V\$?

So my idea was just to make node equations to solve these to find \$v_o\$, but when I do that I completely ignore the diode. I do like this.
For this op amp we have: \$v_-=v_+=0V\$
When \$v_{in}=3V\$:
\$\frac{v_--3V}{R}+\frac{v_--v_o}{R}=0\$
Inserting \$v_-=0V\$ and solving this equation we find that: \$v_o=-3V\$
When \$v_{in}=-3V\$:
\$\frac{v_-+3V}{R}+\frac{v_--v_o}{R}=0\$
Inserting \$v_-=0V\$ and solving this equation we find that: \$v_o=3V\$
As you can see, I'm not really thinking about the diode at all. Am I solving the problem correctly?

A:
simulate this circuit – Schematic created using CircuitLab

*

*When Vi > 0 the diode conducts and shorts out R2. Stability will be reached when Vo = -0.7 V (for a real Si diode) and at 0 V for the ideal diode in the question.

*When Vi < 0 the diode is reverse biased and is effectively out of the circuit. \$ V_O = - V_I \$.

*The circuit when created with a real diode is an imperfect (due to the -0.7 V output) inverting half-wave rectifier.

From the comments:

Doesn't an op-amp force the voltage on both inputs to be the same?

Yes, in negative feedback configuration.

*

*In Figure 1b we have a current flowing through R3 tending to raise the voltage on the inverting input. This will cause the output to swing negative.

*When the output swings to just below zero (or just below -0.7 V with a real diode) the input will have been pulled down to 0 V and will match the voltage at the non-inverting input. The output will stabilise at that point.


text:
Q: Unity webview loading webpage locally/by storing cache I am trying to build a unity project, in my project i have to show the web page in app using unity webview either by loading locally or by once storing cache of that web page. i have tried loading locally by downloading a web page but without internet the content of the html files loaded but CSS, JS and Images are not. for loading locally i have pasted the folders and HTML file to a folder in project-> Assests-> Streaming Assets. Image for folders and HTML file is Streaming Assets directory Image the underlined folders and file is used. And in unity editor link for the file is provided like this:- Unity Editor Image and script used to load the file is below
case RuntimePlatform.OSXEditor:
    case RuntimePlatform.OSXPlayer:
    case RuntimePlatform.IPhonePlayer:
    case RuntimePlatform.Android:
        if (Url.StartsWith("http")) {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        } else {
            webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
            var src = System.IO.Path.Combine(Application.streamingAssetsPath, Url);
            var dst = System.IO.Path.Combine(Application.persistentDataPath, Url);
            var result = "";
            if (src.Contains("://")) {
                var www = new WWW(src);
                yield return www;
                result = www.text;
            } else {
                result = System.IO.File.ReadAllText(src);
            }
            System.IO.File.WriteAllText(dst, result);
            webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
        }
        if (Application.platform != RuntimePlatform.Android) {
            webViewObject.EvaluateJS(
                "window.addEventListener('load', function() {" +
                "   window.Unity = {" +
                "       call:function(msg) {" +
                "           var iframe = document.createElement('IFRAME');" +
                "           iframe.setAttribute('src', 'unity:' + msg);" +
                "           document.documentElement.appendChild(iframe);" +
                "           iframe.parentNode.removeChild(iframe);" +
                "           iframe = null;" +
                "       }" +
                "   }" +
                "}, false);");
        }
        break;
    #else

If anyone Knows Please help.


text:
Q: VPN disconnects after exactly 3 minutes and 30 seconds I have set up a vpn server using the scripts in https://github.com/hwdsl2/setup-ipsec-vpn.
I am connecting from my Mac to my personal vpn running on an Ubuntu server.
It disconnects after 3 minutes and 30 seconds.
Here is what i see from Mac vpn client logs:
tail -100f /var/log/ppp.log

Mon Apr 27 13:34:51 2020 : L2TP received StopCCN
Mon Apr 27 13:34:51 2020 : L2TP hangup
Mon Apr 27 13:34:51 2020 : ipcp: down
Mon Apr 27 13:34:51 2020 : Connection terminated.
Mon Apr 27 13:34:51 2020 : L2TP clearing port-mapping for en0
Mon Apr 27 13:34:51 2020 : Connect time 2.6 minutes.
Mon Apr 27 13:34:51 2020 : Sent 1028457 bytes, received 5762343 bytes.
Mon Apr 27 13:34:51 2020 : L2TP disconnecting...
Mon Apr 27 13:34:51 2020 : L2TP sent CDN
Mon Apr 27 13:34:51 2020 : L2TP sent StopCCN
Mon Apr 27 13:34:51 2020 : L2TP disconnected

Here is what i see on the server side:
tail -f /var/log/auth.log

Apr 27 10:34:20 ip-172-31-40-152 pluto[3459]: "l2tp-psk"[2] 149.0.138.78 #1: IKEv1 DPD action - clearing connection kind CK_INSTANCE
Apr 27 10:34:20 ip-172-31-40-152 pluto[3459]: "l2tp-psk" #2: deleting state (STATE_QUICK_R2) aged 120.084s and sending notification
Apr 27 10:34:20 ip-172-31-40-152 pluto[3459]: "l2tp-psk" #2: ESP traffic information: in=1MB out=6MB
Apr 27 10:34:20 ip-172-31-40-152 pluto[3459]: "l2tp-psk" #1: deleting state (STATE_MAIN_R3) aged 121.125s and sending notification
Apr 27 10:34:20 ip-172-31-40-152 pluto[3459]: "l2tp-psk"[2] 149.0.138.78: deleting connection "l2tp-psk"[2] 149.0.138.78 instance with peer 149.0.138.78 {isakmp=#0/ipsec=#0}

tail -f /var/log/syslog

Apr 27 10:52:03 ip-172-31-40-152 xl2tpd[3043]: Maximum retries exceeded for tunnel 39830.  Closing.
Apr 27 10:52:03 ip-172-31-40-152 pppd[4266]: Modem hangup
Apr 27 10:52:03 ip-172-31-40-152 systemd-networkd[700]: ppp0: Link DOWN
Apr 27 10:52:03 ip-172-31-40-152 pppd[4266]: Connect time 3.6 minutes.
Apr 27 10:52:03 ip-172-31-40-152 systemd-networkd[700]: ppp0: Lost carrier
Apr 27 10:52:03 ip-172-31-40-152 pppd[4266]: Sent 94682 bytes, received 107101 bytes.
Apr 27 10:52:03 ip-172-31-40-152 systemd-timesyncd[526]: Network configuration changed, trying to establish connection.
Apr 27 10:52:03 ip-172-31-40-152 xl2tpd[3043]: Terminating pppd: sending TERM signal to pid 4266
Apr 27 10:52:03 ip-172-31-40-152 xl2tpd[3043]: Connection 24 closed to 149.0.138.78, port 59243 (Timeout)
Apr 27 10:52:03 ip-172-31-40-152 pppd[4266]: Connection terminated.
Apr 27 10:52:03 ip-172-31-40-152 pppd[4266]: Exit.
Apr 27 10:52:03 ip-172-31-40-152 systemd-timesyncd[526]: Synchronized to time server 91.189.91.157:123 (ntp.ubuntu.com).

The server runs on AWS. I tried changing server IP address, recreating the server from the image. But they didn't work.
(!) I used to connect the vpn server without hassle before. After I changed my ISP, I started to have this problem. ISP support has no idea about the issue.
What could be wrong with the setup?

A: After experimenting some configuration changes in /etc/ipsec.conf, I found out increasing dpdtimeout resolved my problem:
I updated dpdtimeout value from 120 to 1200.
dpdtimeout=1200

Now, I do not get disconnected from VPN server any more.


text:
Q: How to assign new column based on the list of string values in pandas I have a dataframe that one of the column contains string values, and I want to assign new column if this column values are in the list I specified.
my_list = ['AA', 'TR', 'NZ']
For example:
My dataframe : df

country

AA

TR

SG

The dataframe I want to have:

country
flag

AA
1

TR
1

SG
0

I tried this one but I gave an Value Error.
df.assign(flag = lambda df: '1' if df['country'].isin(my_list) else '0')

What should I do? Thank you

A: You can directly convert your boolean to 0/1 with astype(int):
df.assign(flag= df['country'].isin(my_list).astype(int))

Or for a string:
df.assign(flag= df['country'].isin(my_list).astype(int).astype(str))

Alternatively, use numpy.where:
import numpy as np
df.assign(flag=np.where(df['country'].isin(my_list), '1', '0'))

output:
  country flag
0      AA    1
1      TR    1
2      SG    0

A: import pandas as pd

my_list = ['AA', 'TR', 'NZ']
df = pd.DataFrame(columns=["Country", "Flag"])

df.loc[0] = ["AA", 0]
df.loc[1] = ["TR", 0]
df.loc[2] = ["SG", 0]

print(df)

for i in range(len(df)):
    if df["Country"].iloc[i] in my_list:
        df["Flag"].iloc[i] = 1

print(df)


text:
Q: Problem with jQuery's order of effects I would like to fadeOut a button, then fadeIn the response an Ajax call. The response is a a new button. What the following code does, however, is fadeOut the first button, fade it back in, then replace it with the new one. I tried a few combinations but could not get it to work. where did I go wrong?
beforeSend: function()
{
    $(this).fadeOut("slow");
},

success: function(response)
{
    $(this).fadeIn("slow", function () {
        $(this).parent().html(response);
    });
}

A: this inside an AJAX call is not the previous element anymore. You must store it in a var previous to the AJAX call, like:
var button = $(this);
and later:
button.fadeOut();
and so on.

A: Try this (note the mistyped "show" on fadeOut):
beforeSend: function()
{
    $(this).fadeOut("slow");
},

success: function(response)
{
    $(this).parent().html(response);
    $(this).stop().fadeIn("slow");
}

A: $(this).parent().html(response); would effectively eliminate this.  So changing it to this should fix it:
$(this).parent().html(response);
$("#thething").stop().fadeIn("slow");

where #thething is the id of "this"
EDIT: also what morgar said.


text:
Q: Initialization of global variable requires a constant value I've been trying to find an answer to this problem for some time now and I still can't find the root to my problem.
I'm working with procedures in maya (mel), and I'm having a really hard time being able to use global variables as a means to work with saving data between different procedures.
My main problem is represented here:
In the first example I can replace the already declared global variable inside a procedure as I need it to be.
But then in the second example when trying to change the value of the global variable it says the procedure needs a constant value.
Also, I've tried making a local variable only to pass it later on to the global variable, yet I still get the same problem.
global string $value[];

proc test()
{
    global string $value[] = {"door", "knob"};
    print ($value);

}

test();

//Result: door, knob

global string $value[];

proc test()
{
    global string $value[] = `ls -sl`;
    print ($value);

}

test();

//Result: Initialization of global variable "$value" requires a constant value.

Waiting for possible solutions, been searching for a lot now.

A: Try this in the second proc instead:
 global string $value[];
 $value = `ls -sl`;

The message is telling you the problem --  ls -sl is not a constant value, it will be different every time. so you can't use it as the initial value of the the global  - the proc does not know that $value exists yet, so it's trying to create a new one and MEL does not want you to create a new global with a non-constant value.
It's good practice in any case not to declare and fill a global at the same time unless you plan on leaving it constant or want  predictable default value.  That's why MEL wants you to separate declaration from assignment.


text:
Q: How do I get rid of dotted line on x axis of Pandas/Matplotlib bar plot? EDIT: This line was removed in Pandas (https://github.com/pydata/pandas/issues/9088).
I am plotting a bar plot using the plot function of Pandas. It keeps showing up with a strange dotted line right above the x axis.
It is not the ticks or x axis, both of which I've gotten rid of:
plt.tick_params(axis="both", which="both", bottom="off", top="off",
        labelbottom="on", left="off", right="off", labelleft="on")
ax.spines["bottom"].set_visible(False)

But I still have this dotted line on the x axis! What is that line even called if it not ticks or x axis?

A: pandas adds a dashed horizontal line on the axis of bar plots.  There is a line in pandas/tools/plotting.py, in BarPlot._post_plot_logic (line 1842 in my version):
ax.axhline(0, color='k', linestyle='--')

This doesn't seem to be explicitly documented, and there's apparently no way to stop it from doing this.  Worse, the plot doesn't keep any reference to the line, so there's no clear way to safely remove it.  If the barplot is "plain", then this will work:
ax.get_lines()[0].set_visible(False)

This only works because in the plain barplot, this is the only Line artist in the plot.  If you do anything else that adds other lines to the plot, it could get tricky to determine which one is the axis line you want to remove.


text:
Q: Filtering a list of processes based on a list of string objects I have a List of string objects which represent process names. I want to filter a collection of running Processes (retrieved by using GetProcesses()), by using the list of string objects I have. So if I want to look for the Sql Server process running in the processes collection, I will look for the string name as stored in the string list.
How can I filter a list of processes to get only the processes which have the same process names as a list of strings (the different generic types makes it hard - for me, anyway)?
I am using .NET 4.0 and LINQ.
Thanks

A: This should do it..
var targetNames = new [] { "processone", "Processtwo" };

var processes = from p in Process.GetProcesses()
                where targetNames.Any(n => n == p.ProcessName)
                select p;


text:
Q: Spring Boot ObjectFactory Performance Cost I work on a team where every little bit of performance on our application is critical. We're working on migrating from Java to spring boot and there are several instances where we'd need a ObjectFactory<?> to handle the dependency injection of required beans.
I wrote a simple test where we create an object 1 million times using new and 1 million times using spring ObjectFactory<?>.get(). I was seeing a huge difference in performance from this where the pure java version took 0.06 seconds and then the spring version took 23+ seconds.
Test Files
main
@SpringBootApplication
public class DemoApplication {

    public static List<Employee> employees = new ArrayList<>();

    @Autowired
    ObjectFactory<Employee> employeeObjectFactory;

    public static void main(String[] args) {
        startSpringless();
        SpringApplication.run(DemoApplication.class, args);
        System.out.println(employees.size());
    }

    @PostConstruct
    public void start(){
        var startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            var employee = employeeObjectFactory.getObject();
            employee.goToWork();
            employees.add(employee);
        }
        double totalTime = System.currentTimeMillis() - startTime;
        System.out.println("Spring seconds: " +totalTime/1000);
    }

    public static void startSpringless(){
        var startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            var employee = new Employee(new Car(), new Clothes());
            employee.goToWork();
            employees.add(employee);
        }
        double totalTime = System.currentTimeMillis() - startTime;
        System.out.println("No Spring seconds: " +totalTime/1000);
    }
}

Employee
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Component
public class Employee {

    private final Car car;
    private final Clothes clothes;

    @Autowired
    public Employee(Car car, Clothes clothes) {
        this.car = car;
        this.clothes = clothes;
    }

    public void goToWork(){
    }
}

Car and Clothes
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Component
public class Car {
}

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Component
public class Clothes {
}

Is there anyway to create prototype beans that is more peformant? Or is my performance test not working how I expect it is?


text: Q: GRASS 8.3 not downloading sample data or addons/extensions on Window's 11 I m trying to install addons in GRASS 8.3 and download the sample datasets, but the error message says I m not connected to the internet. I am. The only sample dataset that was downloaded was the Natural Earth mapset. I recently upgraded OS from Windows 10 to Windows 11 and tried on GRASS 8.2 and 8.3. I have searched but found no solution.


text:
Q: Is there a version of Ubuntu which boots to command line without needing to install onto the hard drive? I am a tech support technician and I am using the shred function in ubuntu to securely wipe company laptops. I am currently using the desktop version and clicking "try" in order to run this command and then move onto the next laptop without needing to install. I want to use a version of Ubuntu that just boots to command line to make this more efficient. I have tried ubuntu server but I cannot find any "try" option. Can anyone help?

A: "I want to use a version of Ubuntu that just boots to command line"
The Ubuntu Server (20.04 and newer) install image includes a Live shell environment.
It's under the "Help" menu.

A: The Ubuntu Server is [also] distributed as a compressed image file. When extracted to a drive, it is an installed system that can boot PC computers both in UEFI mode and BIOS mode. You can find more details about it at this link to the Ubuntu Forums.
This system boots into text mode alias command line when extracted and cloned to any drive that is big enough for the extracted image, also a USB pendrive or USB SSD.
As long as it is supported (until April 2027), you may prefer the Jammy version, alias 22.04.x LTS, found via
http://cdimage.ubuntu.com/ubuntu-server/jammy/daily-preinstalled/current/

A: Any bootable USB should work, though you might want to preinstall shred. https://wiki.ubuntu.com/LiveUsbPendrivePersistent explains how to install a "persistent" bootable USB stick where you can store stuff you want on the stick along with the live bootable Ubuntu.

A: While all Ubuntu installers support live booting (try the "Help" menu), you probably want a lightweight USB boot system. Maybe try SystemRescue.
(I still remember the days of tomsrtbt, which crammed a great utility collection onto a floppy disk. When Knoppix, the first notable live CD, came out, I remember being astounded. Then Ubuntu came out and set the new norm: nearly all modern desktop OS installers are now also live CDs.)

A: You say you're using company laptops and using Linux to shred the data.  I'm assuming these are Windows machines that you're completely wiping to reinstall the OS onto.  If that's the case, I would recommend: Darik's Boot and Nuke: DBAN.  This will boot into an OS that will allow you to securely destroy/shred all data on whatever drives you choose.  After this, you'll be able to reinstall Windows and go about your day.  Take caution when using this as it is designed to make your data unrecoverable for the most part.


text:
Q: Authenticate multiple application with Ruby CAS Server I have two different web applications which are already build. Now one new requirement comes i.e Implement Common Authentication. My one application is build in rails and another application is build in Drupal. I have installed ruby-casserver, but for the CAS we need to set Authenticator in config.yml file, I have set that.
But my problem is how to migrate my old users on CAS, because I am storing the username and also password(i.e encrypetd) on CAS server. Encrypted Passwords which are stored in CAS user table are encrypted using SHA1 algorithm. But the oldest user which are on Drupal uses the MD5 for password encryption.
So my question is how to migrate old users on CAS, or how to Design the CAS which can authenticate for Rails and Drupal users.

A: if you understand how your passwords are hashed, all you have to do is make sure that your authenticator hashes the passwords in the same way -- overriding it if you need to.  Take a look at CASino, it is a CAS server that makes it pretty easy to override authenticators; also it allows multiple data sources to be used simultaneously, be it multiple databases or LDAP.


text:
Q: stop closing showDialogue itself after 15 seconds I am trying to display an information dialog when starting an application. After closing, another window appears asking for permission. I call it all in the initState function. It works, but I noticed that this first info dialog also closes on its own when 15 seconds have elapsed. How do I fix this? So that while the dialog is not closed by the user, the application will not be loaded further?
class _MyAppState extends State<MyApp> {
final keyIsFirstLoaded = 'is_first_loaded';
@override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final context = MyApp.navKey.currentState.overlay.context;
       await showDialogIfFirstLoaded(context);
       await initPlatformState();
    });
  }
showDialogIfFirstLoaded(BuildContext context, prefs) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isFirstLoaded = prefs.getBool(keyIsFirstLoaded);
    if (isFirstLoaded == null) {
      return showDialog(
        context: context,
        builder: (BuildContext context) {
          // return object of type Dialog
           return new AlertDialog(
                 // title: new Text("title"),
                 content: new Text("//"),
                 actions: <Widget>[
                  new FlatButton(
                    child: new Text(".."),
                    onPressed: () {
                  Navigator.of(context).pop();
                  prefs.setBool(keyIsFirstLoaded, false);
                },
              ),
            ],
          );
        },
      );
    }
  }
initPlatformState() async {
    print('Initializing...');
    await BackgroundLocator.initialize();
    print('Initialization done');
    final _isRunning = await BackgroundLocator.isRegisterLocationUpdate();
    setState(() {
      isRunning = _isRunning;
    });
    onStart();
    print('Running ${isRunning.toString()}');
  }
@override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        // ... app-specific localization delegate[s] here
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      navigatorKey:MyApp.navKey,
      navigatorObservers: [
        FirebaseAnalyticsObserver(analytics: analytics),
      ],
      debugShowCheckedModeBanner: false,
      title: '',
      theme: ThemeData(),
      home: new SplashScreen(),}
class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => new _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> with SingleTickerProviderStateMixin {
  Timer _timer;
  bool _visible = true;
  startTime() async {
      _timer = Timer(new Duration(seconds: 5), navigationPage);
  }
  void navigationPage() {
    Navigator.of(context).pushReplacementNamed('/home');
  }
  @override
  void initState() {
    _timer = Timer(Duration(seconds: 4),
          () => setState(
            () {
          _visible = !_visible;
        },
      ),
    );
    startTime();
    super.initState();
  }
  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return new Stack(
      children: <Widget>[
        Container(
          width: double.infinity,
          child: Image.asset('images/bg.jpg',
            fit: BoxFit.cover,
            height: 1200,
          ),
        ),
        Container(
          width: double.infinity,
          height: 1200,
          color: Color.fromRGBO(0, 0, 0, 0.8),
        ),
        Container(
          alignment: Alignment.center,
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 2,
                child: Container(
                  child: Text(''),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

A: This code displays an Alert dialogue if the user is new and after the button click, it will direct him to another dialogue.
I have tested the code and it doesn't close after 15 seconds. I'm still not sure what you're trying to accomplish but I hope this helps.
Init State
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await dialog1(context);
      //await initPlatformState();
    });
    super.initState();
  }

Alert Dialog 1
dialog1(BuildContext context)async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isFirstLoaded = prefs.getBool("keyIsFirstLoaded")??true;

    if (isFirstLoaded) {
      showDialog(
        barrierDismissible: false, //disables user from dismissing the dialog by clicking out of the dialog
        context: context, builder: (ctx) {
        return AlertDialog(
          title: Text("dialog 1"), content: Text("Content"), actions: [
            TextButton(
            child: new Text(".."),
            onPressed: () async{
            Navigator.pop(ctx);
            await dialog2(context);
            prefs.setBool("keyIsFirstLoaded", false);
          },
        ),],);
      },);
    }else{
      //not first time
    }
  }

Alert Dialog 2
void dialog2(BuildContext context)async{
    print("dialog 2");
    showDialog(context: context, builder: (context) {
      return AlertDialog(title: Text("Dialog 2"),content: Text("permissions"),actions: [
        TextButton(
        child: new Text("close"),
        onPressed: () async{
          Navigator.pop(context);
          //await dialog1(context); //uncomment if you want to go back to dialoge 1
        },
      ),],);
    },);
  }

A: You can return a value from Navigator in the first dialog
Navigator.of(context).pop(true);
prefs.setBool(keyIsFirstLoaded, false);

Once it receive true, then only call the second method.
var value = await showDialogIfFirstLoaded(context);
if(value == true) {
   await initPlatformState();
}


text:
Q: Haskell, sum up two elements of a list with pattern matching? i am learning the pattern syntax in Haskell and now i have a problem with my small function.
I want to add two elements of a list like in the example:
input 1: [1,2,3,4,5],  output2: [3,5,7,9]

input 2: [1,2,3,4,5,6],  ouput 2: [3,5,7,11]

My Code(i tried to make a pattern for two elements but it says that the patterns are overlapping):
g4 [] = []
g4 [x] = []
-- g4 (x:y:xs) = x+y: g4 xs
g4 (x:y:z:xs) = x+y:y+z: g4 (xs)

It should look like this, but i dont know how to create the pattern for 2 elements:
g1 [1,2,3,4,5]
 = 1+2 : 2+3 : g1 [3,4,5]
          = 3+4 : 4+5 : g1 [5]
               = []

g1 [1,2,3,4,5,6]
 = 1+2 : 2+3 : g1 [3,4,5,6]
          = 3+4 : 4+5 : g1 [5,6]
                = 5+6

Test:
*Main> g4 [1,2,3]
[3,5] -- worked
*Main> g4 [1,2,3,4]
[3,5,4] -- did not work
*Main> g4 [1,2,3,4,5]
*** Exception: Test.hs:(127,1)-(130,32): Non-exhaustive patterns in function g4 -- didnt work

[3,5*Main> g4 [1,2,3,4,5,6]
[3,5,9,11] -- worked

A: You can call g4 on the combination of (y:xs) for your recursive component:
g4 [] = []
g4 [x] = []
g4 (x:y:xs) = x+y : g4 (y:xs)

A: You can just zip the list with a "shifted" version of itself.
g4 xs = zipWith (+) xs (tail xs)


text:
Q: PySide Child Window I want to open a child window in the MainWindow of my app. I want to disallow the user to interact with the parent window, and only allow him to open that child window once. For example, the 'About' window in many applications.
class Ui_AboutDialog(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(500, 300)
        MainWindow.setMinimumSize(QtCore.QSize(500, 300))
        MainWindow.setMaximumSize(QtCore.QSize(500, 300))
        MainWindow.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(10, 10, 481, 181))
        self.label.setObjectName("label")
        #MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)

Here is how I call it in the MainWindow:
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        ...
        ...
        self.actionAbout.triggered.connect(lambda: self.openAbout(MainWindow))

    def openAbout(self, MainWindow):
        aboutDialog = QtGui.QDialog(MainWindow)
        aboutUi = Ui_AboutDialog()
        aboutUi.setupUi(aboutDialog)
        aboutDialog.show()

       ...
       ...

Solution
def openAbout(self, MainWindow):
    if self.AboutDialog is None:
        self.AboutDialog = QtGui.QDialog(MainWindow)
        aboutUi = Ui_AboutDialog()
        aboutUi.setupUi(self.AboutDialog)
    self.AboutDialog.setModal(True)
    self.AboutDialog.show()

self.AboutDialog is set to None in setupUi of class Ui_MainWindow.
I think while using self.AboutDialog.setModal(True) we may go without self.AboutDialog as follows:
def openAbout(self, MainWindow):
    AboutDialog = QtGui.QDialog(MainWindow)
    aboutUi = Ui_AboutDialog()
    aboutUi.setupUi(AboutDialog)
    AboutDialog.setModal(True)
    AboutDialog.show()

A: Though not explicitly stated, I assume you are asking how to make the QDialog only appear once? If so, how about implementing a variable in your Ui_MainWindow class which tracks whether the child window has already been opened once before. You could easily modify your openAbout function to check this variable and only open the child window if it hasn't been opened before.


text:
Q: Duplicate table fields vs indexing only I have a huge and very busy table (few thousands INSERT / second). The table stores loginlogs, it has a bigint ID which is not generated by MySQL but rather by pseudorandom generator on MySQL client.
Simply put, the table has loginlog_id, client_id, tons,of,other,columns,with,details,about,session....
I have few indexes on this table such as PRIMARY_KEY(loginlog_id) and INDEX(client_id)
In some other part of our system I need to fetch client_id based on loginlog_id. This does not happen that often (just few hundreds SELECT client_id FROM loginlogs WHERE loginlog_id=XXXXXX / second). Table loginlogs is read by various other scripts now and then, and always various columns are needed. But the most frequent call to read is for sure the above mentioned get client_id by loginlog_id.
My question is: should I create another table loginlogs_clientids and duplicate loginlog_id, client_id in there (this means another few thousands INSERTS, as for every loginlogs INSERT I get this new one). Or should I be happy with InnoDB handling my lookups by PRIMARY KEY efficiently.
We have tons of RAM (128GB, most of which is used by MySQL). Load of MySQL is between 40% and 350% CPU (we have 12 core CPU). When I tried to use the new table, I did not see any difference. But I am asking for the future, if our usage grows even more, what is the suggested approach? Duplicate or index?
Thanks!

A: No.
Looking up table data for a single row using the primary key is extremely efficient, and will take the same time for both tables.
Exceptions to that might be very large row sizes (e.g. 8KB+), and client_id is e.g. a varchar that is stored off-page, in which case you might need to read an additional data block, which at least theoretically could cost you some milliseconds.
Even if this strategy would have an advantage, you would not actually do it by creating a new table, but by adding an index (loginlog_id, client_id) to your original table. InnoDB stores everything, including the actual data, in an index structure, so that adding an index is basically the same as adding a new table with the same columns, but without (you) having the problem of synchronizing those two "tables".
Having a structure with a smaller row size can have some advantages for ranged scans, e.g. MySQL will evaluate select count(*) from tablename using the smallest index of the table, as it has to read less bytes. You already have such a small index (on client_id), so even in that regard, adding such an additonal table/index shouldn't have an effect. If you have any range scan on the primary key (which is probably unlikely for pseudorandom data), you may want to consider this though, or keep it in mind for cases when you have.


text:
Q: Retaining NaN values after get_dummies in Pandas I have a dataframe 'df' like this -
Id    v1    v2
0     A     0.23
1     B     0.65
2     NaN   0.87

If I use
df1 = get_dummies(df)
df1

I get
Id    v1_A    v1_B    v2
0     1       0       0.23
1     0       1       0.65
2     0       0       0.87 .

How can I get the following efficiently?
Id    v1_A    v1_B    v2
0     1       0       0.23
1     0       1       0.65
2     NaN     NaN     0.87 .

I was using this initially, but it takes too long
import numpy as np
dfv1 = df[[v1]]    #Slicing the v1 column
dfs = get_dummies(dfv1)
dfsum = dfs.apply(np.sum, axis=1)    #Calculating row by row sum of dfs
for i in range(dfs.size):    #Iterating over the entire dataframe
    if dfsum.iloc[i]==0:     #and if the sum is zero for some 'i'
        dfs.iloc[i][:]==np.nan    #changing corresponding row to NaN
del df['v1']    #Deleting original column
df = pandas.concat([df, dfs], axis=1)    #Appending the new one

I am using Python 3.5.1 on Jupyter, and Pandas 0.18 . Thanks.

A: Method #1 would be to use v1's nans directly, without loops:
>>> df1 = pd.get_dummies(df)
>>> df1.loc[df.v1.isnull(), df1.columns.str.startswith("v1_")] = np.nan
>>> df1
   Id    v2  v1_A  v1_B
0   0  0.23   1.0   0.0
1   1  0.65   0.0   1.0
2   2  0.87   NaN   NaN

Method #2 would be to use the dummy_na argument to get us a column we could use:
>>> df1 = pd.get_dummies(df, dummy_na=True)
>>> df1
   Id    v2  v1_A  v1_B  v1_nan
0   0  0.23   1.0   0.0     0.0
1   1  0.65   0.0   1.0     0.0
2   2  0.87   0.0   0.0     1.0
>>> df1.loc[df1.v1_nan == 1, ["v1_A", "v1_B"]] = np.nan
>>> del df1["v1_nan"]
>>> df1
   Id    v2  v1_A  v1_B
0   0  0.23   1.0   0.0
1   1  0.65   0.0   1.0
2   2  0.87   NaN   NaN

A: I'll use a simple data frame as an example:
df1 = pd.DataFrame([['A', 'A'],[np.nan, 'B'], ['C', np.nan]])

>>> df1
     0    1
0    A    A
1  NaN    B
2    C  NaN

Then one-hot-encode it:
df1_ohe = pd.get_dummies(df1, dummy_na=True)

>>> df1_ohe
   0_A  0_C  0_nan  1_A  1_B  1_nan
0    1    0      0    1    0      0
1    0    0      1    0    1      0
2    0    1      0    0    0      1

Now get a subset of this data frame, containing only the NaN columns:
nan_df = df1_ohe.loc[:, df1_ohe.columns.str.endswith("_nan")]

>>> nan_df
   0_nan  1_nan
0      0      0
1      1      0
2      0      1

Finally, use a little regex and iterate over each row in the data frame and each NaN column.
If this position [row, NaN column] contains 1, then that position on the original data frame (before OHE) is a NaN.
Therefore, I use regex to identify the original columns "col_id" (i.e., 1_nan gives me 1, which is the column that contains NaN in the non-OHE data frame).
So I target all columns that contain that position (i.e., 1_A, 1_B and 1_nan) and replace their values with NaN.
pattern = "^([^_]*)_"
regex = re.compile(pattern)

for index in df1_ohe.index:
    for col_nan in nan_df.columns:
        if df1_ohe.loc[index,col_nan] == 1:
            col_id = regex.search(col_nan).group(1)
            targets = df1_ohe.columns[df1_ohe.columns.str.startswith(col_id+'_')]
            df1_ohe.loc[index, targets] = np.nan

Giving me:
>>> df1_ohe
   0_A  0_C  0_nan  1_A  1_B  1_nan
0  1.0  0.0    0.0  1.0  0.0    0.0
1  NaN  NaN    NaN  0.0  1.0    0.0
2  0.0  1.0    0.0  NaN  NaN    NaN

Finally, I remove the NaN columns from the OHE data frame
df1_ohe.drop(df1_ohe.columns[df1_ohe.columns.str.endswith('_nan')], axis=1, inplace=True)

>>> df1_ohe
   0_A  0_C  1_A  1_B
0  1.0  0.0  1.0  0.0
1  NaN  NaN  0.0  1.0
2  0.0  1.0  NaN  NaN


text:
Q: TYPO3 IRRE Fluid Frontend In my extension I tried to make an IRRE. Finally the Backend works fine but the frontend is my problem. I want to use a normal fluid template but all names I try are empty.
So here the fluid:

    {data.header}
    <f:if condition="{data.tx_examples_noclap} == 1">
        <f:then></f:then>
    </f:if>

<f:if condition="{data.tx_examples_noclap} == 1">
    <f:then>
</f:then>
    <f:else>
</f:else>
</f:if>

{data.bodytext}

            {termine}
            <f:for each="{termine}" as="termin">

                    {termin.title}
                    {termin.termin2}
                    {termin.termin3}
                    {termin.platz}

            </f:for>

Here the typoScript
tt_content.stalla_hp_distribution_termin = COA
tt_content.stalla_hp_distribution_termin {
    10 = FLUIDTEMPLATE
    10 {
        file = EXT:stalla_hp_distribution/Resources/Private/Template/Termin.html
        stdWrap.dataWrap =
|

    }
}

Here the Controler..
1.Classes/Domain/Model/Termin.php

    <?php
    namespace stalla_hp_distribution\Domain\Model;

    /**
     *
     *
     * @package stalla_hp_distribution
     * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later
     *
     */
    class Termin extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
        protected $farbe = NULL;
        protected $title = NULL;
        protected $termin2 = NULL;
        protected $termin3 = NULL;
        protected $platz = NULL;

        public function getFarbe(){
            return $this->farbe;
        }

        public function getTitle(){
            return $this->title;
        }

        public function getTermin2(){
            return $this->termin2;
        }

        public function getTermin3(){
            return $this->termin3;
        }

        public function getPlatz(){
            return $this->platz;
        }

        public function setFarbe(){
            $this->farbe = $farbe;
        }

        public function setTitle(){
            $this->title = $title;
        }

        public function setTermin2(){
            $this->termin2 = $termin2;
        }

        public function setTermin3(){
            $this->termin3 = $termin3;
        }

        public function setPlatz(){
            $this->platz = $platz;
        }
    }
    ?>

2. Classes/Domain/Repository/TerminRepository.php

    <?php
    namespace stalla_hp_distribution\Domain\Repository;

    class TerminRepository extends \TYPO3\CMS\Extbase\Persistence\Repository {
    }
    ?>

3. Classes/Controller/TerminController.php

    <?php
    namespace stalla_hp_distribution\Controller;
    /**
     * TerminController
     */
    class TerminController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {
        /**
         * @var stalla_hp_distribution\Domain\Repository\TerminRepository
         * @inject
         */
        protected $terminRepository;
        /**
         * action list
         *
         * @return void
         */
        public function listAction() {
            $termine = $this->terminRepository->findAll();
            $this->view->assign('termine', $termine);
        }
    }

    ?>

I'm looking forward to hearing from You.
Kind Regards
Ascawath

A: If you can reference many titles to a termin, try this
...

{data.bodytext}

        <f:for each="{termine}" as="termin">

                <f:for each="{termin.title}" as="title" iteration="iterator">
                    <f:if condition="{iterator.isFirst}">
                                    {title}
                    </f:if>
                </f:for>
                ...

        </f:for>

A: You could use the DatabaseQueryProcessor to access the Data of your IRRE and make it available in your Fluid Template
Here is an Example TS
tt_content.slickcarouselbgimg = FLUIDTEMPLATE
tt_content.slickcarouselbgimg {
    templateName = Slickcarouselbgimg
    templateRootPaths {
        10 = EXT:slickcarousel/Resources/Private/Templates/
    }

    partialRootPaths {
        10 = EXT:slickcarousel/Resources/Private/Partials/
    }

    layoutRootPaths {
        10 = EXT:slickcarousel/Resources/Private/Layouts/
    }

    dataProcessing {
        20 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor
        20 {
            table = tx_slickcarouselbgimg
            pidInList.field = pid
            where {
                data = field:uid
                intval = 1
                wrap = tt_content=|
            }
            orderBy = sorting
            as = slides
            dataProcessing {
                10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
                10 {
                    references.fieldName = image
                    as = images
                }
            }
        }
    }
}

Here you could see the whole setup:
https://github.com/misterboe/slickcarousel


text:
Q: How to mock the flutter universal html package I am using this library to use the html.window.open() method in my code, but I'm not able to mock it for my tests. I have imported the lib like this import "package:universal_html/html.dart" as html; in the code. My test tries to verify (using mockito) whether this method was called and also verify what argument was used.
Please help! Thanks :)


text:
Q: Vue js - multiple components with each a different initial selected value I'm creating a multiselect in Vue js, but wat i dont understand is how can i get multiple instance of the component with each a different initial selected value (v-model). Every component is getting the same initial value because of the selected data on the parent. Should i also use props here instead of v-model? or should i move the data object from the parent to the component itself?
Wat i want
Component one should have initial select "{ id: "0", text: "One"}" and
Component two should have initial select "{ id: "1", text: "Two"}"
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="icon" href="data:;base64,iVBORw0KGgo=">

  <multi-select v-model="selected" :options='[{ id: "0", text: "One"}, { id: "1", text: "Two"}'></multi-select>
  <multi-select v-model="selected" :options='[{ id: "0", text: "One"}, { id: "1", text: "Two"}'></multi-select>

A: Pass index as props and your child component can use this index to decide the default value.
v-bind:index="0"
v-bind:index="1"

A: v-model means the selected value, pay attention that you are assigning both multiselects
to the same variable.
a possible solution is creating another variable, lets say selector2 and selector1
and assigning your v-model accordingly.
data: {
      selected1: [{ id: "0", text: "One"}],
      selected2: [{ id: "1", text: "Two"}],
    }

and on assignment

  <multi-select v-model="selected1" :options='[{ id: "0", text: "One"}, { id: "1", text: "Two"}'></multi-select>
  <multi-select v-model="selected2" :options='[{ id: "0", text: "One"}, { id: "1", text: "Two"}'></multi-select>


text:
Q: Vasya - Clerk ----- codewars kata The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollars bill. An "Avengers" ticket costs 25 dollars.
Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.
Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
Return YES, if Vasya can sell a ticket to each person and give the change with the bills he has at hand at that moment. Otherwise return NO.
Examples:
tickets([25, 25, 50]) # => YES
tickets([25, 100]) # => NO. Vasya will not have enough money to give change to 100 dollars
tickets([25, 25, 50, 50, 100]) # => NO.
can anyone tell whats the issue i get TypeError: unorderable types: list() >= int() error when i click submit
def tickets(people):
a=[]

if people[0] ==25:
    a.append(people[0])
    for x in people[1:]:
        if x == 25:
            a.append(people[0])
        else:
            a = sum(a) - x

    if a >= 0:
        return 'YES'
    else:
        return "NO"

else:
    return 'NO'

thank you

A: You definitely have problems with your variable a, which starts out as a list, but in this part of your code, if anyone tries to pay with 50 or 100, you're assigning an integer value to a instead
if x == 25:
    a.append(people[0])
else:
    a = sum(a) - x

And in this line
if a >= 0:

you're comparing it to an int value 0 -- the way your code is set up, for a test case where each person in line has 25, when your code gets to the above line, a will still be a list, and you'll get the error you describe because you're trying to compare a list to an integer.


text:
Q: Parse valid objects from JSON array in Swift I have a codable struct like this
struct User: Codable {
    let id: String
    let registrationId: String
    let firstName: String?
    let lastName: String?
}

Now, the response from the server contains an array like this
 [
  {
    "id": "1",
    "registrationId": "r1",
    "firstName": "Jon",
    "lastName": "Doe"
  },
  {
    "id": "2",
    "registrationId": null,
    "firstName": null,
    "lastName": null
  },
  {
    "id": "3",
    "registrationId": null,
    "firstName": null,
    "lastName": null
  },
  {
    "id": "4",
    "registrationId": "r4",
    "firstName": "Jon",
    "lastName": "Snow"
  }
]

I want to parse this as [User] but only those who have a valid(not null) registrationId. I know how to parse JSON in swift. But the problem here is because of the two invalid data in the middle the whole response will run into decoding error. But I want to parse it as an array of [User] containing valid ones(in this case first and last object).
Any hints or help is much appreciated.

A: 1- Make registrationId an optional
 let registrationId: String?

2-
 let res = try JSONDecoder().decode([User].self,from:data)
 let filtered = res.filter { $0.registrationId != nil }

A: after all, this data must come from a database or an array. By making the id parameter as the primary key, the registrationId parameter as a foreign key, and if you are working on the registrationId parameter, you can make a productive sequence or if it is on the array, you can link the method that generates the sequence for that registrationId.

A: Now I know how to achieve this.
struct User: Codable {
    let id: String
    let registrationId: String
    let firstName: String?
    let lastName: String?
}

struct WrappedDecodableArray<Element: Decodable>: Decodable {
    let elements: [Element]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        var elements = [Element]()
        while !container.isAtEnd {
            if let element = try? container.decode(Element.self) {
                elements.append(element)
            } else {
                // move the container currentIndex forward
                _ = try container.decode(Block.self)
            }
        }
        self.elements = elements
    }

    private struct Block: Decodable {}
}

func testUserParsing() {
    let jsonStr = """
    [
      {
        "id": "1",
        "registrationId": "r1",
        "firstName": "Jon",
        "lastName": "Doe"
      },
      {
        "id": "2",
        "registrationId": null,
        "firstName": null,
        "lastName": null
      },
      {
        "id": "3",
        "registrationId": null,
        "firstName": null,
        "lastName": null
      },
      {
        "id": "4",
        "registrationId": "r4",
        "firstName": "Jon",
        "lastName": "Snow"
      }
    ]
    """

    let jsonData = jsonStr.data(using: .utf8)!
    let wrappedArray = try! JSONDecoder().decode(WrappedDecodableArray<User>.self, from: jsonData)
    print(wrappedArray.elements)
}

It would have been more elegant if we could override the init(from decoder: Decoder) for Array under certain conditions like extension Array where Element == User. But looks like this is not possible. Initializer inside the extension can not override the original one and hence never get called.
So for now looks like wrapping with a struct is the only solution.


text:
Q: Why does a Box pointer passed to C and back to Rust segfault? Some C code calls into the Rust open call below which returns a pointer.  Later the C code passes the exact same pointer back to the close function which tries to drop (free) it.  It segfaults in free(3).  Why?
use std::os::raw::{c_int, c_void};

struct Handle;

extern "C" fn open(_readonly: c_int) -> *mut c_void {
    let h = Handle;
    let h = Box::new(h);
    return Box::into_raw(h) as *mut c_void;
}

extern "C" fn close(h: *mut c_void) {
    let h = unsafe { Box::from_raw(h) };
    // XXX This segfaults - why?
    drop(h);
}

A: The problem is you didn't cast the pointer back to a Handle pointer while transforming it back to a Box, and got a Box of the wrong type.
This works:
fn close(h: *mut c_void) {
    let h = unsafe { Box::from_raw(h as *mut Handle) };
    //                               ^^^^^^^^^^^^^^
    drop(h);
}

In your code, h is a std::boxed::Box<std::ffi::c_void>.

A: In close, you end up creating a Box<c_void> instead of a Box<Handle> because you didn't cast the *mut c_void back to *mut Handle before invoking Box::from_raw.
fn close(h: *mut c_void) {
    let h = unsafe { Box::from_raw(h as *mut Handle) };
    drop(h);
}

By the way, Box doesn't actually allocate any memory for a zero-sized type (such as Handle here) and uses a fixed, non-zero pointer value instead (which, in the current implementation, is the alignment of the type; a zero-sized type has an alignment of 1 by default). The destructor for a boxed zero-sized type knows not to try to deallocate memory at this fictitious memory address, but c_void is not a zero-sized type (it has size 1), so the destructor for Box<c_void> tries to free memory at address 0x1, which causes the segfault.
If Handle wasn't zero-sized, then the code may not crash, but it would still run the wrong destructor (it'd run c_void's destructor, which does nothing), and this may cause memory leaks. A destructor runs Drop::drop for the type if present, then drops the type's fields.


text:
Q: Opencv: Get all objects from segmented colorful image How to get all objects from image i am separating image objects through colors.
There are almost 20 colors in following image. I want to extract all colors and their position in a vector(Vec3b and Rect).
I'm using egbis algorithum for segmentation

Segmented image

Mat src, dst;
  String imageName("/home/pathToImage.jpg" );
  src = imread(imageName,1);
  if(src.rows < 1)
      return -1;
  for(int i=0; i<src.rows; i=i+5)
  {    for(int j=0; j<src.cols; j=j+5)
      {
          Vec3b color = src.at<Vec3b>(Point(i,j));
          if(colors.empty())
            {
                colors.push_back(color);
            }
          else{
              bool add = true;
            for(int k=0; k<colors.size(); k++)
            {
                 int     rmin = colors[k].val[0]-5,
                  rmax = colors[k].val[0]+5,
                  gmin = colors[k].val[1]-5,
                  gmax = colors[k].val[1]+5,
                  bmin = colors[k].val[2]-5,
                  bmax = colors[k].val[2]+5;
                if((
                        (color.val[0] >= rmin && color.val[0] <= rmax) &&
                        (color.val[1] >= gmin && color.val[1] <= gmax) &&
                        (color.val[2] >= bmin && color.val[2] <= bmax))

                )
                {
                    add = false;
                    break;
                }

            }
            if(add)
                colors.push_back(color);

          }
      }
  }
  int size = colors.size();
  for(int i=0; i<colors.size();i++)
  {
      Mat inrangeImage;
      //cv::inRange(src, Scalar(lowBlue, lowGreen, lowRed), Scalar(highBlue, highGreen, highRed), redColorOnly);
      cv::inRange(src, cv::Scalar(colors[i].val[0]-1, colors[i].val[1]-1, colors[i].val[2]-1), cv::Scalar(colors[i].val[0]+1, colors[i].val[1]+1, colors[i].val[2]+1), inrangeImage);
      imwrite("/home/kavtech/Segmentation/1/opencv-wrapper-egbis/images/inrangeImage.jpg",inrangeImage);
  }
  /// Display
  namedWindow("Image", WINDOW_AUTOSIZE );
  imshow("Image", src );
  waitKey(0);

I want to get each color position so that
i can differentiate object positions. Please Help!

A: That's just a trivial data formatting problem. You want to turn a truecolour image with only 20 or so colours into a colour-indexed image.
So simply step through the image, look up the colour in your growing dictionary, and assign and integer 0-20 to each pixel.
Now you can turn the images into binary images simply by saying one colour is set and the rest are clear, and use standard algorithms for fitting rectangles.


text:
Q: Input string was not in a correct format Error when using repo.find(int32.Parse) I have the below code:
var ConLeads = repo.Find(Int32.Parse(Request.QueryString["id"]));

***var Customer = Custrepo.Find(Int32.Parse(ConLeads.ClientName));***

IDTextBox.Text = ConLeads.ID;
CreatedByTextBox.Text = ConLeads.CreatedBy;
***ExisitingClientTextBox.Text = Customer.Client_Name;***
NewClientTextBox.Text = ConLeads.PotentialClientName;
ContactNameTextBox.Text = ConLeads.ContactName;
IssueDateTextBox.Text = ConLeads.IssueDate;
DetailsTextBox.Text = ConLeads.Details;
ClientTelNoTextBox.Text = ConLeads.ClientTelNo;
ClientIDTextBox.Text = ConLeads.ClientName;

I receive the below error message when running my code on the lines above in Bold and Italic:
Input string was not in a correct format Error
The reason the error occurs is due to the cell in the database being blank. This is correct as not all entries will have a value as the ExisitingClientTextBox is not a mandatory filed that required an entry into the database. Is there a way to stop this error occurring when the Database value is blank?

A: This is a specific behavior of parse. It is know to throw "Vexing Exceptions": Exceptions you have to handle and can not avoid without implementing the whole thing yoruself. As taht was too annoying, the Framework team added TryParse() pretty much with Framework 2.0.
See also: http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx
Aside from filtering out the "blank" case, TryParse would be the obvious solution.
However as others pointed out, your database design might be broken. For starters, why is a number stored or transmited as string that you need to parse? And some Rows do not have a primary key (ID) apparently?

A: You can try :
int result;
if(int.TryParse(Request.QueryString["id"], out result))
                {
                   var ConLeads = repo.Find(result);

                }


text:
Q: getDate with Jquery Datepicker i am trying to get date from my implementation of jquery date picker, add it to a string and display the resulting image in my div. Something however is just not working. Can anyone check out the code and have a look at it?
The code is supposed to take the date from date picker, combine it in a string which is to have the necessary code to display  tag, images are located in /image and in the format aYY-MM-DD.png, new to this date picker and can't quite get it down yet.

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <link type="text/css" href="css/ui-lightness/jquery-ui-1.8.custom.css" rel="stylesheet" />

Date Value: <input type="text" id="datepicker_value" />

A: I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle
$(document).ready(function(){
    // Datepicker
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        inline: true,
        minDate: new Date(2010, 1 - 1, 1),
        maxDate:new Date(2010, 12 - 1, 31),
        altField: '#datepicker_value',
        onSelect: function(){
            var day1 = $("#datepicker").datepicker('getDate').getDate();
            var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;
            var year1 = $("#datepicker").datepicker('getDate').getFullYear();
            var fullDate = year1 + "-" + month1 + "-" + day1;
            var str_output = "

";
            $('#page_output').html(str_output);
        }
    });
});

A: Instead of parsing day, month and year you can specify date formats directly using datepicker's formatDate function.  In my example I am using "yy-mm-dd", but you can use any format of your choice.
$("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    inline: true,
    minDate: new Date(2010, 1 - 1, 1),
    maxDate: new Date(2010, 12 - 1, 31),
    altField: '#datepicker_value',
    onSelect: function(){
        var fullDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
        var str_output = "

";
        $('#page_output').html(str_output);
    }
});

A: This line looks questionable:
page_output.innerHTML = str_output;

You can use .innerHTML within jQuery, or you can use it without, but you have to address the selector semantically one way or the other:
$('#page_output').innerHTML /* for jQuery */
document.getElementByID('page_output').innerHTML /* for standard JS */

or better yet
$('#page_output').html(str_output);

A: try
$('#page_output').html(str_output);

A: You can format the jquery date with this line:
moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");
http://momentjs.com


text:
Q: SPARQL and linked data: Getting the attribute of an external property I think I'm having a logical problem that might be connected to the understanding of the linked data structure, but it could also just be a SPARQL issue.
I inserted the following extract of a turtle-code to my triple store. I create an observation. And one of the properties (SPACE) I try to take from another server and also its value (X01).
<http://myserver/mydataset/observation/B> a cube:Observation ;
   <https://otherserver/property/SPACE> <https://otherserver/code/X01> .

Now, generally I managed to insert the property to my triple store. But I cannot access the attributes of that property (that I have not defined from my side, but I thought that it would be possible to access them in a linked way?). Thus the following partial pseudo-code, where the schema:name of that property is supposed to be extracted does not work:
SELECT ?obs ?place
WHERE {
  <http://myserver/mydataset> a cube:Cube;
             cube:observationSet/cube:observation ?obs.
   ?obs <https://otherserver/property/SPACE>/<https://schema.org/name> ?place .
}

However, the code works without the schema:name - it then just shows the property-link that I defined.
Why does he not give me the schema:name that is defined in the other server? Do I have to specify all attributes from my side as well?


text:
Q: conflicting types for Function' struct error in C I currently am trying to pass a struct to a different file using a header file. It also gives me the warning "struct Connection' declared inside parameter list". Three are three files, piggy1.h,piggg1.c, and ear.c. Any thoughts on why I can't get this code to compile?
Thanks so much guys!
//piggy1.h----------------------------------------
void ear(struct Connection *connect1);

//-------------------------------------------------*
//ear.c --------------------------------------------
include "piggy1.h"

void ear(struct Connection *connect1){}

//---------------------------------------------------*
//piggy1.c -------------------------------------------

include "piggy1.h"

struct Connection{
int llport;
int rrport;
char rraddr[50];
int noleft;
int noright;
};

 main(argc, argv)

int argc;
char *argv[];
{
int cases;
int noright = -1;
int noleft = -1;
int rraddr = -1;
int llport = -1;
int rrport = -1;
struct Connection connect;
}

A: I defined the struct into the header file and this solved the problem! Place the following code into the header file.
struct Connection{

   int llport;
   int rrport;
   char rraddr[50];
   int noleft;
   int noright;
};

A: Conflicting error means the parameters passes in your definition section and parameters passed in your declaration section do not match.
In your case, the error is shown because definition and declaration of ear function is done before the struct definition.
The compiler doesn't recognise your parameters and so an error is thrown.


text:
Q: Java: Using a method to get values from an ArrayList I need to use a method inside of a class to get values from an ArrayList that is inside the main area.
I have searched high and low for answers and I cannot for the life of me figure it out.
I need the ArrayList "objectList" to be run through the minArea function. I just don't know how to reference the values within the ArrayList from the minArea/maxArea function. I can surely figure out how to do the actual functions on my own, but I just need to know how to reference the Circle and Square objects within ...
public static class geometricObject {
    String color = "white";
    public String fillColor() {
        return color;
    }

    public double minArea() {
        return 0;
    }

    public double maxArea() {
        return 0;
    }
}

public static class Circle extends geometricObject {
    public static double radius;
    public Circle(double radius) {
        this.radius = radius;
    }
    public double getArea() {
        double ans = Math.PI * (radius * radius);
        return ans;
    }
}

public static class Square extends geometricObject {
    public double width;
    public Square(double width) {
        this.width = width;
    }
    public double getArea() {
        double ans = width * width;
        return ans;
    }
}

public static void main(String[] args) {

    ArrayList<geometricObject> objectList = new ArrayList<geometricObject>();
    objectList.add(new Circle(8));
    objectList.add(new Circle(3));
    objectList.add(new Square(5));
    objectList.add(new Square(4));
    objectList.add(new Square(3));
    int i = 5;
    System.out.println(objectList..minArea());
}

A: Try this out:
ArrayList<geometricObject> objectList;
public static void main(String[] args) {

    objectList = new ArrayList<geometricObject>();
    objectList.add(new Circle(8));
    objectList.add(new Circle(3));
    objectList.add(new Square(5));
    objectList.add(new Square(4));
    objectList.add(new Square(3));
    int i = 5;
    System.out.println(objectList..minArea());

}

What I did: I put the undefined variable before the method is called, and declared it in the main. In your case however, you may want to put the undefined variable:
ArrayList<geometricObject> objectList;

Before all the methods.

A: You could do something like:
for (i=0; i<5; i++) {
    geomtericObject g = objectList.get(i);
    System.out.println(g.minArea());
    System.out.println(g.getArea());
}

or get away from using indexes:
foreach (geomtericObject g : objectList) {
    System.out.println(g.minArea());
    System.out.println(g.getArea());
}


text:
Q: AppDomain.CurrentDomain.BaseDirectory path issue when running MVC project This code creates a log file in App_Data folder. If file doesn't exist it's created. It works when the MVC page is published on my IIS.
 var filename = AppDomain.CurrentDomain.BaseDirectory +
                "App_Data//" +
                label +
                DateTime.Now.ToString() +
                ".txt";

 var sw = new System.IO.StreamWriter(filename, true);

However when i run the project local, i get :

NotSupportedException. the StreamWriter says that my path is not supported. This is the path im getting:

"C:\Projects\x- chefsportalen 2.0\Chefsportalen\App_Data//Paragå manuell2015-05-18 11:00:18.txt"
The App_Data folder exist and the path is correct, why am i getting this error?

A: Filenames are not allowed to contain the ":" character.
Use an explicit format string to specify a format that doesn't contain ":", e.g.
DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss", CultureInfo.InvariantCulture)

I'm not sure why it's working when you publish to IIS - maybe because IIS is using a culture that doesn't have ":" as time separator.


text:
Q: Running in same child process two times Can I be running in the same child process two times in the same fork? Ex.
pid_t pid;
pid = fork();
if (pid == 0){
    some code here
}else{
    some code here
}
wait(NULL)
if (pid ==0){
    some code here
}else{
    some core here
}

A: When you leave the if/else, the code runs in both the parent and child. The next if/else again switches to different code in each.
pid_t pid;
pid = fork();
if (pid == 0){
    // child code here
}else{
    // parent code here
}
wait(NULL) // runs in both
if (pid ==0){
    // more child code here
}else{
    // more parent code here
}

Unless the child forks another child, wait(NULL) in the child will return immediately (it will return -1 and set errno to ECHILD to indicate that it has no children to wait for). But in the parent process it will wait for the child to exit. So the second if/else block will run immediately in the child, while it will not run in the parent until the child exits.


text:
Q: list all files in folder excluding subdirectories I use a specific file to load to my application. The user provides the path and I need to get the correct file. If the file isn't there I want to notify the user. I need to scan the folder the user provides. I don't want to check sub-directories. I use the following:
File f = new File(fileName);
        String[] allFiles = f.list();
        for (String files:allFiles) {

I don't want the f.list() to go recursively into all the sub-directories as there might be many files there and is a waste of time for me as if the file is not in the top directory then I can't do something anyway.
I couldn't find anything on google/stack overflow - can anyone suggest a solution to save on this time?
thanks,


text:
Q: unix sas teradata sql: no observation recoreded in the created table In the below query, i am trying to create a table. The table is created but there is not observations recorded. I have also tried using "With Data" but getting error for that. Could you please tell me what is wrong with the query. I am fairly new to this entire system. Any help would be appreciated.
options mlogic mprint symbolgen COMPRESS=YES;

proc sql;

         *this is changed .... libname lib1  teradata  user=abcdedede password="abcdcdcd123@" database=Mydatabase tdpid="Myserver" ;

         connect to teradata  as td (user="abcdedede" password="abcdcdcd123@" mode=teradata fastexport=yes database=Mydatabase  tdpid="Myserver");

libname lib '/export/home/userID/';

         create  table lib.feedbackds AS select * from connection to td
         (
         SELECT
         z.USER_ID,
         y.respns,
         y.txt,
         b.item_price*b.quantity as total

         FROM DB1.Table2 x

         LEFT  JOIN DB1.Table1 y
         ON
         x.RSPNS_ID=y.RSPNS_ID
         AND
         x.CRE_DATE=y.CRE_DATE

         JOIN DB2.table3 z
         ON
         x.S_ID=z.S_ID

         LEFT JOIN MyDatabase.table4 b
         ON
         z.USER_ID=b.G_id OR z.USER_ID=b.D_id

         WHERE y.CRE_DATE BETWEEN '2014-06-25' and '2014-06-30'
         AND y.respns IS NOT NULL
         AND  x.CRE_DATE  BETWEEN '2014-06-29' and '2014-06-30'
        AND x.col_ID IS NOT NULL
         AND x.S_ID=5000001479
         ) ;
         quit;


text:
Q: Ubuntu 22.04 - Laptop does not wake up after sleep I am using Ubuntu 22.04 and facing that problem. My laptop does not wake up after suspend and I have to restart it.
My output of sudo dmesg | grep -i "acpi"
[    0.000000] BIOS-e820: [mem 0x000000009d36e000-0x000000009d36efff] ACPI NVS
[    0.000000] BIOS-e820: [mem 0x00000000ab6ec000-0x00000000ab73bfff] ACPI data
[    0.000000] BIOS-e820: [mem 0x00000000ab73c000-0x00000000abef4fff] ACPI NVS
[    0.011496] ACPI: Early table checksum verification disabled
[    0.011500] ACPI: RSDP 0x00000000000ED2B0 000024 (v02 DELL  )
[    0.011505] ACPI: XSDT 0x00000000AB70D0A8 0000D4 (v01 DELL   CBX3     01072009 AMI  00010013)
[    0.011512] ACPI: FACP 0x00000000AB72E1D0 00010C (v05 DELL   CBX3     01072009 AMI  00010013)
[    0.011518] ACPI: DSDT 0x00000000AB70D210 020FC0 (v02 DELL   CBX3     01072009 INTL 20120913)
[    0.011522] ACPI: FACS 0x00000000ABEF3F80 000040
[    0.011525] ACPI: APIC 0x00000000AB72E2E0 000084 (v03 DELL   CBX3     01072009 AMI  00010013)
[    0.011529] ACPI: FPDT 0x00000000AB72E368 000044 (v01 DELL   CBX3     01072009 AMI  00010013)
[    0.011532] ACPI: FIDT 0x00000000AB72E3B0 00009C (v01 DELL   CBX3     01072009 AMI  00010013)
[    0.011536] ACPI: MCFG 0x00000000AB72E450 00003C (v01 DELL   CBX3     01072009 MSFT 00000097)
[    0.011539] ACPI: HPET 0x00000000AB72E490 000038 (v01 DELL   CBX3     01072009 AMI. 0005000B)
[    0.011543] ACPI: SSDT 0x00000000AB72E4C8 00050E (v01 SataRe SataTabl 00001000 INTL 20120913)
[    0.011546] ACPI: LPIT 0x00000000AB72E9D8 000094 (v01 INTEL  SKL      00000000 MSFT 0000005F)
[    0.011550] ACPI: SSDT 0x00000000AB72EA70 000248 (v02 INTEL  sensrhub 00000000 INTL 20120913)
[    0.011554] ACPI: SSDT 0x00000000AB72ECB8 002BAE (v02 INTEL  PtidDevc 00001000 INTL 20120913)
[    0.011557] ACPI: SSDT 0x00000000AB731868 00094B (v02 INTEL  xh_rvp07 00000000 INTL 20120913)
[    0.011561] ACPI: DBGP 0x00000000AB7321B8 000034 (v01 INTEL           00000000 MSFT 0000005F)
[    0.011564] ACPI: DBG2 0x00000000AB7321F0 000054 (v00 INTEL           00000000 MSFT 0000005F)
[    0.011568] ACPI: SSDT 0x00000000AB732248 0035DA (v02 SaSsdt SaSsdt   00003000 INTL 20120913)
[    0.011571] ACPI: UEFI 0x00000000AB735828 000042 (v01                 00000000      00000000)
[    0.011575] ACPI: SSDT 0x00000000AB735870 000E73 (v02 CpuRef CpuSsdt  00003000 INTL 20120913)
[    0.011578] ACPI: SSDT 0x00000000AB7366E8 003BFD (v02 DptfTa DptfTabl 00001000 INTL 20120913)
[    0.011582] ACPI: MSDM 0x00000000AB73A2E8 000055 (v03 DELL   CBX3     06222004 AMI  00010013)
[    0.011585] ACPI: SLIC 0x00000000AB73A340 000176 (v03 DELL   CBX3     01072009 MSFT 00010013)
[    0.011589] ACPI: TCPA 0x00000000AB73A4B8 000032 (v02 ALASKA NAPAASF  00000001 MSFT 01000013)
[    0.011592] ACPI: DMAR 0x00000000AB73A4F0 0000A8 (v01 INTEL  SKL      00000001 INTL 00000001)
[    0.011596] ACPI: ASF! 0x00000000AB73A598 0000A5 (v32 INTEL   HCG     00000001 TFSM 000F4240)
[    0.011599] ACPI: Reserving FACP table memory at [mem 0xab72e1d0-0xab72e2db]
[    0.011601] ACPI: Reserving DSDT table memory at [mem 0xab70d210-0xab72e1cf]
[    0.011602] ACPI: Reserving FACS table memory at [mem 0xabef3f80-0xabef3fbf]
[    0.011604] ACPI: Reserving APIC table memory at [mem 0xab72e2e0-0xab72e363]
[    0.011605] ACPI: Reserving FPDT table memory at [mem 0xab72e368-0xab72e3ab]
[    0.011606] ACPI: Reserving FIDT table memory at [mem 0xab72e3b0-0xab72e44b]
[    0.011607] ACPI: Reserving MCFG table memory at [mem 0xab72e450-0xab72e48b]
[    0.011609] ACPI: Reserving HPET table memory at [mem 0xab72e490-0xab72e4c7]
[    0.011610] ACPI: Reserving SSDT table memory at [mem 0xab72e4c8-0xab72e9d5]
[    0.011611] ACPI: Reserving LPIT table memory at [mem 0xab72e9d8-0xab72ea6b]
[    0.011612] ACPI: Reserving SSDT table memory at [mem 0xab72ea70-0xab72ecb7]
[    0.011613] ACPI: Reserving SSDT table memory at [mem 0xab72ecb8-0xab731865]
[    0.011615] ACPI: Reserving SSDT table memory at [mem 0xab731868-0xab7321b2]
[    0.011616] ACPI: Reserving DBGP table memory at [mem 0xab7321b8-0xab7321eb]
[    0.011617] ACPI: Reserving DBG2 table memory at [mem 0xab7321f0-0xab732243]
[    0.011618] ACPI: Reserving SSDT table memory at [mem 0xab732248-0xab735821]
[    0.011619] ACPI: Reserving UEFI table memory at [mem 0xab735828-0xab735869]
[    0.011620] ACPI: Reserving SSDT table memory at [mem 0xab735870-0xab7366e2]
[    0.011621] ACPI: Reserving SSDT table memory at [mem 0xab7366e8-0xab73a2e4]
[    0.011622] ACPI: Reserving MSDM table memory at [mem 0xab73a2e8-0xab73a33c]
[    0.011624] ACPI: Reserving SLIC table memory at [mem 0xab73a340-0xab73a4b5]
[    0.011625] ACPI: Reserving TCPA table memory at [mem 0xab73a4b8-0xab73a4e9]
[    0.011626] ACPI: Reserving DMAR table memory at [mem 0xab73a4f0-0xab73a597]
[    0.011627] ACPI: Reserving ASF! table memory at [mem 0xab73a598-0xab73a63c]
[    0.068153] ACPI: PM-Timer IO Port: 0x1808
[    0.068161] ACPI: LAPIC_NMI (acpi_id[0x01] high edge lint[0x1])
[    0.068163] ACPI: LAPIC_NMI (acpi_id[0x02] high edge lint[0x1])
[    0.068164] ACPI: LAPIC_NMI (acpi_id[0x03] high edge lint[0x1])
[    0.068165] ACPI: LAPIC_NMI (acpi_id[0x04] high edge lint[0x1])
[    0.068194] ACPI: INT_SRC_OVR (bus 0 bus_irq 0 global_irq 2 dfl dfl)
[    0.068196] ACPI: INT_SRC_OVR (bus 0 bus_irq 9 global_irq 9 high level)
[    0.068201] ACPI: Using ACPI (MADT) for SMP configuration information
[    0.068202] ACPI: HPET id: 0x8086a701 base: 0xfed00000
[    0.153048] ACPI: Core revision 20210730
[    0.199023] ACPI: PM: Registering ACPI NVS region [mem 0x9d36e000-0x9d36efff] (4096 bytes)
[    0.199023] ACPI: PM: Registering ACPI NVS region [mem 0xab73c000-0xabef4fff] (8097792 bytes)
[    0.201417] ACPI FADT declares the system doesn't support PCIe ASPM, so disable it
[    0.201417] ACPI: bus type PCI registered
[    0.201417] acpiphp: ACPI Hot Plug PCI Controller Driver version: 0.5
[    0.202695] ACPI: Added _OSI(Module Device)
[    0.202695] ACPI: Added _OSI(Processor Device)
[    0.202695] ACPI: Added _OSI(3.0 _SCP Extensions)
[    0.202695] ACPI: Added _OSI(Processor Aggregator Device)
[    0.202695] ACPI: Added _OSI(Linux-Dell-Video)
[    0.202695] ACPI: Added _OSI(Linux-Lenovo-NV-HDMI-Audio)
[    0.202695] ACPI: Added _OSI(Linux-HPI-Hybrid-Graphics)
[    0.254214] ACPI: 8 ACPI AML tables successfully acquired and loaded
[    0.257462] ACPI: [Firmware Bug]: BIOS _OSI(Linux) query ignored
[    0.268801] ACPI: Dynamic OEM Table Load:
[    0.268809] ACPI: SSDT 0xFFFF8BC081020800 0005DC (v02 PmRef  Cpu0Ist  00003000 INTL 20120913)
[    0.270513] ACPI: \_PR_.CPU0: _OSC native thermal LVT Acked
[    0.272231] ACPI: Dynamic OEM Table Load:
[    0.272238] ACPI: SSDT 0xFFFF8BC080FD2C00 00037F (v02 PmRef  Cpu0Cst  00003001 INTL 20120913)
[    0.273808] ACPI: Dynamic OEM Table Load:
[    0.273814] ACPI: SSDT 0xFFFF8BC0811AA6C0 00008E (v02 PmRef  Cpu0Hwp  00003000 INTL 20120913)
[    0.275212] ACPI: Dynamic OEM Table Load:
[    0.275217] ACPI: SSDT 0xFFFF8BC0801F8800 000130 (v02 PmRef  HwpLvt   00003000 INTL 20120913)
[    0.277417] ACPI: Dynamic OEM Table Load:
[    0.277424] ACPI: SSDT 0xFFFF8BC081024000 0005AA (v02 PmRef  ApIst    00003000 INTL 20120913)
[    0.279417] ACPI: Dynamic OEM Table Load:
[    0.279422] ACPI: SSDT 0xFFFF8BC0801F8200 000119 (v02 PmRef  ApHwp    00003000 INTL 20120913)
[    0.280947] ACPI: Dynamic OEM Table Load:
[    0.280952] ACPI: SSDT 0xFFFF8BC0801F9C00 000119 (v02 PmRef  ApCst    00003000 INTL 20120913)
[    0.284935] ACPI: EC: EC started
[    0.284936] ACPI: EC: interrupt blocked
[    0.289174] ACPI: EC: EC_CMD/EC_SC=0x934, EC_DATA=0x930
[    0.289177] ACPI: \_SB_.PCI0.LPCB.ECDV: Boot DSDT EC used to handle transactions
[    0.289179] ACPI: Interpreter enabled
[    0.289227] ACPI: PM: (supports S0 S3 S4 S5)
[    0.289228] ACPI: Using IOAPIC for interrupt routing
[    0.289275] PCI: Using host bridge windows from ACPI; if necessary, use "pci=nocrs" and report a bug
[    0.290100] ACPI: Enabled 8 GPEs in block 00 to 7F
[    0.292298] ACPI: PM: Power Resource [PG00]
[    0.292952] ACPI: PM: Power Resource [PG01]
[    0.293493] ACPI: PM: Power Resource [PG02]
[    0.297846] ACPI: PM: Power Resource [WRST]
[    0.298214] ACPI: PM: Power Resource [WRST]
[    0.298578] ACPI: PM: Power Resource [WRST]
[    0.298942] ACPI: PM: Power Resource [WRST]
[    0.299311] ACPI: PM: Power Resource [WRST]
[    0.300016] ACPI: PM: Power Resource [WRST]
[    0.300387] ACPI: PM: Power Resource [WRST]
[    0.300762] ACPI: PM: Power Resource [WRST]
[    0.302079] ACPI: PM: Power Resource [WRST]
[    0.302441] ACPI: PM: Power Resource [WRST]
[    0.302808] ACPI: PM: Power Resource [WRST]
[    0.303173] ACPI: PM: Power Resource [WRST]
[    0.303535] ACPI: PM: Power Resource [WRST]
[    0.303897] ACPI: PM: Power Resource [WRST]
[    0.304259] ACPI: PM: Power Resource [WRST]
[    0.304622] ACPI: PM: Power Resource [WRST]
[    0.304987] ACPI: PM: Power Resource [WRST]
[    0.328291] ACPI: PCI Root Bridge [PCI0] (domain 0000 [bus 00-7e])
[    0.328300] acpi PNP0A08:00: _OSC: OS supports [ExtendedConfig ASPM ClockPM Segments MSI HPX-Type3]
[    0.330450] acpi PNP0A08:00: _OSC: OS now controls [PCIeHotplug SHPCHotplug PME AER PCIeCapability LTR]
[    0.330452] acpi PNP0A08:00: FADT indicates ASPM is unsupported, using BIOS configuration
[    0.345982] ACPI: PCI: Interrupt link LNKA configured for IRQ 11
[    0.346057] ACPI: PCI: Interrupt link LNKB configured for IRQ 10
[    0.346131] ACPI: PCI: Interrupt link LNKC configured for IRQ 11
[    0.346203] ACPI: PCI: Interrupt link LNKD configured for IRQ 11
[    0.346275] ACPI: PCI: Interrupt link LNKE configured for IRQ 11
[    0.346346] ACPI: PCI: Interrupt link LNKF configured for IRQ 11
[    0.346418] ACPI: PCI: Interrupt link LNKG configured for IRQ 11
[    0.346490] ACPI: PCI: Interrupt link LNKH configured for IRQ 11
[    0.348683] ACPI: EC: interrupt unblocked
[    0.348685] ACPI: EC: event unblocked
[    0.348695] ACPI: EC: EC_CMD/EC_SC=0x934, EC_DATA=0x930
[    0.348697] ACPI: EC: GPE=0x14
[    0.348699] ACPI: \_SB_.PCI0.LPCB.ECDV: Boot DSDT EC initialization complete
[    0.348701] ACPI: \_SB_.PCI0.LPCB.ECDV: EC: Used to handle transactions and events
[    0.348782] ACPI: bus type USB registered
[    0.349439] PCI: Using ACPI for IRQ routing
[    0.375458] pnp: PnP ACPI init
[    0.382784] pnp: PnP ACPI: found 12 devices
[    0.388542] clocksource: acpi_pm: mask: 0xffffff max_cycles: 0xffffff, max_idle_ns: 2085701024 ns
[    0.410050] ACPI BIOS Error (bug): Could not resolve symbol [\_SB.PCI0.LPCB.HEC.CHRG], AE_NOT_FOUND (20210730/psargs-330)
[    0.410069] ACPI Error: Aborting method \PNOT due to previous error (AE_NOT_FOUND) (20210730/psparse-529)
[    0.410077] ACPI Error: Aborting method \_SB.AC._PSR due to previous error (AE_NOT_FOUND) (20210730/psparse-529)
[    0.410086] ACPI: \_SB_.AC__: Error reading AC Adapter state: AE_NOT_FOUND
[    0.410187] ACPI: button: Lid Switch [LID0]
[    0.410240] ACPI: button: Power Button [PBTN]
[    0.410282] ACPI: button: Sleep Button [SBTN]
[    0.410333] ACPI: button: Power Button [PWRF]
[    0.412812] ACPI: thermal: Thermal Zone [THM] (25 C)
[    0.485733] ACPI: battery: Slot [BAT0] (battery present)
[    0.763446] acpi LNXPOWER:03: hash matches
[    2.863827] parport_pc 00:06: reported by Plug and Play ACPI
[    3.780702] ACPI: video: Video Device [GFX0] (multi-head: yes  rom: no  post: no)


text:
Q: active(selected), hover and inactive tab/div css logic I have been stuck with this for a while now. I have no code to show here. I would like an algorithm/pseudocode for the below using jquery/css:
A tab /
 that:

*

*When selected (the active element) - is highlighted with the color blue

*When hovered - highlighted with color aqua

*unselected/mouseout - colored white

*selected element on hoverout (mouseout) - should retain color blue
I hope I am clear with my need. Any help is appreciated.

A: i think this Demo: http://jsfiddle.net/sahilosheal/caB3a/1/ will help you to solve your problem,
        please go through it and let me know.

$('.tab').click(function() {
  $(this).addClass('active').siblings().removeClass('active');
});
div.active {
  background-color: #2e2e2e !important;
  color: white;
  height: 25px;
  width: 100px;
  float: left;
  margin-right: 2px;
  text-align: center;
  padding-top: 5px;
}

div.bat:hover {
  background-color: #80a3bb;
  height: 25px;
  width: 100px;
  float: left;
  margin-right: 2px;
  text-align: center;
  padding-top: 5px;
}

div.bat {
  background-color: orange;
  height: 25px;
  width: 100px;
  float: left;
  margin-right: 2px;
  text-align: center;
  padding-top: 5px;
}

select1

select2

select3

A: CSS:
.tab {
    background: white;
}
.tab.active {
    background: blue;
}
.tab:hover {
    background: aqua;
}

jQuery:
$('.tab').click(function() {
    $(this).addClass('active').siblings().removeClass('active')
})

A: HTML

Tab

Tab

Tab

CSS
div.active {
    background-color: blue;
}

div:hover {
    background-color: aqua;
}

See fiddle.

A:

$('.tab').click(function() {
  $(this).addClass('active').siblings().removeClass('active');
})
.main {
  width: 325px;
}

div.tab {
  background: white;
  width: 100px;
  border: 1px solid grey;
  padding-left: 5px;
}

div.tab.active {
  background: blue;
}

div.tab:hover {
  background: aqua;
}

.blue {
  background: blue;
}

Tab 3

Tab 2

Tab 1

Here's a sample!


text:
Q: What is the term for replacing a letter with a number in a word? What is the term for replacing a letter with a number in a word, such as UNREAL being written as UNR34L?  Quite often seen on licence plates, it is almost satirical misspelling, but the definition of that does not seem to include substitution of letters for numbers.

A: I think the correct term is "leet" or "leetspeak" used as a noun. I've never seen it used as a verb but you probably could.
"leet" is a contraction of "elite" and is often written "l33t" and it hearkens back to when people would express their own technical superiority in online chat rooms by using leetspeak and thereby making it harder for n00bs (new users) to understand what's going on.
Leet consists of much more than the substitution of numbers for letter, though that is a big part of it, it is a fairly complex code with its own vocabulary, thereby being quite effective at excluding the uninitiated.


text:
Q: Estimates involving Schrodinger Equation Estimates of the extension operator can be seen as estimates of the initial value problem for the evolution Schrodinger equation. If $u(x,t)=e^{it\Delta}u_0$ is the solution to the IVP:
$$i\partial_t u(x,t) + \Delta u(x,t)=0$$
$$u(x,0)=u_0$$
Then the following estimates hold:
$a)$ if $D^\gamma$ is the fractional derivative  $D^\gamma _x =\int e^{ix\epsilon } |\epsilon|^{\gamma} \hat{f(\epsilon)}d\epsilon$ then $\|D^\gamma _x e^{it\Delta}u_0\|_{L^q_x(L^2_t)}\leq C\|u_0\|_{L^2}$
$b)$ $\|D^\gamma _x e^{it\Delta}u_0\|_{B^*_{1/2}(L^2)}\leq C\|u_0\|_{L^2}$
And this is know as Strichartz Estimate for the Schrodinger equation. I know this was proved by Strichartz and also by Thao for more general family of functions but  the way to do this with polar coordinates is writing $D^{\gamma}_xe^{it\Delta}u_0(x)=\int e^{ix\epsilon} e^{it|\epsilon|^2}|\epsilon|^{\gamma} \hat{u_0}(\epsilon)d\epsilon $ and then writing this in polar coordinates. I dont know how to apply polar coordinates in this step $(r,\theta)$ would it be just:
$\int e^{ix\cdot (rcos(\theta),rsen(\theta))} e^{it|r|^2}r^{\gamma} \hat{u_0}(r,\theta)rdr d\theta $ but then changing the variable $s=r^2$ would difficult me the sinus and cosinus terms... so I think I am doing something wrong.
Then I have to use Plancherel in $t$ and then Minkowski integral inequality but I dont know how to follow from here.
Thanks in advance.