text:
Q: Explanation of this Lambda Expression I am creating a Word Comparison class and it will count the occurrences of words as well. (This is Java)
This was my original method:
/**
 * @param map The map of words to search
 * @param num The number of words you want printed
 * @return list of words
 */
public static List<String> findMaxOccurrence(Map<String, Integer> map, int num) {
    List<WordComparable> l = new ArrayList<>();
    for (Map.Entry<String, Integer> entry : map.entrySet())
        l.add(new WordComparable(entry.getKey(), entry.getValue()));

My IDE suggested that the loop and list assignment could be replaced with a "collect call": "stream api calls"
In which it generated this code:
    List<WordComparable> l =
            map.entrySet().stream()
                    .map(entry -> new WordComparable
                            (entry.getKey(), entry.getValue())).collect(Collectors.toList());

I am kinda confused on how the lambda math works. If my memory serves correctly, the -> is the for each loop, but the other calls are completely confusing.
My IDE can also expand the code into these two snippets:
    List<WordComparable> l =
            map.entrySet().stream()
                    .map(entry -> {
                        return new WordComparable
                                (entry.getKey(), entry.getValue());
                    }).collect(Collectors.toList());

And
    List<WordComparable> l =
            map.entrySet().stream()
                    .map(new Function<Map.Entry<String, Integer>, WordComparable>() {
                        @Override
                        public WordComparable apply(Map.Entry<String, Integer> entry) {
                            return new WordComparable
                                    (entry.getKey(), entry.getValue());
                        }
                    }).collect(Collectors.toList());

Any light-shedding would be awesome.

A: Let's take a look at the for loop a bit closer to see how we can write it functionally:
List<WordComparable> l = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet())
    l.add(new WordComparable(entry.getKey(), entry.getValue()));

If we read that code in plain English, we might say "for each entry of my map, let's convert it to a WordComparable and add it to a list".
Now, we can rephrase that sentence to "for each entry of my map, let's convert it to a WordComparable, and when we have converted it all, let's make a list out of it".
Using that sentence, we see that we need to create a function: one that takes an entry of the map and converts it to a WordComparable. So let's build one! Java 8 introduces a new type named Function, which has one important method: apply. This method takes one input, transforms it and returns one output.
Writing good old Java, since Function is an interface, we can implement it to write our conversion code:
public class EntryConverter implements Function<Map.Entry<String, Integer>, WordComparable> {

    public WordComparable apply(Map.Entry<String, Integer> entry) {
        return new WordComparable(entry.getKey(), entry.getValue());
    }

}

Now that we have this converter, we need to use it on all the entries. Java 8 also introduces the notion of Stream, that is to say, a sequence of elements (note that this sequence can be infinite). Using this sequence, we can finally write into code what we said earlier, i.e. "for each entry, let's convert it to a WordComparable". We make use of the map method, whose goal is to apply a method on each element of the stream.
We have the method: EntryConverter, and we build a Stream of our entries using the stream method.
So, we get:
map.entrySet().stream().map(new EntryConverter());

What remains is the last part of the sentence: "make a List out of it", i.e. collect all the elements into a List. This is done using the collect method. This method takes a Collector as argument, i.e. an object capable of reducing a stream into a final container. Java 8 comes with a lot of prebuilt collectors; one of them being Collectors.toList().
Finally, we get:
map.entrySet().stream().map(new EntryConverter()).collect(Collectors.toList());

Now, if we remove the temporary class EntryConverter and make it anonymous, we get what your IDE is proposing:
List<WordComparable> l = map.entrySet()
                            .stream() //make a Stream of our entries
                            .map(new Function<Map.Entry<String, Integer>, WordComparable>() {
                                 @Override
                                 public WordComparable apply(Map.Entry<String, Integer> entry) {
                                     return new WordComparable(entry.getKey(), entry.getValue());
                                 }
                             }) //let's convert each entry to a WordComparable
                             .collect(Collectors.toList()); //and make a List out of it

Now, writing all that code is a bit cumbersome, especially the declaration of the anonymous class. Java 8 comes to the rescue with the new -> operator. This operator allows the creation of a Function much more painlessly than before: the left side corresponds to the argument of the function and the right side corresponds to the result. This is called a lambda expression.
In our case, we get:
entry -> new WordComparable(entry.getKey(), entry.getValue())

It is also possible to write this lambda expression using a block body and a return statement:
entry -> {
    return new WordComparable(entry.getKey(), entry.getValue());
}

Notice how that corresponds to what we had written earlier in EntryConverter.
This means we can refactor our code to:
List<WordComparable> l = map.entrySet()
                            .stream()
                            .map(entry -> new WordComparable(entry.getKey(), entry.getValue()))
                            .collect(Collectors.toList());

which is much more readable, and is what your IDE proposes.
You can find more about lambda expressions on Oracle site.

A: This is a lambda expression for a Function. It takes an object and returns an object. In this case, it takes a Map.Entry<String, Integer>, and returns a WordComparable.
entry -> new WordComparable(entry.getKey(), entry.getValue())

You could write the equivalent code by hand:
final class ConversionFunction
  implements Function<Map.Entry<String, Integer>, WordComparable>
{
  @Override
  public WordComparable apply(Map.Entry<String, Integer> entry) {
    return new WordComparable(entry.getKey(), entry.getValue());
  }
}

map.entrySet().stream().map(new ConversionFunction()).collect(...);

The Stream.map() method takes a Function that can be applied to each element (Map.Entry) in the stream, and produces a stream of elements of a new type (WordComparable).
The Stream.collect() method uses a Collector to condense all elements of a stream to a single object. Usually it's a collection, like it is here, but it could be any sort of aggregate function.

A: List<WordComparable> l = map.entrySet().stream()
   .map(entry -> new WordComparable(entry.getKey(), entry.getValue()))
   .collect(Collectors.toList());

"->" is a part of lambda itself.
In this snippet .stream() is like foreach loop and then begins the set of data processing "directives" (map, collect, etc).
map means than you map each element of current collection to some new collection with some rule:
entry -> new WordComparable(entry.getKey(), entry.getValue())

your rule means that you use each element (with "entry" alias) to create the new elements for the map() result collection.
then you should collect your elements to appropriate collection by using suitable collector.
note, that collect applies to map() result.


text:
Q: Lua Sandbox with special functions which leak I am trying to use How can I create a secure Lua sandbox? to build my own leaky sandbox.
I am trying to create a Lua sandbox where some Lua functions can access some other Lua functions outside the sandbox. For example I want my sandbox to have a special "display" function which can call "print" but not have "print" in the sandbox too.
The main problem is that I am trying to build a sandbox within an already large codebase, so I cannot nil away functions.
How is this possible?
The solution has to be a pure Lua function due to no fault of mine.

A: When you create a sandbox, you do it by cherry picking functions and values from a larger environment to create a new sandbox environment. You do not need to destroy or "nil out" anything in the original environment.

*

*Create your sandbox environment by cherry picking functions and values

*Load a script (this compiles it and returns it as a function to call)

*Set the environment of the script to the sandbox environment

*Execute the script in the sandbox

So,
local script = loadstring "display(math.log(2, 3))"
local env = {display = print, math = math, string = string}
setfenv(script, env)
pcall(script)

prints
0.69314718055995

whereas
local script = loadstring "print(math.log(2, 3))"
local env = {display = print, math = math, string = string}
setfenv(script, env)
pcall(script)

fails with
false   [string "print(math.log(2, 3))"]:1: attempt to call global 'print' (a nil value)

A: Does it specifically need to call the Lua standard library print function? Can you instead emulate the functionality of print? Because that would be the easiest way.
However, if you want to have a wrapper around print, there are two ways to do it: with pure Lua code, and with C/C++ code.
The pure Lua solution is as follows. Note that this should be done before loading any external scripts. First, open the Lua standard library that has print in it. Then run this Lua script:
local internal_print = print

return function(...)
    --Do display logic.
    internal_print(...) --Or whatever else you want.
end

This will return the "display" function. You can store it in a global variable called display if you like, or called something else.
After that, you can nil out the print global variable, thus making it almost entirely inaccessible.
If you want to do it from C/C++, it's very similar. First, as before, you register the Lua standard library that includes print, so that you can get the function for it. Then, you use lua_getglobal(L, "print") to get the print function and push it onto the stack. Next, you register your C/C++ function using using lua_pushcclosure. But you want to specify one upvalue, which Lua pops off the stack at registration time.
And now your registered function is on the stack, waiting to be pushed into a Lua variable or global table entry.
Warning: the Lua debug library can poke at upvalues and thus get the print function from your new function. So if you want perfect security, get rid of debug.getupvalue.

A: Build your sandbox (or multiple sandboxes if they each have different requirements) and move the untrusted code into the sandbox one piece at a time. In my quick cli tests, both 5.1 and 5.2 will run functions that were defined outside of the sandbox without modification. To use Doug's example, assume display is part of your pre-existing code that uses print:
-- 5.1
local function display(...)
  print(...)
end
local script = loadstring "display(math.log(2, 3))"
local env = {display = display, math = math, string = string}
setfenv(script, env)
print(pcall(script))

-- 5.2
local function display(...)
  print(...)
end
local script = loadstring "display(math.log(2, 3))"
local e=_ENV
_ENV={display = display, math = math, string = string}
e.print(e.pcall(script))
_ENV=e

Note that in both of the above examples, the display function is using print without modification to that code since you were not in the sandbox when this function was created.
In the past, I've stored a local pointer to the un-sandboxed environment, but I can't reproduce the situation where that's needed in my quick cli tests. If you can come up with an example, I can probably come up with a workaround that doesn't require the e variable. Here's an example of that code using 5.2:
local e=_ENV

for k,v in e.pairs(value) do
-- iterate
end

another example, for my read only table code, I'm again using the e:
function ro_table (t)
  local t = t
  if t then
    return e.setmetatable({},
      { __index=t,
        __newindex= function(_,_,_) e.error ("Attempt to modify read-only table") end,
      })
  else
    return nil
  end
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compare different heuristics over a large number of test instances I have 3 different heuristics (H1, H2, H3) that are variation of genetic algorithms combined with some other techniques.
The problem that I try to solve is The problem  to minimize energy costs for public transportation mean.
So to test the performance of the heuristics , I did  generate randomly about 1,000 test instances that consist on passenger demands for this public tranpsort service
On those instances, I did run the 3 heuristics to get for each algorithm on each instance the cost of the solution  using a fixed seed.
I have as a final data the founded  gap (difference from a lower bound) for each algorithm on each instance(about 1000 gap for each algorithm).
By analyzing only the mean of overall gaps for each heuristic, it was clear that the H3 is better as it get the lower mean gap.
I want to know what statistical test could I make  to verify that there is any real difference  between those 3 algorithms (that it does not happen only by chance) and if it would be that H3 is really the best algorithm to get the lower gap?
Thanks.

A: I'm slightly out of my depth on the details of statistical testing, but I think an appropriate method here would be to do pairwise comparisons between the algorithms using a Wilcoxon signed-rank test. This should let you say whether the difference between H1 and H2, H1 and H3, or H2 and H3 respectively are consistent with random chance. Like I said though, I'm open to being corrected by someone with a bit more expertise.
You should be somewhat careful with the interpretation of the results. Hypothesis testing is notorious for being misused in several ways, but despite those caveats, I think it's still the most commonly accepted method for verifying results in the metaheuristics literature.


text:
Q: Is there a way in Pandas to slice multiple datetime values? I have a Dataset of minute prices for EURUSD currency. My prefered timeframe to work with is "60min" so therefore I resample the dataset into 1hr (as below). However, I also want to access the minute data with my new dataset. What I'm looking for is a method where I can pass a time, such as "2019-01-01 17:00:00" and access all minute data within that hour. I have tried to slice my original "Rates" df but get the error message "Cannot index by location index with a non-integer key"
What is the best method to do it?
         #import libraries
            import pandas as pd
            from datetime import datetime
            numpy as np

            #read excel
            Rates = pd.read_excel("test.xlsx")
            #Set columns
            Rates.columns = ["Date","Open","High","Low","Close","Volume"]
        print(Rates)

        Date    Open    High    Low Close   Volume
        2019-01-01 17:03:00 1.14598 1.14607 1.14598 1.14607 0
        2019-01-01 17:04:00 1.14607 1.14607 1.14606 1.14606 0
        2019-01-01 17:05:00 1.14606 1.14621 1.14606 1.14621 0
        2019-01-01 17:06:00 1.14619 1.14666 1.14604 1.14665 0
        2019-01-01 17:07:00 1.14665 1.14672 1.14607 1.14607 0
        2019-01-01 17:08:00 1.14607 1.14607 1.14606 1.14607 0
        2019-01-01 17:09:00 1.14607 1.14617 1.14606 1.14606 0
        2019-01-01 17:10:00 1.14607 1.14607 1.14607 1.14607 0
        2019-01-01 17:11:00 1.14607 1.14617 1.14606 1.14607 0
        2019-01-01 17:12:00 1.14607 1.14608 1.14607 1.14608 0
        2019-01-01 17:13:00 1.14608 1.14608 1.14607 1.14607 0
        2019-01-01 17:14:00 1.14607 1.14608 1.14607 1.14608 0
        2019-01-01 17:15:00 1.14607 1.14608 1.14607 1.14607 0
        2019-01-01 17:16:00 1.14607 1.14608 1.14607 1.14607 0
        2019-01-01 17:17:00 1.14607 1.14607 1.14607 1.14607 0
        2019-01-01 17:18:00 1.14606 1.14617 1.14606 1.14607 0
        2019-01-01 17:19:00 1.14617 1.14617 1.14606 1.14606 0
        2019-01-01 17:20:00 1.14607 1.14616 1.14606 1.14616 0

            #Convert "Date" column to DateTime
            DateTime = pd.to_datetime(Rates.Date)

            #Set index to Datetime object
            Rates.index = DateTime

            #Remove previous "Date" Column
            df = Rates.drop(["Date"],axis=1)

            #Resample to hourly data
            df = df.resample('1H').first()

    print(df)

    2019-01-01 17:00:00  1.14598  1.14607  1.14598  1.14607     0.0
    2019-01-01 18:00:00  1.14605  1.14653  1.14566  1.14603     0.0
    2019-01-01 19:00:00  1.14612  1.14612  1.14606  1.14606     0.0
    2019-01-01 20:00:00  1.14561  1.14563  1.14559  1.14563     0.0
    2019-01-01 21:00:00  1.14521  1.14524  1.14506  1.14512     0.0

#Now when I have the data resampled, I try to access all minute wise data by slicing.
Rates.iloc[str(df.index[-1])], buy i get the error message: "Cannot index by location index with a non-integer key"

My desired output would be to pass a date, ex: "2019-01-01 17:00:00" and then access all minute data within that hour.
Many Thanks!


text:
Q: LINQ-to-XML XElement query NULL I am trying to UPDATE a child element of something (in this case, "Regex") WHERE one of the child elements ("Name") == selected name ("AccountNumber").
Here is a sample of my XmlDoc
<?xml version="1.0" encoding="utf-8"?>
<Bill>
  <Element>
    <Name>AccountNumber</Name>
    <Regex></Regex>
    <Left></Left>
    <Right></Right>
    <Top></Top>
    <Bottom></Bottom>
    <Relations></Relations>
  </Element>
  <Element>
    <Name>BillDate</Name>
    <Regex></Regex>
    <Left></Left>
    <Right></Right>
    <Top></Top>
    <Bottom></Bottom>
    <Relations></Relations>
  </Element>
</Bill>

and here is the code I have so far.
XElement x = XmlDoc.Element("Bill")
                    .Elements("Element")
                    .Where(xel => xel.Element("Name").ToString() == CurrentSelection.ElementName)
                    .SingleOrDefault();
                x.Element("Regex").Value = details[1].Value;

After the query runs, the XElement, x, is still null... I am very new to LINQ (and Lambdas) and could use a little guidance here.
Thanks!

A: It returns null because you Convert Element to String,not it's value.You should check child Element value like this
xel.Element("Name").Value.ToString() == CurrentSelection.ElementName

And i think Value returns string so ToString is redundant here just type
xel.Element("Name").Value == CurrentSelection.ElementName


text:
Q: Can i bind against a DynamicObject in WinRT / Windows 8 Store Apps I have the following code:
    public class MyClass: DynamicObject, INotifyPropertyChanged
    {
    Dictionary<string, object> properties = new Dictionary<string, object>();

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (properties.ContainsKey(binder.Name))
        {
            result = properties[binder.Name];
            return true;
        }
        else
        {
            result = "Invalid Property!";
            return false;
        }
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        properties[binder.Name] = value;
        this.OnPropertyChanged(binder.Name);
        return true;
    }

    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        dynamic method = properties[binder.Name];
        result = method(args[0].ToString(), args[1].ToString());
        return true;
    }

    ///.... Rest of the class.
    }

When i bind against it from xaml, debug points in TryGetMember is not triggeret. Do i miss something?
<DataTemplate x:Key="SearchResults">
    <Grid Width="294" Margin="6">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,0,0,10" Width="40" Height="40">
            <Image Source="{Binding Path=Banner}" Stretch="UniformToFill"/>
        </Border>
        <StackPanel Grid.Column="1" Margin="10,-10,0,0">
            <TextBlock Text="{Binding SeriesName}" Style="{StaticResource BodyTextStyle}" TextWrapping="NoWrap"/>
            <TextBlock Text="{Binding Subtitle}" Style="{StaticResource BodyTextStyle}" Foreground="{StaticResource ApplicationSecondaryForegroundThemeBrush}" TextWrapping="NoWrap"/>
            <TextBlock Text="{Binding Overview}" Style="{StaticResource BodyTextStyle}" Foreground="{StaticResource ApplicationSecondaryForegroundThemeBrush}" TextWrapping="NoWrap"/>
        </StackPanel>
    </Grid>
</DataTemplate>

The datacontext is set to
public ObservableCollection<dynamic> SearchResults {get;set;}

and
 ICollection col = item.SearchResults;
 this.DefaultViewModel["Results"] = col;  //this is the datacontext of the gridview

A: Here is a solution I am using for kind-of dynamic binding.
The binding syntax just needs to include []:

public class DynamicLocalSettings : BindableBase
{
    public object this[string name]
    {
        get
        {
            if (ApplicationData.Current.LocalSettings.Values.ContainsKey(name))
                return ApplicationData.Current.LocalSettings.Values[name];
            return null;
        }
        set
        {
            ApplicationData.Current.LocalSettings.Values[name] = value;
            OnPropertyChanged(name);
        }
    }
}


text:
Q: Using case when in Spark Scala I am new with Apache Spark, I am using Scala to work with it.
I have some doubts and one of them is how to use case when for my example.
I have to work with distributed systems and what I have to do is classify some instances. To do this I have a DataFrame as you can see here:
+--------------------+------------+
|       group        |   info     |
+--------------------+------------+
|gr=nat, dfn         |   x1betdfn |
|gr=pjc, ntp         |   x2b1trkn |
|gr=ntp, ntt         |   x3b2td3n |
+--------------------+------------+

So through the column called group I have to filter or do a regex to get just the three letters after gr= (would be nat, pjc or ntp) and then write it in a new column.
What is the most efficient way to do this?
This is what I am doing:
val df2 =
  df.withColumn("tgroup", when(col("group").match === "nat", "nat_1_nm")
  .when(col("group").match === "pjc", "pjc_determined")
  .when(col("group").match === "ntp", "ntp_dway")
  .otherwise("Unknown"))

But is not working. I am trying to get this:
+--------------------+------------+----------------+
|       group        |   info     |                |
+--------------------+------------+----------------+
|gr=nat, dfn         |   x1betdfn | nat_1_nm       |
|gr=pjc, ntp         |   x2b1trkn | pjc_determined |
|gr=e2p, ntt         |   x3b2td3n | Unknown        |
|gr=ntp, ntt         |   x3b2td3n | ntp_dway       |
+--------------------+------------+----------------+

What am I doing wrong? Thanks in advance.

A: Try to do something like this, using rlike. Just build your own regexp:
val df2 =
      df.withColumn("tgroup",when(col("group").rlike("(?i)^*nat,\\s[a-zA-Z]*$"), "nat_1_nm").
        otherwise(when(col("group").rlike("(?i)^*pjc,\\s[a-zA-Z]*$"), "pjc_determined").
          otherwise(when(col("group").rlike("(?i)^*ntp,\\s[a-zA-Z]*$"), "ntp_dway").otherwise("Unknown"))))

I tried it with an example and I am getting your expected output:
import spark.implicits._
    val df = Seq(
      ("gr=nat, dfn"),
      ("gr=pjc, ntp"),
      ("gr=e2p, ntt"),
      ("gr=ntp, ntt")
    ).toDF("group")

A: If the values of group column always of the form gr=XXX, using startsWith method should be enough in your case :
val df2 = df.withColumn(
  "tgroup",
  when(col("group").startsWith("gr=nat"), "nat_1_nm")
    .when(col("group").startsWith("gr=pjc"), "pjc_determined")
    .when(col("group").startsWith("gr=ntp"), "ntp_dway")
    .otherwise("Unknown")
)

df2.show
//+-----------+--------+--------------+
//|      group|    info|        tgroup|
//+-----------+--------+--------------+
//|gr=nat, dfn|x1betdfn|      nat_1_nm|
//|gr=pjc, ntp|x2b1trkn|pjc_determined|
//|gr=e2p, ntt|x3b2td3n|       Unknown|
//|gr=ntp, ntt|x3b2td3n|      ntp_dway|
//+-----------+--------+--------------+

You may also want to extract the value XXX after gr= using regexp_extract function:
val df2 = df.withColumn(
    "tgroup",
    regexp_extract(col("group"), "^gr=(.{3}),.*", 1)
).withColumn(
    "tgroup",
    when(col("tgroup") === "nat", "nat_1_nm")
      .when(col("tgroup") === "pjc", "pjc_determined")
      .when(col("tgroup") === "ntp", "ntp_dway")
      .otherwise("Unknown")
)


text:
Q: how can you pulse a progress bar in Qt? Is there a way of using CSS or something else to make a pulsing QProgressBar in pyqt as illustrated below?

The default progress bar has an animation when using the windows vista theme, but I'm not sure how to edit it.

A: http://qt-project.org/doc/qt-4.8/qgraphicsdropshadoweffect.html
http://qt-project.org/doc/qt-4.8/qgraphicseffect.html#details
http://qt-project.org/doc/qt-4.8/qpropertyanimation.html
This should get you what you want.  Combine the dropshadow effect (large blur radius + green + zero offset) with a looping QPropertyAnimation (adjusting the opacity property), and you have your flashing, glowing progress bar.


text:
Q: Edit textbox in parallel to asynchronous updating So in my project I have a few textBoxes that hold the coordinates of two corners (Latitude & Longitude). The textBoxes are updated by a timer (which gets a value from a server and sets the textBoxes if the value received is different from the current value). Problem is, I want the textBoxes to be available for manual editing; However if I'm in the middle of typing the number and the timer checks the current value he sees that it's a different thing from what the server returned and changes it immediately. Is there a way to check if the textBox is being edited at the moment, or a better way to solve this solution?
code (samples, the code is the same for the two corners):
if (northEastLatitude != double.Parse(neLatTB.Text)) //neLatTB is the textBox
      neLatTB.Text = northEastLatitude.ToString();

else //No answer returned from the server so we need to reset the textBoxes
{
      northEastLatitude = 0;
      northEastLongitude = 0;
      if(neLatTB.Text != "0")
             neLatTB.Text = northEastLatitude.ToString();
      if(neLngTB.Text != "0")
             neLngTB.Text = northEastLongitude.ToString();
}

in addition, I have functions for TextChanged events for all of the textBoxes (so that when I set the coordinates manually it uploads them to the server). Is there any way to prevent this function from being called whenever I press the dot key? apparently it calls the event too (marks the ending of the text entering).

A: It really depends on your design but if you want to use TextBox to show updatable values and also make it possible to edit you have to suppress code from your timer to execute. WinForms TextBox doesn't have an option to show you if text is changing programmatically or by user interaction. You have to somehow make it by yourself.
There is plenty of ways to do that of courde. One way is to use Enter/Leave events to detect when your TextBox gets or loses focus. But there will be a need to click somwhere out from the control after edit.
Another one, and probably desired by you would be using TextChanged event preventing your timer from updating field until text in TextBox will be typed in full. I would do it something like that:
Fisrtly I would declare two bool variables for blocking parts of code from execution:
private bool _isDirty; // used when user types text directly
private bool _suppresTextChanged; // used when timer updates value programmatically

After that I would write TextBox.TextChanged event listener:
private void neLatTBTextChanged(object sender, EventArgs args)
{
    if(_suppressTextChanged)
        return;
    _isDirty = true; // toggle dirty state

    if(/* text has good format */)
    {
        // Upload changes to server
        _isDirty = false; // end manual edit mode
    }
}

And inside timer method i would set:
_suppresTextChanged = true; // on the beginning

if (northEastLatitude != double.Parse(neLatTB.Text)) //neLatTB is the textBox
  neLatTB.Text = northEastLatitude.ToString();
else //No answer returned from the server so we need to reset the textBoxes
{
      northEastLatitude = 0;
      northEastLongitude = 0;
      if(neLatTB.Text != "0")
             neLatTB.Text = northEastLatitude.ToString();
      if(neLngTB.Text != "0")
             neLngTB.Text = northEastLongitude.ToString();
}

_suppresTextChanged = false; // after edit was made

Personally i think this design can lead to a lot of problems (consider what to do when user stops typing and leave the TextBox in _isDirty state etc...). Instead of using just TextBox I would add a Label to store data from timer (and probably data the user will type) and left TextBox just for entering user specific values.


text:
Q: Is a struct {...}; a type or an unnamed variable? Is the following, at file scope, a type declaration or an unnamed variable?
struct student_s {
    char* name;
    int age;
    double height;
    struct student_s* next;
};

If it is a type definition, then what is the difference with:
typedef struct student_s {
    char* name;
    int age;
    double height;
    struct student_s* next;
};

?
(Background: see my answer at Changing a variable from global to local - C, where I believe the first introduces an unnamed variable that is then optimized away by the compiler.)
Note: the question has been flagged as a possible duplicate of In what scope is a struct member identifier put? but I believe I am not asking a question about the scope of the members but about what the declarations actually create. However. answers to Difference between 'struct' and 'typedef struct' in C++? do explain my question.

A: As per the C standard, a structure declaration in the form like
struct student_s {
    char* name;
    int age;
    double height;
    struct student_s* next;
};

is the declaration of a type. Quoting C11, chapter §6.7.2.1

The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type, within a translation unit. The struct-declaration-list is a sequence of declarations for the members of the structure or union. [...]

C standard does not mandate creating a variable (either named or unnamed) for that type.
In your second snippet, you actually (try to) typedef to nothing. However, if you change your snippet to the form of
typedef struct {
         //.....members
} student_s ;

you'll be creating a type student_s (typedef to an unnamed structure type) which you can use later.
FWIW, we never talked about a variable being created here, anyways. It's all about types.

A: First declaration declares a type. After that declaration, the type struct student_s is known, and you can declare variables of that type or pointer to it :
struct student_s student1;
struct student_s *pStudent;

The second declaration is weird even if is compiles. The common usage would be :
typedef struct {
    char* name;
    int age;
    double height;
    struct student_s* next;
} studend_t;

which declares an alias student_t to an anonymous struct. It can then be used directly :
student_t student1;
student_t *pStudent;

BUT THE SECOND EXAMPLE DOES COMPILE (even with a warning) AND IS THE SAME AS FIRST ONE !
What it really does is to declare a void alias to struct student_s. The typedef is ignored and produces a warning : typedef requires a name, but as a side effect, the struct is declared, exactly as it was in first example.
So the true answer to the actual question is THERE ARE NO DIFFERENCES except for a warning.

A: Both are type definitions. The second one is one incomplete. It doesn't supply a name as the the argument of typedef. Much better is to use
typedef struct student_s {
    char* name;
    int age;
    double height;
    struct student_s* next;
} student;

Regarding the legality of
typedef struct student_s {
    char* name;
    int age;
    double height;
    struct student_s* next;
};

I've asked that as a separate question, Legality of `typedef struct foo {int bar};`

A: It's a type, and you can't have an anonymous instance of a struct. For comparison, this declares both the type struct_type and an instance struct_instance of that type:
struct struct_type {
    /* blah */
} struct_instance;

If you wanted to declare another instance in isolation (from the type decl) you'd use
struct struct_type another_instance;

The use of typedef - if done correctly, unlike your example - just allows you to give the type another name which doesn't require the struct keyword to declare an instance:
typedef struct_type MyStruct;
MyStruct yet_another_instance;

or equivalently
typedef struct struct_type {
    /* blah */
} MyStruct;

omitting the name (struct_type) gives you an anonymous struct type which can only referred to by its typedef'd name.

Note 1
Since your original struct contains a next pointer to its own type, that type must have a name at the point the member is declared. So, you cannot declare an anonymous struct with a self-typed pointer. If you give your anonymous struct type a name with typedef, that name doesn't exist until after the member declaration, so can't be used there.
typedef struct /*S*/ {
    struct S *next; /* T doesn't exist yet, so without S, you can't declare this */
} T;

Note 2
You can declare an anonymous instance of an anonymous union, as a member:
struct S {
    union {
        int i;
        unsigned u;
    };
};

struct S s;
s.i = -1;
printf("%x\n", s.u);

but that's a very special case. I took the remark about this out of the main argument, in case it was misleading.

A: struct A { ... }

creates struct 'A' visible in struct namespace (which has nothing common with C++ namespaces). So, to access struct you have to use struct keyword;
struct A a;

When defined with typedef struct
typedef struct A { ... } B;

becomes visible and bound to B, and you can easily create struct like common variable of type B
B a;

Please, correct me someone, if I am wrong.

A: The difference is that with the first example, you have to declare a new variable like this: struct student_s variable;, however with the second example, you may simply do student_s variable;.


text:
Q: wxpython self made widget and drag and drop it in a canvas I want to build an app for making UML diagrams. For visibility problems, I wish I could move classes using the mouse.
So here is my problem :
Do you know how can I drag and drop a widget in a canvas using wxPython ?
Found some things about ogl, but sound strange to me ...
Thx guys

A: Take a look at the FloatCanvas sample in the wxPython demo.  There is also a sample for the OGL package there.  Either, or both of those would likely be suitable for diagrams depending on your needs.


text:
Q: How to access a superclass method from a nested class? I hope this code explains the problem:
class Foo {
    void a() { / *stuff */ }
}

class Bar extends Foo {
    void a() { throw new Exception("This is not allowed for Bar"); }

    class Baz {
        void blah() {
            // how to access Foo.a from here?
        }
    }
}

I know that I may be doing something wrong, because inheritance perhaps shouldn't be used in such way. But it's the easiest way in my situation. And, beside that, I'm just curious. Is it possible?

A: You can call any method from the outer class with Outer.this.method().
But methods are resolved at runtime, so if you have overridden it in your subclass, only the subclass method (Bar.a()) can access the original (by calling super.a()).
As you probably discovered, you can't write Bar.this.super.a() -- but even if you could, it would still give you Bar.a(), not Foo.a().

A: Bar.super.a() appears to work.
Per JLS section 15.12

ClassName . super . NonWildTypeArguments_opt Identifier ( ArgumentList_opt )

is a valid MethodInvocation


text:
Q: C++ pointer mechanism - error 2440
Possible Duplicate:
Conversion of pointer-to-pointer between derived and base classes?
Converting Derived** to Base** and Derived* to Base*

I have an intf + class
class IList
{
public:
    virtual IList** GetChildList()=0;
    virtual void SetChildList(IList**)=0;
    ~IList();
};

class CList:public IList
{
    CList** m_lst;
public:
    IList** GetChildList()=0;
    virtual void SetChildList(IList**);
//...
};

IList** CList::GetChildList()
{
    return m_lst;
}

Why do I get error 2440 in MSVC in GetChildList saying "'return' : cannot convert from 'CList** **' to 'IList **"
Thanks for the help, in advance!

A: CList is derived from IList, so you can convert CList* to IList*.  However, you can't convert CList** to IList**.  You need a reinterpret_cast.


text:
Q: Raphael js drag inside javascript object I had a little problem today and thought I could try stack overflow. I'll be short and sweet (I removed lot of code to make this clear).
I recently discovered raphaeljs and I like it.
I make some circle draggable and it works fine like this:
Working script:
<script>
var paper = Raphael(100,100,500,500);
var circ = paper.circle(50,50,10)

var start = function(){ };
var move = function(dx,dy)
{
    this.attr({cx: this.ox + dx, cy: this.oy + dy});
};
var up = function(){};
circ.drag(move,start,up);
<script>

Ok fine, it works and all functions are called properly!
BUT!
I want my move ,start ,up functions to be inside an object and not in the main page
SO
here's my next code
<script src="myobject.js"></script>
<script>
    var paper = Raphael(100,100,500,500);
    var myobj = new myobject("12","12","6");
<script>

Content of myobject.js :
function myobject(vx,vy,vr)
{
    var x,y,r;
    x=vx;y=vy;r=vr
    paper.circle(x,y,r);
    var start = function(){};
    var move = function(dx,dy){};
    var up = function(){};

    this.drag(move,start,up);  // error here this line crash

}

I cannot find how to use the drag function inside my object to make it draggable.
Well, that's it. I hope I've been clear and pardon me if there's anything wrong with the way I made this post but it is my first one!
Thanks to everyone that will try to help me!
Wilson

A: Inside myobject, this variable points to this object, and not to Raphael circle. As myobject does not have drag function, the code yields an error. To make it work, you must refer to Raphael object that has to be dragged, i.e.
function myobject(vx,vy,vr) {
    ...
    this.circle = paper.circle(x,y,r);
    ...
    this.circle.drag(move,start,up);
    ...
}

A: Fine, @Hubert OG was right but I also had to change the way I declared my function from
var start()=function
to
this.start() = function
WARNING: Fill your circle/forms because if you don't you have to click the fine border to move it around.


text:
Q: How do I loop through a DataGridView where RowCount / Rows.Count changes I have a VB.Net Form with a DataGridView where I wish to change between a Detailed View and a General View.
The DataGridView shows the Distance and Estimated Time between places - called the Route Leg Data and is termed the General View
I have implemented a CheckBox to select between the general and detailed view. When the CheckBox is Checked, I am trying to loop through all of the Route Leg entries and insert the Route Steps which is the Detailed information about the Leg entries.
I have tried various loop options: For..Next, For Each...Next, While...End While, and only the first row (Route Leg) gets processed, even if I have 5 more Route Leg entries.
Important: Keep in mind that when the Detail View is selected, the DataGridView row count increments for every new Route Step entry that gets inserted.
I tried to use both dgv.RowCount and dgv.Rows.Count but I keep getting the same result.
I have added some code to show what I am trying to achieve. Any help or guidance will be much appreciated.
'Show / Hide Route Step Data
Private Sub chkShowRouteStep_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowRouteStep.CheckedChanged
    Try
        If chkShowRouteStep.Checked Then
            'Show Route Steps
            For i As Integer = 0 To dgvQuote.RowCount - 1
                txtRowCount.Text = i
                If dgvQuote.Rows(i).Cells(0).Value.ToString <> "" Then
                    For j As Integer = 1 To 5
                        i += 1
                        dgvQuote.Rows.Insert(i, "Step")
                        'dgvQuote.Rows.Insert(j + i, "Step")

                    Next
                End If
            Next

        Else
            'Hide Route Steps - WORKS GREAT
            For i As Integer = dgvQuote.RowCount - 1 To 0 Step -1
                If dgvQuote.Rows(i).Cells(0).Value.ToString = "Step" Then
                    dgvQuote.Rows.RemoveAt(i)
                End If
            Next
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

A: My impatience, as well as a refocus, provided me with the answer.
My focus was always on the DataGridView and the feedback from it with regards to the number of rows contained in the control.
However, the execution of a loop took a snapshot of the number of rows at the start of the loop execution and did NOT update the number of rows every time rows were added to the DataGridView.
I took a different approach where I compared my current loop number (i += 1) with the current number of rows in the DataGridView (dgv.Rows.Count - 1) thereby forcing a recheck on the number of rows. This means that any new rows added to the DataGridView will now be counted in.
I added a trigger (True/False) to be set to true if the last row in the DataGridView was reach and the While...End While loop was exited.
'Show / Hide Route Step Data
Private Sub chkShowRouteStep_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowRouteStep.CheckedChanged
    Try
        Dim lastRow As Boolean = False 'This will get set when we have reached the last row in the DGV
        Dim i As Integer = 0

        If chkShowRouteStep.Checked Then
            'Show Route Steps
            While lastRow <> True

                txtRowCount.Text = i

                If dgvQuote.Rows(i).Cells(0).Value.ToString <> "" Then

                    For j As Integer = 1 To 2
                        'i += 1
                        dgvQuote.Rows.Insert(i + j, "", "Step")

                    Next

                End If
                'Check to see if we have reached the last row, set lastRow to TRUE if it is the last row

                If i = dgvQuote.Rows.Count - 1 Then
                    lastRow = True
                End If

                i += 1

            End While

        Else
            'Hide Route Steps - WORKS GREAT
            For x As Integer = dgvQuote.RowCount - 1 To 0 Step -1
                If dgvQuote.Rows(x).Cells(1).Value.ToString = "Step" Then
                    dgvQuote.Rows.RemoveAt(x)
                End If
            Next
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

The result is as follows and error free:
Before

After

A: Since the comment in the code says you want to hide route steps, why not do just that? Instead of removing and inserting rows, populate the grid with everything and then use the checkbox to set the rows .Visible property?


text:
Q: MiniFilter Driver - The right implementation and the Microsoft signature I am working on malware analysis. I use a mini-filter driver to intercept file system access. Then I apply algorithms to detect malicious activity.
My questions:
It know that the driver will need a signature by Microsoft for a public release.
https://learn.microsoft.com/fr-fr/windows-hardware/drivers/dashboard/attestation-signing-a-kernel-driver-for-public-release
Is it authorized to implement the algorithms as AI in kernel space, or I must implement them in userspace? What is recommended concerning Microsoft, the right architecture, and security?

A: If you can implement a Windows kernel driver, you can do whatever you want. Not only algorithms, we ever ported OpenSSL, SQLite and other open source projects (of course in C and C++) to our Windows kernel drivers. It's not something mission impossible. Just you need to know how and limitations with work-around.
The idea of driver signing from MS is to avoid rogue driver developers to run malware in kernel. This was the biggest issue for 32 bit Windows for very long time, since in kernel you are not only able to implement something but you can also abuse anything, including kernel variable, file system data, registry and you can even hook to any code you want (if system protection is not running). However, such certificate is also not perfect. Years ago hackers stole certificates from companies (RealTek, if I recall it correctly) and signed their malware drivers.


text:
Q: Selenium radiobutton selection I have an HTML code as follows:

<input id="id_gender2" type="radio" value="2" name="id_gender">

Mrs.

The radio button is getting selected after mouse hover.
I have tried with all possible attributes for selection but I am getting element not found exception.Please let me know how to write java script in webdriver.

A: Try following code and let me know the result:
Actions action = new Actions(driver);
WebElement hover = driver.findElement(By.xpath("//*[@class='radio hover']"));
action.moveToElement(hover).moveToElement(driver.findElement(By.xpath("//input[@id='id_gender2']"))).click().build().perform();

UPDATE
Actually there is no need in mouse hover. Target radio seem to be initially non-clickable, so you just need extra time to wait for page complete rendering:
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#id_gender2")));
driver.findElement(By.cssSelector("input#id_gender2")).click();

A: Try javascript executor as follow:
WebElement element = driver.findElement(By.id("id_gender2"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);

A: Your element is probably not loaded properly while getting error. You'd better use explicit wait in your script. Wait until your specific element loaded to be visible/clickable. I think, this may help you.
Code snippet:
    By yourElementToSelect = By.id("id_gender2");
    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(yourElementToSelect));
    driver.findElement(yourElementToSelect).click();


text:
Q: Docker - check private registry image version What CLI commands do I need to use in order to check if the image in my private docker registry is a newer version than the one currently running on my server?
E.g. I have a container that I ran using docker run -d my.domain.com:5000/project1
and I would like to know if it is out-of-date.

A: Even when there is no command, you can use the API to check for tags on the registry and compare against what you are running.
$ curl --silent my.domain.com:5000/v1/repositories//project1/tags | grep latest
{"latest": "116f283e4f19716a07bbf48a562588d58ec107fe6e9af979a5b1ceac299c4370"}

$ docker images --no-trunc my.domain.com:5000/project1
REPOSITORY           TAG                 IMAGE ID                                                           CREATED             VIRTUAL SIZE
my.domain.com:5000   latest              64d935ffade6ed1cca3de1b484549d4d278a5ca62b31165e36e72c3e6ab8a30f   4 days ago          583.2 MB

By comparing the ids, you can know that you are not running the latest version.

A: Not sure about the version but if you mean the tag of image, it can be easily checked through the registry v2 api . Note that in context of docker images tag has nothing to do with the version of software.
Use curl command in CLI
 curl <docker_host_ip>:<docker_host_port>/v2/<repository_name>/tags/list

To get a list of repositories pushed on the private registry, use
curl <docker_host_ip>:<docker_host_port>/v2/_catalog

A: Brownie points to @mbarthelemy and @amuino who put me on track. From that I was able to come up with the following bash script that others may find useful. It just checks if the tag on the registry is different from the currently executing container.
#!/bin/bash
# ensure running bash
if ! [ -n "$BASH_VERSION" ];then
    echo "this is not bash, calling self with bash....";
    SCRIPT=$(readlink -f "$0")
    /bin/bash $SCRIPT
    exit;
fi

REGISTRY="my.registry.com:5000"
REPOSITORY="awesome-project-of-awesomeness"

LATEST="`wget -qO- http://$REGISTRY/v1/repositories/$REPOSITORY/tags`"
LATEST=`echo $LATEST | sed "s/{//g" | sed "s/}//g" | sed "s/\"//g" | cut -d ' ' -f2`

RUNNING=`docker inspect "$REGISTRY/$REPOSITORY" | grep Id | sed "s/\"//g" | sed "s/,//g" |  tr -s ' ' | cut -d ' ' -f3`

if [ "$RUNNING" == "$LATEST" ];then
    echo "same, do nothing"
else
    echo "update!"
    echo "$RUNNING != $LATEST"
fi

A: AFAIK, this is not possible right now.
The only thing I see would be to pull the registry to check if there is a new version of your image (would then have a different ID than your locally stored image):
docker pull your/image:tag

But yes, that would mean fetching the new images (if any).
If you have a look at the registry API documentation, you'll see that if you don't mind scripting a bit, you could get this information without actually downloading the image, by fetching the image tags and check if the returned ID for the tag matches the ID of the local image you have with the same tag.
That being said, having something to "check for updates" integrated into the docker CLI would be a nice addition.

A: I don't know if this works as advertised. Just a quick hack I just put together.
But this will at least give you a little push on how this might be done.
#!/bin/bash

container=$1
imageid=$(docker inspect --format '{{.Config.Image}}' ${container})

echo "Running version from: $(docker inspect --format '{{.Created}}' ${container})"
echo "Image version from: $(docker inspect --format '{{.Created}}' ${imageid})"

Example output:
[root@server ~]# sh version_check.sh 9e500019b9d4
Running version from: 2014-05-30T08:24:08.761178656Z
Image version from: 2014-05-01T16:48:24.163628504Z

A: You can use a bash script running in a cron scheduled task:
#!/bin/bash

docker_instance='YOUR_RUNNING_INSTANCE'

instance_id=$(docker ps -qa --filter name=$docker_instance)
image_name_tag=$(docker inspect $instance_id | jq -r [] |.Config.Image')

if [ "-${image_name_tag}-" != "--" ]; then

    status=$(docker pull $image_name_tag | grep "Downloaded newer image")
    if [ "-${status}-" != "--" ]; then

        echo ">>> There is one update for this image ... "

        # stop the docker instance
        docker stop $docker_instance

        # remove the docker instance
        docker rm $docker_instance

        # restart the docker using the last command, using the new image from the remote repository
        run-my-docker-instance.sh

    fi
fi

A: An older question, but this sounds like a problem that Watchtower can solve for you.  It is another dockerized application that runs adjacent to your other containers and periodically check to see if their base images are updated.  When they are, it downloads the new image and restarts them.
If given the correct credentials, it can work with a local registry.

A: FWIW I solved it with the bash script below for a while until I decided that Watchtower was the easier way to go (by the way: note the maintainer switched from v2tec to containrrr a while ago, the v2tec one isn't getting updates anymore). Watchtower gave me an easy way to schedule things without having to rely on cron (which gets blown away in a reinstall - granted, you could have something like Ansible recreate that for you, but this was easier for me). It also adds easy notifications (I like using Telegram) for updates, which I appreciate knowing about so that if something goes sideways at  least I know there was an update that could be to blame.
I'm not saying this is will never cause issues, but I've been running Watchtower on various Docker hosts (3 of them, 2 in my homelab, one on Linode) for about a year now and I have yet to have an issue with it. I prefer this to having to manually update my containers on a regular basis. For me the risk of something getting screwed up is lower than the risks of running outdated containers, so this is what I chose for myself. YMMV.
I honestly don't get the apparent hate for automated update solutions like Watchtower - I see so many comments saying that you shouldn't use automated updates because they'll cause problems... I don't know what folks have been burned by - would love to hear more about where this caused problems for you! I mean that, I genuinely don't understand and would love to learn more. I keep having some vague unease about doing automated updates, but given my experience so far I can honestly only recommend it. I used to use Diun for getting notified about updates and then would go and manually update my containers. That got real old after it became a daily chore! (With ~45 different containers running, you can pretty much guarantee that at least one of them will have an update every single day.)
If I really need to keep a container from updating, I can always stick a com.centurylinklabs.watchtower.enable=false label on the container. Or you can whitelist only the containers you want automatically updated, or... There are loads of possibilities with Watchtower.
However, for reference if you still want to use it, see my script below. I used docker-compose pull to get the latest version - it does a check first to see if there is a new image, so doesn't waste a whole lot of bandwidth if there is nothing to update. It's effectively like doing the curl you guys used. Also I prefer the docker inspect -f commands to check the versions to the solutions that pipe through grep, sed, and co. since that is less likely to get broken by changes to docker inspect output format.
#!/usr/bin/env bash
cd /directory/with/docker-compose.yml/
image_name=your-awesome-image
docker-compose pull
container_version=$(docker inspect -f '{{ index .Config.Labels "org.opencontainers.image.version" }}' "$image_name")
latest_image_version=$(docker inspect -f '{{ index .Config.Labels "org.opencontainers.image.version" }}' "$image_name")
if [[ "$container_version" != "$latest_image_version" ]]; then
  echo "Upgrading ${image_name} from ${container_version} to ${latest_image_version}"
  docker-compose down
  docker-compose up -d
fi


text:
Q: HTML text input rounded when numbers entered i'm developing a PHP application and i have one problem when i use HTML text inputs, and this is the first time where i deal with this case.
When i try to insert a float value as 34.4 in HTML text input to put it in MySQL DB, but when i go to my DB i find the value 35.
I don't know why this value is rounded, i do not use any function like ceil.
If someone can help me i'll be so thankful.

A: If you are working with decimal, the  default is DECIMAL(10, 0), you should specify the precision and scale, for example:
DECIMAL(10, 4)

The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments in MySQL 5.7 are as follows:
M is the maximum number of digits (the precision). It has a range of 1 to 65. (Older versions of MySQL permitted a range of 1 to 254.)
D is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger than M.
Reference:
http://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html
Also, check this answer: How do I interpret precision and scale of a number in a database?

A: Set column type to float in Mysql

A: The problem was in DB column type, it was DECIMAL(10,0) for this reason the MySQL rounded the float number to an INT number.


text:
Q: Inserting a BeautifulSoup object into another Hey guys so what im tryng to do is insert the content of a html page into another page using beautiful soup
with open("testpage.html") as fp:
    mainSoup = BeautifulSoup(fp)

with open("navbarContent.html") as fp:
    extraSoup = BeautifulSoup(fp)

for elm in mainSoup.find_all('nav', {"id":"sidebar"}):
    elm.string= str(extraSoup)

So i want the html content of the navbarContent.html to be inserted in the testpage.html in  the  tag.
Any ideas?

A: You can add the html code in triple quotes like this:
htmlCode = ´´´
<html>
</html>
´´´

then add the content of the navbarContent to it and then you can write the whole thing into the html file again using write().
But first you have to open() and after you have to close() the file.
I hope you know how that works.


text:
Q: flip between an img and text I'm trying to add animation so when I hover over my pictures they fade out and another div with text fades in. Just like on this page: http://jack-hughes.com/
But, I have my pictures in a bootstrap container with class of "col-md-4" and every time one of the photos fades out, the others move into its spot.
How can I make something just like the example website?
This is what I have so far, but it's not even close.
$(".box-1").on('mouseover', function() {
    $(this).fadeToggle(300).addClass('back');
});

A: Have you tried using hover? It will handle both your mouse in and mouse out events.
You can wrap each image with its text in a surrounding div, and use your hover function on this div. Also, if you use the same classes for each image/text combo, your jQuery is very simple.
HTML

  About

       text

       text

       text

jQuery
$('.about-box-container').hover(
function() {
    $(this).find('.front').fadeOut(300, function() {
    $(this).siblings('.back').fadeIn(300);
    });
},
function() {
    $(this).find('.back').fadeOut(300, function() {
    $(this).siblings('.front').fadeIn(300);
    });
}

)
Demo here

A: jQuery's fade effects set element's display property to 'none', and its place is freed to use for other elements. Try to use opacity and :hover without any JS (actually, this is what is done at http://jack-hughes.com):
CSS:
.test {
  position: relative;
}

.test img {
  width: 100px;
  height: 100px;
  border: solid 1px lightgray;
  padding: 10px;
}

.test .test2 {
  width: 102px;
  height: 102px;
  padding: 10px;
  display: flex;
  text-align: center;
  align-items: center;
  justify-content: center;
  background: lightgray;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: all 0.3s ease-out;
}
.test .test2:hover {
  opacity: 1;
}

here is updated plunker based on @Tricky12's HTML: https://plnkr.co/edit/pGYckIcRDPZKS7Ma4vSQ?p=preview


text:
Q: Как производить математические вычисления над определенной колонкой DataFrame? Как можно вычислить пример со следующим видом "с_с = (с – с_min)/с_max" со всеми элементами колонки с, и вывести в другой dataframe, где будут хранится данные из колонки с из прежнего df и вычисленные значения c_c?
Csv:
a,b,c,d
1,2,3,4
5,6,7,8
9,8,7,6
5,4,3,2
1,8,4,6

Скрипт:
import pandas as pd
import numpy as nm

pd = pd.read_csv("test1.csv", delimiter=',')
pd.head(len(pd.index))
c_min = pd['c'].min()
c_max = pd['c'].max()
print(c_min, c_max)

A: pd = pd.read_csv("test1.csv", delimiter=',')

Не делайте так - не называйте разные сущности одним именем. У вас тут переменная pd перекрыла алиас pd пакета pandas и вы дальше по коду не сможете этим алиасом пользоваться. Называйте датафрейм стандартно - df.
А так то всё просто. Скопировать колонку в новый датафрейм можно с помощью copy:
df1 = df[['c']].copy()

Обратите внимание, что скобок две пары. С одной парой если сделать, то это будет Series, а не Dataframe.
Дальше просто записываете формулу как есть, но с использованием датафрейма:
df1['c_c'] = (df1['c'] - df1['c'].min())/df1['c'].max()

Ну или можете использовать ваши заранее посчитанные переменные для min и max, разницы нет.


text:
Q: Messaging probabilities I am part of a large family - we have twenty-four people who send texts back and forth, in various configurations. What would be the total number of possible message threads? All the different one-on-ones - the three persons groups, four, etc., up to all twenty-four of us on one thread.

A: $\require{cancel}$
Alternatively, suppose that we have a thread that only $2$ members participate. Because order doesn't matter, we have $\dbinom{24}{2}$ such threads. The number of threads that any $3$ members participate is $\dbinom{24}{3}$. Following the same procedure, we have that the total amount of threads is:
$$\sum_{n=2}^{24} \dbinom{24}{n}=16,777,191,$$
which agrees to ToolPurger's answer.

We can work the same way, as we did before. Suppose that we fix a person (yourself), which we want to participate in every thread. Let's begin with the thread with $2$ participants (the one is yourself). Thus, we have to pick the other person from the rest $23$ people. We can do that with $\dbinom{23}{1} = 23$ ways. The number of threads with $2$ people (again, the one is yourself) is $\dbinom{23}{1}$.
Moving to the thread with $3$ participants (the one is yourself) means that we have to pick the $2$ participants from the rest $23$ people. We can do so with $\dbinom{23}{2}$ different ways. That means the number of threads consisting of $3$  people (again, the one is yourself) is $\dbinom{23}{2}$.
Following the same procedure, we have eventually that that number of threads you are included is:
$$\sum_{n=1}^{23}\dbinom{23}{n}=8,388,607.$$
 You can do the math .

A: If we encode:
$(0110\cdots)$ as 1st member (alphabetical ordering say) not included, 2nd and 3rd included, 4th not, so forth...
Then there are $2^{24}-25$ ways.
$2^{24}$ is the number of such binary strings, and 24 of those are messages to oneself, which we discount, as well as empty threads (messages to no one)

It is worth noting that the sums of  nCr and 2n are related, in fact:
  $$\sum^n_{i=0}\ ^nC_i=2^n$$
  So what this answer has is:
  $\sum^{24}_{n=2}\ ^{24}C_n=\sum^{24}_{n=0}\ ^{24}C_n -\ ^{24}C_0 - \ ^{24}C_1=2^{24}−1−24=2^{24}−25$ - as I claimed.


text:
Q: Unable to indicate server_name with Apache HttpClient 5.1 and Java 11 I'm trying to make API call to a server that uses 2-way SSL authentication. I'm using Apache HttpClient 5.1 along with Java 11. I'm loading TrustMaterial into SSL context and later creating a CloseableHttpClient to make API call, in this case a GET call. But I keep getting Connection Reset error. So, I enabled debugging on handshake System.setProperty("javax.net.debug","ssl,handshake"). I noticed that ClientHello was missing  server_name in its extensions. I'm thinking this might be causing the issue with connection.
Code
public class ClientCustomSSL {
    public final static void main(final String[] args) throws Exception {
        System.setProperty("javax.net.debug","ssl,handshake");

        File file = new File("C:\\Mycerts.jks");
        final SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(file,"passcode".toCharArray()).build();
        final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
                .setSslContext(sslcontext).build();
        final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
                .setSSLSocketFactory(sslSocketFactory)
                .build();
        try (CloseableHttpClient httpclient = HttpClients.custom()
             .setConnectionManager(cm).build()) {

            final HttpGet httpget = new HttpGet("https://mysite-s123/");
            final HttpClientContext clientContext = HttpClientContext.create();
            try (CloseableHttpResponse response = httpclient.execute(httpget, clientContext)) {
                System.out.println(response.getCode() + " " + response.getReasonPhrase());
            }
        }
    }

Error
javax.net.ss1|WARNING|01|main|2022-07-08 14:39:57.291 EDT|ServerNameExtension.java: 261 | Unable to indicate server name
javax.net.ss1|DEBUG|01|main|2022-07-08 14:39:57.291 EDT|SSLExtensions.java: 260|Ignore, context unavailable extension: server name
javax.net.ss1 WARNING| 01|main|2022-07-08 14:39:57.293 EDT|SignatureScheme.java:295|Signature algorithm, ed25519, is not supported by the underlying providers
javax.net.ss1|WARNING|01|main|2022-07-08 14:39:57.293 EDT|SignatureScheme.java: 295|Signature algorithm, ed448, is not supported by the underlying providers
javax_net.ss1|INFO|01|main|2022-07-08 14:39:57.297 EDT|AlpnExtension.java:178|No available application protocols
javax.net.551| DEBUG (02 |main|2022-25-08 14:39:57.297 EDT|SSLExtensions. java: 260| Ignore, context unavailable extension: application layer protocol _negotiation
javax.net.ss1|DEBUG|01|main|2022-07-08 14:39:57.297 EDT|SSLExtensions.java:260|Ignore,context unavailable extension: renegotiation_ info
javax.net-ss1|DEBUG|01|main|2022-07-08 14:39:57.299 EDT|ClientHello.java: 642 Produced ClientHello handshake message
"ClientHello":{
"client version":"TLSv1.2",
"random":"E1 A8 CF DD 06 87 B9 FD 6C EB FE C6 BC E3 C4 7F EE DC 22 B3 B7 AC 40 0A DO 53 7F 81 51 5D 78 D9",
"session id":"E1 A8 CF DD 06 87 B9 FD 6C EB FE C6 BC E3 C4 7F EE DC 22 B3 B7 AC 40 0A DO 78 D9",
"cipher suites":"[TLS_AES_256_GCM_SHA384(0x1302),TLS_ECOHE_ECDSA_WITH_AES_256_GCM_SHA384(exCe2C), TLS_ECDHE_ECOSA WITH AES_128 _ GCM SHA256(exC82B), TLS_ECDHE_ECOSA_WITH_CHACHA2®_POL Y1305 _SHA256 (exCCA9)...]",
"compression methods": "00",
"extensions": [
    "status request (5)":{
    "certificate status type": ocsp
    "OCSP status request": {
        "responder id": ‹empty>
        "request extensions":{
        ‹empty>
        }
    }
},
"supported_groups (10)": {
    "versions": [x25519, secp256r1, secp384r1, secp521r1, x448, ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192]
},
"ec point formats (11)": {
    formats": [uncompressed]
},
"signature algorithms (13)": {
        "signature schemes": [ecdsa_secp256r1 sha256, ecdsa_ secp384r1_ sha384, ecdsa_secp521r1_ sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa pss_ pss_sha256, dsa_sha1]
},
    "signature algorithms_cert (50)": {
        "signature schemes" : [ecdsa secp256r1 sha256, ecdsa secp384r1_ sha384, ecdsa_secp521r1_ sha512, rsa_pss_rsae_sha256, rsa_pss_ rsae_sha384, rsa pss_rsae_sha512, rsa pss_pss_sha256,dsa_sha1]
        },
        "status request_v2 (17)": {
        "cert status request":{
        "certificate status type": ocsp multi
}
]
}
javax.net.ss1|WARNING|01|main|2022-07-07 09:26:16.233 EDT| SSLSocketImp1.java: 1648| handling exception ("throwable" : {
    java.net.SocketException: Connection reset
        at java.base/java.net.SocketInputStream.read(SocketInputstream.java:186)
        at java.base/java.net.SocketInputstream.read (SocketInputstream.java: 140)
        at java.base/sun.security.ss1.SSLSocketInputRecord.read(SSLSocketInputRecord.java:478)
        at java.base/sun.security.ssl.SSLSocketInputRecord.readHeader(SSLSocketInputRecord.java:472)
        at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:160)
        at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:111)
        at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1501)
        at java.base/sun.security.ssl.SSLSocketImp1.readHandshakeRecord(SSLSocketImpl.java:1411)
        at java.base/sun.security.ssl.SSLSocketImp1.startHandshake(SSLSocketImpl.java:451)
        at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:422)
        at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:436)
        at org.apache.http.conn.ss1.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384)
        at org.apache.http.impl.conn.DefaultHttpclientConnectionoperator.connect(DefaultHttpclientconnectionoperator.java:142)
        at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpclientconnectionManager.java:376)
        at org.apache.http.impl.execchain.MainclientExec.establishRoute(MainclientExec.java:393)
        at org.apache.http.impl.execchain.MainclientExec.execute(MainclientExec.java:236)
        at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
        at org.apache.http.imp1.execchain.RetryExec-execute(RetryExec-java:89)
        at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
        at org.apache.http.imp1.client.InternalHttpClient.doExecute(InternalHttpclient.java:185)
        at org.apache.http.impl.client.closeableHttpclient.execute(CloseableHttpclient.java:83)
        at org.apache.http.impl. client.closeableHttpclient. execute(closeableHttpclient. java:108)
        at ClientCustomSSL.main(ClientCustomSSL.java:62)}

Based on some of the StackOverflow answers, SNI extension does not require any custom configuration and should work transparently. But I don't understand why this is not working though. Can anyone please let know if I'm missing something here and point me in the right direction.
Thank you in advance!!!


text:
Q: Bootstrap nav-collapse hide in single page app I am currently using 2.x Bootstrap version for my single-page application.
On the desktop, it works fine.
However on my ipad and mobile phones, it shows a nav button which is good. However, when I click an item in the dropdown item shown, it does not close automatically.
Since, it's a single page app, I find it annoying to click it again to hide to look at the contents.
I tried collapse('hide') when li is clicked on nav-collapse elements but it hides other li elements in the dropdown menus.
$('.nav-collapse > li').click(function(e)
$(this).collapse('hide')
What's the best way to hide when a link is clicked?
Thanks.

A: I hit the same issue as well, and solved it by adding data attributes (modified to collapse only the open .nav-collapse) to the nav item links themselves.
Note the data-target on the links is ".nav-collapse.in" which only selects the expanded nav, thereby acting as a close only.
For example:

            Link

This is tested in Bootstrap 2.2.1 on Mac OSX Chrome only. Although it is repetitive and not DRY, it does keep the collapsing declaration to the HTML.

A: In Bootrap 3.3.4 you can add the following to the anchor tags to auto-close the nav.
data-toggle="collapse" data-target="#navbar"

A: There is a bug in Twitter Bootstrap's Dropdown plugin (see Issue #4497) which was introduced in 2.1.0 and inadvertently blocks the click events on dropdown menu items.  It should be fixed in 2.1.1.
If you are using a CDN or simply don't want to edit/recompile the bootstrap-dropdown.js, you can just add the following workaround to your page, loading it after bootstrap:
$('body')
  .off('click.dropdown touchstart.dropdown.data-api', '.dropdown')
  .on('click.dropdown touchstart.dropdown.data-api'
    , '.dropdown form'
    , function (e) { e.stopPropagation() })

If you are hosting your own code, and are comfortable building the bootstrap.min.js, then you can make the following edit to bootstrap-dropdown.js on line 145:
'.dropdown'

should be changed to
'.dropdown form'


text:
Q: Lync Database - Mobile vs PC users G'day all,
I'm looking to find out how Microsoft distinguishes between mobile and non-mobile subscribers/users in Lync's database (not SDK or API!), would anyone be able to suggest a direction to look at?
Thanks!

A: Check out the table 'rtcdyn' in the Pool Configuration Store.  Here is blog post that describes it in more detail.  If I find anything else I'll append it to my answer.
http://blog.insidelync.com/2011/04/the-lync-server-databases/


text:
Q: how to solve the problem with indexing and sorting I have a problem.There is a text file, you need to find 5 frequently occurring words. The program receives the file name.  Output: top 5 words in alphabetical order. The problem is that indexes are not updated and sorted crookedly. Help me please.  thanks in advance.
This is code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int MAX = 100000;
string words[MAX];
int instances[MAX];
int cast = 0 ;

void insert (string input)
{
    for (int i = 0 ; i < cast; i++ )
    {
        if (input == words[i] )
        {
            instances[i]++;
            return ;
        }
    }
    if (cast < MAX)
    {
        words [cast] = input ;
        instances[cast] = 1;
        cast ++;
    }
    else
    {
        return ;
    }
 return ;
}
int FindTop (string & word)
{
    int TopCast = instances[0];
    int TopIndex = 0;
    for (int i = 1; i<cast; i++ )
    {
        if(instances[i] > TopCast )
        {
            TopCast = instances[i];
            TopIndex = i;
        }
    }
    instances[TopIndex] = 0;
    word = words[TopIndex ];
    return TopCast;
}
int main ()
{
    string word;
    string file;
    cin>>file;
    ifstream data (file);
    while(data >> word)
    {
        insert(word);
    }

    for (int i = 0; i < 5 ; i++)
    {
        cout<<FindTop(word)<<" "<<word<<endl;
    }
}

A: Update your FindTop() function as follows
        int FindTop (string & word)
        {
            int TopCast = instances[0];
            int TopIndex = 0;
            for (int i = 1; i<cast; i++ )
            {
                if(instances[i] > TopCast )
                {
                    TopCast = instances[i];
                    TopIndex = i;
                }
                else if(TopCast == instances[i])
                {
                     //for making sure you get the smallest word (asc order) first if multiple words
                     // have same frequency
                    if( words[TopIndex].compare(words[i]) > 0 )
                    {
                      TopCast = instances[i];
                      TopIndex = i;
                    }
                }
            }
            instances[TopIndex] = 0;
            word = words[TopIndex ];
            return TopCast;
        }

A: The insert function works as intended. However, if the demand really is the top 5 words, according to occurrence, sorted in alphabetical order, you might want to save the words in a vector and sort it alphabetically using a self-made string compare function.
If somehow you are not getting the top 5 words, check if your text file is in the correct directory and if you write the correct file name to the console.
Please provide a short text file and the console output.

A: I would like to provide an additional solution.
This is not based on your initial draft, but with a more modern-C++ solution, using STL containers and algorithms.
I would strongly recommend to NOT use C-Style arrays at all. Please use STL containers.
Then, back to your problem. We will split the problem basically into 3 tasks.

*

*Read file

*Count words

*Sort

Reading the file into words is ultra simple. Just use the extractor operator and get the words as std:string out of the text. The words may contain non alpha characters. This we will eliminate with a std::regex_replace.
Counting is also very simple. We use the std::maps index operator[]. This will create a word in the std::map if it is not yet existing```` and increment the counter. If the word is already existing, then there will be simply an incrementation of the counter for this word.
Because the std::map is per default sorted by the key vale (the word), we copy the word counts to a std::vector, then sort it and show the result.
Please see
#include <iostream>
#include <sstream>
#include <iterator>
#include <string>
#include <array>
#include <algorithm>
#include <regex>
#include <map>
#include <iomanip>
#include <utility>

std::istringstream sourceFile{R"(Lorem ipsum dolor sit amet,
consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt
ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum
dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum
dolor sit amet.)"
};

int main() {

    std::string word{};
    std::map<std::string, size_t> counter;

    // Read complete file into words
    while(sourceFile >> word) {
        // Replace special characters
        word = std::regex_replace(word,std::regex(R"([\.\,\;\:\!\?])"),"");
        // Count the occurence of each word
        counter[word]++;
    }

    // We need to sort and will copy the word-counts into a vector
    std::vector<std::pair<size_t, std::string>> countedWords;
    for( auto const& [key, val] : counter ) {
        countedWords.emplace_back(std::pair<size_t, std::string>(val,key));
    }

    // Do the sort, with a lambda, for the specific request
    std::sort(countedWords.begin(), countedWords.end(),
         [](std::pair<size_t, std::string> &l, std::pair<size_t, std::string> &r){
        return ((r.first == l.first) ? (l.second < r.second) : (r.first < l.first));});

    // Show result on screen
    int outputCounter{ 5 };
    for (const auto& [word, count] : countedWords) {
        std::cout << std::setw(20) << word << " --> " << count << "\n";
        if (0 >= --outputCounter) break;
    }

    // Output all words
    std::cout << "\n\nAll different word in alphabetical order:\n\n";

    // Write all words on screen.
    for (const auto& [word, count] : counter)   std::cout << word << "\n";

    return 0;
}

EDIT:
I added at the end the output for all words in alphabetical order.
Additionally: Please note: std::istringstream is a std::istream. There is no difference to a file stream. So "sourceFile" can be an open std::ifstream or std::cin or any other std::istream. There is no difference. So open a file using std::ifstream sourceFile("c:\\temp\nameOfFile")- That's it.

A: Since your example is more like C-ish I would like to show you my take on the problem.
I highly encourage you to take a look at the various standard containers (especially vector and unordered_map) and on the algorithm library. With just these you will end up with a much cleaner and less error-prone code.
#include <algorithm> // sort
#include <cstdlib> // EXIT_FAILURE, EXIT_SUCCESS
#include <fstream> // ifstream
#include <iostream> // cin, cout
#include <string> // string
#include <unordered_map> // unordered_map
#include <utility> // pair
#include <vector> // vector

using namespace std;

int main()
{
    cout << "Filename: ";
    string filename;
    cin >> filename;

    ifstream file{filename};
    // Check that the file was opened successfully.
    if (!file) {
        cout << "File cannot be opened for reading: " << filename << '\n';
        return EXIT_FAILURE;
    }

    // Count the words in the file.
    // unordered_map is an associative container that stores key-value pairs
    // with unique keys. We use this to store word-occurrence pairs.
    unordered_map<string, int> words;
    for (string word; file >> word;)
        // By default if 'word' is not contained in 'words' it will be placed
        // there with the default value of 0 (default value of ints). This allow
        // us the eliminate the special case when 'word' is not in 'words' yet.
        ++words[word];

    // Sort the word-occurrence pairs in descending order by occurrence.
    // vector is a dynamic array that we use to sort the word-occurrence pairs
    // because unordered_map cannot be sorted.
    vector<std::pair<string, int>> sorted_words{words.begin(), words.end()};
    // The sort algorithm takes the begining and the end of the interval that we
    // want to sort. As a third argument we pass it a lamda function that tells
    // the algorithm how to order our word-occurrence pairs.
    sort(sorted_words.begin(), sorted_words.end(), [](const auto& a, const auto& b) {
        return a.second > b.second;
    });
    // Sort the first 5 (most frequent) words in alphabetic order.
    sort(sorted_words.begin(), sorted_words.begin() + 5, [](const auto& a, const auto& b) {
        return a.first < b.first;
    });

    for (auto i = 0; i < 5 && i < sorted_words.size(); ++i)
        cout << sorted_words[i].first << '\n';

    return EXIT_SUCCESS;
}


text:
Q: Is ftp connection to secure server in c++ program secure with libcurl? Is ftp connection to secure server in c++ program secure with libcurl?I need to make a client program that will receive and write data to the host.

A: FTP is insecure, it transfers data, user names & passwords in the clear. Don't use it. Use either https, scp or sftp.


text:
Q: Ace editor with ReactJS - undo functionality I am using Ace editor with React (https://github.com/securingsincity/react-ace, version: 8.0.0)
I have managed to add an undo button, but undoing on a new editor instance is erasing the whole document.
My code so far :
class AceEditor extends React.Component {

  constructor(props, context) {
    super(props, context);

    this.editor = React.createRef();
  }

  componentDidMount() {
    this.setState({
      code: "Test text"
    })
  }

  render() {
    const {code} = this.state;

    return (
      <div>
        <Button onClick={() => {
          this.editor.current.editor.undo()
        }}/>

        <AceEditor
          ref={this.editor}
          value={code}
          // more props
          onLoad={editor => {
            const session = editor.getSession();
            const undoManager = session.getUndoManager();
            undoManager.reset();
            session.setUndoManager(undoManager);
          }}
        />
      </div>
    );
  }
}

What am I missing, any workarounds?

A: this happens because onload is called before value={code} is processed, a hacky workaround is:
onLoad={editor => {
    editor.once("change", function() {
        editor.session.getUndoManager().reset();
    });
}}

https://codesandbox.io/s/sharp-kalam-yen89


text:
Q: Give an example to show that $f_n$ fails to converge to $f$ uniformly over $S$ if $S$ is not compact Given the theorem: Suppose $S \subset \Bbb R^n$ is compact, and $P$ is an equicontinuous sequence of functions ($f_n$) over $S$ converging pointwise to a function $f$ at each $x \in S$, then $f_n$ converges to $f$ uniformly over $S$.
Note that the definition here is: $Q$ as a set of real-valued functions defined over $S \subset \Bbb R^n$ is equicontinuous at $y \in S$ if given $\epsilon \gt 0$ there is a $\delta \gt 0$ such that $|f(x)-f(y)|\lt \epsilon$ for all $|x-y|\lt \delta$ and all $f \in Q$. Also, it is equicontinuous over $S$ if it is equicontinuous at all $x \in S$
I want to give an example to show that the above theorem fails if $S$ is not compact but stuck on finding one. Could someone provide an example please?Thanks a lot.


text:
Q: Convert the NetCDF writing code from annual to monthly using 'datatime' library I have a NetCDF file of shape 180 x 360 x 720. Data is saved such that 180 refers to 12 months from '2001 to 2015', 360 and 720 refers to central latitudes and longitudes ranging from 89.75 degree to -89.75 degree and from -179.75 degree to 179.75 degree in 0.5 degree interval, respectively.
I want to write this to a NetCDF using datetime packages.
The code which I use for writing yearly data is mentioned below:
import datetime
from netCDF4 import Dataset,num2date,date2num
# -----------------------
nyears = 15;   ## From 2001-2015 but time axis is 180 in shape
unout = 'days since 2001-01-01 00:00:00'
# -----------------------
res = 0.5
lon = np.arange(-179.75,180,res);
lat = np.arange(-89.75,-90,res);

dataout = X; # create some random data
datesout = [datetime.datetime(2001+iyear,1,1) for iyear in range(nyears)]; # create datevalues
# =========================
ncout = Dataset('/home/chandra/data/Temp_data_evap/BESS_ET.nc','w','NETCDF4'); # using netCDF3 for output format
ncout.createDimension('lon',nx);
ncout.createDimension('lat',ny);
ncout.createDimension('time',nyears);
lonvar = ncout.createVariable('lon','float32',('lon'));lonvar[:] = lon;
latvar = ncout.createVariable('lat','float32',('lat'));latvar[:] = lat;
timevar = ncout.createVariable('time','float64',('time'));timevar.setncattr('units',unout);timevar[:]=date2num(datesout,unout);
myvar = ncout.createVariable('Evaporation','float32',('time','lat','lon'));myvar.setncattr('units','mm');myvar[:] = dataout;
ncout.close();

Can someone help me convert the code from yearly to monthly?

A: You should use number of months as the size of your time axis i.e the length of the dimension. So, if you have 15 years of monthly data, you have 15*12 = 180 values in time.
Here is the example code:
#!/usr/bin/env ipython
import datetime
from netCDF4 import Dataset,num2date,date2num
import numpy as np
# -------------------------------------------------
# Make date axis:
yystart = 2001
nyears = 15
monperyear = 12
ntime = nyears*monperyear
unout = 'days since 2001-01-01 00:00:00'
# -------------------------------------------------
res = 0.5
lon = np.arange(-179.75,180,res);nx=np.size(lon)
lat = np.arange(-89.75,90,res);ny=np.size(lat)

dataout = np.random.random((ntime,ny,nx))
datesout = [datetime.datetime(yy,mm,15,0) for yy in range(yystart,yystart+nyears) for mm in range(1,13)]
# =========================
ncout = Dataset('BESS_ET.nc','w','NETCDF4'); # using netCDF3 for output format
ncout.createDimension('lon',nx);
ncout.createDimension('lat',ny);
ncout.createDimension('time',ntime);
lonvar = ncout.createVariable('lon','float32',('lon'));lonvar[:] = lon;
latvar = ncout.createVariable('lat','float32',('lat'));latvar[:] = lat;
timevar = ncout.createVariable('time','float64',('time'));timevar.setncattr('units',unout);timevar[:]=date2num(datesout,unout);
myvar = ncout.createVariable('Evaporation','float32',('time','lat','lon'));myvar.setncattr('units','mm');myvar[:] = dataout;
ncout.close();


text:
Q: Mutliple day VEVENT crashing in iCal I've created an ICS file for users to subscribe to their calendar on their iPhone and other Calendar software. Everything seems to be working great, no issues anywhere.
The only problem I keep running into is that on the iPhone all events that are covering more then 1 day crash when you try to look at them. Calendar on the Mac or Google Calendar shows them just fine. Am I overlooking anything stupid?
Here's an example, first event crashes, second event works just fine:
BEGIN:VEVENT
DTSTAMP:20141219T170203Z
UID:kSChyB7KjAHQxS0eUSQ_5-Jm05PfeFqa4F4JKW17-IswWXqUFPRGiBGV
DTSTART:20141226T190000
DTEND:20141227T021500
DESCRIPTION:x
LOCATION:x
SUMMARY: x
END:VEVENT
BEGIN:VEVENT
DTSTAMP:20141219T170224Z
UID:HdhK2VXwuLuTxeGKJtCkeUTPElV5DMMawMMeG6Wj_1MAOqeAIL1rR3yj
DTSTART:20141226T100500
DTEND:20141226T164500
DESCRIPTION:x
LOCATION:x
SUMMARY:x
END:VEVENT

A: Don't know what type of event you want to represent here but it is generally not advisable to use floating time (for your DTSTART/DTEND).
If your events are not recurring you probably want to use date in zulu.
See https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5 for the definition of floating time versus zulu time.
This might not solve your crash issue but it should help interoperability at least.

A: I'd say the date start and date end are ill formatted. Formatting the date start and end as follows
DTSTART;TZID=Europe/Amsterdam:20150101T000000

should make them work. A datetime without a timezone is a weird thing :)


text:
Q: Does iOS11 handle viewport different? On my iPad Mini I can only install up to iOS 9.3, the website looks fine there and on any other device. But colleagues with a new iPad and iOS 11.0.3 have the website only filling about 60% of the screen (both portrait and landscape mode).
see iPod photo a colleague sent me
I made the website for 100% screen width on all devices and never had a problem, worked fine the last 2 years. I would say the website code is sober, the problem comes from iOS. But since I can only check iOS 9.3 or iOS 11, I do not exactly know at which version of iOS the error exactly started.
I can not find any information whatsoever about where this may come from or other people mentioning such a problem. Does iOS11 handle viewport different?


text:
Q: Find all lines in a file with a certain character at a certain position I have a lab question asking me to use grep with a regex pattern to match every word where the third letter from the beginning of the line is an "a" and save it with a redirect. How can I do that?

A: The solution proposed by @rahmu is simple if you look for low positions, but what if you look for the character number 25? Put in 25 dots?
In such a case the following solutions could be at hand. With grep
grep '^.\{24\}a' input >output

With awk
awk -F '' '$25 == "a"' input >output

A: This should answer your question:
grep -e "^..a" < input > savefile


text:
Q: Place the sidebar exactly below without setting any value of `top` or `bottom` I want to design an option to toggle the sidebar in the small devices.
So, I have tried to set the some div as a sidebar, so that I have set the value of div as top-0 and left-0, giving the class as inset-y-0 left-0, so it is showing up exactly from the top-0 but I want to make the sidebar start from the end of the top-navbar.
How does it will be possible to place the sidebar exactly below the top-bar without setting any value of top or bottom?
Also, the sidebar should be in line with the logo when the devices are greater than sm.

<link href="https://unpkg.com/tailwindcss@1.0.0/dist/tailwind.min.css" rel="stylesheet" />

    <button @click="this.isOpen = !this.isOpen" type="button" class="rounded-full hover:bg-purple-200 h-10 w-10
        flex items-center justify-center focus:outline-none sm:hidden">
        <svg
          class="w-6 h-6"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            v-if="!isOpen"
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M4 6h16M4 12h16M4 18h16"
          ></path>
          <path
            v-else
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M6 18L18 6M6 6l12 12"
          ></path>
        </svg>
      </button>

      <svg class="h-10 w-32 fill-current" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M12.372 31.672a27.83 27.83 0 01-1.974-2.1c-.224-.252-.868-1.036-1.932-2.352l-2.142-2.856c.784-.504 1.372-.952 1.764-1.344 1.176-1.232 1.764-2.73 1.764-4.494 0-.952-.042-1.876-.126-2.772a42.615 42.615 0 00-.21-2.394h3.78c-.196-.14-.35-.252-.462-.336-.7-.56-1.232-1.078-1.596-1.554l-.882-1.386a7.642 7.642 0 01-.882.42c-.728.336-1.218.518-1.47.546a6.48 6.48 0 01-.714.042h-.504c-1.232 0-2.632-.168-4.2-.504a42.191 42.191 0 01-1.974-.504l2.73 2.268 2.814 1.008v5.502h-2.94a.915.915 0 00-.714.336c-.196.224-.294.49-.294.798 0 .952.784 2.506 2.352 4.662 1.204 1.652 2.66 3.416 4.368 5.292l2.478 2.646 2.604 1.176-1.638-2.1zm10.555-18.816l5.208.504v4.83a4.483 4.483 0 01-.63.546 3.674 3.674 0 01-1.974.546c-.336 0-.784-.056-1.344-.168-.532-.112-.91-.224-1.134-.336.112-.224.196-.49.252-.798a5.88 5.88 0 00.084-.966c0-.532-.084-1.288-.252-2.268-.14-.98-.21-1.61-.21-1.89zm2.016 18.732l-3.36-5.166-1.974-3.15c.28-.168.504-.308.672-.42.504-.364.91-.714 1.218-1.05.224-.224.462-.574.714-1.05.084-.14.196-.364.336-.672.224.224.406.392.546.504.924.728 1.736 1.162 2.436 1.302l.42.084h.462c.364 0 .686-.014.966-.042.28-.028.532-.07.756-.126v6.762l8.4 5.46-4.452-5.628V13.402h2.688c-.196-.14-.35-.252-.462-.336-.7-.56-1.232-1.078-1.596-1.554a44.373 44.373 0 01-.588-.966 21.59 21.59 0 01-.336-.588c-.14.028-.252.042-.336.042-1.12.252-1.96.42-2.52.504-.56.084-1.246.14-2.058.168-.812.028-1.274.042-1.386.042-1.904 0-4.102-.154-6.594-.462a51.503 51.503 0 01-3.192-.462c.308.308.56.546.756.714.644.532 1.288.924 1.932 1.176.392.14.644.35.756.63.112.252.252.378.42.378.084 0 .126.574.126 1.722 0 .672-.014 1.33-.042 1.974 0 .644-.014 1.246-.042 1.806h-2.94c-.672 0-1.008.392-1.008 1.176 0 .84.686 2.366 2.058 4.578.896 1.456 2.198 3.318 3.906 5.586l2.184 2.856 2.1 1.68-.966-2.478zm13.907-18.06v15.12l8.358 5.376-4.41-5.544-.042-15.12h2.31c-.308-.252-.546-.448-.714-.588-.588-.504-1.008-.924-1.26-1.26l-.882-1.386-3.024.294c-1.092.112-1.96.168-2.604.168-.532 0-.868-.028-1.008-.084a.901.901 0 01-.294-.168l.252.378c.476.644 1.022 1.092 1.638 1.344l1.68 1.47zM31.066 5.59c.252-.14.602-.252 1.05-.336a7.32 7.32 0 011.428-.126c.784 0 1.498.112 2.142.336.644.196 1.106.518 1.386.966l3.444 4.914h1.554c-.14-.252-.714-1.176-1.722-2.772-1.288-2.016-2.436-3.696-3.444-5.04-.392-.504-.812-.896-1.26-1.176-.448-.308-.966-.462-1.554-.462h-4.494l1.47 3.696zm38.456 7.77l3.192.042c-.196-.14-.35-.252-.462-.336-.7-.56-1.232-1.078-1.596-1.554l-.882-1.386c-.364.028-.784.056-1.26.084-.476.028-1.106.098-1.89.21-.756.112-1.694.168-2.814.168a48 48 0 01-5.124-.294 31.867 31.867 0 01-2.394-.336c.448.308.812.546 1.092.714.868.532 1.582.924 2.142 1.176.56.224 1.274.462 2.142.714.28.084.644.182 1.092.294l2.814.504v8.61c-.112.252-.56.588-1.344 1.008-1.064.588-2.17.882-3.318.882-.7 0-1.19-.056-1.47-.168-.448-.196-.672-.574-.672-1.134 0-1.4 1.008-2.436 3.024-3.108.672-.224 1.694-.42 3.066-.588l-1.428-3.108c-1.96 0-3.514.322-4.662.966-1.428.784-2.142 1.96-2.142 3.528 0 1.848.532 3.472 1.596 4.872 1.092 1.4 2.478 2.1 4.158 2.1.7 0 1.54-.224 2.52-.672.168-.056.392-.182.672-.378v2.394l8.484 5.46-4.536-5.628V13.36zM57.652 3.322c.168-.056.756-.084 1.764-.084h1.05c.308.056.518.084.63.084.42 0 .84.084 1.26.252.42.14.728.406.924.798l4.284 6.552h1.218c0-.168-.602-1.26-1.806-3.276-1.344-2.268-2.52-4.074-3.528-5.418C62.692 1.194 61.74.676 60.592.676h-4.2l1.26 2.646zm-2.226 2.352l1.554 2.394 2.688-.084c.336 0 .658.014.966.042.28 0 .518.098.714.294l2.268 2.604h1.092a154.037 154.037 0 01-2.058-3.15c-.924-1.4-1.89-2.1-2.898-2.1h-4.326zm27.425 7.182l5.208.504v4.83a4.483 4.483 0 01-.63.546 3.674 3.674 0 01-1.974.546c-.336 0-.784-.056-1.344-.168-.532-.112-.91-.224-1.134-.336.112-.224.196-.49.252-.798a5.88 5.88 0 00.084-.966c0-.532-.084-1.288-.252-2.268-.14-.98-.21-1.61-.21-1.89zm2.016 18.732l-3.36-5.166-1.974-3.15c.28-.168.504-.308.672-.42.504-.364.91-.714 1.218-1.05.224-.224.462-.574.714-1.05.084-.14.196-.364.336-.672.224.224.406.392.546.504.924.728 1.736 1.162 2.436 1.302l.42.084h.462c.364 0 .686-.014.966-.042.28-.028.532-.07.756-.126v6.762l8.4 5.46-4.452-5.628V13.402h2.688c-.196-.14-.35-.252-.462-.336-.7-.56-1.232-1.078-1.596-1.554a44.373 44.373 0 01-.588-.966 21.59 21.59 0 01-.336-.588c-.14.028-.252.042-.336.042-1.12.252-1.96.42-2.52.504-.56.084-1.246.14-2.058.168-.812.028-1.274.042-1.386.042-1.904 0-4.102-.154-6.594-.462a51.503 51.503 0 01-3.192-.462c.308.308.56.546.756.714.644.532 1.288.924 1.932 1.176.392.14.644.35.756.63.112.252.252.378.42.378.084 0 .126.574.126 1.722 0 .672-.014 1.33-.042 1.974 0 .644-.014 1.246-.042 1.806h-2.94c-.672 0-1.008.392-1.008 1.176 0 .84.686 2.366 2.058 4.578.896 1.456 2.198 3.318 3.906 5.586l2.184 2.856 2.1 1.68-.966-2.478zm14.957-9.114l-3.108 3.108 3.108 3.108 3.108-3.108-3.108-3.108zm-3.108-6.636l3.108 3.024 3.108-3.024-3.108-3.15-3.108 3.15z"
            fill="#A886EF"
          />
          <path
            d="M51.057 25.078l-3.108 3.15 3.108 3.024 3.108-3.024-3.108-3.15z"
            fill="#FEFEFF"
          />
        </svg>

        Destinations
        Trip Plan
        About Us

Expected result:

A: The way I would do it is to add a class to the sidebar which adds margin-top: 40px; to create an offset the same height as the top nav-bar.
This of course assumes that your top-nav bar is a fixed height.


text:
Q: Magnets falling through solenoid I'm unsure about something in electromagnetism....When a bar magnet falls through a solenoid, does it travel at a constant velocity due to the opposing force caused due to Lenz's Law? Or does the gravitational acceleration not affected by this?

A: Changing magnetic field caused by falling magnet induces current in the solenoid such that the magnetic field caused by induced current is opposite to magnetic field that induces a current (Lenz's Law). The induced current is proportional to the rate of change of the magnetic field so, the faster the magnet is going, the more current it induces and therefore the stronger magnetic field is induced that opposes the motion of the magnet.
If there is no sources of current in the solenoid other than the falling magnet, the force on the magnet will get stronger and stronger until gravity cancels it out and after that, magnet will fall with constant velocity.