text:
Q: Converse to Lebesgue Differentiation Theorem Suppose we are given two finite positive Borel measures $\mu$, $\nu$ on $\mathbb{R}^n$ such that the function
$$ f(x) := \limsup_{r\to 0} \frac{\mu(B(x,r))}{\nu(B(x,r))} $$
is in $L^1(\nu)$. Is it true that $\mu \ll \nu$? Note that in a sense, this would be a converse of the Lebesgue differentiation theorem, since if we started off assuming that $\mu \ll \nu$, then $\nu$-a.e., $f$ would be equal to the Radon-Nikodym derivative of $\mu$ with respect to $\nu$, which is in $L^1(\nu)$.
If it helps, I think I'm OK with also assuming that $\nu \ll \mu$, or even $\nu \leq \mu$.
For some context, this is coming up in my research constructing equilibrium states in dynamics. I tried a google search and I couldn't find very much, so any leads would be appreciated, even if not a full response. Thank you!

A: This answer is intended as a complement to Bob's.
In "Geometry of sets and measures in euclidean spaces" by P. Mattila, the following theorem is proved (theorem 2.12 in my edition):
Let $\mu,\nu$ be Radon measures on $\mathbb{R}^n$. Define $\underline{D}(\mu,\nu,x)=\liminf \frac{\mu(B(x,r))}{\nu(B(x,r))}$ and $\overline{D}$ in the same way with $\limsup$. Then

*

*$D=\overline{D}=\underline{D}$ exists finite $\nu-$almost everywhere

*$Dd\nu\le d\mu$ (as measures) and the equality holds iff $ \mu\ll \nu$

*$\mu\ll \nu$ iff $\underline D$ is finite $\mu-$a.e.

A: Counterexample: if $\mu$ is the Dirac's delta in $0$ and $\nu$ is a Gaussian measure (say, with parameters $\mu = 0$ and $\sigma^2 = 1$), then $f$ is the zero function, apart from the point $0$ where it equals to $+\infty$. It follows that $f$ is in $L^1(\nu)$. However $\mu$ is not absolutely continuous with respect to $\nu$.
I don't know if there are counterexamples with the further requirement that $f$ is well-defined and finite everywhere.


text:
Q: Missing dependency while upgrading AEM 6.5.1 to 6.5.10 I am upgrading AEM 6.5.1 (Service pack 1) to AEM 6.5.10 (Service pack 10). For this I installed SP10 in AEM as well updated the uber-jar version to 6.5.10 in my source code POM.xml file.
I see that in the OSGI console, my bundle is in Installed and not Active state. This is because certain dependencies (which before the update were not present) are missing. I have been able to get those dependencies, except one.
com.microsoft.schemas.office.powerpoint -- Cannot be resolved

I am unable to find any JARs online that fixes this issue. I tried Apache POI but no success. Does anyone know what this dependency is and where I can get it?
Thanks!

A: If you are not using it at all, you can exclude it.
<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <extensions>true</extensions>
    <configuration>
        <instructions>
            <!-- Import any version of javax.inject, to allow running on multiple versions of AEM -->
            <Import-Package>
                javax.inject;version=0.0.0,
                !sun.misc;resolution=optional,!javax.persistence,!com.sun.jdi.*,
                !com.microsoft.schemas.office.powerpoint,*
            </Import-Packages>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel indirect drag down formula I am trying to drag an INDIRECT formula down a column but can't figure out how to get it to change the reference for each row. It's a sum formula that multiples two columns. I am using the INDIRECT in it because this is a master template and columns get deleted. Previous to using the INDIRECT formula I would get a #REF error when deleting those columns. So the INDIRECT works great now - I just need to know how to drag it down the column so that I don't have to manually change each cell. The formula I am using is =SUM(INDIRECT("I4")*Z4). I know since I have the I4 in the " " - it keeps it static. So what is the work around for it to still work how it does but be able to drag the formula down the column?

A: To make the INDIRECT() also adjust, use something like:
=SUM(INDIRECT("I" & ROWS($1:4))*Z4)

So dragging down one row will make a formula that behaves like:
=SUM(INDIRECT("I5")*Z5)


text:
Q: C# - Import lines from a text file into a Process.Start statement I am currently trying to import a list of executables from a text file into a statement:
private void button19_Click(object sender, EventArgs e)
{
    Process.Start("test.exe", <Process Name Here>);
}

So If a text file named process.txt contained:

notepad.exe
calc.exe

I would end up with:
Process.Start("test.exe", notepad.exe);

and
Process.Start("test.exe", cacl.exe);

A: This ought to be what you're after, Michael.
foreach(string exename in System.IO.File.ReadAllLines("yourfile.txt"))
{
  Process.Start("test.exe", "\"" + exename + "\"");
}

A: This will do it:
using (var reader = File.OpenText(pathToFile))
{
    string exe = "";

    while ((exe = reader.ReadLine()) != null)
    {
        Process.Start("test.exe", exe);
    }
}


text:
Q: SAS: Why am I getting an 'Invalid data' error? Why do I keep getting an invalid data error? I verified the numbers are in the correct columns and that the dates are structured in 'input' just as it is in 'datalines'.
data ThreeDates;
input   @1  Date1 mmddyy10.
        @12 Date2 mmddyy10.
        @23 Date3 date9.;
format  Date1
        Date2
        Date3 mmddyy10.;

datalines;
 01/03/1950 01/03/1960 03Jan1970
 05/15/2000 05/15/2002 15May2003
 10/10/1998 11/12/2000 25Dec2005
 ;
 run;

NOTE: Invalid data for Date1 in line 185 1-10.
NOTE: Invalid data for Date2 in line 185 12-21.
NOTE: Invalid data for Date3 in line 185 23-31.
RULE:      ----+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9-
185         01/03/1950 01/03/1960 03Jan1970
Date1=. Date2=. Date3=. _ERROR_=1 _N_=1
NOTE: Invalid data for Date1 in line 186 1-10.
NOTE: Invalid data for Date2 in line 186 12-21.
NOTE: Invalid data for Date3 in line 186 23-31.
186         05/15/2000 05/15/2002 15May2003
Date1=. Date2=. Date3=. _ERROR_=1 _N_=2
NOTE: Invalid data for Date1 in line 187 1-10.
NOTE: Invalid data for Date2 in line 187 12-21.
NOTE: Invalid data for Date3 in line 187 23-31.
187         10/10/1998 11/12/2000 25Dec2005
Date1=. Date2=. Date3=. _ERROR_=1 _N_=3
NOTE: The data set WORK.THREEDATES has 3 observations and 3 variables.
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

A: Is it due to the space in front of each dataline? Make sure you also put the semicolon in column 1. Also, use datalines4 always as a habit.

A: The issue is clearly shown in the SAS log.
NOTE: Invalid data for Date1 in line 185 1-10.
NOTE: Invalid data for Date2 in line 185 12-21.
NOTE: Invalid data for Date3 in line 185 23-31.
RULE:      ----+----1----+----2----+----3----+----4----+----5
185         01/03/1950 01/03/1960 03Jan1970

The RULE line with the dashes. plus sign and digits is there to help you understand exactly what was in the columns listed in the NOTE.
SAS only recognizes dates back to 1582, so trying to create dates in the year 195, 196 or 197 like on the first data line is not going to work.
You have misaligned your fixed column input with where the data is on the line.  Probably because of the extra space you have added in front of every line of data, including the line with the semicolon that marks the end of the data (and also marks the end of the data step.)
Either remove the leading spaces or adjust the cursor movement to match the actual locations.
For this data you could also just use LIST MODE input instead of FORMATTED MODE and then the number of leading spaces or number of spaces between the values wouldn't matter.   Adding the colon modifier in front of any in-line informats in the INPUT statement will insure the INPUT still operates in LIST MODE.
Note that in list mode the width specified for the informat is ignored, the whole next "word" on the line is used whatever its length.
Use a single period to indicate a missing value (numeric or character) when using LIST MODE input, The period will make sure that the values are used in the right order.
data ThreeDates;
  input date1 :mmddyy. date2 :mmddyy. date3 :date.;
  format date1-date3 yymmdd10.;
datalines;
     01/03/1950 01/03/1960 03Jan1970
05/15/2000 05/15/2002          15May2003
 10/10/1998     11/12/2000 25Dec2005
;
proc print;
run;

Results

You should get in the habit of starting both the DATALINES statement and the terminal line with the semicolon in first column to avoid getting column numbers confused.


text:
Q: Angular component gets out of sync when using the angular router I'm trying to figure out a weird behavior from Angular Router 12.2.0.
I'm using websockets to update a table in real time.
Everything works as expected as long as I don't use the router (either by clicking an achor tag with a [routerLink] attribute or by calling router.navigate method).
Steps to reproduce

*

*Navigate to the component hosting the table, say /employees

*Confirm the table is updated in real time

*Navigate away

*Come back to /employees

*The table is now frozen with the data received at page load

The issue doesn't come from the socket. The component keeps receiving data from the server and updates the model as expected. Only the GUI is out of sync with the model.
Oddly enough, the UI will reflect the changes if I trigger the exact same updates manually (i.e. by executing a function bound to a button).
The only way to restore the live updates is to manually reload the entire page using F5.
Is this behavior related to the "angular zone"?
Why does this behavior only happen when I navigate using angular router? What is going on?
Code example
The code is simple. I simply subscribe to a STOMP Broker location by providing an uri and a callback. I update the model in the callback. The model (a simple array) is rendered in the view using an *ngFor directive.
// callback executed everytime a message from the server is received
const callback = (message: Message) => {
    const e: Employee = JSON.parse(message.body);
    // update the model
    this.employees.push(e);
}
this.stompClient.subscribe(uri, callback, headers);

And in the template:
<td *ngFor="let e of employees">{{e.name}}</td>

What I tried
I of course tried the following approaches:

*

*ApplicationRef.tick()

*NgZone.run(callback)

*ChangeDetectorRef.detectChanges()

None of the solutions of these answers worked for me:
How to force a component's re-rendering in Angular 2?
Angular2 View Not Changing After Data Is Updated
Angular 6 View is not updated after changing a variable within subscribe
Angular component not updating when input changes value
ANGULAR 7 reload component view
Triggering change detection manually in Angular
The correct method of updating a MatTableDataSource in angular 2 version 6
Nothing solved my issue. The view stays frozen every time I use the router. It's getting to the point where I'm thinking about using window.location.reload() if nothing else works.
Update
I tried both yehonatan yehezkel and MikeOne suggestions in the comments.
They both work as long as I don't use the router. As soon as I start navigating, the view is not updated anymore.
So this confirms the common denominator is the router here.
What am I missing? Why does the router prevent the view from updating?
Update2
Addressing Gergő Éles comment:
Could the problem come from the way I declared the routes for my nested modules?
In app-routing.module
const routes: Routes = [
  {
    path: employees
    canActivate: [CanActivateRoute],
    loadChildren: () => import('./modules/employee/employee.module').then(mod => mod.EmployeeModule)
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes),
    ...
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

And in employee.module:
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: EmployeeListComponent
      }
    ]
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routes),
    ...
  ],
  declarations: [
    EmployeeListComponent,
    ...
  ]
})
export class EmployeeModule { }


text:
Q: how to know exception point I have a source code of 500Mb having more than 5K of files written in Python. Sometimes I get exception messages but no idea about the line number and file name of exception. Even sometimes exceptions are not seen on terminal unlit I specifically use pdb.
Is there any convenient way to get to know about the exception location ?
Thanks.

A: Try the traceback module: https://docs.python.org/3/library/traceback.html
It contains the tb_lineno function which takes the traceback as a parameter, returning the line number of the exception.
EDIT:
import sys, traceback

def lumberjack():
    bright_side_of_death()

def bright_side_of_death():
    return tuple()[0]

try:
    lumberjack()
except IndexError:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print("*** print_tb:")
    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    print("*** print_exception:")
    traceback.print_exception(exc_type, exc_value, exc_traceback,
                          limit=2, file=sys.stdout)
    print("*** print_exc:")
    traceback.print_exc()
    print("*** format_exc, first and last line:")
    formatted_lines = traceback.format_exc().splitlines()
    print(formatted_lines[0])
    print(formatted_lines[-1])
    print("*** format_exception:")
    print(repr(traceback.format_exception(exc_type, exc_value,
                                      exc_traceback)))
    print("*** extract_tb:")
    print(repr(traceback.extract_tb(exc_traceback)))
    print("*** format_tb:")
    print(repr(traceback.format_tb(exc_traceback)))
    print("*** tb_lineno:", exc_traceback.tb_lineno)


text:
Q: Magnet moving in electric field
Consider a magnet moving with a velocity $v$ in an electric field (voltage of 1000KV,distance between electrodes as 10 cm).
So my question is what will happen? Will magnet feel a force against it or will electrodes will feel a force?
Also consider this whole setup is in space with no other force.

A: The magnetization of a magnet is part of the magnetization-polarization tensor $$M^{\mu \nu} = \left(
\begin{array}{cccc}
 0 & c P_x & c P_y & c P_z \\
 -c P_x & 0 & -M_z & M_y \\
 -c P_y & M_z & 0 & -M_x \\
 -c P_z & -M_y & M_x & 0 \\
\end{array}
\right)$$ for the magnet shown all of the $P_i$ are zero in its rest frame. So in a frame where it is moving the magnetization-polarization tensor transforms to $$ M'^{\mu \nu} = \left(
\begin{array}{cccc}
 0 & 0 & -\frac{v \gamma  M_z}{c^2} & \frac{v \gamma  M_y}{c^2} \\
 0 & 0 & -\gamma  M_z & \gamma  M_y \\
 \frac{v \gamma  M_z}{c^2} & \gamma  M_z & 0 & -M_x \\
 -\frac{v \gamma  M_y}{c^2} & -\gamma  M_y & M_x & 0 \\
\end{array}
\right) $$ where $\gamma$ is the usual Lorentz factor for a frame moving at $v$ relative to the magnet's rest frame and the $M_i$ are in the magnet's frame.
Note that the $M_x$ produces no polarization at all, but there is some z polarization produced by the $M_y$. This polarization will result in a torque being applied by electric field between the plates. However, this torque will be very small. First, most of the magnetization will be in the $M_z$ direction, so it will only be whatever imperfections exist in the magnet or its alignment. Second, it is divided by $c^2$ so it is quite small unless the magnet is moving at highly relativistic velocities.
So, ideally there will be no torque applied to the magnet, but if there is any imperfection in the alignment or in the magnetization of the magnet there will be a small polarization which will result in a small amount of torque


text:
Q: Understanding part of log4j2 configuration file I am able to understand log4j2 configuration via XML, however I have some confusion when we configure it via properties file.
1. appender.console.type = Console
2. appender.console.name = STDOUT
3. appender.console.layout.type = PatternLayout

In line 1, we use console at two places, so which one really tells that I want to use ConsoleAppender, and what does appender.console represent? I understand that in XML we specify Console as the appender type and we give it a name using name attribute, so that we can refer to it later in the Logger element.

A: In appender.console console is the identifier for this component. It's the same as the name attribute in the XML configuration.
In your case you could also achieve the same configuration with:
appender.foo.type = Console
appender.foo.name = STDOUT
appender.foo.layout.type = PatternLayout

See the docs for more information.
What is the appender.foo.name property used for?
The docs for appenders state that "Appenders always have a name so that they can be referenced from Loggers." For each logger you have to reference at least one appender so that the logmessages are written out somewhere. Use the name you defined earlier for that.
In your example you would add the appender to a logger like this:
rootLogger.level = info
rootLogger.appenderRef.stdout.ref = STDOUT


text:
Q: Rails image not rendering inside li tag There is likely an easy answer to this, but I can't seem to figure it out. My blog image won't display in an li tag once my rails form is submitted with the image.
Is there a way around this? The image displays when the li tag is removed.
I would like to show multiple images though.
Thanks

      <%= image_tag @post.image.url(:medium), class: "img-responsive" %>

A: Try to check in the developer tools to see if your ul tag styles are not causing a conflict with your
 tags styles;
and l think this:

is suppose to look like this:

I hope this helps.


text:
Q: fill object's empty values with anything As a beginner still in JS, I have to crack someone else's code that is not documented, obviously.
At some point this code arrives to the function that is supposed to build an object.
let obj = {
catName:"cat",
catAge: someAge,
catLength: "one half of a meter no one cares how many cm",
...
}

This object is then sent to another function that is assigning keys to the table names to print out this object in .csv format against column names (to be able to open it in Excel for example)
The datamodel is saved in a separate JS file.
function that would parse to csv format uses this:
    const pathtoFile = `////directories/cat.csv`;

    const globalParser = new Parser({
      header: !fs.existsSync(pathtoFile),
      delimiter: ";",
      excelStrings: false,
      fields: ReportFields,   //here is where the object data model comes from
    });

    const data = globalParser.parse(**catOBJ**) + "\n"; //catObj here is exactly what arrives and what is to be parsed

    if (!fs.existsSync(pathtoFile)) {
      fs.mkdirpSync(tmpcatReportsPath);
      fs.writeFileSync(pathtoFile, data, "utf-8");
    } else {
      fs.appendFileSync(pathtoFile, data, "utf-8");
    }

Problem:
I need to make sure that even if I do not know some of the values for some keys( ex: catLength), I can still assure that the object will get to .csv format and instead of this column name I will simply have ""
Questions:

*

*Does it look more reasonable to you that I first fetch this template object , create an instance of it and then assign the parameters I know to it and then send it to the function?

*if not, how do you proceed to make sure that the values that are not known are positioned as "" if I do not have a clue what these key-names are?

A:
how do you proceed to make sure that the values that are not known are positioned as "" if I do not have a clue what these key-names are?

1) To obtain the keys of an object you should ouse the Object.keys() function, which returns an array with keys like ['catName', 'catAge', 'catLength', ...].
2) Once you have the keys of the object, you should map each of them and check if there is a null value:
let keys = Object.keys(obj);    // Get array of keys

let result = {};

// Iterate all keys
keys.forEach(key => {
    result[key] = (obj[key] == null ? "" : obj[key]);
});

*

*Notice that using obj[key] == null will also catch undefined values.

You can try the code in the snippet:

let obj = {
  catName: "cat",
  catAge: 5,
  catLength: "one half of a meter no one cares how many cm",
  catColor: null   // Need to catch this
};

let keys = Object.keys(obj);

let result = {};

keys.forEach(key => {
  result[key] = (obj[key] == null ? "" : obj[key]);
});

console.log(result);


text:
Q: Polynomial identity for a sum If $$f(x) = \sum_{i=0}^{n}A_i x^i \quad \text{ and } \quad g(x) = \sum_{i=0}^{n}B_i x^i$$ are two degree $n$ polynomials, then we can say that the polynomial
$$h(x) = \sum_{k=0}^{2n}C_k x^k \quad \text{ where } \quad C_k = \sum_{\substack{0\leq i, j\leq n \\ i + j = k}}A_i B_j$$
can be expressed as $$h(x) = f(x)\cdot g(x).$$
Is there a similar method to express the polynomial
$$r(x) = \sum_{k=0}^{n^2}D_k x^k \quad \text{ where } \quad D_k = \sum_{\substack{0\leq i, j\leq n \\ i\cdot j = k}}A_i B_j$$
like $r(x) = \mathcal{F}\thinspace (f(x), g(x))$ ?

A: I think this would be along the lines of $F(f(x),g(x))=\sum_{j=0}^nf (x)^jg (x)^{n-j}$

A: There is a partial answer. Given the power series expansion for $f(x)$ in the question, the function $r(x)$ can be expressed as follows.
$$r(x) = \sum_{i=0}^n A_i g(x^i)$$
I am unable to make the form more compact that this.


text:
Q: How to bind to collection 2 deep? I have the following collection structure and need to bind a combo box to it:
MainCollection.Items

Items contains a list of elements I'd like to display as choices in a combo box. MainCollection is of type List.  Items is of type List.  There is a Name property on the Item class that I'd like to display in the combo box.
The layout will be setup as a grid.  Each row will have a combo box.
I'm not sure how to access properties on Item elements inside the Items collection.
<ComboBox ItemsSource="{Binding MainCollection}"></ComboBox>

How should this be setup?

A: So If I understand the question correctly, you would like to have a DataGrid, with each row containing a Combobox, and the values available inside must be the Name property of the Item objects that are in the List Items
You didn't said what kind of data you want to show in each row, let's take a simple User :
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Item Item { get; set; }
}

With Item having a Name (let's keep it simple for the example) :
public class Item
{
    public string Name { get; set; }
}

Now that we have the models, we can set the DataContext with random Users and Items :
public partial class MainWindow : Window
{
    // Could also be
    // public ObservableCollection<Item> Items { get; set; }
    public List<Item> Items { get; set; }
    public List<User> Users { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        // Creating our list of Items
        Items = new List<Item> {
            new Item { Name = "firstItem" },
            new Item { Name = "secondItem" },
            new Item { Name = "thirdItem" },
        };

        // Somes users for the example
        Users = new List<User>{
            new User { Id = 1, Name = "Bill", Item = new Item { Name = "firstItem" }},
            new User { Id = 2, Name = "Steeve", Item = new Item { Name = "secondItem" }}
        };

        // Don't forget to set the datacontext
        DataContext = this;
    }
}

And now the XAML :
<Grid>
    <DataGrid Name="testGrid" AutoGenerateColumns="False" ItemsSource="{Binding Users}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridComboBoxColumn
                DisplayMemberPath="Name"
                SelectedValuePath="Name"
                SelectedValueBinding="{Binding Item.Name}"
                Header="Item">
                <DataGridComboBoxColumn.ElementStyle>
                    <Style TargetType="{x:Type ComboBox}">
                        <Setter Property="ItemsSource" Value="{Binding Path=Items, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
                    </Style>
                </DataGridComboBoxColumn.ElementStyle>
                <DataGridComboBoxColumn.EditingElementStyle>
                    <Style TargetType="{x:Type ComboBox}">
                        <Setter Property="ItemsSource" Value="{Binding Path=Items, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
                    </Style>
                </DataGridComboBoxColumn.EditingElementStyle>
            </DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

The result :

Hope that the answer you were looking for :)


text:
Q: Not able to print forestplot in high resolution format in R I need to create a forestplot of high resolution. I used the forestplot() function from library(forestplot) to create my plot, and then attempted to use the tiff() function to create a high resolution image for publication. However, my image turned blank.
It works if I export directly from R but not as high resolution as it was supposed to.
library(forestplot)

df <- structure(list(
  mean = c(NA, 0.22, 0.20, 0.27),
  lower = c(NA, 0.05, 0.04, 0.01),
  upper = c(NA, 0.95, 1.08, 9.12)),
  .Names = c("mean", "lower", "upper"),
  row.names = c(NA, -4L),
  class = "data.frame")

tabletext <- cbind(
  c("", "Pooled", "Group 1", "Group 2"),
  c("N", "4334", "3354", "980"),
  c("HR (95% CI)", "0.22 (0.05, 0.95)", "0.20 (0.04, 1.08)", "0.27 (0.01, 9.12)"),
  c("p-value", "0.042", "0.061", "0.467")
)

ggfp <- forestplot(tabletext,
                   df,
                   new_page = TRUE,
                   is.summary = c(TRUE, rep(FALSE, 3)),
                   clip = c(0, 2),
                   colgap = unit(5, "mm"),
                   line.margin = unit(2, "mm"),
                   lineheight = unit(1, "in"),
                   txt_gp = fpTxtGp(label = gpar(cex = 1),
                                    ticks = gpar(cex = 1)),
                   align = c("l", "c", "c", "c"),
                   boxsize = 0.2,
                   xticks = seq(0, 2.0, 0.5),
                   zero = 1,
                   col = fpColors(box = "royalblue",
                                  line = "darkblue"),
                   mar = unit(c(-1, 0.5, -2, 0.5), "in"))

tiff("forestplot.tiff", units = "in", width = 9, height = 7, res = 300)
ggfp
dev.off()

The file was created but it was a blank page

A: This works for me (output file is 17MB):
library(forestplot)

setwd("/path/to/directory/for/plot")

df <- structure(list(
  mean = c(NA, 0.22, 0.20, 0.27),
  lower = c(NA, 0.05, 0.04, 0.01),
  upper = c(NA, 0.95, 1.08, 9.12)),
  .Names = c("mean", "lower", "upper"),
  row.names = c(NA, -4L),
  class = "data.frame")

tabletext <- cbind(
  c("", "Pooled", "Group 1", "Group 2"),
  c("N", "4334", "3354", "980"),
  c("HR (95% CI)", "0.22 (0.05, 0.95)", "0.20 (0.04, 1.08)", "0.27 (0.01, 9.12)"),
  c("p-value", "0.042", "0.061", "0.467")
)

tiff("forestplot.tiff", units = "in", width = 9, height = 7, res = 300)

forestplot(tabletext,
                   df,
                   new_page = TRUE,
                   is.summary = c(TRUE, rep(FALSE, 3)),
                   clip = c(0, 2),
                   colgap = unit(5, "mm"),
                   line.margin = unit(2, "mm"),
                   lineheight = unit(1, "in"),
                   txt_gp = fpTxtGp(label = gpar(cex = 1),
                                    ticks = gpar(cex = 1)),
                   align = c("l", "c", "c", "c"),
                   boxsize = 0.2,
                   xticks = seq(0, 2.0, 0.5),
                   zero = 1,
                   col = fpColors(box = "royalblue",
                                  line = "darkblue"),
                   mar = unit(c(-1, 0.5, -2, 0.5), "in"))
dev.off()


text:
Q: how to do something in all slides by just one code? i use this code and you can see it just work for slide 1  :
 Sub o_c_LTab(shape As shape)

Lt = ActivePresentation.Slides(1).Shapes("LT").Left
If Lt = -175 Then
    Do
    DoEvents
    Lt = Lt + 25
        ActivePresentation.Slides(1).Shapes("LT").Left = Lt
        ActivePresentation.Slides(1).Shapes("LT_handle").Left = ActivePresentation.Slides(1).Shapes("LT_handle").Left + 25
        ActivePresentation.Slides(1).Shapes("1").Left = ActivePresentation.Slides(1).Shapes("1").Left + 25
        ActivePresentation.Slides(1).Shapes("2").Left = ActivePresentation.Slides(1).Shapes("2").Left + 25
        ActivePresentation.Slides(1).Shapes("3").Left = ActivePresentation.Slides(1).Shapes("3").Left + 25
        ActivePresentation.Slides(1).Shapes("4").Left = ActivePresentation.Slides(1).Shapes("4").Left + 25
        ActivePresentation.Slides(1).Shapes("5").Left = ActivePresentation.Slides(1).Shapes("5").Left + 25

    timeout (0.01)
    Loop Until Lt = 0
ElseIf Lt = 0 Then
    Do
    DoEvents
    Lt = Lt - 25
        ActivePresentation.Slides(1).Shapes("LT").Left = Lt
        ActivePresentation.Slides(1).Shapes("LT_handle").Left = ActivePresentation.Slides(1).Shapes("LT_handle").Left - 25
        ActivePresentation.Slides(1).Shapes("1").Left = ActivePresentation.Slides(1).Shapes("1").Left - 25
        ActivePresentation.Slides(1).Shapes("2").Left = ActivePresentation.Slides(1).Shapes("2").Left - 25
        ActivePresentation.Slides(1).Shapes("3").Left = ActivePresentation.Slides(1).Shapes("3").Left - 25
        ActivePresentation.Slides(1).Shapes("4").Left = ActivePresentation.Slides(1).Shapes("4").Left - 25
        ActivePresentation.Slides(1).Shapes("5").Left = ActivePresentation.Slides(1).Shapes("5").Left - 25
    timeout (0.01)
    Loop Until Lt = -175
End If

End Sub

Sub timeout(duration_ms As Double)
    Start_Time = Timer
    Do
    DoEvents
    Loop Until (Timer - Start_Time) >= duration_ms
End Sub

i have this shapes in 200 slides and i should write this for 200 times , how can i do that in all slides by just one code?

A: Each Slide will be an item in the Slides collection.
You can step through each item in a collection using:
Sub Test()

    Dim sl As Slide

    For Each sl In ActivePresentation.Slides
        Debug.Print sl.Name
    Next sl

End Sub

Then rather than use ActivePresentation.Slides(1).Shapes("LT") you can use sl.Shapes("LT")


text:
Q: Java recursion output different from expected Just when I thought I was starting to understand recursion this one seems simple when n is 1  but when n is 2  In my head I  end up with [[, [, [,]
public void ps (int n){

  if (n==0) {
    System.out.print ("*");
  }
  else {
    System.out.print ("[");
    ps (n-1);
    System.out.print (",");
    ps (n-1);
    System.out.print ("]");
  }
}

A:   ps(2):
     Current output ""
     n != 0 so else: print [ output = "["
     call ps(1)
     ps(1):
       Current output "["
       n != 0 so else: print [ output = "[["
       call ps(0)
       ps(0):
        Current output "[["
         n == 0: print "*" output = "[[*"
         return
     ps (1): after first call
       output = "[[*"
       print "," output = "[[*,"
       call ps(0):
       ps(0):
         current output "[[*,"
         n == 0: print "*" output = "[[*,*"
         return
    ps(1): after second call
       output = "[[*,*"
       print "]" output = "[[*,*]"
       return
  ps(2): after first call
    output = "[[*,*]"
    print , output = "[[*,*],"
    call ps(1)
             ps(1):
       Current output [[*,*],
       n != 0 so else: print [ output = "[[*,*],["
       call ps(0)
       ps(0):
        Current output "[[*,*],["
         n == 0: print "*" output = "[[*,*],[*"
         return
     ps (1): after first call
       output = "[[*,*],[*"
       print "," output = "[[*,*],[*,"
       call ps(0):
       ps(0):
         current output "[[*,*],[*,"
         n == 0: print "*" output = "[[*,*],[*,*"
         return
    ps(1): after second call
       output = "[[*,*],[*,*"
       print "]" output = "[[*,*],[*,*]"
       return
   ps(2): after second call
       output = "[[*,*],[*,*]"
       print "]" output = "[[*,*],[*,*]]"
       return

Final output: "[[*,*],[*,*]]"

A: Well, you probably heard the terms stack frame and call stack already. They are quite important to understand what happens in a recursion.
My tip is to draw the stack frames in a tree, according to their invocation.
In this case it would look like:
ps(2)
  |
  |--ps(1)
  |    |
  |    |--ps(0)
  |
  |--ps(1)
  |    |
  |    |--ps(0)

Now add to this the output from each invocation, and you should be fine.

*

*As mentioned, on future questions try to explain what you expect or what you are trying to achieve.


text:
Q: Return name of empty columns from a list I have a named list of data frames that all contain the same columns, but for some of these data frames some of these columns are empty. What Im hoping to return is the name of the data frame in the list, and the name(s) of the empty column.
The repex below mirrors the process I am using on the full problem
library(tidyverse)

data("diamonds")

data1 <- diamonds

data1$color <- NA

data1$price <- NA

data2 <- diamonds

data2$carat <- NA

data1$Type <- "data1"

data2$Type <- "data2"

data1%>%
  bind_rows(data2) -> dataFull

dataSplit <- split(dataFull, f = dataFull$Type)

for(i in dataSplit){

  which(sapply(dataSplit[[i]], function(x) all(is.na(x))))

}

My hope is to return something like
data1: price, color
data2: carat
I've tried the very basic for-loop included above, which are admittedly not my strong suit.

A: Your sapply idea was right, but you need to subset the names of each data frame with the output. Also, since you are loading the tidyverse, you may as well use map instead of a loop for brevity:
map(dataSplit, ~ names(.x)[sapply(.x, \(x) all(is.na(x)))])
#> $data1
#> [1] "color" "price"
#>
#> $data2
#> [1] "carat"

A: library(tidyverse)

data("diamonds")

data1 <- diamonds

data1$color <- NA

data1$price <- NA

data2 <- diamonds

data2$carat <- NA

data1$Type <- "data1"

data2$Type <- "data2"

data1%>%
  bind_rows(data2) -> dataFull

dataSplit <- split(dataFull, f = dataFull$Type)

lapply(dataSplit, function(x) {
  cn <- colnames(x)
  isempty <- apply(x, 2, function(col) is.na(col) |> all())
  cn[ isempty ]
})

$data1
[1] "color" "price"

$data2
[1] "carat"

A: Using select
library(dplyr)
library(purrr)
map(dataSplit, ~ .x %>%
      select(where(~ all(is.na(.x)))) %>%
      names)
$data1
[1] "color" "price"

$data2
[1] "carat"

Or in base R
 lapply(dataSplit, \(x) names(x)[!colSums(!is.na(x))])
$data1
[1] "color" "price"

$data2
[1] "carat"


text:
Q: IFstatements in VBA arrays to run code faster than loops Context: I am trying to learn more about arrays and their use, specifically since I learnt that loops can have huge runtime limiting their use to just few iterations. As matter of fact, related to this issue, I had made a simple VBA macro that runs IFstatements on 8000 cells and whenever the result was positive it would move the whole row to a different sheet. Needless to say, stopwatching this macro took me around 10 minutes bringing me to the conclusion that there must have been a faster way otherwise the whole point of using Macro would just be obsolete. I even tried using Application.Calculation/EnableEvents/ScreenUpdating to achieve a faster solution but it again took me another 10 minutes to run it all.
Sample loop code:
Public Sub MoveOutTyres()
'this macro moves Pneu Complete, Hiver or Ete and Status 1 tyres in their sheets: it should be under Test worksheet
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    Application.ScreenUpdating = False

'Declare All Variables
Dim myCell As Range
Dim LastRow As Integer
Dim myRange As Range
Dim LastCol As Integer
Dim ws As Worksheet

'frame the table
    With ThisWorkbook

    LastRow = Range(Cells(1, 1), Cells(1, 1).End(xlDown)).Count
    LastCol = Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count

            'the following code will verify if the worksheet Pneu_Complete exists or not

                   Dim wsSheet2 As Worksheet
                   On Error Resume Next
                   Set wsSheet2 = Sheets("Pneu_Complete")
                   On Error GoTo 0
                   If Not wsSheet2 Is Nothing Then
                        MsgBox "The worksheet Pneu_Complete exists"
                        Else
                        MsgBox "The worksheet Pneu_Complete does not exist please create a worksheet with the name: 'Pneu_Complete'"
                   End If

'Create a ListObjects table of a specific size

On Error Resume Next
    Worksheets("Test").ListObjects.Add(xlSrcRange, Range(Cells(1, 1), Cells(LastRow, LastCol)), , xlYes).Name = _
      "data_gardi_LPLU"
    ActiveSheet.ListObjects("data_gardi_LPLU").TableStyle = "TableStyleLight2"
On Error GoTo 0

'move rows with specific criteria
                    'move rows with Pneu tyre in worksheet Pneu_Complete

                    For m = 2 To LastRow

                        With ThisWorkbook.Sheets("Test").ListObjects("data_gardi_LPLU")

                        Set myRange = ThisWorkbook.Sheets("Test").ListObjects("data_gardi_LPLU").ListColumns("Season").DataBodyRange
                            For Each myCell In myRange
                                If myCell.Value = "Summer" Then
                                        myCell.EntireRow.Cut
                                        m = m + 1

                                End If
                            Next
                        End With
                    Next
For i = 1 To CntRow_updated
    Set myRange = Range(Cells(2, 2), Cells(LastRow, 2))

        For Each myCell In myRange
        myCell.Offset(0, LastCol - 3).Value = WorksheetFunction.CountIf(myRange, myCell.Value)
        Next

Next
    End With

Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = False

End Sub

Desired Code: I would like my code to read the values from an excel sheet then store the entry row in an array and copy the rows that meet a certain criteria into another sheet. As ultimate, I would like to count how many entries with the same ID I have in my dataset and copy such values in the last column
Data Sample
   ID     Tyre_Width    Tyre_Diameter  Season
   101    15            50cm           Winter
   101    15            50cm           Winter
   101    15            50cm           Winter
   101    15            50cm           Winter
   201    14            55cm           Summer
   201    14            55cm           Summer
   102    18            50cm           Winter
   102    18            50cm           Winter

Data Result: As explained before the IF statement would be used to remove in this example the summer tyres and then I would need to count the number of the ids in the last column
    ID     Tyre_Width    Tyre_Diameter  Season   Cnt
    101    15            50cm           Winter   4
    101    15            50cm           Winter   4
    101    15            50cm           Winter   4
    101    15            50cm           Winter   4
    102    18            50cm           Winter   2
    102    18            50cm           Winter   2

A: After watching a guide on Youtube on how to create and modify arrays I was finally able to find a solution. The videoguide I watched can be find here https://www.youtube.com/watch?v=h9FTX7TgkpM. To be specific, I reproduced the macro shown in the last exercise. Following you can find the code.
Sub Array_Winter()
    Dim Arr() As Variant
    Dim r As Range
    Dim Counter As Long, LoopCounter As Long

    Sheet1.Activate

    For Each r In Range("A2", Range("A1").End(xlDown))

        If LCase(r.Offset(0, 7).value) = "Winter" Then
            Counter = Counter + 1

            ReDim Preserve Arr(1 To 21, 1 To Counter)

            For LoopCounter = 1 To 21
                Arr(LoopCounter, Counter) = r.Offset(0, LoopCounter - 1)
            Next LoopCounter

        End If

    Next r

    Worksheets("Winter").Activate
    Worksheets("Winter").Range("A1", Range("A1").Offset(UBound(Arr, 2) - 1, 20)).value = Application.Transpose(Arr)

End Sub


text: Q: Add a new column in a dataframe from another dataframe using category column and then finding max for each category I have a dataframe (DF2, subset of DF1) with category column and count in each category. This was created from an original dataframe (DF1) which has date, and 7 float columns. Using one of the columns, this category column was created (continous to categorical data). Now for each of these categories, I need to find the max value from each of the remaining 6 columns and add new columns in DF2.


text:
Q: Chrome and Internet Explorer doesn't work Offline, works fine on Firefox Mobile Web Offline browser support problem ----
I am working on mobile web application, when i open web site on mobile and go offline, Firefox works fine. But it doesn't work in chrome and IE browsers. Please help me.......

A: Have you validated the appcache using Firefox?

*

*Press shift F2 to bring up the Firefox command line.

*Go to your site.

*appcache clear

*appcache validate


text:
Q: I get no data when download images so iam trying to download images by this code i successfully download the images but they without any data and corrupted
like the images have 0 bytes
function get_chapter_images(){

include('simple_html_dom.php');

$url = 'http://localhost/wordpress/manga/manga-name-ain/chapter-4/';

 $html = file_get_html($url);

 $images_url = array();

foreach($html->find('.page-break img') as $e){

  $image_links =  $e->src;

array_push( $images_url, $image_links);

   }

   return $images_url;

}
$images_links = get_chapter_images();

    foreach( $images_links as $image ){

        $imag_fliter = str_replace( '?ssl=1', '', $image );

        $data = @file_get_contents( $image );

                $pathinfo = pathinfo( $image );

                    $file_name = $pathinfo['basename'];

                    @file_put_contents("manld/$file_name", $data );

    }


text:
Q: how to read multiple lines using BufferedReader? I am sending a Text from Xcode (that a user enters on a textView) to java server.
the text may contain more than one line.
the problem is when receiving the text, only even lines are being read.
here is my code.
server:
            StringBuilder sb = new StringBuilder();
            while(inFromClient.readLine()!=null){   //infromClient is the buffered reader

                sb.append(inFromClient.readLine());
                sb.append('\n');
            }
            System.out.println ("------------------------------");
            System.out.println (sb.toString()); //the received text

client side:
           NSString *notecontent=[NSString  stringWithFormat:@"%@",self.ContentTextView.text];
        NSData *notecontentdata = [[NSData alloc] initWithData:[notecontent dataUsingEncoding:NSASCIIStringEncoding]];
        [outputStream write:[notecontentdata bytes] maxLength:[notecontentdata length]];

A: You're consuming three lines:

*

*Check if there's next line

*Printing line

*Storing one.

Noted here:
while(inFromClient.readLine()!=null) { //1.
    System.out.println (inFromClient.readLine()); //2.
    sb.append(inFromClient.readLine()); //3.
    sb.append('\n');
}

Store the line in a String and then do what you want/need with it:
String line = "";
while ((line = inFromClient.readLine()) != null) {
    System.out.println(line);
    sb.append(line);
    sb.append('\n');
}

A: I think the issue is this:
while(inFromClient.readLine()!=null){   //infromClient is the buffered reader
    System.out.println (inFromClient.readLine());
    sb.append(inFromClient.readLine());
    sb.append('\n');
}

The issue, specifically, is the three readLine() calls. Each call will read another line from the client. So effectively you're reading a line to check if the client has stuff to send, reading another line and printing printing it, then reading another and storing it.
What you want to do is store the read line in a temp variable, print it, then append it:
String s;
while((s = inFromClient.readLine()) !=null){   //infromClient is the buffered reader
    System.out.println (s);
    sb.append(s);
    sb.append('\n');
}


text:
Q: Graph_tool 's find_vertex() raises a Exception I generate a graph with the word of a sentence as tokens and dependency relations as edges.
This info comes from a external Tool in the format of ((word, index), (word, index),  relation) tuple. Each word can have many dependencies and I want only one node per word.
When I process each dependency I want to search it by their ID, but when i Try to use find_vertex() i get the next Exception:
TypeError: No registered converter was able to extract a C++ reference to type graph_tool::GraphInterface from this Python object of type Graph

This is the code:
def graph(self, sentence, sentenceNamespace="sentence", separator="_"):
    graph = Graph()
    root_node = graph.add_vertex()
    # Create a link to Root Node
    graph.graph_properties['root'] = graph.new_graph_property("python::object", root_node)
    # Create Node's properties
    graph.vertex_properties['id'] = graph.new_vertex_property("string")
    graph.vertex_properties['form'] = graph.new_vertex_property("string")
    graph.vertex_properties['ord'] = graph.new_vertex_property("int64_t")
    # Create edge's properties
    graph.edge_properties['type'] = graph.new_edge_property("string")
    # Create the root node
    graph.vertex_properties['form'][root_node] = "S"
    graph.vertex_properties['ord'][root_node] = -1
    # Find or create the dependant and governor nodes and link with a new edge
    for dependency in self.dependency(sentence):
        dependency_governor = dependency[0]
        # Governor's generated ID
        governor_name = "{1}{0}{2[0]}{0}{1[1]}".format(separator, sentenceNamespace,dependency_governor )
        dependency_dependant = dependency[1]
        # Dependant's generated ID
        dependant_name = "{1}{0}{2[0]}{0}{1[1]}".format(separator, sentenceNamespace, dependency_dependant)
        # Relation Type
        relation = dependency[2]

# This is the problematic Line ################################################

        governor = find_vertex(graph, graph.vertex_properties['id'], governor_name)

##############################################################
        # If search is successful use the first node else create a new one
        if governor :
            governor = governor[0]
        else:
            governor = graph.add_vertex()
            graph.vertex_properties['id'][governor] = governor_name
            graph.vertex_properties['form'][governor] = dependency_governor[0]
            graph.vertex_properties['ord'][governor] = dependency_governor[1]

        dependant = find_vertex(graph, 'id', dependant_name)
        # If search is successful use the first node else create a new one
        if dependant :
            dependant = dependant[0]
        else:
            dependant = graph.add_vertex()
            graph.vertex_properties['id'][dependant] = dependant_name
            graph.vertex_properties['form'][dependant] = dependant_dependant[0]
            graph.vertex_properties['ord'][dependant] = dependency_dependant[1]
        # Link the nodes with the new dependency relation
        dependency_edge = graph.add_edge(governor, dependant)
        graph.edge_properties['type'][dependency_edge]= relation
    return graph

A: This bug has been fixed in the git version.


text:
Q: handling comp3 and ebcidic conversion in java to ASCII for large files I am trying to convert comp3 and EBCIDIC characters in my java code but im running into out of memory exception as the amount of data handled is huge about 5 gb. my code is currently as follows:
byte[] data = Files.readAllBytes(path);

this is resulting in an out of memory exception which i can understand, but i cant use a file scanner as well since the data in the file wont be split into lines.
Can anyone point me in the correct direction on how to handle this
Note: the file may contain records of different length hence splitting it based on record length seams not possible.

A: As Bill said you could (should) ask for the data to be converted to display characters on the mainframe and if English speaking you can do a ascii transfer.
Also how are you deciding where comp-3 fields start ???

You do not have to read the whole file into memory, you can still read the file in blocks, This method will fill an array of bytes:
protected final int readBuffer(InputStream in, final byte[] buf)
throws IOException {

    int total = 0;
    int num = in.read(buf, total, buf.length);

    while (num >= 0 && total + num < buf.length) {
        total += num;
        num = in.read(buf, total, buf.length - total);
    }
    return num;
}

if all the records are the same length, create an array of the record length and the above method will read one record at a time.
Finally the JRecord project has classes to read fixed length files etc. It can do comp-3 conversion. Note: I am the author of JRecord.

A:
I'm running into out of memory exception as the amount of data handled is huge about 5 gb.

You only need to read one record at a time.

My code is currently as follows:

byte[] data = Files.readAllBytes(path);

This is resulting in an out of memory exception which i can understand

Me too.

but i cant use a file scanner as well since the data in the file wont be split into lines.

You mean you can't use the Scanner class? That's not the only way to read a record at a time.
In any case not all files have record delimiters. Some have fixed-length records, some have length words at the start of each record, and some have record type attributes at the start of each record, or in both cases at least in the fixed part of the record.

I'll have to split it based on an attribute record_id at a particular position(say at the begining of each record) that will tell me the record length

So read that attribute, decode it if necessary, and read the rest of the record according to the record length you derive from the attribute. One at a time.
I direct your attention to the methods of DataInputStream, especially readFully(). You will also need a Java COMP-3 library. There are several available. Most of the rest can be done by built-in EBCDIC character set decoders.


text:
Q: Discrete population models Consider the model:
$y_{n+1}=ry_n(1-\frac{y_n}{k}); r>0$
a)Show that $y_{n+1}<0$ if and only if $y_n>k$.
b)Show that $y_{n+1}>k$ is possible with $0<y_n<k$ only for $r>4$.
c)What conditions on $y_0$ are necessary and sufficient to guarantee $y_n>0$ for n=1,2,3...
I block in question (c), I was unable to determine the condition.
I await your explanation.

A: Assuming a), b) are correct,
by b) if $r\le 4$ then given $y_0\in (0,k)$ we have $y_n\in (0,k)$ for all $n$.
If $r>4$ then it is possible that $y_{n+1}>k$ even if $y_n\in (0,k)$ for some $n$, and by a) it then implies that $y_{n+2} <0$. So $r>4$ then postivity is not guranteed.
Hence necessary and sufficient condition is $r\le 4$, and $y_0 \in (0,k)$


text:
Q: Python extract values of a key from a list of lists of dictionaries I have a list of lists of dictionaries. The list is continuously building with new data from a stream.
[
  [{'T': 1626610583088, 'p': '12562.12'}, {'T': 1626610583088, 'p': '12562.12'}],
  [{'T': 1626610583088, 'p': '12562.12'}, {'T': 1626610583088, 'p': '12562.12'}, {'T': 1626610583088, 'p': '12562.12'}],
  [{'T': 1626610583088, 'p': '12562.12'}], ....... and so on ]

(new lists are creating continuously from the stream)
I need to extract the values from 'p', but keeping format of the lists exactly as they are:
[[12562.12, 12562.12], [12562.12, 12562.12, 12562.12], [12562.12], ....... and so on ]

A: You can do this with a list comprehension:
pValues = [[d["p"] for d in row] for row in data]

This iterates through each row of your list of lists of dictionaries, then iterates through each dictionary in the row and gets the value of "p" for each of them. (Note data is your list of lists of dictionary)

A: You can try a regular expression:
import re

s = '''[[{'T': 1626610583088, 'p': '12562.12'}, {'T': 1626610583088, 'p': '12562.12'}],
  [{'T': 1626610583088, 'p': '12562.12'}, {'T': 1626610583088, 'p': '12562.12'}, {'T': 1626610583088, 'p': '12562.12'}],
  [{'T': 1626610583088, 'p': '12562.12'}]]'''

results = []
for line in s.splitlines():
    results.append(re.findall("(?<='p': ').*?(?=')", line))
    print(results)

Output:
[['12562.12', '12562.12']]
[['12562.12', '12562.12'], ['12562.12', '12562.12', '12562.12']]
[['12562.12', '12562.12'], ['12562.12', '12562.12', '12562.12'], ['12562.12']]

Where the
for line in s.splitlines():

will be replaced with your continuous stream.


text:
Q: How to Import API data into a Material UI Card I am currently making a Recipe app and I am pulling data from this API called edamame. I imported cards from Material UI and imported it into my .js file that calls the API for the data. I stored the data in a const called recipes but I am struggling to get the data to appear in my imported cards. I can create cards locally without importing from Material UI and make the API data show just fine. But once Material UI shows up, I start having problems. How should I approach this?
MealPlan.Js (calls the API and stores data)
import React, { useState, useEffect } from "react";
import style from "./recipe.module.css";
import "./App.css";
import NavigationBar from "./NavigationBar";
import Card from "./card";
import { Grid } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
    gridContainer: {
        paddingLeft: "20px",
        paddingRight: "20px",
    },
});

export default function MealPlan() {
    //  below we define the useStates

    const [recipes, setRecipes] = useState([]); //Recipes pulled from the api through the search function are stored in this const
    const [search, setSearch] = useState("");
    const [query, setQuery] = useState("chicken");
    const APP_ID = "removed";
    const APP_KEY = "removed";

    useEffect(() => {
        //dispatch call to fetch items // get recipes runs the function when useEffect is active
        getRecipes(); // eslint-disable-next-line
    }, [query]); //only refreshes when query is called

    const getRecipes = async () => {
        const response = await fetch(
            `https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`
        );

        const data = await response.json();
        setRecipes(data.hits);
        console.log(data.hits);
    };

//my personal card
    const MealPlanCard = ({ title, calories, image, ingredients }) => {
        const round = Math.round(calories);

        return (

{title}

        );
    };

    return (

                {recipes.slice(0, 1).map((recipe) => (
                    <MealPlanCard
                        key={recipe.recipe.label}
                        title={recipe.recipe.label}
                        calories={recipe.recipe.calories}
                        image={recipe.recipe.image}
                        ingredients={recipe.recipe.ingredients}
                    />
                ))}

<Grid container spacing={4} className={classes.gridContainer}>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
            </Grid>

    );
}

Here is the jsx for the imported cards from Material UI
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";

const useStyles = makeStyles({
    root: {
        minWidth: 200,
    },
    bullet: {
        display: "inline-block",
        margin: "0 2px",
        transform: "scale(0.8)",
    },
    title: {
        fontSize: 14,
    },
    pos: {
        marginBottom: 12,
    },
});

export default function SimpleCard() {
    const classes = useStyles();
    const bull = •;

    return (
        <Card className={classes.root}>
            <CardContent></CardContent>
            <CardActions>
                <Button size="small">Button</Button>
            </CardActions>
        </Card>
    );
}

Here is how my page currently looks https://imgur.com/a/MsTtCP1
My Goal is to populate the imported cards on the bottom, with the contents of my personal card on the top. How can I do that?

A: If I understood you correctly, you want your functional component SimpleCard to receive data from MealPlan...
If that is the case, consider the following:
SimpleCard.js
export default function SimpleCard(props) {
    const classes = useStyles();
    const bull = •;

    return (
        <Card className={classes.root}>
            <CardContent>{props.ingredient}</CardContent>
            <CardActions>
                <Button size="small">{props.calories}</Button>
            </CardActions>
        </Card>
    );
}

And on your MealPlan.js you import this file
import SimpleCard from 'pathTo/SimpleCard'

and instead of rendeind Card you should render SimpleCard - that you have imported and pass down your variables as props (nutrition, calories...)
<Grid item xs={12} sm={6} md={4}>
      <SimpleCard
           ingrediend={"banana"}
           calories={40}
      />
</Grid>

Basically the concept here is to create components such as the one you created - SimpleCard and populate it the data that you pass over it, called props, like ingredient and calories.
Therefore you have multiple instances of SimpleCard with diferent data on them.
<Grid item xs={12} sm={6} md={4}>
      <SimpleCard
           ingrediend={"chocolate"}
           calories={100}
      />
</Grid>
<Grid item xs={12} sm={6} md={4}>
      <SimpleCard
           ingrediend={"banana"}
           calories={40}
      />
</Grid>

and so on!


text:
Q: probability of drawing marbles based on coin flip
An urn contains 4 red and 3 white marbles. A random marble $M_1$ is drawn and a fair coin is flipped. If the flip is heads then $M_1$ is put back into the urn. On the other hand, if the flip is tails, the marble $M_1$ is not put back into the urn. Now another random marble $M_2$ is drawn from the urn.
(i) What is $\mathrm{Pr}(M_2 = \text{red})$?
  (ii) What is $\mathrm{Pr}(M_1 = \text{red}\mid  M_2 = \text{red})$?
  (iii) What is $\mathrm{Pr}(\text{flip is heads}\mid M_2 = \text{white})$?
Solutions:
  (i) $\dfrac{4}{7}$;   (ii) $\dfrac{15}{28}$;   (iii) $\dfrac{1}{2}$

(iii)'s answer is a half because the the marble color is independent of the coin flip, correct?
Why is (i)'s answer $\dfrac{4}{7}$, why not $\dfrac{3}{6}$ or $\dfrac{4}{6}$ if the coin flip outcome is tails?
As for (ii), I'm completely lost.
Can someone explain please?

A: (i) The probability that $M_2$ is red depends on what happened on the first draw. Consider three events: the coin comes up heads ($H$); $M_1$ is red and the coin comes up tails ($R$); $M_1$ is white and the coin comes up tails ($W$). Then $\Pr(H)=\frac12$, $\Pr(R)=\frac12\cdot\frac47=\frac27$, and $\Pr(W)=\frac12\cdot\frac37=\frac3{14}$. The probability that $M_2$ is red is $\frac47$ if $H$ occurred, $\frac36=\frac12$ if $R$ occurred, and $\frac46=\frac23$ if $W$ occurred, so $$\Pr(M_2\text{ is red})=\frac12\cdot\frac47+\frac27\cdot\frac12+\frac3{14}\cdot\frac23=\frac27+\frac17+\frac17=\frac47\;.$$
(ii) You can use Bayes' theorem, but you can also think it through without using any formula, and it's not a bad idea to do so at least once. I already did much of the necessary calculation in answering (i). Informally, we know from (i) that on average $M_2$ is red $4/7$ of the time; we want to know in what fraction of that $4/7$ $M_1$ was also red. In (i) we didn't care what $M_1$ was when the coin came up heads, because we put it back, and its color didn't affect the probability that $M_2$ was red. Now we do care, so we split the event $H$ into $RH$ and $WH$: $RH$ is the event that $M_1$ is red and the coin comes up heads, and $WH$ is the event that $M_1$ is white and the coin comes up heads. Clearly $\Pr(RH)=\frac12\cdot\frac47=\frac27$, and $\Pr(WH)=\frac12\cdot\frac37=\frac3{14}$. The probability that $M_2$ is red if $RH$ occurred is $\frac27\cdot\frac47=\frac8{49}$, and the probability that $M_2$ is red if $WH$ occurred is $\frac3{14}\cdot\frac47=\frac6{49}$. We now have the following probabilities:
$$\begin{array}{cl|l}
&\text{Event}&\text{Probability}\\ \hline
*&M_1\text{ is red and }M_2\text{ is red and coin is heads}&\frac8{49}\\
&M_1\text{ is white and }M_2\text{ is red and coin is heads}&\frac6{49}\\
*&M_1\text{ is red and }M_2\text{ is red and coin is tails}&\frac17\\
&M_1\text{ is white and }M_2\text{ is red and coin is tails}&\frac27\\ \hline
&\text{total probability that }M_2\text{ is red}&\frac47
\end{array}$$
The starred lines show the cases in which $M_1$ is red. As you can see, they contribute a total of $\frac8{49}+\frac17$ to the total probability of $\frac47$ that $M_2$ is red. This means that
$$\Pr(M_1\text{ is red}\mid M_2\text{ is red})=\frac{\frac8{49}+\frac17}{\frac47}=\frac{\frac{15}{49}}{\frac47}=\frac{15}{28}\;.$$
(iii) Once $M_1$ has been drawn and the coin flipped, the probability that $M_2$ is white depends on the outcome of the coin flip, since it depends on whether $M_1$ was replaced or not. Thus, you have to make a calculation similar to the one in (ii). I'll just outline it:
$$\begin{array}{cl|l}
&\text{Event}&\text{Probability}\\ \hline
*&M_1\text{ is red and }M_2\text{ is white and coin is heads}&\frac47\cdot\frac37\cdot\frac12=\frac6{49}\\
*&M_1\text{ is white and }M_2\text{ is white and coin is heads}&\frac37\cdot\frac37\cdot\frac12=\frac9{98}\\
&M_1\text{ is red and }M_2\text{ is white and coin is tails}&\frac47\cdot\frac12\cdot\frac12=\frac17\\
&M_1\text{ is white and }M_2\text{ is white and coin is tails}&\frac37\cdot\frac13\cdot\frac12=\frac1{14}\\ \hline
&\text{total probability that }M_2\text{ is red}&\frac37
\end{array}$$
Now the starred cases contribute $\frac6{49}+\frac9{98}=\frac3{14}$ to the total probability of $\frac37$ that the coin comes of heads, so
$$\Pr(\text{coin is heads}\mid M_2\text{ is white})=\frac{3/14}{3/7}=\frac12\;.$$

A: (i) Every marble is just as likely to be picked for $M_2$ as any other marble.  That is why the probability is $\frac{4}{7}$.  If you want to see this in more detail, lets look at all the possible ways of getting $M_2$ = red.  Flip heads: white then red, red then red, flip tails: White then red, red then red.  Total probability:
$$\frac{1}{2} \frac{3}{7} \frac{4}{7} + \frac{1}{2} \frac{4}{7} \frac{4}{7} + \frac{1}{2} \frac{3}{7} \frac{4}{6} + \frac{1}{2} \frac{4}{7} \frac{3}{6} = \frac{4}{7}$$
(ii) Using $P(A|B) = P(A \cap B) / P(B)$
$$ P(M_1 = \text{red} \cap M_2 = \text{red}) = \frac{1}{2} \frac{4}{7} \frac{3}{6} + \frac{1}{2} \frac{4}{7} \frac{4}{7} = \frac{15}{49}$$
Giving $\frac{15}{49}/\frac{4}{7} = \frac{15}{28}$ as the answer.
(iii)
$$ P(\text{flip = heads} \cap M_2 = \text{white}) = \frac{1}{2} \left(\frac{4}{7} \frac{3}{7} + \frac{3}{7} \frac{3}{7}\right) = \frac{3}{14}$$
$P(M_2 = \text{white}) = \frac{3}{7}$ by similar argument to (i) and so using the conditional probability rule, the final answer is $\frac{3}{14} / \frac{3}{7} = \frac{1}{2}$

A: (i)
Given there are 4 red and 3 white marbles, there is a $\frac 4 7$ probability that $M_1 =$ red is drawn and a $\frac37$ probability that $M_1 =$ white. Now here is the tricky bit. A fair coin is flipped.

*

*If the coin flip is heads, then the urn will contain 4 red and 3 white for the 2nd draw.

*If the coin flip is tails, then there is a $\frac47$ probability that the urn will contain 3 red and 3 white; and a $\frac37$ probability that the urn will contain 4 red and 2 white.

Both these events have a $50/50$ probability of occurring. So taking into account all this
$$P(M_2 \text{is red}) = 0.5\begin{pmatrix}\frac47\end{pmatrix} + 0.5\begin{bmatrix}\begin{pmatrix}\frac47\end{pmatrix}\begin{pmatrix}\frac36\end{pmatrix} +\begin{pmatrix}\frac37\end{pmatrix}\begin{pmatrix}\frac46\end{pmatrix}\end{bmatrix} = \frac47$$
(ii)
$$P(M_1 \text{is red} \cap M_2 \text{is red})\\= 0.5\begin{pmatrix}\frac47\end{pmatrix}\begin{pmatrix}\frac47\end{pmatrix} +
\begin{bmatrix}
0.5\begin{pmatrix}\frac47\end{pmatrix}\begin{pmatrix}\frac36\end{pmatrix}\end{bmatrix}=\frac{15}{49}
$$
Taking the conditional probability formula,
$$
\begin{align*}
P(M_1 \text{is red} | M_2 \text{is red}) &= \frac{P(M_1 \text{is red} \cap M_2 \text{is red})}{P( M_2 \text{is red})}\\
&= \frac{\frac{15}{49}}{\frac47}\\
&=\frac{15}{28}
\end{align*}
$$


text:
Q: Parse string in Powershell Learning powershell, trying to find out how to parse the first value from this resultset (10.60.50.40):
IPAddresses
-----------
{10.60.50.40, fe80::5ddf:a8f4:e29c:b66}

Normally I would just look it up, however, I don't know if {x, x} is a standard datatype of sorts in Powershell land.
Do I have to do rough string parsing, or is there some standard command to extract the first one, such as:
... | Select-Object IPAddresses | Select-String [0]

(I just made the select string part up. I'm lost.)

A: This is most likely the result of of the IPAddresses property of your object containing an array. The output you're seeing is stylized for display purposes, so it's not a string you would have to parse. Assuming your object is $obj, you should be able to do either of these:
$obj.IPAddresses[0]
$obj.IPAddresses | Select-Object -First 1

A: One solution is to use split function to convert the string into array and work with that like in the next steps:

*

*Split the string into an array using the split function (comma is the item delimiter).

*Grab the first item of the array (or whatever needed) and then also sanitize it (remove unnecessary curly bracket).

Example below:
$str = "{10.60.50.40, fe80::5ddf:a8f4:e29c:b66}"

$strArr = $str.Split(",")

Write-Host $strArr[0].Replace("{", "")

A: This is what I ended up doing:
$str = ... | Select-Object IPAddresses | ForEach {$_.IpAddresses}
Write-Host $str[0]

A: Depending on the source of your IPAddresses, this might not be optimal. You might get multiple IPAddresses per devices.
You might want to combine both approaches:
$str = ... | Select-Object -ExpandProperty IPAddresses | Select-Object -First 1

This will return the First IP address in your list per device.


text:
Q: AngularJs inject providers error I'm trying to inject two providers and I have an error:

Error: [$injector:modulerr] Failed to instantiate module App due to:
  [$injector:unpr] Unknown provider: $paginationTemplateProvider

Here's my code:
var app = angular.module('App', ['angular-loading-bar', 'angularUtils.directives.dirPagination'])
    .config(function ($paginationTemplateProvider, $cfpLoadingBarProvider) {
        $paginationTemplateProvider.setPath('../lib/angular-utils-pagination/dirpagination.tpl.html');
        $cfpLoadingBarProvider.includeSpinner = false;
    });

Do you have any idea what is wrong?


text:
Q: About floating ground and circuit problems Good morning,
I have a power supply with floating ground that drives my circuit.
Since the circuit doesn't work as expected (it works fine only if the ground is tied to earth) I did some measures with oscilloscope. I left the ground of both probes (with 10x) disconnected and I did the difference between the two channels connected respectly to gnd and to the input signal of an opamp. What I see (see picture) is that the difference (white band) is not flat but there are peaks
I'm wondering if:
- it's a my mistake in the measure or
- the two points don't float together creating a voltage difference in the opamp input
- there is a way to reduce the float voltage difference
Thanks

A: Your measurement technique is invalid. See Fig. 1.  Imagine that instead of using an oscilloscope you have a multimeter, and you connect only the meter's "+" probe to the test point on the device under test (DUT); you leave the meter's "-" probe disconnected from the DUT.  The multimeter performs a voltage measurement and displays a voltage value.  Is the displayed voltage value a valid representation of the voltage between the DUT's test point and the DUT's ground reference potential?

Figure 1.
The answer is "It depends." If the multimeter's "-" input randomly happens to be at the same potential as the DUT's ground reference potential, then the voltage value shown on the multimeter is probably valid; otherwise it is definitely invalid.
Now imagine using two DMMs.  The negative terminals of the two DMMs are connected together, but as before the negative terminals are not connected to the DUT.  The positive terminals on the two DMMs are attached to two different test points on the DUT.  Both DMMs make a voltage measurement.  In this scenario, does each individual multimeter make a valid single-ended voltage measurement?  If the answer is "No" (and it is "No"), one cannot now synthesize a valid differential voltage measurement by calculating the difference of the two invalid single-ended voltage measurements.
Also consider Fig. 2. Ask yourself this question: "What is the voltage across the resistor on the left side of the figure?" (which represents the input impedance at the oscilloscope's analog input).  It's impossible to say what the voltage is because you cannot know voltage ΔV, the change in voltage between the oscilloscope's chassis ground (which is usually Earth ground) and the DUT's "floating" ground potential. (HINT: Using Kirchoff's Voltage Law, start at the oscilloscope's chassis ground potential and add up the voltage drops from that chassis ground node to the top of the resistor at the oscilloscope's input; that sum—i.e., the voltage across the resistor— is the voltage the oscilloscope measures.) Because voltage ΔV is undefined, the oscilloscope measures a random voltage.

Figure 2.
Now imagine repeating Fig. 2 with two analog input channels on the oscilloscope, leaving the probe grounds disconnected and connecting the probes to different test points on the DUT. Both analog inputs perform a single-ended voltage measurement that yields a random voltage value for each channel. These two random voltages cannot be synthesized into a valid differential voltage measurement by subtracting one from the other.
To make this measurement you should use

*

*A battery-powered oscilloscope that is not connected to Earth ground potential, OR

*A differential voltage oscilloscope probe (Keysight Labs video on YouTube), OR

*An oscilloscope whose input channel(s) can be safely isolated from chassis (Earth) ground potential, OR

*A custom measurement setup that uses (for example) an isolation amplifier that provides galvanic isolation between the oscilloscope ground potential and the DUT's floating ground potential.
See also:

*

*Dave Jones' EEVblog #932 - How Does A HV Differential Probe Work? (YouTube)

A: Most isolated power supplies will have a certain amount of leakage from primary to secondary. This is because there is some capacitive coupling across the transformer. You can see this leakage if you measure the AC voltage of your floating secondary, which might be surprisingly high but at very low current.
Now, where the problems begin to occur is if the secondary encounters something that is grounded - or has a path to ground (like your hand, for example.) The leakage noise is looking for a path to ground, and if it finds one, you get noise.
So you've already found a solution: grounding the secondary side to shunt this leakage away from your sensitive circuitry. Another solution is to shield the sensitive stuff so it can't couple to a nearby source.

A:
check C4 capacitor in ur power supply as in my picture.


text:
Q: passing char[] around functions I am trying to chain together a few overloaded functions. It is something that should be really simple but I am getting errors. Here is the code:
void output(char c[])
{
    output(c, 0);
}

void output(char c[], int x)
{
    int l = strlen(c) - x;
    output(c, x, l);
}

void output(char c[], int x, int y)
{
    cout << c;
}

int main()
{
    output("myname");
    output("myname", 3);
    output("myname", 2, 4);
}

The errors I am getting relate the chained parts (output(c, 0); and output(c, x, l);.
The errors are:
"No matching function for call to 'output (char *&, int)'
"No matching function for call to 'output (char *&, int &, int &)'

An explanation of what I have done wrong would be good as well.

A: I think the problem has to do with the fact that your functions lack prototypes. In cases like that, you should re-order functions so that the ones you call appear ahead of the ones that call them:
void output(const char c[], int x, int y)
{
    cout << c;
}
void output(const char c[], int x)
{
    int l = strlen(c) - x;
    output(c, x, l);
}
void output(const char c[])
{
    output(c, 0);
}

But it is best to stick to using prototypes for all functions ahead of defining them.
Also note that string literals are const. Since your functions do not modify the content of string literals, you should declare const char c[] instead of char c[].

A: You must first define all the functions that will be used later on. So in your case I would suggest to define function prototypes first, and later on to implement all of them.
Here is what I mean:
void output(char c[], int x);
void output(char c[], int x, int y);

void output(char c[])
{
    output(c, 0);
}

void output(char c[], int x)
{
    int l = strlen(c) - x;
    output(c, x, l);
}

void output(char c[], int x, int y)
{
    std::cout << c;
}

int main()
{
    output("myname");
    output("myname", 3);
    output("myname", 2, 4);
}

A: C++ requires all functions you call to be declared first. You simply can't call a function without the compiler's having seen its declaration (in other words, its prototype) somewhere before in your code.
So, to get it working, you should first declare all your functions (in other words, place all their prototypes), before you call them:
// Declarations go first
void output(char [], int);
void output(char [], int, int);

void output(char c[])
{
    output(c, 0);
}

void output(char c[], int x)
{
    int l = strlen(c) - x;
    output(c, x, l);
}

void output(char c[], int x, int y)
{
    cout << c;
}

That way, the compiler will get all needed prototypes before calling the functions.


text:
Q: Angular 11 cannot route to named outlet We have a basic application with 2 tabs, each with its own named outlet
<mat-tab-group>
    <mat-tab label="Tab1">
        <router-outlet name="tab1"></router-outlet>
    </mat-tab>
    <mat-tab label="Tab2">
        <router-outlet name="tab2"></router-outlet>
    </mat-tab>
</mat-tab-group>

One of the 2 named outlets just renders a component and that's fine. For the second one, we want to be able to route between different views so we created its own module and lazy load it.
App routing looks like
const routes: Routes = [{
    path: '',
    children: [{
        path: '',
        redirectTo: '/home',
        pathMatch: 'full'

    }, {
        path: 'login',
        loadChildren: () => import('./login/login.module').then(m => m.LoginModule)
    },
    {
        path: 'home',
        loadChildren: () => import('./home/home.module').then(m => m.HomeModule)
    }]
}]

Home page's routing looks like
const routes: Routes = [{
    path: '',
    component: HomeComponent,
    children: [{
        path: '',
        component: Tab1Component,
        outlet: 'tab1'
    }, {
        path: '',
        outlet: 'tab2',
        loadChildren: () => import('./tab2/tab2.module').then(m => m.Tab2Module)
    }]
}];

Tab2Module is implemented as follows
const routes: Routes = [{
    path: '',
    component: Tab2Child1Component
}, {
    path: 'tab2-child',
    outlet: 'tab2',
    component: Tab2Child2Component
}]

Tab2Child1Component gets rendered fine but we cannot navigate to Tab2Child2Component.
I am trying the following:
this.router.navigate([{ outlets: { tab2: 'tab2-child' } }], { relativeTo: this.route });

I can see in tracing that router is indeed trying to route to /home/(tab2:tab2-child) but in the end it just redirects back to /home with an error:
 Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
Error: Cannot match any routes. URL Segment: 'home'

Stackblitz showcasing the error:
https://stackblitz.com/edit/angular-ivy-pv5jsi

A: You have two issues with your design that cause it not to work.

*

*Your home component has empty path which does not work with named outlets. They work only if the path of the of the component is named. Maybe this will change in the future since there is an open bug regarding this in the Angular GitHub.

*The components you display in the named outlets must be direct children of the component that contains the outlets in the routing configuration. Your configuration with loadChildren for tab2 is like the component inside tab2 will have more internal routes which is not true in your case since you do not have another router outlet in the Tab2Child1Component.

To change your sample to something that works you need to add a path to the HomeComponent inside the HomeModule. To lazy load the tabs you need to put all the tabs in one module that is loaded as the children of the home component.
Here is my implementation of the HomeModule with the changes needed.
const routes: Routes = [
  {
    path: '',
    redirectTo: 'hc',
    pathMatch: 'full'
  },
  {
    path: 'hc',
    component: HomeComponent,
    loadChildren: () => import("./tab.module").then(m => m.TabModule)
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  declarations: [HomeComponent]
})
export class HomeModule {}

And the implementation of the tab module that defines the tabs for both outlets.
const routes: Routes = [
  {
    path: '',
    component: Tab1Component,
    outlet: "tab1"
  },
  {
    path: '',
    outlet: 'tab2',
    component: Tab2Child1Component
  },
  {
    path: 'tab2-child',
    outlet: 'tab2',
    component: Tab2Child2Component
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  declarations: [Tab2Child1Component, Tab2Child2Component]
})
export class TabModule {}

In the app module redirect directly to the sub path for some reason the redirect in the module does not work if you redirect just to home.
 {
   path: "",
   redirectTo: "/home/hc",
   pathMatch: "full"
 },

Here is a link to a fork of your StackBlitz with the full implementation.
If it is a requirement for you to have separate lazy load modules for each tab then you need to create separate components for each tab that have one router outlet inside to display the tab child components so you get a two level navigation structure. Since I don't know what is your exact use case I cannot say if this would be a better solution.


text:
Q: First element disappearing using Linked Lists in C I am a beginner learning about data structures and Abstract Data Types in C. I am creating a simple linked-list implementation, but when I try to print the list, I seem to lose the first element. The Node type just consists of an integer and a pointer to itself.
My main file
  int main()
  {
     Node * List=createList();

     int testData[] = {1,2,3,4,5,6};

     for (int i = 0 ; i < 6 ; i++)
     {
       addFront(List,testData[i]);
       printList(List);
       printf("\n");
     }

  }

addToFront and its supporting initNode are defined thusly:
 void addFront(Node * List, int value)
 {
    Node * toAdd = initNode(value);

    toAdd-> next = List->next;

    List->next = toAdd;
 }

 Node * initNode(int val)
 {
    Node * newNode = malloc(sizeof(Node));
    newNode -> value = val;
    newNode-> next = NULL;

    return newNode;
 }

EDIT: As per request, printList() is:
  void printList(Node * List)
  {
     Node * original = List->next;

     while (List->next != NULL)
     {
        printf("%d\n",List->value);
        List = List ->next;
     }

     List = original;
  }

Any ideas of what could be wrong?

A: You are adding to the front, yet you are setting the next element in toAdd to List->next. You are skipping the first element.
Furthermore, you are setting List->next to toAdd afterwards.
What you want to do is this:
void addFront(Node** List, int value)
{
    Node * toAdd = initNode(value);
    toAdd->next = *List;
    *List = toAdd;
}

Pass in a pointer to the Node pointer, that allows you to modify the head from within the function.
As per alk's comment, call it this way now: addFront(&List,testData[i]);

A: Assuming that the first node is not used for data but only to point to the rest of the list, most of your code looks ok.  The problem is that you're not printing all the nodes in your list.
Inside printList(), you don't need original since List from the function arguments is local anyway... and you need to break the loop when the node you're looking at is NULL instead of when its next node is NULL (since the while test happens before the loop body).
Here's a shortened and corrected version, which also updates the List pointer inside the while condition instead of before the loop and in the loop body.
void printList(Node * List)
{
   while ((List = List->next) != NULL)
   {
      printf("%d\n",List->value);
   }
}

A: Here's problem in your print list function.you should need to print until current node is not equal to null. i.e in Java I use while loop ..
While (curnode!=null)
*Remember.next not used here because when you use it then your One element will be skip


text:
Q: Assembly Resolve Not Fully Loading My DLL? I'm using a method to load a dll on an AssemblyResolve event.  It's not quite working the way I want it to.  Here's some code:
in my form load:
var a = AppDomain.CurrentDomain;
a.AssemblyResolve += (object sender, ResolveEventArgs args) => LoadDLL(sender, args, anArg);

LoadDLL:
public Assembly LoadDLL(object sender, ResolveEventArgs agrs, bool anArg){
    //Let's just ignore anArg, it doesn't affect anything related to the problem
    asseblyPath = @"XXX";//path to my dll
    return Assembly.LoadFrom(assemblyPath);
}

So that's all well and good.  I set Copy Local to false for my DLL so the AssemblyResolve event is called and I can load the desired version of my DLL.
One strange thing that is happening is this: After running this code, my code tries to access a public variable from a class containing global constant values (this class should be in my DLL).
public class GCV{
    public GCV(){}
    public string value1= "asdf";
}

Unfortunately, when I'm in debug mode, GCV.value1 is set to null when it clearly has a value in the class definition.  This is one symptom that I can describe here, hopefully enough to diagnose the problem?
Thanks!

A: It seems that in debug the version loaded differ from the one it load in release. Try to look in the Output folder when debugging, and look for the Loaded .... to find your dll. This should point to a different version that the one you expect.


text:
Q: Easy to install JACK GUI for Mac OS X Does anyone know of an easy to install GUI for JACK on Mac OS X?

A: Have you tried Jack OS X?  It includes the JackPilot application for controlling the Jack server and managing connections between plugins.
I'm not an OSX user so I can't address how "easy to use" it is.


text:
Q: How to send Json object through java sockets? How do you send Json object's through sockets preferable through ObjectOutputStream class in java this is what I got so far
    s = new Socket("192.168.0.100", 7777);
    ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
    JSONObject object = new JSONObject();
    object.put("type", "CONNECT");
    out.writeObject(object);

But this gives an java.io.streamcorruptedexception exception  any suggestions?

A: Instead of using ObjectOutputStream, you should create an OutputStreamWriter, then use that to write the JSON text to the stream. You need to choose an encoding - I would suggest UTF-8. So for example:
JSONObject json = new JSONObject();
json.put("type", "CONNECT");
Socket s = new Socket("192.168.0.100", 7777);
try (OutputStreamWriter out = new OutputStreamWriter(
        s.getOutputStream(), StandardCharsets.UTF_8)) {
    out.write(json.toString());
}

A: An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a network socket stream, the objects can be reconstituted on another host or in another process.
A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in." You don't need to write primitive data types in binary, so do not use DataOutputStream
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
You need to create an OutputStreamWriter for sending json objects to the client
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
JSONObject obj = new JSONObject();
obj.put("name", "harris");
obj.put("age", 23);
out.write(obj.toString());

You can read the output data from the client using InputStreamReader by this way
InputStreamReader input = new InputStreamReader(socket.getInputStream());
int data = input.read();
while (data != -1) {
    System.out.print((char)data);
    data = input.read();
}


text:
Q: npm audit Arbitrary File Overwrite I recently updated my version of angular using ng update
and when running npm audit it found 1 high severity vulnerability but offered no suggestions on how to resolve it. It usually suggests to upgrade a package from package.json like: "angular-devkit/build-angular" but I am already using their latest version.
                   === npm audit security report ===

                             Manual Review
         Some vulnerabilities require your attention to resolve

      Visit https://go.npm.me/audit-guide for additional guidance

High            Arbitrary File Overwrite

Package         tar

Patched in      >=4.4.2

Dependency of   @angular-devkit/build-angular [dev]

Path            @angular-devkit/build-angular > node-sass > node-gyp > tar

More info       https://npmjs.com/advisories/803

found 1 high severity vulnerability in 29707 scanned packages
1 vulnerability requires manual review. See the full report for details.

I thought of installing npm i tar but I am not sure.

A: The following worked for me:
Go to node_modules > node_gyp > package.json, then locate tar under dependencies and replace 2.0.0 with 4.4.8.
Then run:

*

*npm i

*npm audit

*npm audit fix

*npm audit

you should see 0 vulnerabilities.
I've updated a few angular projects and each project had the same issue. Doing the above worked all the time.

A: angular-cli relies on node-gyp, who have an open issue for this: https://github.com/nodejs/node-gyp/issues/1714
To work around, you can patch node-gyp and then patch angular to use your patched node-gyp. Or wait and hope that they will fix it soon.

A: You should search in your package-lock.json  this:
"tar": {
  "version": "2.2.1",
  "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.1.tgz",

And reemplace for that:
"tar": {
  "version": "4.4.8",
  "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.8.tgz",

That worked for me


text:
Q: 401 authentication error MS Graph with Outlook 365 account I have a website where I can access to outlook accounts. I developed with MS Graph and works properly with my old App (created with a old hotmail account). I can log in and read mails folder.
A new email account have been given to me (an outlook 365 account) in order to config that website with this email account.
Now, when I set the new APP_ID and APP_PASSWORD properties in my code, website launch 401 error.
What is happening? Is anything related Outlook 365 account permission or a MS Graph problem? Have been authetication via MS Graph deprecated?

A: Problem was related with account permissions. I have talked with IT customer to rise permissions account and problem was fixed.


text:
Q: Hover on a link and change the background-image of a div - JQuery I'm having trouble making a div's background-image change when hovering over a link the code looks fine to me so I'm at a loss here is the code:
Javascript:
   $('#hover-01').on('mouseover', function(){
   $('#hover-change').css('background-image', 'url("images/1.jpg")');
});
$('#hover-01').on('mouseout', function(){, function(){
  $('#hover-change').css('background-image', 'url("images/5.jpg")');
});

HTML:

    Bowman Clay

jQuery version: v2.1.1
Any idea's or advice?
Edit: the code does work however it was a problem with a 3rd party plugin (I assume) so I fixed it with normal javascript and not jQuery

A: 'mousein' isn't an event handler that you can use. You should use mouseover and mouseout, or mouseenter and mouseleave. See jQuery mouse events here.
You also need to give a width/height to your container that will hold the image, since it has no contents. Also, you have two function() declarations in your mouseout function, I fixed it in the following code sample:

  $('#hover-01').on('mouseenter', function(){
   $('#hover-change').css('background-image', 'url(http://www.w3schools.com/css/trolltunga.jpg)');
});
$('#hover-01').on('mouseleave', function(){
  $('#hover-change').css('background-image', 'url(https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4)');
});
#hover-change {
  width:1000px;
  height:300px;
}

    Bowman Clay

A: Use this fiddle:
JS:
$('#hover-01').on('mouseenter', function(){
   $('#hover-change').css('background-image', 'url("images/1.jpg")');
});
$('#hover-01').on('mouseout', function(){
  $('#hover-change').css('background-image', 'url("images/5.jpg")');
});

A: You can use jQuery's toggleClass() method to solve your problem like this:

$(document).on('ready', function() {

  $('#link').on('mouseover', function() {
    //alert('sadasd');
    $('body').toggleClass('colored');
  });

  $('#link').on('mouseleave', function() {
    //alert('sadasd');
    $('body').toggleClass('colored');
  });

});
body.colored {
  background-color: #ccc;
}

  This is a Link

Hope this helps!

A: You can use the CSS :hover ~ to change the hover-change div when hover-01 is hovered over as follows:
#divToHover:hover ~ #divToChange {
  /*your code here*/
}

#change {
  height: 300px;
  width: 300px;
  background-image: url("//www.google.com/favicon.ico");
}
#hover {
  height: 40px;
  width: 40px;
  background-color: green;
}
#hover:hover ~ #change {
  background-image: url(/favicon.ico);
}

hover

A: Try the following code. Make sure to set height and width for the div for which you want the background change.
Issue was with your event name used. Refer here for list of mouse events

$('#hover-01').on('mouseover', function() {
     $('#hover-change').css('background-image', 'url("https://placehold.it/350x150/ffff00")');
   }).on('mouseout', function() {
     $('#hover-change').css('background-image', 'url("https://placehold.it/350x150/ff0000")');
   });
.responsive-section-image {
  height: 150px;
  width: 350px;
}

  Bowman Clay


text:
Q: Pickle file to graphML I am trying to visualise large graphs in Gephi and am unsure which format is best to save my graph as. At the moment I am simply creating a pickle file as
with open('stochastic.pickle', 'rb') as handle:
    sto = pickle.load(handle)

However, this format is not supported by Gephi. Having looked through their supported formats I think a graphML format is most versatile.
How can I convert my pickle file to a graphML format?


text:
Q: How to Odoo backup and restore via terminal for different user? I have tow Odoo installed in the same server ubuntu (production - test) every Odoo is with different user.
So i need to write a scripte to make backup from Odoo production with user "production" and restore it in Odoo test with user test.
what i do:

*

*Copy filestore from production and put it for test.

*and then:

*sudo su production

*pg_dump production > test

*dropdb test

*sudo su test

*createdb test

*psql test < test

but when i run Odoo test i can login and see my module but i can't make any changes.
Would you please tell me how to do backup and restore Odoo for different users via terminal ubuntu?
Thank you


text:
Q: Django tastypie POST 400 bad request I have the following problem with Django 1.7 and django-tastypie 0.13.3, upgrading from Django 1.6 and django-tastypie 0.9.14.
urls.py
from relationships.api import RelationResource

v1_api = Api(api_name='v1')
v1_api.register(RelationResource())

In the template this code is called:
var Relationships = Relationships || {};

$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if(options["type"].toLowerCase() != "get") {
        options["contentType"] = "application/json";
        options["data"] = JSON.stringify(originalOptions["data"]);
    }
});

Relationships.Relation = can.Model({
    attributes: {
        id: 'to_int'
    },
    convert: {
        to_int: function(raw) {
            return parseInt(raw);
        }
    },
    models: function(data){
        return data.objects;
    },
    model: function( attributes ) {
        return new this(attributes);
    },

    findAll: "GET /api/v1/relationships/",
    findOne: "GET /api/v1/relationships/{id}/",
    create: "POST /api/v1/relationships/",
    update: "PUT /api/v1/relationships/{id}/",
    destroy: "DELETE /api/v1/relationships/{id}/"
},{
});

Relationships.Button = can.Control({
    init: function(element, options){
    },
    'click': function(el, ev){
        var following = Boolean(el.data('following'));
        var from_user = el.data('from_user');
        var to_user = el.data('to_user');

        var url = '/api/v1/relationships/';
        var from_user_uri = '/api/v1/users/' + from_user + '/';
        var to_user_uri = '/api/v1/users/' + to_user + '/';

        var self = this;
        if(following) {
            Relationships.Relation.findAll({
                'from_user': from_user, 'to_user': to_user}, function(items){
                    if(items.length == 1) {
                        var item = new Relationships.Relation(items[0]);
                        item.destroy(function(){
                        });
                    }
            });
        } else {
            var item = new Relationships.Relation({'to_user': to_user_uri});
            item.save(function(){
            });
        }
    }
});

This gives an error:
POST http://0.0.0.0:8000/api/v1/relationships/ 400 (BAD REQUEST)
Firebug output Post tab

to_user "/api/v1/users/6/"

Response tab

{"relationships": {"to_user": ["Select a valid choice. That choice is
  not one of the available choices ."]}}

This code worked fine with the previous versions of django and tastypie. Any idea what I am missing?


text:
Q: VB datetimepicker format as 09-SEP-2012 I am trying to get datetimepicker to return the date in the following format: 08-SEP-2012.
The returned format will be part of a web address and therefore very specific.
It is set on custom formatting, and I can get the day and year right. only the 3 letter month give me a problem. Maybe there is a very simple solution but I can't find it..
I'm fairly new to Visual Basic (or any programming in general) so any assistance would be greatly appreciated.

A: To convert a date into a string in your required format, use:
Dim s = theDate.ToString("dd-MMM-yyyy").ToUpper()


text:
Q: How Do I Initialize OpenGL.NET with GLFW.Net? I am trying to use OpenGL and GLFW in C#. I Have Installed NuGet Packages for GLFW.Net and OpenGL.Net. What I cannot for my life figure out, is how do I setup the context for OpenGL.Net with GLFW.Net?? No error messages appeared when I tried to run my very basic test OpenGL Code. i.e.
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Glfw.Init();
            GLFWwindow window = Glfw.CreateWindow(1080, 720, "Yeet", null, null);
            Glfw.MakeContextCurrent(window);
            Gl.Initialize();

            uint vao = Gl.CreateVertexArray();
            Gl.BindVertexArray(vao);

            uint vbo = Gl.CreateBuffer();
            Gl.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            Gl.BufferData(BufferTarget.ArrayBuffer, 6, new float[] { -0.5f, -0.5f, 0.5f, -0.5f, 0.0f, 0.5f }, BufferUsage.StaticDraw);
            Gl.VertexAttribPointer(0, 2, VertexAttribType.Float, false, 0, null);

            while (Glfw.WindowShouldClose(window) != 1)
            {
                Glfw.PollEvents();

                Gl.ClearColor(0.0f, 1.0f, 1.0f, 1.0f);
                Gl.Clear(ClearBufferMask.ColorBufferBit);
                Gl.BindVertexArray(vao);
                Gl.EnableVertexAttribArray(0);
                Gl.DrawArrays(PrimitiveType.Triangles, 0, 3);
                Gl.DisableVertexAttribArray(0);
                Gl.BindVertexArray(0);

                Glfw.SwapBuffers(window);
            }

            Glfw.DestroyWindow(window);
            Glfw.Terminate();
        }
    }

But Nothing Renders. Does this mean my Context does not exist or that I have been stupid and left something?

A: On the first glace, I can see an obvious issue. The size of the buffer data has to be specified in bytes (see glBufferData). Hence the size has to be 6*4 rather than 6:
var vertices = new float[] { -0.5f, -0.5f, 0.5f, -0.5f, 0.0f, 0.5f };
Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(4 * vertices.Length),
    vertices, BufferUsage.StaticDraw);

It turns out that the OpenGL.NET library has to be initialized before making the OpenGL Context current (for whatever reason):
Gl.Initialize();
Glfw.MakeContextCurrent(window);

A: All I had to do was move Gl.Initialize() Above Glfw.MakeContextCurrent(window). I guess you have to create the OpenGL context first and then make the context current. This is unlike LWJGL in which one must call GLFW.glfwMakeContextCurrent() before calling GL.createCapabilities().
Hope this helped! :)