text:
Q: Images in a Horizontal StackPanel are being displayed Vertically I am building a layout in Silverlight 4, and am trying to display some thumbnail images horizontally with a horizontal scrollbar. To do this I tried using a StackPanel with Horizontal Orientation, but the resulting images are always displayed Vertically.
<ScrollViewer Height="140" VerticalAlignment="Top" VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Auto">
    <StackPanel Height="140" Orientation="Horizontal">
        <ListBox Height="140" ItemsSource="{Binding SelectedUser.ProfileImages}" />
    </StackPanel>
</ScrollViewer>

The ItemsSource is a List of System.Windows.Controls.Image. To test I am seeding it with 4 thumbnails and setting the size on each to 120x160.
BitmapImage bmpImage1 = new BitmapImage { UriSource = new Uri("Style/Images/thumbnail1.jpg", UriKind.Relative) };
Image image1 = new Image { Source = bmpImage1, Height = 120, Width = 160 };

The resulting page object ends up looking like the image linked below. Height 140, Width 160, but the images are arranged Vertically and not Horizontally. Any ideas how to get these images to display horizontally instead of vertically?
http://img824.imageshack.us/img824/8211/stackpanel.png

A: Rather than trying to manager the ScrollViewer yourself (which ListBox already does) you just need to replace the default ItemsPanel with a Horizontal StackPanel.  Like this:-
<ListBox Height="140" ItemsSource="{Binding SelectedUser.ProfileImages}">
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
</ListBox>


text:
Q: Legend handle to an xarray plot I cannot modify the legend of plot of a dataset made with xarray plotting function.
The code below returns No handles with labels found to put in legend.
import xarray as xr
import matplotlib.pyplot as plt

air = xr.tutorial.open_dataset("air_temperature").air

air.isel(lon=10, lat=[19, 21, 22]).plot.line(x="time", add_legend=True)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

A: You can use seaborn's sns.move_legend(), followed by plt.tight_layout().   sns.move_legend() is new in seaborn 0.11.2.
import xarray as xr
import matplotlib.pyplot as plt
import seaborn as sns

air = xr.tutorial.open_dataset("air_temperature").air

air.isel(lon=10, lat=[19, 21, 22]).plot.line(x="time", add_legend=True)
sns.move_legend(plt.gca(), loc='center left', bbox_to_anchor=(1, 0.5))
plt.tight_layout()
plt.show()

PS: If you don't want to import seaborn, you could copy the function from its source.  You'll need to remove a reference to sns.axisgrid.Grid and import matplotlib as mpl; import inspect:
import matplotlib.pyplot as plt
import matplotlib as mpl
import inspect
import xarray as xr

def move_legend(obj, loc, **kwargs):
    """
    Recreate a plot's legend at a new location.
    Extracted from seaborn/utils.py
    """
    if isinstance(obj, mpl.axes.Axes):
        old_legend = obj.legend_
        legend_func = obj.legend
    elif isinstance(obj, mpl.figure.Figure):
        if obj.legends:
            old_legend = obj.legends[-1]
        else:
            old_legend = None
        legend_func = obj.legend
    else:
        err = "`obj` must be a matplotlib Axes or Figure instance."
        raise TypeError(err)

    if old_legend is None:
        err = f"{obj} has no legend attached."
        raise ValueError(err)

    # Extract the components of the legend we need to reuse
    handles = old_legend.legendHandles
    labels = [t.get_text() for t in old_legend.get_texts()]

    # Extract legend properties that can be passed to the recreation method
    # (Vexingly, these don't all round-trip)
    legend_kws = inspect.signature(mpl.legend.Legend).parameters
    props = {k: v for k, v in old_legend.properties().items() if k in legend_kws}

    # Delegate default bbox_to_anchor rules to matplotlib
    props.pop("bbox_to_anchor")

    # Try to propagate the existing title and font properties; respect new ones too
    title = props.pop("title")
    if "title" in kwargs:
        title.set_text(kwargs.pop("title"))
    title_kwargs = {k: v for k, v in kwargs.items() if k.startswith("title_")}
    for key, val in title_kwargs.items():
        title.set(**{key[6:]: val})
        kwargs.pop(key)

    # Try to respect the frame visibility
    kwargs.setdefault("frameon", old_legend.legendPatch.get_visible())

    # Remove the old legend and create the new one
    props.update(kwargs)
    old_legend.remove()
    new_legend = legend_func(handles, labels, loc=loc, **props)
    new_legend.set_title(title.get_text(), title.get_fontproperties())

air = xr.tutorial.open_dataset("air_temperature").air

air.isel(lon=10, lat=[19, 21, 22]).plot.line(x="time", add_legend=True)
move_legend(plt.gca(), loc='center left', bbox_to_anchor=(1, 0.5))
plt.tight_layout()
plt.show()

redpajama_set_name: RedPajamaStackExchange


text:
Q: the application stopped unexpectedly please try again? When I run below code, it's giving a message that:
 the application stopped unexcepctedlly pleas try again

Any one can help to deal with this problem.
public class TheNewActivity extends Activity {
    /** Called when the activity is first created. */
    int counter;
    Button sub,add;
    TextView display;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        add=(Button) findViewById(R.id.button1);
        display=(TextView) findViewById(R.id.dis);

     add.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            counter++;
            display.setText("your total is"+counter);
        }
    });
     sub.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            counter--;
            display.setText("your total is"+counter);
        }
    });
    }
}

A: you have not instantiated "sub" ....... and you are implementing its onClickListner()

A: You need to add this before setting onClickListener:
sub=(Button) findViewById(R.id.urbtnname);

A: You have not initialized Button sub. Add in your code:
sub=(Button) findViewById(R.id.button2); // if button2 is the id for sub in xml file.

A: Here no  sub button Reference like this add=(Button) findViewById(R.id.button1);
Thanks


text:
Q: Given that matrix $C$ is invertible and $A=CBC^{-1}$, prove that if $A$ is invertible then $B$ is also invertible So far, my working proof is just a basic implication.
Proof: Matrix $A$ invertible implies that there exists a matrix $D$ such that $DCBC^{-1}=I$
I was thinking that I could use the associativity property to prove my result, but I'm not sure how, since $B$ is in between $C$ and $C^{-1}$.

A: An easier proof is to use the following facts about determinants:

For square matrices $A$ and $B$
  $$\det(A) \neq 0 \Leftrightarrow A~ \text{is invertible}$$
  $$\det(AB)=\det(A)\det(B)$$

and also

For an invertible matrix $C$
  $$\det(C^{-1})=\frac{1}{\det(C)}$$

Now, if $A$ is invertible, then $\det(A)\neq 0$
Look at the determinant of the RHS now.  $\det(CBC^{-1})=\det(C)\det(B)\det(C^{-1})$
What can you conclude about $\det(B)$?

For an alternate proof, if you have $A=CBC^{-1}$ then that implies that $B=C^{-1}AC$.
Now, noting that since $A$ is invertible, $A^{-1}$ exists.  Multiplying both sides of the equation on the right by $C^{-1}A^{-1}C$ gives...
Now, use the definition of what it means to be invertible (that there exists a matrix called the inverse such that when multiplied by will produce the identity)

A: More straight forward:
$I = C^{-1}C = C^{-1}IC = C^{-1}AA^{-1}C = C^{-1}CBC^{-1}A^{-1}C = B C^{-1}A^{-1}C = B(C^{-1}A^{-1}C)$
And similarily:
$I = C^{-1}A^{-1}AC = C^{-1}A^{-1}CBC^{-1}C = (C^{-1}A^{-1}C)B$
That is $C^{-1}A^{-1}C$ is the inverse of $B$

A: $$A=CBC^{-1}$$
$$\implies B = C^{-1}AC$$
As each of the component of $B$ is invertable, so $B$ is also invertiable.


text:
Q: How to programmatically output fragmented mp4 file using Bento4 I want to record video conference. I can receive rtp media from video conferencing server. I want to output fragmented  mp4 file format for live streaming. So, how to write a fragmented mp4 file programmatically using Bento4?

A: MP4Box supports DASH. i supply the following simple example:
MP4Box -dash 4000 -frag 4000 -rap -segment-name test_ input.mp4
'-dash 4000' to segment the input mp4 file into 4000ms chunks

'-frag 4000' since frag = dash, actually segments are not fragmented further.

'-rap' to enforce each segment to start random access points, i.e. at keyframes. In such case the segment duration may differ from 4000ms depending on distribution of key frames.

'-segment-name' to specify the pattern of segments names. So in this case, the segments will be named like this: test_1.m4s, test_2.m4s, ...


text:
Q: Изображение не может быть показано, так как содержит ошибки Приветствую всех.
Такой вот парадокс, на FireFox выскакивает данная ошибка. Изображение должно просто сохраняться после генерации. (Да, работает), в других браузерах показывает просто пустое окно. Но, на firefox такая вот штука, с чем это связано? (Ради интереса, хочется узнать, почему так)


text:
Q: Can't run hello world in PL/SQL I am trying to learn PL/SQL, but I cannot run a basic script. At this point I feel there is not a syntax issue, but something basic I'm missing.
BEGIN
dbms_output.put_line('Hello world');
END

When I run it I get an error saying
Error starting at line : 1 in command -
BEGIN
dbms_output.put_line('Hello world');
END

When I run the script I get an error saying:
Error report -
ORA-06550: line 4, column 3:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

   ; <an identifier> <a double-quoted delimited-identifier>
The symbol ";" was substituted for "end-of-file" to continue.
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

If you know what I might be missing let me know.

A: You just need a semicolon and "/" at the end, before you run the script.
BEGIN
dbms_output.put_line('Hello world');
END;
/

Don't forget to "set serveroutput on" to see the actual output.


text:
Q: pre-stratification(blocking) vs post-stratification $Q:$ When should I consider pre-stratification(blocking) vs post-stratification? From experiments, I would certainly consider pre-stratification but post-stratification seems to homogenize the sample after the study.
$Q':$ How do I justify each usage in general? Note that in ANOVA, blocking depends upon the efficiency of blocking. Thus blocking might not be preferred. However, I have never seen justification for post-stratification.


text:
Q: Verilog sync counter module syncounter(qa,qabar,qb,qbbar,overflow,ja,ka,jb,kb,clk,rst);
output qa,qabar,qb,qbbar,overflow;
input ja,ka,jb,kb,clk,rst;
reg qa,qb,qabar,qbbar,overflow;
//var1 = qa;

jkflip jk1(qa,qabar,ja,ka,clk,rst);
assign var1 = qa;
jkflip jk2(qb,qbbar,var1,var1,clk,rst);
always @ (ja,ka,jb,kb)
begin
if(qa & qb)
begin
overflow = 1;
end
end
endmodule

The code for flip flop is
module jkflip(q,qbar,j,k,clk,rst);
input j,k,clk,rst;
output q,qbar;
wire j,k,clk,rst;
reg q,qbar;
always @(posedge clk)
begin
if(rst) q<=~q;
else
begin
case ({j,k})
    2'b00 : q<=q;
    2'b01 : q<=1'b0;
    2'b10 : q<=1'b1;
    2'b11 : q<=~q;
endcase
end
end
endmodule

Testbench for counter
module syncountw();

reg j0,k0,j1,k1,clk,rst;
wire q0,q0bar,q1,q1bar,overflow;
syncounter syn1(q0,q0bar,q1,q1bar,overflow,j0,k0,j1,k1,clk,rst);
always #1 clk = !clk;
//always #1 j0 =1 ;
//always #1 k0 = 1;
initial begin
clk = 1;
j0 = 1;
k0 = 1;
#2
j0 = 1;
k0 = 1;
#2
j0 = 1;
k0 = 1;
#2
j0 = 1;
k0 = 1;
#2
j0 = 1;
k0 = 1;
#2
j0 = 1;
k0 = 1;
#2
j0 = 1;
k0 = 1;
#2
j0 = 1;
k0 = 1;

end
endmodule

I am getting a error called:

 Error (suppressible): (vsim-3053)   C:/Modeltech_pe_edu_10.4/examples/syncounter.v(7): Illegal output or inout port connection for port 'q'.
#    Time: 0 ns  Iteration: 0  Instance: /syncountw/syn1/jk1 File:   C:/Modeltech_pe_edu_10.4/examples/jkflip.v
# ** Error (suppressible): (vsim-3053)   C:/Modeltech_pe_edu_10.4/examples/syncounter.v(7): Illegal output or inout port    connection for port 'qbar'.
#    Time: 0 ns  Iteration: 0  Instance: /syncountw/syn1/jk1 File:   C:/Modeltech_pe_edu_10.4/examples/jkflip.v
# ** Error (suppressible): (vsim-3053)   C:/Modeltech_pe_edu_10.4/examples/syncounter.v(9): Illegal output or inout port   connection for port 'q'.
#    Time: 0 ns  Iteration: 0  Instance: /syncountw/syn1/jk2 File:   C:/Modeltech_pe_edu_10.4/examples/jkflip.v
# ** Error (suppressible): (vsim-3053)   C:/Modeltech_pe_edu_10.4/examples/syncounter.v(9): Illegal output or inout port   connection for port 'qbar'.
#    Time: 0 ns  Iteration: 0  Instance: /syncountw/syn1/jk2 File:   C:/Modeltech_pe_edu_10.4/examples/jkflip.v

A: qa, qb, qabar, & qbbar are declared as reg, they should be wire. The reg type is for signals assigned by procedural blocks (i.e.: initial & always) in the scope of the current module.
var1 is assigned, but never declared.
Change:
reg qa,qb,qabar,qbbar,overflow;
//var1 = qa;

To:
reg overflow;
wire var1;

FYI: you forgot to assign qbar a value


text:
Q: C# Form element with VARIABLE name? #UPDATE:
i have  C# form, that contain 20 textbox element.
Is there a way to select those element by using whats called variable name.

Let imagine this scenario:

 textBox1.Text="foobar";
 textBox2.Text="foobar";
 textBox3.Text="foobar";
 textBox4.Text="foobar";
 textBox5.Text="foobar";
 textBox6.Text="foobar";
 textBox7.Text="foobar";
 textBox8.Text="foobar";
.....

And i wood Something like this:

for(int i=1;i<10;i++){

textBox[i].Text="foobar";

}

A: I get response from @Idle_Mind, great job. that work for me!

for(int i=1;i<10;i++){
this.Controls["textBox" + i].Text = "foobar";
}

it's exactely what i need.


text:
Q: LonglistSelector in scrollViewer not scrollable In my project, I need to show a list of buttons with choices in custommessagebox.
Now, I have no problem in setting it up, but when I create the longlistselector, add it to scrollviewer and show the cusstommessagebox, only a few buttons are shown and i can't scroll for more.
The code I have is following:
    private void btnChronicity_ButtonClicked(object sender, Events.LinkEventArgs e)
    {
        editBox = new CustomMessageBox()
        {
           ....
        };

        ScrollViewer viewer = new ScrollViewer();
        choiceSelector = new Controls.MessageBocChoiceSelectorControl();
        List<items> chronicity = new List<items>();
        foreach (ChronicityModel chronicity in ...Chronicities)
        {
            chronicity.Add(new items(chronicity.Name, chronicity.Selected, chronicity.Id));
        }

        choiceSelector.ItemSource = chronicity;
        editBox.Content = viewer;
        editBox.Show();
    }

and the choiceselector is usercontrol, which looks like:
<StackPanel>
    <Controls:LongListSelector x:Name="LayoutRoot">
        <Controls:LongListSelector.ItemTemplate>
            <DataTemplate>
                <Controls1:CheckableListButton Header1="{Binding Header}"
                                           Selected="{Binding Selected}"
                                           Link="{Binding Link}"
                                           ButtonClicked="CheckableListButton_ButtonClicked"/>
            </DataTemplate>
        </Controls:LongListSelector.ItemTemplate>
    </Controls:LongListSelector>
</StackPanel>

where listbutton is another control, basically button containing several textBlocks, boolean indicating whether it is selected (another style) or not and a string Link, which is returned in custom click event.
The result looks this way:

But the problem is I can't scroll...
Why is it behaving like that? How to fix it?
EDIT:
As I play with the longlistselector and stuff around I have found out that the scrolling works, the problem is the LongListSelector only loads as much items as fits the messagebox instead all of them..... (when i create smaller messagebox, it shows less items, when i create bigger, it shows more)
So the question shifted a bit to:
HOW TO MAKE LONGLISTSELECTOR SHOW ALL OF THE ITEMS INSTEAD OF JUST AS MUCH AS FITS THE SCREEN.

A: So there are three distinct problems I see with the code:

*

*You are creating a new instance of the ScrollViewer in C#, but you are not actually adding the choiceSelector instance to the viewer instance. Not sure if you just left that out in your sample, or you are not actually adding it.

*I would not recommend adding a LongListSelector in a ScrollViewer.... because it already scrolls by default. Your problem is that you're putting the LongListSelector in a StackPanel, which will not constrain the height of the LongListSelector in any way.
Instead I would put the LongListSelector in a Grid control, with the
row height defined as *. This will mean that the Grid height is
constrained to the parent container.

*Having said that, have you looked into the ListPicker control from the http://phone.codeplex.com Toolkit? That seems like it is a little closer to what you are looking for.
HTH

A: This is how I used longlistselector in my code and it works perfectly for me with infinite scrolling.
See if it helps you.
<Grid Background="#FFE6E2E2" Margin="10,10,0,0">
 <phone:LongListSelector x:Name="lb" Margin="0,0,0,0" ItemTemplate="{StaticResource ItemTemplate}"></phone:LongListSelector>
</Grid>

A: Restrict the height of the longlistselector to some 200 or so, which is less than the height of the usercontrol. Make sure you mention the Height = " " property in the xaml of the longlist selector.


text:
Q: Not able to plot a parabola I am making a multiple choice problem.  (Here, I display two of the choices.)  I am trying to plot parabolas using pgfplots.  Why is TikZ not compiling my code?  I put a % in front of the parabolas that I would like plotted so that TikZ will compile the code.
Also, I would like the picture to be flush against the left margin.  I typed \hspace{\fill} after the end of the tikzpicture environment.
\documentclass{amsart}
\usepackage{tikz}
\usetikzlibrary{calc,angles,positioning,intersections}

\usepackage{pgfplots}
\pgfplotsset{compat=1.11}

\begin{document}

\begin{tikzpicture}
%These four commands give commands to draw a rectangle in which the graphs are to be drawn.
\draw[gray,dashed,line width=0.1pt,name path=top] (-6,4.25) -- (6,4.25);
\draw[gray,dashed,line width=0.1pt,name path=right] (6,0) -- (6,4.25);
\draw[gray,dashed,line width=0.1pt,name path=bottom] (-6,0) -- (6,0);
\draw[gray,dashed,line width=0.1pt,name path=left] (-6,0) -- (-6,4.25);

%These commands place the letters indicating the choices.
\node[left] (a) at (-6,4) {$\mathrm{a.)}$};
\node[left] (b) at (1,4) {$\mathrm{b.)}$};

%These commands place the axes for the graphs.
\draw[draw=gray!30,latex-latex] (-3.5,4) +(0,0.5cm) node[above right] {$y$} -- (-3.5,1) -- +(0,-0.5cm);
\draw[draw=gray!30,latex-latex] (-5.5,2) +(-0.5cm,0) -- (-1.5,2) -- +(0.5cm,0) node[below right] {$x$};
%\addplot[samples=201,domain=-3.75:-3.25,blue] {-4*(x + 3.5)^(2) + 1.5};

%These commands plot the second parabola on the Cartesian plane.
\draw[draw=gray!30,latex-latex] (3.5,4) +(0,0.5cm) node[above right] {$y$} -- (3.5,1) -- +(0,-0.5cm);
\draw[draw=gray!30,latex-latex] (1.5,2) +(-0.5cm,0) -- (5.5,2) -- +(0.5cm,0) node[below right] {$x$};
%\addplot[samples=201,domain=-2.75:-2.25,blue] {(x - 3.5)^(2) + 2.5};

\end{tikzpicture}
\hspace{\fill}

\end{document}

A: Here is a partial answer.  You will need to then put this into your context.  Personally, I would build each graphic picture with the standalone class building a 'library' of reusable diagrams.  Then I would just use \inputgraphics to place the graphics where needed.  But this code answers your question.  However, to get the parabolas you will need to properly state the domain and the graphic window. (I leave the math to you.)
\documentclass{amsart}
\usepackage{tikz}
\usetikzlibrary{calc,angles,positioning,intersections}
\usepackage{adjustbox}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}

\begin{document}

a.) \adjustbox{valign=t}{\begin{tikzpicture}[scale=.5]
%These commands plot the second parabola on the Cartesian plane.
\draw[draw=gray!30,latex-latex] (3.5,4) +(0,0.5cm) node[above right] {$y$} -- (3.5,1) -- +(0,-0.5cm);
\draw[draw=gray!30,latex-latex] (1.5,2) +(-0.5cm,0) -- (5.5,2) -- +(0.5cm,0) node[below right] {$x$};
\begin{axis}[axis lines=none]\addplot[samples=201,domain=-2.75:-2.25,blue] {(x - 3.5)^(2) + 2.5};\end{axis}
% axis lines=none comes from pg 219 of the pgfplots documentation
\end{tikzpicture}}%
%
b.) \adjustbox{valign=t}{\begin{tikzpicture}[scale=.5]
%These commands plot the second parabola on the Cartesian plane.
\draw[draw=gray!30,latex-latex] (3.5,4) +(0,0.5cm) node[above right] {$y$} -- (3.5,1) -- +(0,-0.5cm);
\draw[draw=gray!30,latex-latex] (1.5,2) +(-0.5cm,0) -- (5.5,2) -- +(0.5cm,0) node[below right] {$x$};
\begin{axis}[axis lines=none]\addplot[samples=201,domain=-2.75:-2.25,blue] {(x - 3.5)^(2) + 2.5};\end{axis}
\end{tikzpicture}}%
%

c.) \adjustbox{valign=t}{\begin{tikzpicture}[scale=.5]
%These commands plot the second parabola on the Cartesian plane.
\draw[draw=gray!30,latex-latex] (3.5,4) +(0,0.5cm) node[above right] {$y$} -- (3.5,1) -- +(0,-0.5cm);
\draw[draw=gray!30,latex-latex] (1.5,2) +(-0.5cm,0) -- (5.5,2) -- +(0.5cm,0) node[below right] {$x$};
\begin{axis}[axis lines=none]\addplot[samples=201,domain=-2.75:-2.25,blue] {(x - 3.5)^(2) + 2.5};\end{axis}
\end{tikzpicture}}%
%
d.) \adjustbox{valign=t}{\begin{tikzpicture}[scale=.5]
%These commands plot the second parabola on the Cartesian plane.
\draw[draw=gray!30,latex-latex] (3.5,4) +(0,0.5cm) node[above right] {$y$} -- (3.5,1) -- +(0,-0.5cm);
\draw[draw=gray!30,latex-latex] (1.5,2) +(-0.5cm,0) -- (5.5,2) -- +(0.5cm,0) node[below right] {$x$};
\begin{axis}[axis lines=none]\addplot[samples=201,domain=-2.75:-2.25,blue] {(x - 3.5)^(2) + 2.5};\end{axis}
\end{tikzpicture}}%
%

e.) \adjustbox{valign=t}{\begin{tikzpicture}[scale=.5]
%These commands plot the second parabola on the Cartesian plane.
\draw[draw=gray!30,latex-latex] (3.5,4) +(0,0.5cm) node[above right] {$y$} -- (3.5,1) -- +(0,-0.5cm);
\draw[draw=gray!30,latex-latex] (1.5,2) +(-0.5cm,0) -- (5.5,2) -- +(0.5cm,0) node[below right] {$x$};
\begin{axis}[axis lines=none]\addplot[samples=201,domain=-2.75:-2.25,blue] {(x - 3.5)^(2) + 2.5};\end{axis}
\end{tikzpicture}}

\hspace{\fill}

\end{document}

A: Here is a two column enumerate like environment using tasks package.
\documentclass{amsart}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\usepackage[more]{tasks}
\NewTasks[style=enumerate,counter-format=tsk[a]),label-width=1em,item-indent = 1em,column-sep =2em,after-item-skip =3ex]{choices}[\choice](2)
\begin{document}
\begin{choices}
\choice
\begin{tikzpicture}[baseline=(current bounding box.north)]
\begin{axis}[hide axis,width=0.4\textwidth,clip=false]
\addplot[samples=201,domain=-3.75:-3.25,blue] {-4*(x + 3.5)^(2) + 1.5};
\draw[draw=gray!30,latex-latex] (axis cs: -3.5, 1.55) node[below right] {$y$} -- (axis cs: -3.5, 1.25);
\draw[draw=gray!30,latex-latex] (axis cs: -3.85, 1.35) -- (axis cs: -3.15, 1.35) node[below right] {$x$};
\end{axis}
\end{tikzpicture}
\choice
\begin{tikzpicture}[baseline=(current bounding box.north)]
\begin{axis}[hide axis,width=0.4\textwidth,clip=false]
\addplot[samples=201,domain=-2.75:-2.25,blue] {(x - 3.5)^(2) + 2.5};
\draw[draw=gray!30,latex-latex] (axis cs: -2.5, 42.75) node[below right] {$y$} -- (axis cs: -2.5, 35.55);
\draw[draw=gray!30,latex-latex] (axis cs: -2.85, 38) -- (axis cs: -2.15, 38) node[below right] {$x$};
\end{axis}
\end{tikzpicture}
\choice
\begin{tikzpicture}[baseline=(current bounding box.north)]
\begin{axis}[hide axis,width=0.4\textwidth,clip=false]
\addplot[samples=201,domain=-3.75:-3.25,blue] {-4*(x + 3.5)^(2) + 1.5};
\draw[draw=gray!30,latex-latex] (axis cs: -3.5, 1.55) node[below right] {$y$} -- (axis cs: -3.5, 1.25);
\draw[draw=gray!30,latex-latex] (axis cs: -3.85, 1.35) -- (axis cs: -3.15, 1.35) node[below right] {$x$};
\end{axis}
\end{tikzpicture}
\choice
\begin{tikzpicture}[baseline=(current bounding box.north)]
\begin{axis}[hide axis,width=0.4\textwidth,clip=false]
\addplot[samples=201,domain=-2.75:-2.25,blue] {(x - 3.5)^(2) + 2.5};
\draw[draw=gray!30,latex-latex] (axis cs: -2.5, 42.75) node[below right] {$y$} -- (axis cs: -2.5, 35.55);
\draw[draw=gray!30,latex-latex] (axis cs: -2.85, 38) -- (axis cs: -2.15, 38) node[below right] {$x$};
\end{axis}
\end{tikzpicture}
\choice
\begin{tikzpicture}[baseline=(current bounding box.north)]
\begin{axis}[hide axis,width=0.4\textwidth,clip=false]
\addplot[samples=201,domain=-3.75:-3.25,blue] {-4*(x + 3.5)^(2) + 1.5};
\draw[draw=gray!30,latex-latex] (axis cs: -3.5, 1.55) node[below right] {$y$} -- (axis cs: -3.5, 1.25);
\draw[draw=gray!30,latex-latex] (axis cs: -3.85, 1.35) -- (axis cs: -3.15, 1.35) node[below right] {$x$};
\end{axis}
\end{tikzpicture}
\end{choices}
\end{document}


text:
Q: Wordpress Plugin conficts with JQuery/JQMIGRATE and CSS and other plugins when is active I just started my first plugin for wordpress.
The functions runs with Vanilla JS.
When the plugin is activated some kind of conflict is happening with JQuery.
Nothing that needs jquery runs in the website and I see it in browser console that there is problem with every plugin files or wordpress jquery files. (check photo below and see the console with my plugin turned on)

When I turn off my plugin I notice, before anything starts to load, there is something called JQMIGRATE that is installed first and then everything else runs normal. When I turn on my plugin, I don't see any JQMIGRATE on top successfully installed, (check photo below and see the console with my plugin turned off)

I tried to find a way to declare that the file Im loading do not need jquery, cause I believe it tries to run a higher version of jquery and thats why JQMIGRATE is not working well. But I can't find how to declare it, any help? (Below you see how I enqueue the js and css files)
function enqueue_css_js() {
  wp_register_style('adaptivebutton', plugins_url('adaptivebutton.css',__FILE__ ));
  wp_enqueue_style('adaptivebutton');
  wp_register_script( 'adaptivebutton', plugins_url('adaptivebutton.js',__FILE__ ));
  wp_enqueue_script('adaptivebutton');
}

add_action( 'wp_enqueue_scripts','enqueue_css_js');

My conclusion about the JQuery version, came after I notice how the page imports the files. After I noticed the version ( "?ver=6.1.1" ) on the end of each js file.
This is mine:
<script type='text/javascript' src='https://landofgods.eu/wp-content/plugins/adaptivebutton/adaptivebutton.js?ver=6.1.1' id='adaptivebutton-js'>

These was there:
<link rel='prefetch' href='https://landofgods.eu/wp-content/themes/flatsome/assets/js/chunk.tooltips.js?ver=3.16.4' />
<link rel='prefetch' href='https://landofgods.eu/wp-content/themes/flatsome/assets/js/chunk.vendors-popups.js?ver=3.16.4' />
<link rel='prefetch' href='https://landofgods.eu/wp-content/themes/flatsome/assets/js/chunk.vendors-slider.js?ver=3.16.4' />

(CHECKPOINT) Then I tried to change the order of the "add_action" and it worked! JQMIGRATE works again. ( Check how I changed the enqueue function below )
function enqueue_css_js() {
  wp_register_script( 'adaptivebutton', plugins_url('adaptivebutton.js',__FILE__ ));
  wp_enqueue_script('adaptivebutton');
  wp_register_style('adaptivebutton', plugins_url('adaptivebutton.css',__FILE__ ));
  wp_enqueue_style('adaptivebutton');
}

add_action( 'wp_enqueue_scripts','enqueue_css_js', 99);

But now I have problem/conflict with css files, the page loads ( I thing all css files ) but does not apply css properties from all files to pages (all pages). NOTICE: even if I turn off/comment the css enqueue, it still conflict with the other css files


text:
Q: UserControl Location in WPF I am new in WPF, I created a new UserControl MyUserControl.
Now I am surprised: the UserContol does not have a location.
How can I read (by code) myUserControl1.Location in the parent container?
I explain:
I have some Dots (UserControls) that the user can drag in a panel. Actually, I am not sure what kind of Panel this will be... Perhaps Grid.
Now, these dots should be linked with a Line.
Actually, I have a Dot.Head and Dot.Queue properties (also Dots). So, when a Head or Queue is added, I need to dinamically create a link (Line) between them [A]-----[B]. This for this Line I search the Start and End points to set.
Control XAML:
<UserControl x:Class="LinePlan.Stop"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d" d:DesignHeight="21" d:DesignWidth="80">
    <Canvas>
        <Path Fill="LightBlue" Width="16" Height="16">
            <Path.Data>
                <EllipseGeometry x:Name="Dot" Center="8,8"
                    RadiusX="4" RadiusY="4"/>
            </Path.Data>
        </Path>
        <TextBlock x:Name="StopText" Text="Eiffel Tower" Canvas.Left="16"/>
    </Canvas>
</UserControl>

Code:
public partial class Stop : UserControl
{
    private Stop head;
    private Stop tail;
    private LineGeometry headLine;
    private LineGeometry queueLine;

    public Stop()
    {
        InitializeComponent();
    }

    public Stop Head
    {
        get { return head; }
        set
        {
            if (head != value)
            {
                head = value;
                if (head == null)
                {
                    if (headLine != null)
                        headLine = null;
                }
                else
                {
                    headLine = new LineGeometry();
                    headLine.StartPoint = head.DotPosition;
                    headLine.EndPoint = this.DotPosition;

                    // ?? Add this line to the parent
                }

            }
        }
    }

    public Stop Tail
    {
        get { return tail; }
        set { tail = value; }
    }

    public Point DotPosition
    {
        get
        {
            double x = Canvas.GetLeft(this) + this.Dot.Center.X;
            double y = Canvas.GetTop(this) + this.Dot.Center.Y;
            return new Point(x, y);
        }
        set
        {
            Canvas.SetLeft(this, value.X - this.Dot.Center.X);
            Canvas.SetTop(this, value.Y - this.Dot.Center.Y);
        }
    }
}

A: The WPF layout system doesn't use absolute positioning, unless you're placing your controls on a container that supports absolute positioning (typically a Canvas). If you're using a Canvas, you can get or set the position of the control using the Canvas.Left, Canvas.Right, Canvas.Top and Canvas.Bottom attached properties:
double x = Canvas.GetLeft(myControl);
double y = Canvas.GetTop(myControl);

Now, if you want the actual location of the control (relative to its parent), you can use the VisualTreeHelper.GetOffset method:
Vector offset = VisualTreeHelper.GetOffset(myControl);
double x = offset.X;
double y = offset.Y;

A: Elements (like user controls) are normally placed in panels in WPF. Depending on which panel you are using the panel may add some attached properties to the user control. If the user control is placed in a Canvas it will get the attached properties Left, Top, Right and Bottom. However, if the user control is placed in a Grid it will get the attached properties Row and Column (and some more). Other panels like StackPanel will not attach any properties. There is no such thing as a universal user control location.
Panels Overview
Attached Properties Overview
Assuming that you are using a Canvas as your panel you can access the attached Left and Top properties like this:
Double x = Canvas.GetLeft(myUserControl1);
Double y = Canvas.GetTop(myUserControl1);


text:
Q: trying recursion to print a pattern based on arithematic progression in Python I am learning recursive function and have been trying to print a pattern based on arithmetic progression. like:
Input 1: n = 12, k = 5
Output 2: 12, 7, 2, -3, 2, 7, 12
Input 2: n = 10, k =2
Output 2: 10, 8, 6, 4, 2, 0, 2, 4, 6, 8, 10.
I am getting a , and None at the end. like :- 12, 7, 2, -3, 2, 7, 12, None
Here is my code.
# Reading the inputs
n = int(input())
k = int(input())

# Function
def pattern(n,k):

    if (n == 0 or n < 0):
        print(n, end = ", ")

    else:
        # First print decreasing order
        print(n, end = ", ")
        pattern(n - k, k)

        # Then print increasing order
        print(n, end = ", ")

print (pattern(n,k))

A: Although @ggorlen's comment fixes your immediate issue (+1), let's try a different approach.  Rather than print as you recurse, we'll recursively create the list of numbers you desire, return it and then print it:
# Function
def pattern(n, k):

    if n <= 0:
        return [n]

    return [n] + pattern(n - k, k) + [n]

# Reading the inputs
n = int(input())
k = int(input())

print(*pattern(n, k), sep=', ')

Besides simplifying the code, you now have the choice of whether to print the result of pattern() or pass it along to some other code to manipulate further.
> python3 test.py
12
5
12, 7, 2, -3, 2, 7, 12
> python3 test.py
10
2
10, 8, 6, 4, 2, 0, 2, 4, 6, 8, 10
>


text:
Q: Convert the array of object into array in react Convert the array of object into array in react
[{id: 1, Tag_name: "larvel"}, {id: 2, Tag_name: "CSs"},{id:4},{id:5}]

I want this output
["1","2","4","5"]

Plz help me

A: You can use Array.prototype.map
[{id: 1, Tag_name: "larvel"}, {id: 2, Tag_name: "CSs"},{id:4},{id:5}].map((e) => e.id.toString())

A: You can use Array.prototype.map():

The map() method creates a new array populated with the results of
calling a provided function on every element in the calling array.

const array = [{id: 1, Tag_name: "larvel"}, {id: 2, Tag_name: "CSs"},{id:4},{id:5}];
const result = array.map(item => item.id.toString());

console.log(result);
// prints ["1","2","4","5"] to the console

A: const arr = [{id: 1, Tag_name: "larvel"}, {id: 2, Tag_name: "CSs"},{id:4},{id:5}]

let newArr = []

arr.forEach((item)=> {

 newArr.push(item.id.toString())

})

A: const arr = [{id: 1, Tag_name: "larvel"}, {id: 2, Tag_name: "CSs"},{id:4},{id:5}].map(item => item.id.toString());

The short way


text:
Q: How to scale a write intesive application with a SQL Server 2014? I am studying about many databases lately and the one thing I can't get the hang of is how to scale a write intensive application in SQL Server, I'm talking about native features, not third party software. I read about Federated Databases that seems to be something close to this, but I'm not sure if it is the best way since it seems to me that is way more read focused than write focused. I make myself clear that it is just an hypothetical situation and I do not have precise information of budget and pain points, I'm just assuming that I have a write intensive application (let's say 30/70) and I diagnosed that the bottleneck is on the database because it doesn't have enough CPU power and I want to scale with more servers therefore making a cluster, something like Oracle RAC.

A: As you are using SQL Server 2014, you could have a look at In-memory OLTP tables (nee Hekaton).  They are suitable to write-intensive applications and there is a published pattern called Shock Absorber.  Start here.


text:
Q: Deploying to App Service Environment from Azure DevOps We have 1 internal ASE in a subnet. In a different subnet in the same network, we have deployed a Virtual Machine that acts as Azure DevOps Agent Windows v2
We are able to deploy Web Apps manually (using Visual Studio) from a machine that access to this Virtual Network, but cant get deployment working from Azure DevOps.
Here's what we have done

*

*Default NSG rules exist so traffic is enabled on 80/443 ports. Updated NSG to allow traffic to/from: 13.107.6.183 and 13.107.9.183 (checked with all ports)

*Pipeline Task added flag -allowUntrusted
The error we get during deployment is:
More Information: Could not connect to the remote computer ("{myapp}.scm.{customdomain}.com"). On the remote computer, make sure that Web Deploy is installed and that the required process ("Web Management Service") is started.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_DESTINATION_NOT_REACHABLE.
Error: Unable to connect to the remote server
Error: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xx.xx.xx.xx:443
Error count: 1.

Are we missing anything in NSG rules?

A: Internet-based CI systems, such as GitHub and Azure DevOps, will still work with an ILB ASE if the build agent is internet accessible and on the same network as ILB ASE. So in case of Azure DevOps, if the build agent is created on the same VNET as ILB ASE (different subnet is fine), it will be able to pull code from Azure DevOps git and deploy to ILB ASE.
https://learn.microsoft.com/en-us/azure/app-service/environment/create-ilb-ase
You can also follow the detailed steps in this article
Hope this helps!


text:
Q: How two ItemSources can be bound to a ListBox item? I have a case,
    public class dictLanguage
    {
        public string EnglishText { get; set; }
        public string FinnishText { get; set; }
    }

    IEnumerable<dictLanguage> result1 = from ....select new dictLanguage{ EnglishText=... };
    IEnumerable<dictLanguage> result2 = from ....select new dictLanguage{ FinnishText=... };

    LstBox.DataContext = result1

In Xaml, I have
<listbox ItemsSource="{Binding}">
  ...
  <TextBlock Text="{Binding EnglishText}">
  <TextBlock Text="{Binding FinnishText}">
  ...
</listbox>

I am reading English text from one  xml file into "result1" and Finnish text from another xml file into "result2", but I can set only one ItemSource to ListBox. I have tried hard, but can't find out any solution. I want to display both values of "dictLanguage", which are being taken from two different XML files.
Looking for ANY solution,

*

*Either I can merge result1 and result2

*Or, Read the two xml files simultaneouly, which Iamunable toread using "from...select" clause

*Or, Binding both, result1 and result2 to the listbox

*Or, any possible, and better solution

Could anyone tell me the solution please? - Thanks!

A: You could union your two lists together to create one items source:
IEnumerable<dictLanguage> result1;
IEnumerable<dictLanguage> result2;
//populate collections....
IEnumerable<dictLanguage> allResults = result1.Union(result2);

A: You can't bind two ItemsSources to a ListBox. Correct and easy way would be to combine data from 2 xml files into one object set (containing all translations). You can write:
from englishText in xml1
from finnishText in xml2
select new DictLanguage() { EnglishText = englishText, FinnishText = finnishText };

Please, read this link on more info for combining multiple sources.


text:
Q: Filtering Look up Columns with Javascript I'm trying to find a way to dynamically filter a look up column on the new and edit forms in SharePoint 2013.
I want to be able to get a value from the URL and use that to filter the look up choices. Something like, only show choices where "column A" equals "Value from URL"
Has anyone ever done this? or know of any references i can use? I do not want to filter the choices based on another column which seems to be the common question people ask.

A: Since CSR is the default rendering mode in SharePoint 2013, I would recommend the following approach to manipulate form fields in New/Edit Form page. As an introductory please follow this article Introduction to Client Side Rendering in SharePoint 2013.
Suppose a Tasks list that contains a Task Category lookup field. Then the following rendering template could be used for setting TaskCategory lookup field value retrieved from a query string parameter named cat:
(function () {
    var ctx = {};
    ctx.Templates = {};
    ctx.Templates.Fields = {
        'TaskCategory': {
            'NewForm': renderTaskCategory
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();

function renderTaskCategory(ctx) {
    var catId = GetUrlKeyValue('cat'); //extract cat parameter from a query string
    ctx.CurrentFieldValue =  catId; //set lookup field value
    return SPFieldLookup_Edit(ctx); //default template for rendering Lookup field control
}

How to apply changes
In order to apply the changes we need to set the JSLink property of XLV web part:

*

*First of all, let's save this JS template and name it Tasks.js. Then upload the specified into SharePoint Site Assets library

*open New Form page in Edit mode and go to web part properties

*find under Miscellaneous group JSLink property and specify its value:
~sitecollection/SiteAssets/Task.js as shown on figure below

Result

Parse query string in SharePoint 2013
SharePoint JS Library contains GetUrlKeyValue function for extracting query string parameter, for example:
var itemId = GetUrlKeyValue('ID'); //get Item Id from query string

A: I ended up finding what i needed with SPServices. I used the filter drop down function, Code below.
http://spservices.codeplex.com/wikipage?title=%24%28%29.SPServices.SPFilterDropdown
$().SPServices.SPFilterDropdown({
         relationshipList: "{*List ID*}",
         relationshipListColumn: "*column Name*",
         columnName: "*Column Nam*e",
         CAMLQuery: "**CAML QUERY**",
         completefunc: null,
         debug: true
    });

A: The Jquery code below reads the query string value and prepopulates the lookup field.
 $(document).ready(function () {
        JSRequest.EnsureSetup();
        var dropDownValue = JSRequest.QueryString['AccountReference'];
        if (dropDownValue) {
            $("select[title='External Client Account']").children("option").each(function () {
                if ($(this).text() == dropDownValue) {
                    $(this).attr('selected', 'selected');
                }
            });
        }
    });

Source: http://www.sharepointnadeem.com/2014/10/sharepoint-pre-populate-lookup-field-in.html


text:
Q: Make inserted Matplotlib plot have the correct dimensions I want to do a scatter plot on matplotlib with:
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4,  5])
y = np.array([1.1, 2.2, 3.2, 4.2, 5.2])
param = np.polyfit(x, y, 1)
x_linspace = np.linspace(min(x), max(x), 100)
y_fit = param[0] * x_linspace + param[1]

fig, ax = plt.subplots(1, 1)
ax.scatter(x, y)
ax.plot(x_linspace, y_fit, '--')

Now I want to insert a plot  showing the slope of the curve as:
ax2 = fig.add_axes([0.675, 0.135, 0.2, 0.2])
ax2.plot([0, 2, 2,0], [0,2,0,0], color="k", linewidth=2) # slope 2
ax2.plot([0, 2, 2,0], [0,4,0,0], color="k", linewidth=2) # slope 1
ax2.axis('off')
ax2.text(2.01, 3.75, "2", fontsize=20)
ax2.text(2.01, 1.75, "1", fontsize=20)

How can I make the slopes of the insert match with the main plot?

A: If I understand correctly, you want to show reference gradients with the little triangles, so that you can compare the slope a of the line fit to the data.
Personally I find fiddling about with different scales mentally challenging, so my instinct is to use an undistorted Cartesian plane using ax.axis('equal').
I think this works:
import matplotlib.pyplot as plt
import numpy as np

# Make data.
x = np.array([1, 2, 3, 4,  5])
y = np.array([1.1, 2.2, 3.2, 4.2, 5.2])

# Fit the model.
a, b = np.polyfit(x, y, 1)
x_linspace = np.linspace(min(x), max(x), 100)
y_fit = a * x_linspace + b

# Make the plot.
fig, ax = plt.subplots(1,1)

ax.scatter(x,y)
ax.plot(x_linspace, y_fit, '--')
ax.axis('equal')
ax.grid(c='k', alpha=0.2)

ax2 = fig.add_axes([0.675, 0.135, 0.25, 0.25])
for slope in (0.5, 1, 2):
    ax2.plot([0, 1, 1, 0], [0, slope, 0, 0], color="k", linewidth=2)
    ax2.text(1.1, slope, slope, fontsize=12, va='center')
ax2.axis('off')
ax2.axis('equal')

plot.show()

I generalized the slopes a bit so you can add more or fewer.

A: To be honest I do not like the equal axis approach.
I checked the size of the bounding box and placed it in a scaled fashion.
Thanks for the note on the for loop for plotting multiple slopes
a = ax.get_position()
a = a.get_points()

#scale down to 20%
a = a*0.2
# Plot slope scale

ax2 = fig.add_axes([0.675, 0.135, a[1][0], a[1][1]])

for slope in (0.5, 1, 2):
    ax2.plot([0, 1, 1, 0], [0, slope, 0, 0], color="k", linewidth=2)
    ax2.text(1.1, slope, slope, fontsize=12, va='center')
    ax2.axis('off')

Would you be so kind as to cross-check it?


text:
Q: why does this recursive program for factorial not work? Below is the code, please pin point exactly where i am wrong.
I have declared, defined the function, i don't know what is wrong.
#include<stdio.h>
int factorial(int b); /* Declaration */

int main()
{
    int num;
    printf("Enter number: ");
    scanf("%d", &num);
    printf("%d",factorial(num));
    return 0;
}

int factorial(int b) /*Function definition*/
{

    return b*factorial(b-1);

}

A: You need to end the recursion at some point:
int factorial(int b) /*Function definition*/
{
    if (b == 0) return 1;
    return b*factorial(b-1);

}


text:
Q: How to find whether a sting have "UKV-IVAKVDT4" this pattern I have a random string. So if a string contains this "UKV-IVAKVDT4" it returns true or false. How do i write regex for find this pattern. In "UKV-IVAKVDT4" the first three character may change for every user. What i want is i just find whether a string contains this pattern or not?

A: based on your comment, this should do the trick: ([A-Z0-9]{3})-([A-Z0-9]{8})

A: This should do the trick:
/[A-Z]{3}-[A-Z0-9]{8}/
For javascript it would be:
text.match(/[A-Z]{3}-[A-Z0-9]{8}/)

A: Try this.
function TestString(stringToTest)
{
    return stringToTest.match("[A-Z]{3}-IVAKVDT4")!=null ? true: false;
}

For building regular expressions go through this article.
http://www.codeproject.com/Articles/9099/The-Minute-Regex-Tutorial
[EDIT]
  Answer for your question. "How to use it in Php"
<?php
   $str = "The user ticket id is UKV-IVAKVDT4.Use this for future use";
   $match=  array();
   if(preg_match("/[A-Z]{3}-IVAKVDT4/", $str,$match))
    {
        print_r(array_values($match));
    } else
    {
        print 'No Match found';
    }
?>

A: You can give a try to the following regEx
var matched = false;
var testRegEx = /^([A-Za-z0-9]{3})[\-]{1}([A-Za-z0-9]{8})$/i;
matched = testRegEx.test("your input string")


text:
Q: How to fix a div background image hidden behind other divs in IE7 and IE8 I have the following code...
HTML:

         //slide content

         //slide content

CSS:
#gallery {
   width: 940px;
   height: 317px;
   background: transparent url("../images/banner_bg.png") no-repeat scroll right 0;
   position: relative;
}

I have tried this with .png .gif and .jpg images for background, same result.
The problem is that in IE7 the slideshow div covers the background image from the gallery div. I know this because if I set the opacity of the slideshow div to 80 or less I can see the background image shining through.
The page looks great in firefox, chrome, safari and opera. This is only a problem in IE7 and IE8.
Does anybody know how to fix this? I have spent hours googleing this and have tried everything I came across no matter how unlikely it sounded. I have not been able to find a solution.
(Please help, this is making me insane)

A: I found the problem...
The slide divs were getting their background color set to black and I am assuming that this is an IE interpretation because
1) it was not happening in other browsers and
2) I could not find anywhere in the code where it would have set the bg color to black.
The CSS fix was simple:
#gallery #slideshow div { background-color: transparent !important; }

I did have to add the !important to the end or it would overwrite my style.


text:
Q: How to execute custom sql code in every transaction managed by spring DataSourceTransactionManager? Consider situation in which we have tons of java DAO classes managed by Spring. Every method defined in those beans executes SQL code in Spring's Datasource transaction, defined by annotation on a method. Now we have a requirement to run some custom code just before target execution of mentioned methods, this code MUST be executed in the same transaction as defined by annotation on target method.
Update based on R4J comment:
My proxy for DAO calls which should call procedure PR_Adm_Set_Usr in transaction of every target call in DAO package:
@Aspect
@Order(1000)
@Component
public class DaoProxy {

    private static final Logger logger = LoggerFactory.getLogger(DaoProxy.class);
    @Autowired
    private ContextDAO contextDAO;
    @Autowired
    private DataSourceTransactionManager txManager;

   @Before("execution(* xx.yy.dao.*.*(..)) xx.yy.core.dao.*.*(..))")
    @Transactional(propagation = Propagation.SUPPORTS)
    public void setContext() throws Throwable {
        JdbcTemplate jdbc = new JdbcTemplate(txManager.getDataSource());
        if(SecurityContextHolder.getContext()!=null &&
                SecurityContextHolder.getContext().getAuthentication()!=null &&
                SecurityContextHolder.getContext().getAuthentication().getPrincipal()!=null){
            SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbc)
                    .withProcedureName("PR_Adm_Set_Usr")
                    .withoutProcedureColumnMetaDataAccess().declareParameters(
                            new SqlParameter("user", OracleTypes.VARCHAR));
            jdbcCall.setAccessCallParameterMetaData(false);
            MapSqlParameterSource params = new MapSqlParameterSource()
                    .addValue("user",  SecurityContextHolder.getContext().getAuthentication().getName()  );
            jdbcCall.execute(params);
        }else{
            logger.warn("No context available!!!");
        }
    }
}

Example DAO call in SomeDAO class:
 @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Object shiftDate(Long fileId, Long interval) {
        String a=null;
        a.toString();
        JdbcTemplate jdbc = new JdbcTemplate(txManager.getDataSource());
        SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbc)
                .withCatalogName("somepackage")
                .withProcedureName("someprocedure")
                .withoutProcedureColumnMetaDataAccess()
                .declareParameters(
                        new SqlParameter("p_file_id", OracleTypes.NUMBER),
                        new SqlParameter("p_interval", OracleTypes.NUMBER)
                );
        jdbcCall.setAccessCallParameterMetaData(false);
        MapSqlParameterSource params = new MapSqlParameterSource()
                .addValue("p_file_id", fileId)
                .addValue("p_interval", interval);
        jdbcCall.execute(params);
        return null;

    }

As You can see, first two lines in DAO call cause NullPointerException, which should cause rollback on AOP setContext() method.
Unfortunately this was not working till I added order to my  tag in my context config.
<tx:annotation-driven order="1"/> solved the problem.


text:
Q: Forge Offline Latest Version *7 Js and Css file Where i need to found For Mobile devices Android,IOS I am Looking for Javascript(Viewer3D.js) and style.css  *version 7 file For Mobile devices
please share the link or suggest any alternate solution to get those thinks
Advance Thanks you

A: Running the viewer on mobile is not different than running the viewer in a navigator. All you need is a webview. Note as well that the viewer has a EULA which I am copying here for your convenience which does not allow to use it as a copy (see last paragraph).
The URL to access the viewer are https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.js
https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/style.css
For sure, if there is good reasons to make a copy of the viewer locally, please contact autodesk at forge.help @ autodesk.com and explain what are these reasons.
/*!
 * LMV v7.30.1
 *
 * Copyright 2020 Autodesk, Inc.
 * All rights reserved.
 *
 * This computer source code and related instructions and comments are the
 * unpublished confidential and proprietary information of Autodesk, Inc.
 * and are protected under Federal copyright and state trade secret law.
 * They may not be disclosed to, copied or used by any third party without
 * the prior written consent of Autodesk, Inc.
 *
 * Autodesk Forge Viewer Usage Limitations:
 *
 * The Autodesk Forge viewer can only be used to view files generated by
 * Autodesk Forge services. The Autodesk Forge Viewer JavaScript must be
 * delivered from an Autodesk hosted URL.
 */


text:
Q: "Proper" way to handle signals other than SIGINT in Python? I had some Python code that needed to be able to handle SIGINT. For this purpose I used something like this:
def mymethod(*params):
  obj = MyObj(params)
  try:
    obj.do_some_long_stuff()
  except KeyboardInterrupt:
    obj.cleanup()

Awesome and really straightforward. Yay, Python is great!
However, I now need to also handle other signals, namely SIGTSTP and SIGQUIT. What I'm trying to do is something similar. Here's some pseudocode demonstrating what I'm trying to do with SIGTSTP (I hope it's clear enough):
def mymethod(*params):
  obj = MyObj(params)
  try:
    obj.do_some_long_stuff()
  catch SIGINT:
    obj.cleanup()
  catch SIGTSTP:
    log_stop(obj) # Log that we stopped obj (add info about stop signal happening in obj-specific log file )
    raise SIGTSTP # Do normal SIGTSTP behavior as if we didn't catch the signal

It seems that the way to go here is to use the signal module. However, my problem is that I can then can't access the object state anymore as I could with the KeyboardInterruptException:
import os
import signal

def handler(signum, frame):
  print "I can't access obj from here anymore!" # How to access obj from here?
  signal.signal(signum, signal.SIG_DFL)
  os.kill(os.getpid(), signum) # Rethrow signal, this time without catching it

def mymethod(*params):
  obj = MyObj(params)
  signal.signal(signal.SIGTSTP, handler)
  obj.do_some_long_stuff()

So how can I solve this, i.e. handle the signal while still having some access to the object I'm working with?

A: Or use a closure:
import os
import signal

def create_handler(obj):
    def _handler(signum, frame):
        print "obj is availiable here!"
        print obj
        signal.signal(signum, signal.SIG_DFL)
        os.kill(os.getpid(), signum) # Rethrow signal, this time without catching it
    return _handler

def mymethod(*params):
  obj = MyObj(params)
  signal.signal(signal.SIGTSTP, create_handler(obj))
  obj.do_some_long_stuff()

create_handler(obj) returns a handler function with access to obj.

A: That would work under the condition that handler is a class-method and contains the self-member.
You could make obj global, since than you can access it from each function.
import os
import signal
obj = None

def handler(signum, frame):
    log_stop(obj)
    signal.signal(signum, signal.SIG_DFL)
    os.kill(os.getpid(), signum) # Rethrow signal, this time without catching it

def mymethod(*params):
    global obj # to signal that the obj we are changing here is the global obj

    obj = MyObj(params)
    handler.obj = obj
    signal.signal(signal.SIGTSTP, handler)
    obj.do_some_long_stuff()

(Note: Personally I avoid global parameters as much as possible, since global means really global).


text:
Q: How to change input name background? When I click the mouse on input, Drop down the mailing list, When I bring the mouse to Miles Is changing input background. As shown in the photo.
How to remove or change this time input background?

I have already tried "focus", But it didn't work.
<input type="email" name="email" placeholder="Email">

    input {
        background: none;

        &:focus {
            background: none;
        }
    }

A: For Google chrome you can do the following:

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active  {
    -webkit-box-shadow: 0 0 0 30px white inset !important;
}
<input type="text" name="name">

Replace white for the desired color. I took this snippet from this SO answer. It should also be a good idea to take a deeper look into that SO question has there are slightly different solutions that might work better for you.
Keep in mind that this is non standard and its use should be avoided but for now, this is what you can do.
Ref: MDN

A: input:hover {
   background-color: #fff;
}


text:
Q: Build project file with premake4 - how to? Based on http://arcsynthesis.org/gltut/Building%20the%20Tutorials.html - the book Im reading to learn openGL, I need to build my file projects with premake4. The book says:
"The SDK his library uses Premake to generate its build files. So, with premake4.exe in your path, go to the glsdk directory. Type premake4 plat, where plat is the name of the platform of choice. For Visual Studio 2008, this would be "vs2008"; for VS2010, this would be "vs2010." This will generate Visual Studio projects and solution files for that particular version."
So, I've put the premake4.exe file inside but the problem is: When I execute it, one black command window shows up for a few ms, then fades and nothing happens.
I made one research on google about how to work with premake4 but I couldnt find nothing useful, even here on stack or you tube. Anyway, This seems weard since premake4 is really known, then I ask: Does anyone know what Im missing or could point me to somewhere which I can understand how to build my openGL "sdk" files?
Im using premake 4.3 with Windows 8.
Edit: I just found someone with the same problem - but the solution isnt really applying for me: Can't get premake working - gltut demos
Edit 2: Found once again someone with the same problem, but this no solution on the topic and also the OS is different from mine.. http://industriousone.com/topic/terminal-logout-when-running-premake4exe

A: As it says in the documentation you quoted:

Type premake4 plat, where plat is the name of the platform of choice. For Visual Studio 2008, this would be "vs2008"; for VS2010, this would be "vs2010."

Just running it with no arguments (which is what double-clicking on it does) is not sufficient. You need to open a command prompt, cd to the directory the project is in, and then run premake4 vs2008 (replacing vs2008 with the name of the platform you're targeting).
The most recent version of Visual Studio supported by Premake is 2010, so for later versions, you'll still have to use premake vs2010 - later versions of VS should still be able to load the project.

A: ToxicFrog's answer was extremely helpful, but just to be a little more blunt and clear about the answer for someone who might not how to use the command prompt very well.

*

*Place 'premake4.exe' inside your 'glsdk directory (file).

*In Windows, hold down the 'Shift' key and right-click the glsdk directory.

*Select "Open Command window here" from the drop-down box .

*Type premake4 vs2010 (or whichever platform you are using. For example, if you are using Visual Studio 2013, use vs2013 for your platform.).

Note: According to ToxicFrog and Victor Oliveira the platform vs2010 is the highest it will support .  However, I recently tried it with vs2012 and it worked just fine).


text:
Q: Create a new object and call a method spring configuration Is there a short cut way to implement the following functionality in Spring xml configuration file.
new MyObject().getData()

instead of
Object obj = new MyObject();
obj.getData();

I know how to do it in 2nd case.
<bean id="obj" class="MyObject" />

<bean id="data" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
      <property name="targetObject"><ref local="obj" /></property>
      <property name="targetMethod"><value>getData</value></property>
 </bean>

I am sure there must be a way to do this in a single definition. Please suggest.

A: Have you considered using an anonymous bean in your MethodInvokingFactoryBean?
<bean id="data" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject"><bean class="MyObject" /></property>
    <property name="targetMethod"><value>getData</value></property>
</bean>

This is basically equivalent to what you have, except for the fact that there is no intermediate bean definition.  I am not sure whether or not the MyObject instance will be in your ApplicationContext, though, so if you need it there, you may want to look into that.

A: You could try with @Autowire.
In the classes where you need the MyObject bean, you could use something like this:
public class MyClass {

      @Autowire
      MyObject myObject;

      public void myMethodofMyClass(){
         myObject.oneMethodOfMyObject();
      }

}

You can find more info in the spring reference manual (page 54).


text:
Q: ANTLRv4 : Read double quotes escaped with both \ and " I'm trying to implement a parser using ANTLRv4 for a language that accepts both "" and \" as a way escaping " characters in " delimited strings.
The answers to this question show how to do it for "" escaping. However when I try to extend it to also cover the \" case, it almost works but becomes too greedy when two strings are on the same line.
Here is my grammar:
grammar strings;
strings : STRING (',' STRING )* ;

STRING
 : '"' (~[\r\n"] | '""' | '\"' )* '"'
 ;

Here is my input of three strings:
"This is ""my string\"",
"cat","fish"

This correctly recognises "This is ""my string\"", but thinks that "cat","fish" is all one string.
If I move "fish" down on to the next line it works correctly.
Can anyone figure out how to make it work if "cat" and "fish" are on the same line?

A: Make your STRING rule non greedy to stop at the first quote char it encounters, instead of trying to get as much as possible:
STRING
 : '"' (~[\r\n"] | '""' | '\"' )*? '"'
 ;

A: I've found what I need to do to get this to work as I wanted, though to be honest I'm still not entirely sure why Antlr was doing what it did.
Simply by adding another backslash character to the '\"' clause it works!
So my final STRINGS definition is : '"' (~[\r\n"] | '""' | '\\"' )* '"'
Going back to first principles, I hand drew a state transition diagram of the problem and then realised that the two escaping mechanism sequences are not the same and cannot be treated similarly. Then trying to implement the two patterns in AntlrWorks it became apparent that I needed to add the second backslash at which point it all started working.
Does a single backslash followed by some arbitrary character simply mean that character?


text:
Q: Show that there exists $\alpha$ such that $f(x) = \alpha x^2$ for all $x\in \mathbb{R}$. Problem:

Let $f$ be a real valued continuous function on $\mathbb{R}$ . Suppose that
  $$f(x+y) + f(x-y) = 2[f(x)+f(y)]$$
  for any $x,y\in \mathbb{R}$. Show that there exists $\alpha$ such that $f(x) = \alpha x^2$ for all $x\in \mathbb{R}$.

My attempt:
Frankly, I'm not really sure where to begin. I can rewrite the problem as
$$\frac{f(x+y) + f(x-y)}{f(x)+f(y)} = 2$$
which looks a little bit like the Lipschitz condition. Also, it seems like a clever substitution is going to happend with $f(x-y)$ and $f(x+y)$. Beyond that I can't really get a hold on the problem. Any hints or suggestions?

A: It's not true,  unless you impose an additional requirement such as continuity or measurability.  Suppose $g$ is a nonlinear solution to the Cauchy functional equation (i.e. $g(x+y) = g(x) + g(y)$) but it is not of the form $g(x) = cx$).  Then
 $f(x) = g(x^2)$ satisfies your equation but is not of the required form.

A: Consider $$\lim_{h\to 0}\frac{f(x+h)+f(x-h)-2f(x)}{h^2}=\lim_{h\to 0}\frac{2f(x)+2f(h)-f(x)}{h^2}=\lim_{h\to 0}\frac{2f(h)}{h^2}.$$ Note that if this limit exists, it is equal to $f''(x)$, which is thus constant.
Notice that if we take $y=0$, we obtain $2f(x)=2f(x)+2f(0)$, so $f(0)=0$. Further, consider $x=y=h/2$, and so we obtain $f(h)+f(0)=4f(h/2)$, and thus $$\frac{f(h)}{h^2}=\frac{4f(h/2)}{h^2}=\frac{f(h/2)}{(h/2)^2}.$$ By the continuity of $f$, we have $$\lim_{h\to 0}\frac{f(h)}{h^2}=\lim_{n\to\infty}\frac{f(2^{-n})}{2^{-2n}}=\lim_{n\to\infty}\frac{f(1)}{1}=f(1).$$ Thus, $f$ is second differentiable, and $f''(x)=2f(1)$ for all $x$. It follows that $f(x)=f(1)x^2+cx$ for some constant $c$. Note that $$f(x+y)+f(x-y)=2f(1)(x^2+y^2)+2cx$$ and $$2(f(x)+f(y))=2f(1)(x^2+y^2)+2cx+2cy.$$ Since the two above equations must be equal, we have $2cy=0$ for all $y$, and thus $c=0$.
Thanks to @Ivan for the difference quotient idea.


text:
Q: is DOMCORE v3 still compatible with PHP 5? I use DOMCORE v2 on PHP5 server and I saw that DOMCORE v3 is compatible with PHP7. Is it still compatible with PHP 5 ? is it safe to upgrade ?

A: Yes, the domcore is fully compatible backwards with PHP 5.2- (no traits), PHP 5.3+ (traits) and PHP7 (use of \Error throwable instead of \Exeption)

*

*Phil


text:
Q: OpenMP Matrix Multiplcation Critical Section I am trying to parallelize just the innermost loop of matrix multiplication. However, whenever there is more than 1 thread, the matrix multiplication does not store the correct values in the output array, and I am trying to figure out why.
void matrix() {
int i,j,k,sum;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++){
        sum = 0;
        #pragma omp parallel for shared(sum,i,j) private(k)
            for (k = 0; k < N; k++) {
                #pragma omp critical
                    sum = sum + A[i][k] * B[k][j];
            }
        C[i][j] = sum;
    }
}
}

I also tried using:
void matrix() {
int i,j,k,sum;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++){
        sum = 0;
        #pragma omp parallel for shared(sum,i,j) private(k)
            for (k = 0; k < N; k++) {
                #pragma omp atomic
                    sum += A[i][k] * B[k][j];
            }
        C[i][j] = sum;
    }
}
}

But that didn't work either. I also tried it without the second #pragma, and with:
void matrixC() {
int i,j,k,sum,np;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++){
        sum = 0;
        #pragma omp parallel for reduction(+:sum)
            for (k = 0; k < N; k++) {
                    sum = sum + A[i][k] * B[k][j];
            }
        C[i][j] = sum;
    }
}
}

I'm new to OpenMP but from everything I've read online, at least one of these solutions should work. I know its probably a problem with the race condition while adding to sum, but I have no idea why it's still getting the wrong sums.
EDIT: Here is a more complete version of the code:
double A[N][N];
double B[N][N];
double C[N][N];
int CHOOSE = CH;

void matrixSequential() {
int i,j,k,sum;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
        sum = 0;
        for (k = 0; k < N; k++) {
            sum += A[i][k] * B[k][j];
        }
        C[i][j] = sum;
    }
}
}

void matrixParallel() {
int i,j,k,sum;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++){
        sum = 0;
        #pragma omp parallel for shared (i,j) private(k) reduction(+:sum)
            for (k = 0; k < N; k++) {
                sum = sum + A[i][k] * B[k][j];
            }
        C[i][j] = sum;
    }
}
}

int main(int argc, const char * argv[]) {
//populating arrays
int i,j;
for(i=0; i < N; i++){
    for(j=0; j < N; j++){
        A[i][j] = i+j;
        B[i][j] = i+j;
    }
}

for(i=0; i < N; i++){
    for(j=0; j < N; j++){
        C[i][j] = 0;
    }
}

if (CHOOSE == 0) {
    matrixSequential();
}
else if(CHOOSE == 1) {
    matrixParallel();
}

//checking for correctness
double sum;
for(i=0; i < N; i++){
    sum += C[i][i];
}
printf("Sum of diagonal elements of array C: %f \n", sum);
return 0;
}

A: Making sum a reduction variable is the right way of doing this and should work (see https://computing.llnl.gov/tutorials/openMP/#REDUCTION).  Note that you still have to declare your shared and private variables, such as k.
Update
After you updated to provide a MVCE, @Zboson found the actual bug: you were declaring the arrays as double but adding them as int.

A: IEEE Floating point arithmetic is not associative i.e. (a+b)+c is not necessarily equal to a+(b+c). Therefore the order you reduce an array matters. When you distribute the array elements among different threads it changes the order from a sequential sum. The same thing can happen using SIMD. See for example this excellent question using SIMD to do a recution: An accumulated computing error in SSE version of algorithm of the sum of squared differences.
Your compiler won't normally use associative floating point arithmetic unless you tell it. e.g. with -Ofast, or -ffast-math, or -fassocitaive-math with GCC. For example in order to use auto-vectoirization (SIMD) for a reduction the compile requires associtive math.
However, when you use OpenMP it automatically assumes associative math at least for distributing the chunks (within the chucks the compiler still won't use associative arithmetic unless you tell it to) breaking IEEE floating point rules. Many people are not aware of this.
Since the reduction depends on the order you may be interested in a result which reduces the numerical uncertainty. One solution is to use Kahan summation.


text:
Q: MOSFET Over Heating. So hot it's melting the solder Alright, continuing with the debugging of my new board tonight I found another issue worse than the one before: My switching MOSFET is getting so hot that I'm getting molten solder.
I replaced the MOSFET with a short circuit just to see if the components sorounding the MOS were the cause of the problem (mostly a big Inductor I have right next to it) but the copper reaches a temperature of 110°F, not enough to melt solder.
This is my schematic:

As you can see, my VGS is around -11V and I'm running 3A through it using an Electronic Load. Based on the datasheet of my NTD20P06L-D this thing can do up to 15.5A.
Any ideas of what might be going on?
The only thing I could think of was that the heat on the copper could be increasing RDS(on) but at that particular low current it shouldn't be so serious.
I am using the TO-252-3, DPak (2 Leads + Tab) package.

A: It sounds like you need a heatsink.
Another thing to check is your gate voltage when you have the FET switched on. If your Gate-Drain voltage is too high, the MOSFET may not be properly biased on, a situation which would generate a lot of heat.
Also, how often is this switching? Is it a steady-state thing, or is this part of a switching supply? If it's a switching supply,  you will also need to look at the rate at which the system switches.

Anyways, assuming you have everything biased properly (probably a safe assumption, but measure it anyways):
RDS(on) = 130mΩ @ G-D voltage of 5V
So, with 130 mΩ in series with 3A:
$$V = 0.130 * 3$$
$$V = 0.39$$
$$Power = V * A$$
$$Power = 0.39 * 3$$
$$Power = 1.17W$$
So you're going to be dissipating 1.17W of power in the MOSFET, in the best-case situation.
That will get very toasty without a heatsink. If you're just running this as a bare TO-220 device, it getting extremely hot isn't too suprising.

So, assuming we have a TO-220 in free-air:

TO-220 junction-to-air thermal to ambient equals 62.5 degree per watt.

(From here)
Therefore:
$$Δ°C = 62.5 * 1.17$$
$$Δ°C = 73.125$$
$$Device Temperature °C = 73.125 + Ambient$$
$$Device Temperature °C = 98.125$$
So assuming ideal thermal dissipation on a bare TO-220, it's still going to easily reach ~100°C.
Any environmental factors that further reduce the device's cooling will make it worse.


text:
Q: Debug Xamarin Forms app with source code I have been developing my application using Xamarin Forms and MVVMCross libraries and I have encountered an error, which leads to Xamarin.Forms. I thought I will just download source code for Xamarin Forms and debug it. I have cloned git repository, then added these projects to my solution:

*

*Xamarin.Forms.Core

*Xamarin.Forms.Maps

*Xamarin.Forms.Maps.Android

*Xamarin.Forms.Platform

*Xamarin.Forms.Platform.Android

*Xamarin.Forms.Platform.Android (Forwarders)

*Xamarin.Forms.Platform.Android.FormsViewGroup

*Xamarin.Forms.Xaml

I have removed NuGet references for these libraries and replaced references in my projects. Application is building, everything goes okay at this point, but when I deploy it to an emulator, app crashes. Here is stacktrace:

android.runtime.JavaProxyThrowable: System.ArgumentException: element
  is not of type Xamarin.Forms.View  Parameter name: element    at
  Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement
  (Xamarin.Forms.VisualElement element) [0x00011] in
  F:\workspace\Xamarin.Forms\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:139
  at Xamarin.Forms.Platform.Android.Platform.CreateRenderer
  (Xamarin.Forms.VisualElement element) [0x00022] in
  F:\workspace\Xamarin.Forms\Xamarin.Forms.Platform.Android\Platform.cs:289
  at Xamarin.Forms.Platform.Android.Platform.AddChild
  (Xamarin.Forms.VisualElement view, System.Boolean layout) [0x0001d] in
  F:\workspace\Xamarin.Forms\Xamarin.Forms.Platform.Android\Platform.cs:530
  at Xamarin.Forms.Platform.Android.Platform.SetPage (Xamarin.Forms.Page
  newRoot) [0x000a2] in
  F:\workspace\Xamarin.Forms\Xamarin.Forms.Platform.Android\Platform.cs:414
  at Xamarin.Forms.Platform.Android.FormsApplicationActivity.Inte   at
  md59d637456c2e899bd4a90a05345a07db3.MvxFormsApplicationActivity.n_onCreate(Native
  Method)   at
  md59d637456c2e899bd4a90a05345a07db3.MvxFormsApplicationActivity.onCreate(MvxFormsApplicationActivity.java:31)
    at android.app.Activity.performCreate(Activity.java:5231)   at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
    at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
    at android.app.ActivityThread.access$800(ActivityThread.java:135)
    at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    at android.os.Handler.dispatchMessage(Handler.java:102)     at
  android.os.Looper.loop(Looper.java:136)   at
  android.app.ActivityThread.main(ActivityThread.java:5001)     at
  java.lang.reflect.Method.invokeNative(Native Method)      at
  java.lang.reflect.Method.invoke(Method.java:515)      at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)     at
  dalvik.system.NativeStart.main(Native Method)

It looks, like Xamarin cannot find view rednerer for NavigationPage class.
I am compiling with Xamarin.Android 7.0 and Java 8.

A: I have finally figured out how to run my app. I have found, that in AssemblyInfo class in Xamarin.Forms.Platform.Android namespace I had grayed out attributes, which were telling application to register renderers for views. This is what I am talking about:
#if ROOT_RENDERERS
[assembly: ExportRenderer (typeof (BoxView), typeof (BoxRenderer))]
[assembly: ExportRenderer (typeof (Entry), typeof (EntryRenderer))]
[assembly: ExportRenderer (typeof (Editor), typeof (EditorRenderer))]
[assembly: ExportRenderer (typeof (Label), typeof (LabelRenderer))]
[assembly: ExportRenderer (typeof (Image), typeof (ImageRenderer))]
[assembly: ExportRenderer (typeof (Button), typeof (ButtonRenderer))]
[assembly: ExportRenderer (typeof (TableView), typeof (TableViewRenderer))]
[assembly: ExportRenderer (typeof (ListView), typeof (ListViewRenderer))]
[assembly: ExportRenderer (typeof (Slider), typeof (SliderRenderer))]
[assembly: ExportRenderer (typeof (WebView), typeof (WebViewRenderer))]
[assembly: ExportRenderer (typeof (SearchBar), typeof (SearchBarRenderer))]
[assembly: ExportRenderer (typeof (Switch), typeof (SwitchRenderer))]
[assembly: ExportRenderer (typeof (DatePicker), typeof (DatePickerRenderer))]
[assembly: ExportRenderer (typeof (TimePicker), typeof (TimePickerRenderer))]
[assembly: ExportRenderer (typeof (Picker), typeof (PickerRenderer))]
[assembly: ExportRenderer (typeof (Stepper), typeof (StepperRenderer))]
[assembly: ExportRenderer (typeof (ProgressBar), typeof (ProgressBarRenderer))]
[assembly: ExportRenderer (typeof (ScrollView), typeof (ScrollViewRenderer))]
[assembly: ExportRenderer (typeof (Toolbar), typeof (ToolbarRenderer))]
[assembly: ExportRenderer (typeof (ActivityIndicator), typeof (ActivityIndicatorRenderer))]
[assembly: ExportRenderer (typeof (Frame), typeof (FrameRenderer))]
[assembly: ExportRenderer (typeof (NavigationMenu), typeof (NavigationMenuRenderer))]
[assembly: ExportRenderer (typeof (OpenGLView), typeof (OpenGLViewRenderer))]

[assembly: ExportRenderer (typeof (TabbedPage), typeof (TabbedRenderer))]
[assembly: ExportRenderer (typeof (NavigationPage), typeof (NavigationRenderer))]
[assembly: ExportRenderer (typeof (CarouselPage), typeof (CarouselPageRenderer))]
[assembly: ExportRenderer (typeof (Page), typeof (PageRenderer))]
[assembly: ExportRenderer (typeof (MasterDetailPage), typeof (MasterDetailRenderer))]
#endif

When I have commented this compilation condition, everything went smooth.


text:
Q: Filter of Kendo UI Grid is not executed for specified column Here is my MVC view code :-

And below is the Action Method of controller :-
public ActionResult Report_Read()
{
  return Json(_oRepository.GetReports().ToList(), JsonRequestBehavior.AllowGet);
}

I want to apply filtering on StatusType filed and for that I have bound this filed with dropdownlist.

And my problem is when I am trying to do filtering by selecting one of the status from download its doing nothing.
I am working according to this example:
http://demos.telerik.com/kendo-ui/grid/filter-menu-customization

A: From your code, everything seems fine except the Controller Read Action. Now if the controller is being called when you apply filter from the view on Grid then the only change required on your side is below:
 public JsonResult Report_Read([DataSourceRequest] DataSourceRequest request)
 {
    return Json(_oRepository.GetReports().ToList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
 }

EDIT:
If you don't use Kendo.MVC then you have two option to filtering:
Option 1: Client side filtering
-> You will need to get all the data at read time so when the filtering is applied you have all the data, which is best option if the data source is not large as it saves unwanted controller requests for filtering.
-> First think you need do is subscirbe to filterMenuInit() of grid and add the below Script for client side filtering.
Code:
    filterMenuInit: function(e) {
     if (e.field == "name") {
          alert("apply Filter");
          var filter = []
          ... // Generate filters
          grid.dataSource.filter(filters);
      }
    }

For detailed example: Extact from Kendo Examples

Option 2: Server side filtering
-> I don't have much idea about it, but whilst I was searching for my options to filtering I had came across the below Question which was good but a bit complex for my application. But I think you can use it.

JS Fiddle Sample

Please refer below Link for detailed explanation.

Reference: JS Kendo UI Grid Options

A: Check your rendered html for string you have in td and string you are filtering

*

*Look if your td has any other code than the string you are trying to filter. If the case is there is some other html code inside td like a span or a div, then you have to refactor your code to make sure you have content only in td.

*Make sure you trim your string inside td.

*Try contains instead of equal to. if this works them the issue should be extran text/html or triming.

A: function applyFilter() {

    var filters = [], item_filters = [], brand_filters = [], invoice_id = null;
    var item_nested_filter = { logic: 'or', filters: item_filters };
    var brand_nested_filter = { logic: 'or', filters: brand_filters };

    var gridData = $("#invoicelistgrid").data("kendoGrid");
    var invoiceId = $("#invoiceidsearch").data("kendoDropDownList").value();
    var itemId = $("#itemsearch").data("kendoDropDownList").value();
    var brandId = $("#brandsearch").data("kendoDropDownList").value();
    var partyId = $("#party-dropdown").data("kendoDropDownList").value();

    if (partyId !== "") {
        filters.push({ field: "party_id", operator: "eq", value: parseInt(partyId) });
    }

    if (invoiceId !== "") {
        filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoiceId) });
    }

    if (itemId !== "") {
        for (var i = 0; i < gridData.dataSource._data.length; i++) {
            var data = gridData.dataSource._data[i].tb_invoice_lines;
            for (var j = 0; j < data.length; j++) {
                if (parseInt(itemId) === parseInt(data[j].item_id)) {
                    item_filters.push({ field: "invoice_id", operator: "eq", value: parseInt(data[j].invoice_id) });
                } else {
                    invoice_id = data[j].invoice_id;
                }
            }
        }
        if (item_filters.length > 0) {
            filters.push(item_nested_filter);
        } else {
            filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoice_id) });
        }
    }

    if (brandId !== "") {
        for (var k = 0; k < gridData.dataSource._data.length; k++) {
            var brand_data = gridData.dataSource._data[k].tb_invoice_lines;
            for (var l = 0; l < brand_data.length; l++) {
                console.log("Grid item id = " + brand_data[l].brand_id);
                if (parseInt(brandId) === parseInt(brand_data[l].brand_id)) {
                    brand_filters.push({
                        field: "invoice_id",
                        operator: "eq",
                        value: parseInt(brand_data[l].invoice_id)
                    });
                } else {
                    invoice_id = brand_data[l].invoice_id;
                }
            }
        }
        if (brand_filters.length > 0) {
            filters.push(brand_nested_filter);
        } else {
            filters.push({ field: "invoice_id", operator: "eq", value: parseInt(invoice_id) });
        }
    }

    console.log(filters);

    gridData.dataSource.filter({
        logic: "and",
        filters: filters
    });
}


text:
Q: Viewport for non responsive page? I have a page that has a width of 600px and non responsive. However, I couldnt make the width full stretched to device's width.
<style>
html, body {
  margin: 0px;
  height: 100%;
  width: 100%;
  padding:0px
}
</style>
<meta name="viewport" content="width=600">

What is the correct way to do that ?

A: You need to give width=device-width this way:
<style>
html, body {
  padding: 0;
  margin: 0 auto;     /* Center the body */
  max-width: 600px;   /* Your app width. */
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1" />


text:
Q: Bucket Sorting or sorting an arraylist of objects based on Id? I've heard about the Bucket Sorting. Could any one clarify how it gives the best performance when we sort millions of records? Is there any algorithm with n*log(n) or O(n)
 ?
I have 1000 employee objects each employee object has id, name, salary properties. I added these objects to ArrayList I want to sort these objects based on id property. Is there anyway? With out using Collections.sort() method. Considered below solutions, please anybody help which one gives best performance?
Thanks

A: public class Employee implements Comparable<Employee> {

private int id;
private String name;
private String salary ;

public int compareTo(Employee val) {
      if(id>val.id){
      return 1;
    }else if(id<val.id){
        return -1;
    } else {
        return 0;
    }
}

//getter and setters here
}

and now you can create a list
 List<Employee> emp= new ArrayList<Employee>();

Now you can use
Collections.sort(emp);

to sort by id

A: The ArrayList can store element in the ArrayFormat. If you identify user employee by id, you can use HashTable class which uses the key and value pair, otherwise you can implement your class using Comparable interface.
public class Employee implements Comparable<Employee> {

    private String id;
    private String name;
    private int salary ;

    public int compareTo(Employee val) {
        return id.compareTo(val.id);
    }

    // getter and setters here...

    List<Employee> emp = new ArrayList<Employee>();
    Collections.sort(emp);

A: Without Collections.sort() :
First implement Comparable<Employee> in Empoloyee's class and override compareTo
@Override
public int compareTo(Employee o) {

    return this.id.compareTo(o.id);
}

Pass your unsorted list to TreeSet and get set(sorted on id) then create new List with this set
List<Employee> list=new ArrayList<Employee>();
    list.add(new Employee(1, "A", Double.parseDouble("50")));
    list.add(new Employee(22, "B", Double.parseDouble("11")));
    list.add(new Employee(3, "C", Double.parseDouble("222")));
    list.add(new Employee(34, "D", Double.parseDouble("4")));

    SortedSet<Employee> set=new TreeSet<Employee>( list);

    List<Employee> l=new ArrayList<Employee>();
    l.addAll(set);

    System.out.println(l);

OutPut: Sorted on id withoutCollections.sort()
[Employee [id=1, name=A, price=50.0], Employee [id=3, name=C, price=222.0], Employee [id=22, name=B, price=11.0], Employee [id=34, name=D, price=4.0]]

Edit:
Employee class:
class Employee implements Comparable<Employee>{

Integer id;
String name;
Double price;
       -------

}

A: My requirement is not to use Collections.sort() method

In that case you need to use some existing way of sorting. If the collection is static (no more items being added) I can recommend using either quicksorting or merge-sorting. If there will be items added, heapsorting or binary sorting is probably the best way to go.

A: You can use this code to sort the list:
Collections.sort(list, new Comparator() {
    public int compare(Object a, Object b) {
        Employee ea = (Employee) a;
        Employee eb = (Employee) b;
        return ea.getID() - eb.getID();
    }
}

This uses Collections.sort to sort the list with a custom comparator, which compares IDs.
If you can't use Collections.sort, then surely your teacher told you how to sort a list? Maybe it would pay off to pay attention in the lectures.

A: First convert it into List of your class:
List<Employee> list = new List<Employee>(arraylist);

var sorted = list.OrderBy(o => o.id).ToList();


text:
Q: Como obtener horas extra en Jquery Tengo un html con Jquery pero quiero obtener las horas extra con el siguiente codigo, en mi html tengo 4 input type="time":

*

*para el ingreso (✓).

*para la salida (✓).

*obtiene las horas trabajadas (✓).

*las horas extra, que se obtendría de las horas trabajadas - la jornada laborar de 9 horas diarias. (X)

El detalle esta en que obtiene las horas mas no los minutos, como puedo completar mi código?
<script>
    function HorasExtra() {
        var HrsTrabajadas = $("#HrsTrabajadas").val();
        var HrsExtra = 9;  //esto representa una jornada laboral de 9 horas diarias
        var HrsExtraTrabajadas = $("#HrsExtra").val();

        var Resultado = parseFloat(HrsTrabajadas) - parseFloat(HrsExtra);
        $("#HrsExtra").val(Resultado);
    }

A: Bueno encontré la siguiente solución, espero sirva para posteriores consultas, gracias:
<script>
function CalcularHorasExtra() {
    var hora_inicio = $('#Jornada').val();
    var hora_final = $('#HrsTrabajadas').val();

    // Expresión regular para comprobar formato
    var formatohora = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;

    // Si algún valor no tiene formato correcto sale
    if (!(hora_inicio.match(formatohora)
          && hora_final.match(formatohora))) {
        return;
    }

    // Calcula los minutos de cada hora
    var minutos_inicio = hora_inicio.split(':')
      .reduce((p, c) => parseInt(p) * 60 + parseInt(c));
    var minutos_final = hora_final.split(':')
      .reduce((p, c) => parseInt(p) * 60 + parseInt(c));

    // Si la hora final es anterior a la hora inicial sale
    if (minutos_final < minutos_inicio) return;

    // Diferencia de minutos
    var diferencia = minutos_final - minutos_inicio;

    // Cálculo de horas y minutos de la diferencia
    var horas = Math.floor(diferencia / 60);
    var minutos = diferencia % 60;

    $('#HrsExtra').val(horas + ':'
      + (minutos < 10 ? '0' : '') + minutos);
}

$('#HrsTrabajadas').change(CalcularHorasExtra);
$('#Salida').change(CalcularHorasExtra);
CalcularHorasExtra();


text:
Q: walk through array with nested output in PHP I have this code:
foreach ($_POST as $key1 => $item1):
    if (is_array($item1)):
        foreach ($item1 as $key2 => $item2):
            if (is_array($item2)):
                foreach ($item2 as $key3 => $item3):
                    if (is_array($item3)):
                        foreach ($item3 as $key4 => $item4):
                            $_POST[$key1][$key2][$key3][$key4] = empty($item4) ? NULL : $item4;
                        endforeach;
                    else:
                        $_POST[$key1][$key2][$key3] = empty($item3) ? NULL : $item3;
                    endif;
                endforeach;
            else:
                $_POST[$key1][$key2] = empty($item2) ? NULL : $item2;
            endif;
        endforeach;
    else:
        $_POST[$key1] = empty($item1) ? NULL : $item1;
    endif;
endforeach;

$_POST is a 4 level array, array_walk() would return my array in first level (which I don't want).
The Question is how can I simplify this code with repeating blockes?

A: This is a job for recursion, most easily implemented here with array_walk_recursive.
Make sure that you understand what your code does though, empty returns true for zeros, which could be a problem.
$input = [
    'param1' => [
        'sub1_1' => [
            'sub1_1_1' => [
                'sub1_1_1_1' => 'foo',
                'sub1_1_1_2' => '',
                'sub1_1_1_3' => 0,
                'sub1_1_1_4' => 'bar',
                'sub1_1_1_5' => false,
                'sub1_1_1_6' => [
                    'sub1_1_1_6_1' => 'baz',
                    'sub1_1_1_6_2' => ''
                ]
            ]
        ]
    ]
];

array_walk_recursive($input, function(&$value)
{
    $value = (empty($value)) ? null:$value;
});

// Verify that false-y values were changed to null
assert($input['param1']['sub1_1']['sub1_1_1']['sub1_1_1_2']===null, 'Empty string should be normalized to null');
assert($input['param1']['sub1_1']['sub1_1_1']['sub1_1_1_3']===null, 'Zero should be normalized to null');
assert($input['param1']['sub1_1']['sub1_1_1']['sub1_1_1_5']===null, 'False should be normalized to null');

// Check out the state of the normalized input
var_dump($input);


text:
Q: NSImage and NSBitmapImageRep Memory Leak I am using objective C in a c++ application to load images on OSX. It is an OpenGL application. This is the code I use to load an image into opengl:
bool OSXSpecifics::loadPNGOSX(const char *fileName, int &outWidth, int &outHeight, GLuint *outTexture) {
NSImage *image = [[NSImage alloc] initWithContentsOfFile:[NSString stringWithUTF8String: fileName]];
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithData:[image TIFFRepresentation]];

NSArray* imageReps = [image representations];

bool hasAlpha;

for (NSImageRep *imageRep in imageReps) {
    if ([imageRep pixelsHigh] > outHeight) {
        outHeight = [imageRep pixelsHigh];
    }
    if ([imageRep pixelsWide] > outWidth) {
        outWidth = [imageRep pixelsWide];
    }
}
if ([bitmap hasAlpha] == YES) {
    hasAlpha = true;
} else {
    hasAlpha = false;
}

glGenTextures(1, outTexture);
glBindTexture(GL_TEXTURE_2D, *outTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? 4 : 3, outWidth, outHeight, 0,
             hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, [bitmap bitmapData]);
[bitmap release];
[image release];
return true;
}

Thanks to Instruments I have detected a memory leak every time this function is called. Instruments says [NSImage TIFFRepresentation] and [NSBitmapImageRep bitmapData] are using up a huge amount of memory.
It does not climb out of control but everytime this function is called the memory usage climbs a few hundred kilobytes.
My experience with objective-c is limited and so I do not know how to fix this as I thought release would work fine.
Just so you know the OpenGL texture is freed at a later point and I have confirmed it is not the source of the memory leak.
EDIT: After some further testing I have discovered this is not theoretically a memory leak as Instruments is not reporting a "memory leak" as such. But whenever this function is called the memory usage of the application goes up and never comes down. This function is called when scenes in the game are loaded, and so whenever a scene is loaded memory usage goes up several megabytes. How could this possibly be happening. I am sure it is this function that is using up all the memory.

A: First off: The code doesn't look like it is leaking. My guess is that NSImage is doing some harmless caching internally that ensures it can re-use the same NSImage if you ever load this image file a second time, and that's maybe what you're seeing. Or maybe it's the file system cache. If memory gets tight, these caches will probably get flushed and the freed memory becomes available to your application.
That said, your code seems overly complicated. You create an NSImage (which consists of NSImageReps, one of which is very likely an NSBitmapImageRep) then get its TIFFRepresentation (i.e. re-encode all that data to TIFF, possibly compressing it again), then create an NSBitmapImageRep from that (decompressing and decoding the TIFF again), and then getting its bitmapData.
At the least, you should probably create an NSData from the file and create your NSBitmapImageRep from that. That will skip the entire NSImage creation and TIFF steps.
Even better would probably be if you just went and used the lower-level ImageIO library. Create a CGImageRef from your file, then hand the image's raw, decompressed data off to OpenGL. I vaguely remember there might even be a better way to create an OpenGL texture if you go through CIImage or CoreVideo, but I may be mixing that up with the reverse (texture to CIImage).


text:
Q: Prolog - print the sum of the EVEN numbers from 1 to 10 I am trying to print all the even numbers from 1 to 10 using Prolog, and here is what I have tried:
printn(10,0):- write(10),!.
printn(X,Sum):-
    ( X mod 2 =:= 0 -> Sum is X+Sum, Next is X+1, nl, printn(Next);
      Next is X+1, printn(Next) ).

but it returns false.

A: You don't need to create the list with the numbers from the beginning, it is better to examine numbers once:
print(X,Y):-print_even(X,Y,0).

print_even(X, X, Sum):-
    (   X mod 2 =:= 0 -> Sum1 is X+Sum;
        Sum1 = Sum
    ), print(Sum1).
print_even(X, Y, Sum):-
    X<Y, Next is X+1,
    (   X mod 2 =:= 0 -> Sum1 is X+Sum, print_even(Next, Y, Sum1);
        print_even(Next, Y, Sum)
    ).

Keep in mind that in Prolog Sum is Sum+1 always fails you need to use a new variable e.g Sum1.
Example:
?- print(1,10).
30
true ;
false.

A: The most useful way of obtaining Prolog output is to capture the solution in a variable, either individually through backtracking, or in a list. The idea of "printing", which carries over from using other languages allows for formatting, etc, but is not considered the best way to express a solution.
In Prolog, you want to express your problem as a relation. For example, we might say, even_with_max(X, Max) is true (or succeeds) if X is an even number less than or equal to Max. In Prolog, when reasoning with integers, the CLP(FD) library is what you want to use.
:- use_module(library(clpfd)).

even_up_to(X, Max) :-
    X in 1..Max,
    X mod 2 #= 0,   % EDIT: as suggested by Taku
    label([X]).

This will yield:
3 ?- even_up_to(X, 10).
X = 2 ;
X = 4 ;
X = 6 ;
X = 8 ;
X = 10.

If you then want to collect into a list, you can use: findall(X, even_up_to(X), Evens).

A: What error do you have? Here is my solution:

*

*Create list [1...10]

*Filter it, excluding odd numbers

*Sum elements of the list

Code:
sumList([], 0).
sumList([Head|Tail], Sum) :-
   sumList(Tail, Rest),
   Sum is Head + Rest.

isOdd(X) :-
    not((X mod 2) =:= 0).

sumOfEvenNums(A, B, Out) :-
    numlist(A, B, Numbers),
    exclude(isOdd, Numbers, Even_numbers),
    sumList(Even_numbers, Out).

Now you can call sumOfEvenNums(1, 10, N)

A: In ECLiPSe, you can write with iterator:
sum_even(Sum):-
( for(I,1,10),fromto(0,In,Out,Sum)
    do
  (I mod 2 =:= 0 -> Out is In + I;Out is In)
)

A: With library(aggregate):
evens_upto(Sum) :-
  aggregate(sum(E), (between(1, 10, E), E mod 2 =:= 0), Sum).

Thanks to @CapelliC for the inspiration.


text:
Q: css table element gets stretched if only a single element exists I have a styling problem. When I only create a few elements, the element gets stretched. It only occurs when there are not enough elements to fill a single row. After the first row is filled it has no problems.
What do I need to change in the CSS or can I use js to calculate how many elements would fit into one row?

function create_elem(){
  const parent = document.getElementById("parent");
  let element = document.createElement('div');
  element.innerHTML = '

Title

';
  parent.append(element);
}

function empty_parent() {
  const parent = document.getElementById("parent");
  while (parent.hasChildNodes()) {
    parent.removeChild(parent.firstChild);
  }
}

function get_selector(){
  const select = document.getElementById("select");
  let value = parseInt(select.value);
  if (!select.value || select.value == "") value = 0;
  return value;
}

function setSize(num) {
  empty_parent();
  for(let i = 0; i < num; i++){
    create_elem();
  }
}
.container {
    width: 100%;
    height: 90vh;
    background:rgba(0,0,0,.1);
}
#parent {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    grid-column-gap: 1rem;
    grid-row-gap: 2rem;
    overflow: auto;
}
img {
    width: 100%;
    height: 35vh;
    object-fit: cover;
    border-radius: 5px;
    margin-bottom: 1rem;
}

  <input id="select" type="number" />
  <button onclick="setSize(get_selector())">Submit</button>

A: You can remove the "width: 100%" from img and add a card class to center for example :
.card {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.card img {
    height: 35vh;
    object-fit: cover;
    border-radius: 5px;
    margin-bottom: 1rem;
}