text:
Q: Header font in LyX I would like to change the header font in my book ms from serif to sans serif. I've spent much time trying to find the answer on the web. I'm using book (KOMA script) and fancyhdr.
Can some kind soul show me the light?
A minimal *.lyx file that produces this problem on my system is shown below:
#LyX 2.0 created this file. For more info see http://www.lyx.org/
\lyxformat 413
\begin_document
\begin_header
\textclass scrbook
\begin_preamble
% DO NOT ALTER THIS PREAMBLE!!!
%
% This preamble is designed to ensure that the User's Guide prints
% out as advertised. If you mess with this preamble,
% parts of the User's Guide may not print out as expected.  If you
% have problems LaTeXing this file, please contact
% the documentation team
% email: lyx-docs@lists.lyx.org

\usepackage{ifpdf} % part of the hyperref bundle
\ifpdf % if pdflatex is used

 % set fonts for nicer pdf view
 \IfFileExists{lmodern.sty}{\usepackage{lmodern}}{}

\fi % end if pdflatex is used

% for correct jump positions whe clicking on a link to a float
\usepackage[figure]{hypcap}

% the pages of the TOC is numbered roman
% and a pdf-bookmark for the TOC is added
\let\myTOC\tableofcontents
\renewcommand\tableofcontents{%
  \frontmatter
  \pdfbookmark[1]{\contentsname}{}
  \myTOC
  \mainmatter }

% define a short command for \textvisiblespace
\newcommand{\spce}{\textvisiblespace}

% macro for italic page numbers in the index
\newcommand{\IndexDef}[1]{\textit{#1}}

% for customized page headers/footers
% only needed because they are only used in one section of the document
\usepackage{fancyhdr}
% change header rule width
\renewcommand{\headrulewidth}{1pt}
% workaround for a makeindex bug,
% see sec. "Index Entry Order"
% only uncomment this when you are using makindex
%\let\OrgIndex\index
%\renewcommand*{\index}[1]{\OrgIndex{#1}}
\setkomafont{pagehead}{\normalfont\sffamily\upshape}
\end_preamble
\options refpage,intoc,bibliography=totoc,index=totoc,BCOR7.5mm,captions=tableheading
\use_default_options false
\begin_modules
enumitem
customHeadersFooters
\end_modules
\maintain_unincluded_children false
\language english
\language_package default
\inputencoding utf8
\fontencoding global
\font_roman palatino
\font_sans helvet
\font_typewriter courier
\font_default_family default
\use_non_tex_fonts false
\font_sc true
\font_osf false
\font_sf_scale 100
\font_tt_scale 100

\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize 12
\spacing single
\use_hyperref true
\pdf_title "The LyX User's Guide"
\pdf_author "LyX Team"
\pdf_subject "LyX"
\pdf_keywords "LyX"
\pdf_bookmarks true
\pdf_bookmarksnumbered true
\pdf_bookmarksopen false
\pdf_bookmarksopenlevel 1
\pdf_breaklinks false
\pdf_pdfborder false
\pdf_colorlinks true
\pdf_backref false
\pdf_pdfusetitle false
\pdf_quoted_options "linkcolor=black, citecolor=black, urlcolor=blue, filecolor=blue, pdfpagelayout=OneColumn, pdfnewwindow=true, pdfstartview=XYZ, plainpages=false"
\papersize custom
\use_geometry true
\use_amsmath 1
\use_esint 1
\use_mhchem 1
\use_mathdots 1
\cite_engine basic
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date true
\use_refstyle 0
\notefontcolor #0000ff
\boxbgcolor #e6e6e6
\branch Question
\selected 1
\filename_suffix 0
\color #00ff00
\end_branch
\branch Answer
\selected 0
\filename_suffix 0
\color #aa55ff
\end_branch
\index Index
\shortcut idx
\color #008000
\end_index
\paperwidth 7.5in
\paperheight 9.25in
\secnumdepth 2
\tocdepth 2
\paragraph_separation indent
\paragraph_indentation default
\quotes_language english
\papercolumns 1
\papersides 2
\paperpagestyle fancy
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict true
\end_header

\begin_body

\begin_layout Title
Build it with Nitrogen
\end_layout

\begin_layout Subtitle

\shape italic
\size larger
The fast-off-the-block Erlang web framework
\end_layout

\begin_layout Author

\family sans
Lloyd R.
 Prentice & Jesse Gumm
\end_layout

\begin_layout Standard
\begin_inset CommandInset toc
LatexCommand tableofcontents

\end_inset

\end_layout
\begin_layout Chapter
You want me to build what?
\end_layout

\begin_layout Standard

\end_layout

\begin_layout Chapter
Enter the lion's den
\end_layout

\begin_layout Standard
Whoa! Day after tomorrow? That's harsh.
 But that's Bossman--- no moss under that dude's feet.
 So we best get crackin'.
\end_layout

\begin_layout Standard
These three boxes power our trusted in-house development network.
 We call them Alice, Bob, and Mallory.
 Yes, indeed, we take security seriously.
 Rusty will read you in on our security practices later.
\end_layout

\begin_layout Standard
We also have a remote server--- hostname Charlie.
 Plan to lease another--- probably call it Dora.
\end_layout

\begin_layout Standard
Why all the hardware?
\end_layout

\begin_layout Standard
Erlang was explicitly designed to support distributed computing
\begin_inset Index idx
status open

\begin_layout Plain Layout
distributed computing
\end_layout

\end_inset

.
 So we use the machines on this network to develop and test distributed
 applications and databases.
 Set it up on the cheap.

\end_layout

\begin_layout Standard
Alice and Mallory are old Dell Optiplex 745s running Linux Debian
\begin_inset Index idx
status open
\begin_layout Plain Layout
Debian
\end_layout

\end_inset

 Linux Wheezy.
 Dual-core, gig of RAM.
 Company up the road traded up so Bossman picked these puppies up for fifty
 bucks apiece.
 Bossman likes to say lean-and-mean.
 Truth--- the dude's a cheap skate.
\end_layout

\begin_layout Standard
Yes, we could we use
\shape italic
Vagrant,
\shape default
the cloud, or some such, instead of physical machines.
 But Bossman is old school.
 We're trying to talk him around.
\end_layout

\begin_layout Standard
Bob is a custom built PC running Ubuntu
\begin_inset Index idx
status open

\begin_layout Plain Layout
Ubuntu
\end_layout

\end_inset

 14.04.
 Three-core AMD processor, six gigs of RAM.
\end_layout

\begin_layout Standard
I tap into the network with my personal MacBook Pro
\begin_inset Index idx
status open

\begin_layout Plain Layout
MacBook Pro
\end_layout

\end_inset

.
\end_layout

\begin_layout Standard
Fact is, you don't need all this kit to develop Nitrogen apps.
 You can do it on your Windows
\begin_inset Index idx
status open

\begin_layout Plain Layout
Windows
\end_layout

\end_inset

 notebook at Starbucks if you're so inclined.
 I've heard of folks running Nitrogen on
\shape italic
Raspberry Pi
\shape default

\begin_inset Index idx
status open

\begin_layout Plain Layout
Raspberry Pi
\end_layout

\end_inset

.

\end_layout

\begin_layout Standard
But we're looking toward bigger things here--- reliable, industrial strength,
 scalable apps.
\end_layout

\begin_layout Section*
The big picture
\end_layout

\begin_layout Standard
Before we begin, let me paint the big picture.

\end_layout

\begin_layout Standard
The challenge of web application development comes down to managing a jumble
 of languages and network protocols.

\end_layout

\begin_layout Standard
You, Dude, learned your native language effortlessly in the bosum of your
 family.
 But as a web application developer your task is to convince hardware on
 both server and client sides to do your bidding.
 Problem is, the stupid machines don't speak your native language.

\end_layout
\begin_layout Standard
On the client side, the browser responds to HTTP/HTTPS protocols carrying
 HTML, CSS, and JavaScript messages which, in turn, convey and present informati
on structured as natural language, sound, and images both still and moving.

\end_layout

\begin_layout Standard
The server responds to some babel of computer languages to marshal the HTTP/HTTP
S, HTML, CSS, JavaScript, natural language, sound, and images both still
 and moving through the Internet to the client.
\end_layout

\begin_layout Standard
It's almost too much for the feeble human mind to encompass.
 The nitty gritty tedium of it all is mind numbing.
\end_layout

\begin_layout Standard
So this is where Nitrogen comes in.

\end_layout

\begin_layout Standard
Nitrogen harness the power of Erlang to manage all--- well, most all---
 of the fiddly semantics and syntax of HTTP/HTTPS, HTML, CSS, and JavaScript.
 This means that you have that much less to think about when you craft your
 cunning web application.
 In the spell of creative ferment, you can produce cool web chops all that
 much faster.
\end_layout

\begin_layout Standard
We're not saying that you don't have to understand the alphabet soup of
 web technologies.
 The deeper you understand them the better.
 We are saying that mastery of Erlang Nitrogen will make you far more fluent
 and productive.
\end_layout

\begin_layout Standard
What's the trick?
\end_layout

\begin_layout Standard
Nitrogen combines the structural convenience of Erlang records, the fluency
 of Erlang functions to execute logic and embed JavaScript, and the power
 of Erlang as a development platform to organize and abstract the semantic
 and syntactical fussiness of server/web/browser communication.
\end_layout

\begin_layout Standard
Enough already.
 Let's install Nitrogen.
\end_layout

\end_body
\end_document

A: In your preamble, the line:
\setkomafont{pagehead}{\normalfont\sffamily\upshape}

should change the header font to sans serif, upright. However, you're using the fancy header style which passes control of the header formatting to fancyhdr. So you need to pass the instruction to use sffamily to fancyhdr and not to koma. The default settings on the different classes and packages are different. In order to get the same layout that you currently have, comment out the \setkomafont line and instead add this:
\fancyhead{} % clear all header fields
\fancyhead[RE,LO]{\sffamily\leftmark}

From fancyhdr documentation, section 6.


text:
Q: Applying across a numpy axis (row-wise correlation of every pair of rows between two arrays with NaNs) I've got a function f(x,y) that takes two 1-d arrays and returns a scalar.
If I have a 2d matrix of shape (M,N), how do I efficiently apply the function pairwise across the 0 axis to end up with a square symmetric result of shape (M, M)?
Edit:
I'm trying to calculate pairwise correlation of an array of 1d arrays:
def f(x, y):
    sigma_x_y = np.nanstd(x) * np.nanstd(y)
    covariance = np.nanmean((x-np.nanmean(x))*(y-np.nanmean(y)))
    return covariance/sigma_x_y

A: I think this is what you are looking for. The equations are similar to your function f(x, y):
x_m = x - np.nanmean(x,axis=1)[:,None]
y_m = y - np.nanmean(y,axis=1)[:,None]

X = np.nansum(x_m**2,axis=1)
Y = np.nansum(y_m**2,axis=1)

corr = np.dot(x_m,y_m.T)/np.sqrt(np.dot(X[:,None],Y[None]))

EDIT: If you wish to ignore NaN values in calculating correlation of two rows, simply replace last line with this:
corr = np.dot(np.nan_to_num(x_m), np.nan_to_num(y_m).T)/np.sqrt(np.dot(X[:,None],Y[None]))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can i leave the variables in struct undefined in c++? I have defined a struct like this
Struct rectangle{

int x;
int y;
int z;

};

and then in my main method, i will be assigning the variables:
void main(int argc, const char *argv[])

{

   for(i=0;i<20;i++)

   {

     rectangle[i].x = 20;
     rectangle[i].y = 10;

    }

}

But I wont be assigning the 'z' variable of the struct anytime. Am i allowed to do this?
hope i am not asking something very dumb!!
Thanks in advance!

A: Yes, that's fine.  Any attempt to use rectangle[i].z will result in undefined behaviour,* but that's not a problem so long as you don't try to use it.

* Unless rectangle is declared as a global/static array, in which case all its members are implicitly initialized to zero.

A: You are allowed to do it. The member z will have an indeterminate value though.
So If you use it, without assigning any value to it you will end up with an Undefined Behavior(UB).
However, If the structure object is an global or static object then z will be implicitly initialized to 0 and you do not have to bother about UB.

A: As said before, it won't harm. You can even print rectangle[i].z's value to see what was here before on the stack :).

A: Yes you can get away without declaring z but the value for z will be undefined.
Think about using a default constructor for the struct and also defining rectangle z as a gloabal or static will initialize it to 0 so you don't have to worry about the value it will take on otherwise.


text:
Q: Notebook display won't "work" since Nvidia driver installation As title said, I have an issue with my built-in display of my Notebook. Since the day I installed the NVIDIA drivers I don't have output, even unplugged from external Monitor, on my built-in display.
What I tried:

*

*Unplug my external HDMI connected monitor.

*Set to "on-demand" in NVIDIA-SETTINGS

*Reboot & Reboot after unplugged external HDMI connected monitor.

*$ xrandr --auto

*Asked for help at r/Ubuntu and got 0 responds so far.

BTW: Installed all drivers for Nvidia and Intel from Lutris' documentation.
xRandr:
Screen 0: minimum 8 x 8, current 1920 x 1080, maximum 32767 x 32767

DP-0 disconnected (normal left inverted right x axis y axis)

DP-1 disconnected (normal left inverted right x axis y axis)

HDMI-0 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 522mm x 294mm

1920x1080 60.00 + 144.00* 120.00 119.88 50.00 29.97 25.00 23.98

1680x1050 59.95

1600x1200 60.00

1440x900 59.89

1280x1024 75.02 60.02

1280x960 60.00

1280x720 60.00 59.94 50.00

1152x864 75.00

1024x768 75.03 70.07 60.00

960x1080 60.00

800x600 75.00 72.19 60.32 56.25

720x576 50.00

720x480 59.94

640x480 75.00 72.81 59.94 59.93

My Notebook:

*

*OS: Ubuntu 21.10 x86_64

*Host: HP Pavilion Gaming Laptop 16-a

*Kernel: 5.13.0-28-generic

*DE: GNOME 40.5

*CPU: Intel i5-10300H (8) @ 4.500GHz

*dGPU: NVIDIA GeForce GTX 1650 Ti Mobi

*iGPU: Intel CometLake-H GT2 [UHD Grap

*Memory: 16GB


text:
Q: Sort by priority using Doubly linked list I'm stuck here, anyone can help me out to solve this.
                Integer Personid = rs.getInt("Personid");
                String FirstName = rs.getString("FirstName");
                String LastName = rs.getString("LastName");
                String DateOfArrival = rs.getString("DateOfArrival");
                String PassportNumber = rs.getString("PassportNumber");
                String PriorityLevel = rs.getString("PriorityLevel");
                PriorityNumber = rs.getString("PriorityNumber");

                  ArrayList<String>  queue = new ArrayList<String>();

                   queue.add(Personid.toString());
                   queue.add(FirstName);
                   queue.add(LastName);
                   queue.add(DateOfArrival);
                   queue.add(PassportNumber);
                   queue.add(PriorityLevel);
                   queue.add(PriorityNumber);

                   System.out.println(queue);

result:
 [218, Akhil, Chandran, 2020-02-21, KH1234567, High Priority, 3]
 [219, Emma, Sony, 2020-11-11, HJ73737377, Low Priority, 1]
 [220, Michele, Philip, 2021-10-22, HJ989898, Medium Priority, 2]
 [221, Zania, Zing, 2024-09-26, GH565656, Medium Priority, 2]
 [222, Pole, Mathew, 2020-04-14, HY212121, High Priority, 3]
 [223, Myra, Mary, 2020-03-04, GH6666666, High Priority, 3]

need to get:
  [218, Akhil, Chandran, 2020-02-21, KH1234567, High Priority, 3]
  [222, Pole, Mathew, 2020-04-14, HY212121, High Priority, 3]
  [223, Myra, Mary, 2020-03-04, GH6666666, High Priority, 3]
  [220, Michele, Philip, 2021-10-22, HJ989898, Medium Priority, 2]
  [221, Zania, Zing, 2024-09-26, GH565656, Medium Priority, 2]
  [219, Emma, Sony, 2020-11-11, HJ73737377, Low Priority, 1]


text:
Q: Use `Abstract Syntax Trees` to get all inhereted methods of the class node I am tring to get all inhereted methods from a class by python ast module.  In my case, I have to use a scanning tools to read the *.py file to get all classes' inhereted method lists.
Source code:
# test.py
from PyQt5 import QtWidgets

class InheritedClass(QtWidgets.QDialog, QtWidgets.QMainWindow):
    def closeEvent(self, bool):
        pass

AST code:
import ast

file = open('test.py', 'r')
source = file.read()

class NodeVisitor(ast.NodeVisitor):

    def visit_ClassDef(self, node):
        for base in node.bases:
            print base.__dict__

node = ast.parse(source)
visitor = NodeVisitor()
visitor.visit(node)

Is there a way to get all the methods inhereted by the InheritedClass. My thinking is go through all the parents(the node.bases attribute) of the class node, and then get their methods. But I have a blocker when I want to retrieve all methods from the parent, the bases attributes. And I am open to other ways.


text:
Q: Wpf trigger to change the image of a treeview item I am binding a treeview using a Hierarchical class structure as follows.
Store
   ->ImagePath
   ->List
      ->List
When I am creating the DataTemplate for the Person, I want to use a combination of the person.name
and the image path declared in the Store.
Here is the code behind of my MainWindow.xaml file.
`    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        Customers customers = new Customers();
        customers.Users = new List<Person>
        {
            new Person { Name = "John"},
            new Person { Name = "Adam"},
            new Person { Name = "Smith"}
        };

        Store root = new Store();
        root.ImagePath = "imageone.png";
        root.Add(customers);
        this.DataContext = root;
    }
}

public class Store : ObservableCollection<Customers>
{
    public string ImagePath
    {
        get;
        set;
    }
}
public class Customers
{
    public string Label
    {
        get
        {
            return string.Format("People({0})", Users.Count());
        }
    }
    public List<Person> Users
    {
        get;
        set;
    }
}
public class Person
{
    public string Name
    {
        get;
        set;
    }
}`

and here is the xaml and this Source="{Binding Store.ImagePath}" is not working.
    <Window.Resources >
   <DataTemplate DataType="{x:Type local:Person}" x:Key="personKey" >
        <StackPanel Orientation="Horizontal" >
            <Image Source="{Binding Store.ImagePath}"></Image>
            <TextBlock Text="{Binding Name}" />
        </StackPanel>
    </DataTemplate>
    <HierarchicalDataTemplate x:Key="customerKey" ItemsSource="{Binding Users}" ItemTemplate="{StaticResource personKey }" >
        <TextBlock Text="{Binding Label}" FontWeight="Bold"/>
    </HierarchicalDataTemplate>
</Window.Resources>
<Grid>
    <Canvas>
        <Button HorizontalAlignment="Left" DockPanel.Dock="Top" Height="29" Width="112" Canvas.Left="123" Canvas.Top="5">Image one</Button>  <Button HorizontalAlignment="Left" VerticalAlignment="Top" DockPanel.Dock="Top" Height="28" Width="119" Canvas.Left="249" Canvas.Top="7">Image two</Button>
        <TreeView  HorizontalAlignment="Stretch"  Name="treeView1" VerticalAlignment="Stretch"
               ItemsSource="{Binding .}" ItemTemplate="{StaticResource customerKey}" Height="260" Width="363" Canvas.Left="81" Canvas.Top="45" />
    </Canvas>
</Grid>

I would also like to change the image programaticaaly and all person treeview items change when I click on of the buttons.
Thanks

A: The DataTemplate personKey is going to get bound to a Person object (because it's the ItemTemplate for the customerKey HierarchicalDataTemplate, whose ItemsSource is the Users collection).  As always in WPF, the local DataContext overrides the inherited DataContext, and the DataContext within a DataTemplate is always the object for which the DataTemplate is being materialised.
So the binding path Store.ImagePath is being resolved relative to the Person being displayed in the DataTemplate.  But Person doesn't have a Store property, so the binding fails.
A quick but rather kludgy way to refer to window-level properties is by using a RelativeSource binding:
<Image Source="{Binding Path=DataContext.Store.ImagePath,
                        RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />


text:
Q: C# Web Api - NUnit Testing - Newtonsoft.Json.JsonSerializationException I need to deserialize the following JSON string.

{"status":"success","data":[{"id":4,"domainTitle":"Java","isDeleted":true},{"id":5,"domainTitle":"PHP","isDeleted":true},{"id":6,"domainTitle":"Angular","isDeleted":true}]}

The test code for the same is:
[Test]
    public async Task TestGetDeletedDomainsAsync_UserDomains_StatusCodeOK()
    {
        using (var adminController = new AdminController(_adminService.Object))
        {
            //act
            var response = _adminController.GetDeletedDomainsAsync();
            var successStatus = await response.Content.ReadAsAsync<SuccessStatus>();
            var returnData = JsonConvert.DeserializeObject<List<Domain>>(successStatus.Data.ToString());
            // assert
            Assert.Multiple(() =>
            {
                Assert.That(response, Is.TypeOf<HttpResponseMessage>());
                Assert.That(returnData, Is.TypeOf<List<Domain>>());
                Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
                Assert.IsNotNull(successStatus);
                Assert.AreEqual("success", successStatus.Status);
                Assert.IsNotNull(returnData);
                //checking if same object goes to service and also if that service is called once
                _adminService.Verify(s => s.GetDeletedDomains(), Times.Once);
            });
        }
    }

But when I try using the de-serializer, it gives an exception.

Newtonsoft.Json.JsonSerializationException : Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[IMS_NL.Models.Domain]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
     To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

The line that displays the above error is --
var returnData = JsonConvert.DeserializeObject<List<Domain>>(successStatus.Data.ToString());
Help me with a solution. Thanks in advance.

A: You need to make a class which correspond your JSON string
public class Answer
{
    public string Status { get; set; }
    public List<Domain> Data { get; set; }
}

public class Domain
{
    public int Id { get; set; }
    public string DomainTitle { get; set; }
    public bool IsDeleted { get; set; }
}

Then use
var returnData = JsonConvert.DeserializeObject<Answer>(successStatus.Data.ToString());

A: I think that your problem resides in the declaration of Domain class. You should define the below classes, according to the JSON you have posted:
public class Domain
{
    public int id { get; set; }
    public string domainTitle { get; set; }
    public bool isDeleted { get; set; }
}

public class Result
{
    public string status { get; set; }
    public List<Domain> data { get; set; }
}

var returnData = JsonConvert.DeserializeObject<Result>(...);

You should replace the ... with the JSON you get from that you call.
Optionally, you could rename the above classes as you think that would be more suitable.


text:
Q: Test autocorrelation in irregularly(unevenly) spaced time series I have a dataset that includes observations at different time points. There are multiple observations at the same time points and the time points are not evenly spaced.
Now, I would like to test whether the data are random or autocorrelated in time. Can I call such a dataset as a time series? If so, what kind test methods I can try to use for such an irregularly spaced time series?

A: While it's apparently some form of time series, if there are multiple observations at a single point, it might be a little unusual to call it a time series.
One difficulty I see is how do I relate (say) 2 observations at time $\tau$ to 3 observations at time $\tau-s$? What's the model? Does the expectation at time $\tau$ relate to the average at time $\tau-s$ or what?
With single-observation-at-a-time, there's certainly ways to write continuous-time autocorrelated models.
A common example is the Ornstein-Uhlenbeck process. See also the Vasicek model, a particular example of its use.
It's possible to write an unevenly-sampled observational model based on the O-U process as something of the form (if $s,t$ are consecutive observation times):
$\hspace{1cm}(y_t-\mu) = \phi^{t-s} (y_s-\mu) + n_{t-s}\,,\quad$ where $\:n_u\sim N(0,\frac{\sigma^2}{2\phi} (1-e^{-2\phi u}))$
(I think!), which when $t-s=1$ (i.e. the usual regular-time interval situation) corresponds to an AR(1).


text:
Q: Meteor-react ES6 Class React.Component I'm not sure if this is a known issue in Meteor. They did say that they are not supporting Modules in 1.2,but I don't know if this is a module issue or something else.
I'm attempting to structure my React components using ES6 classes, like so:
class App extends React.Component {
    render() {
        return
Hello World

    }
};

And then I add this route:
const {Router, Route} = ReactRouter;

Meteor.startup(function() {
    React.render((
        <Router>
            <Route path="/" component={App} />
        </Router>
    ), document.body)
});

This runs properly if it's all the same .jsx file.  Unfortunately, it doesn't work if I split the App and Router into separate files.  I get this from the browser:
Uncaught ReferenceError: App is not defined

Any ideas?  It works fine in two separate files if I go back to the createClass() syntax.  I tried adding an "export class", that didn't work, it returns an "Unexpected reserved word" error.
Obviously this isn't a huge problem, I can certainly use the createClass syntax, but I'm building a new app and thought I'd give it a try with the latest and greatest.
Thanks!
--Ivan

A: Change your first line to:
App = class App extends React.Component {

That puts 'App' into the global namespace.

A: Check this demo and add universe:modules to your modules. Try to use this in your app.jsx:
export default class App extends React.Component {
    render() {
        return
Hello World

    }
}

And in your parent:
import App from "./app"


text:
Q: Unexpected log2 error when defining S3 "Math" group generics for a new class I am trying to use S3 "Math" group generics for a custom class. However I am getting a strange result: log() works while log2 and log10 produces errors. Below is a minimal example:
# simple class with just the new name
lameclass <- function(x) {
  class(x) <- append(class(x), "lame")
  x
}

# It prints something when Math generics methods are used
Math.lame <- function(x, ...) {
  print("I am lame")
  NextMethod()
}

# an object of the class
lamevector <- lameclass(1:10)

> class(lamevector)
[1] "integer" "lame"

Now try to call log:
log(lamevector)
[1] "I am lame"
[1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 1.7917595 1.9459101 2.0794415 2.1972246 2.3025851

With base 2:
log(lamevector, 2)
[1] "I am lame"
[1] 0.000000 1.000000 1.584963 2.000000 2.321928 2.584963 2.807355 3.000000 3.169925 3.321928

All above worked. But now log2 wrapper:
log2(lamevector)
[1] "I am lame"
[1] "I am lame"
Error in log2.default(1:10, 2) :
  2 arguments passed to 'log2' which requires 1

Maybe someone can help me with figuring out what is going on here? Did log2 actually went through the generic Math definition 2 times and failed?

A: What appears to be happening is that NextMethod is not stripping the lame class, so when log2 calls log, it re-dispatches to the lame method, which now no longer works, because it's calling log2 with base = 2L, a parameter log2 doesn't have.
Forcing the dispatch to work correctly doesn't require too much work—just strip and re-add the class. (Aside: Subclasses should be prepended, not appended.)
lameclass <- function(x) {
    class(x) <- c("lame", class(x))    # prepend new class
    x
}

Math.lame <- function(x, ...) {
    print("I am lame")
    class(x) <- class(x)[class(x) != "lame"]    # strip lame class
    lameclass(NextMethod())    # re-add lame class to result
}

lamevector <- lameclass(1:5)

log(lamevector)
#> [1] "I am lame"
#> [1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379
#> attr(,"class")
#> [1] "lame"    "numeric"
log(lamevector, 2)
#> [1] "I am lame"
#> [1] 0.000000 1.000000 1.584963 2.000000 2.321928
#> attr(,"class")
#> [1] "lame"    "numeric"
log2(lamevector)
#> [1] "I am lame"
#> [1] 0.000000 1.000000 1.584963 2.000000 2.321928
#> attr(,"class")
#> [1] "lame"    "numeric"

I'm not precisely sure why it's dispatching like that. Group generics are a little weird, and dispatch on oldClass instead of class, which may or may not be part of the issue. It may just be a bug. The idiom of stripping and re-adding the class is used in other Math methods, possibly for this reason:
MASS:::Math.fractions
#> function (x, ...)
#> {
#>     x <- unclass(x)
#>     fractions(NextMethod())
#> }
#> <bytecode: 0x7ff8782a1558>
#> <environment: namespace:MASS>

A: As mentioned in the comment log2 ,log10 aren't in the S3 Math generic. In fact, exp, expm1, log, log10, log2 and log1p are S4 generic and are members of the Math group generic.
One way to implement what do you want to do is to define you class as S4 class.
setClass("lame4", slots = c(x = "numeric"))

And define the method Math group generic :
setMethod("Math","lame4",function(x) {
                x@x <- callGeneric(x@x)
                x
          })
## pretty print
setMethod("show", "lame4",function(object)print(object@x))

Now let's test it :
l1 <- new("lame4",x=1:10)

Then:
log2(l1)
 [1] 0.000000 1.000000 1.584963 2.000000 2.321928 2.584963 2.807355 3.000000 3.169925 3.321928
> log10(l1)
 [1] 0.0000000 0.3010300 0.4771213 0.6020600 0.6989700 0.7781513 0.8450980 0.9030900 0.9542425
[10] 1.0000000

This of course not a direct answer to your question, but explains why your implementation does not work. Here I think that using S4 paradigm is a good idea because you will have  stronger typing which is very helpful with mathematics. S4 methods works fine with R.C/Rcpp interface also. But if you are new to it there is a certain learning curve ( depends in your development background)


text:
Q: IntelliJ code Analyse overview of right side top corner and analyse Inspection shows different data IntelliJ code Analyse overview of right side top corner and analyse Inspection shows different data
When I hover the  right side top corner of code it shows something like this as inspection analyse
But when I run code Inspection for that same file through Analyse -> Inspec code, it shows different result like below
I need to get that same Analysis data which is shown in right side top corner as the result or log. Is there any other way to get that analyse result as text report or something like that. Thanks in advance

A: Due to performance reasons some of the inspections in IntelliJ IDEA differ at the Editor level and while run explicitly with Analyze | Inspect Code, i.e. "unused property" or "unused declaration" inspections etc. So thats why the information in "Analysis completed" window and "Inspections results" pane may be different.


text:
Q: Avoiding NavigatorUserMediaError "Only secure origins are allowed" on HTTP in Chrome I'm trying to make some audio/video tests with a JavaScript library for SIP phones and since Chrome 47 I can no longer test in local development because of this error:
NavigatorUserMediaError {}
constraintName: ""
message: "Only secure origins are allowed (see:https://goo. gl/Y0ZkNV)."
name: "PermissionDeniedError"

Is there an option (flag) in Chrome to disable this?
Or is there a way to download older versions of Chrome (I couldn't find any)?

A: The unsafely-treat-insecure-origin-as-secure flag works for me as documented here.
On OS X this looks like:
$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir=/tmp/foo --unsafely-treat-insecure-origin-as-secure=http://alt.local:8080

For various reasons, my local development server doesn't run on localhost or port 80. Specifying the alternative port appears to be necessary.
The user-data-dir directive appears to create a temporary sandbox profile in Chrome.

A: According to https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features, localhost is supposed to be considered as a secure origin.
If you do not test on localhost but on a real domain, then you should enable an HTTPS access (you can get a free certificate with Let's Encrypt)


text:
Q: Alfresco : How to search for a specific files types? I am working to search all PNG files(i.e. all files which has file name extension ".png") in alfresco.
I am using the followingcode, but it does not return any result:
var docs = search.luceneSearch("@cm\\:content.fileType:\"*.png\"");
for (var i=0; i<docs.length; i++)
   {
     //TO print the name of files--> "Name: " + docs[i].name ;

   }

I am not sure if content.fileType is the right way to code to search for file types. Any suggestion please ?

A: You should go with the content.mimetype query, for example: @\{http\://www.alfresco.org/model/content/1.0\}content.mimetype:text/plain
https://community.alfresco.com/docs/DOC-4673-search#jive_content_id_Finding_nodes_by_content_mimetype

A: If I use this statement, it helps to find only PNG images:
var docs = search.luceneSearch("@cm\\:name:\"png\"");

A: If your really want to search for PNG files you should follow Lista's approach using mimetype but with correct syntax
var docs = search.luceneSearch("@cm\\:content.mimetype:\"image/png\"");

searching for name part "PNG" ("@cm\:name:\"png\"") would find any document having a token "PNG" in it's name like png.name.pdf or any_png.doc since document name is stored tokenized in the index


text:
Q: The geom_line of the corresponding two periods of data There is data recording the changes in the two periods. The data correspond by id and are divided into groups.
In other words, the data shows the change from 2000 to 2007 id1 in group A, .
type <- c("a","a","b","b","b","b","c","c","c","c","c","c")
year <- c(2000,2007,2000,2000,2007,2007,2000,2000,2000,2007,2007,2007)
rate <- c(0.1,0.4,0.2,0.1,0.4,0.3,0.3,0.3,0.4,0.6,0.8,0.4)
id <- c(1,1,2,3,2,3,4,5,6,4,5,6)
d<-cbind(type,year,rate,id)

I want to draw a line with two periods for each id, but it doesn't work well.
ggplot(data=d, mapping=aes(x=year, y=rate), color = type, group = id) +
  geom_line(aes(year, rate), linetype = "solid", size = 2, alpha = .4)

A: I don't know much about the context of your data, but from what you describe, you need to simply put the id and type into the aestetics.
d<-data.frame(type,year,rate,id)

ggplot(data=d, mapping=aes(x=year, y=rate, color = type, group = id)) +
  geom_line(linetype = "solid", size = 2, alpha = .4)


text:
Q: proper use of "to scale" What is the proper way to use "to scale" in this sentence?

This drawing is to scale.

I want to indicate that the drawing is an accurate representation, where the length of objects in the drawing is proportional to their lengths in reality.
But the wording "is to scale" seems awkward for some reason. ("is" and "to" aren't usually adjacent words)

A: Scale:

*

*The map is drawn to scale.

*The map is drawn on a 1:1,000 scale.

A:
This drawing is to scale.

This sentence is perfectly good English. Real publications say stuff like...

The objects have been enlarged ten times, but their distances are to scale. (Astronomy magazine)
The diagram is not to scale: windrows may be more than 300 feet long and up to 10 feet wide, while individual thimbles are about the size of a quarter. (from an article titled "Why jellyfish stick together" in Natural History)
Everything is to scale with him. Many people have long eyelashes; he has lashes as long on the bottom as they are on the top. (Esquire, going on about George Clooney)

(That last example is grammatically flawless, though the writer may not have understood what to scale means.)
The phrase drawn to scale seems to be more common. Both are fine.
Examples are from COCA.

Grammar deep dive
Is to happens all the time in speech and in print. I found a lot of different grammatical situations where it works just fine:

"To alter favour ever is to fear" —Macbeth (infinitive)
The U.S. is to soccer what China is to Procter & Gamble: the last vast, harvestable territory. (analogy)
She is as indifferent to time as it is to her. (weird comparative as ... as construction; it is bizarre to me that something this complicated can be so completely clear and natural to the ear)
Liquor still will be taboo in Disneyland, whose primary appeal is to young children. (the noun appeal in the subject specially licenses the preposition phrase to young children)
The PGA Tour's main responsibility is to its members, which are the players. (ditto for responsibility)

Those don't say anything much about your question, because none of them are grammatically quite like "This map is to scale."
But these are:

When the taste is to your liking, transfer the vinegar to bottles.
In a Newtonian reflector, which inverts the image, south is up and east is to the right.
And -- and all of that is to the benefit of both the north and the south, as well as the region.

In all three of these examples, we have well-worn prepositional phrases starting with to (to your liking, to the right, to the benefit of) being used as predicate nominative. Just like "The map is to scale."
Nobody would bat an eye at any of them. The speaker of the last sentence was then-Senator John Kerry, in 2010.
All the example sentences above, except the Macbeth quote, are from COCA.


text:
Q: Top css Jquery in base a number Hi guys i want to make a number to 100% for apply css in jquery for example:
var number = 14034 - 3000;

Make that number the 100% for apply the css
$(this).css('top', number);

but obviously i not want =
top: 11034%

if 14034 is the 100%, how position one div in order the result, thanks :D

A: The formula is number / total * 100 :D


text:
Q: Persistency of shared preferences I have a game that uses a shared preference to record the users high score and display this on a statistics page.
My question -> Will this shared preference persist even after the user exits the application? How do I ensure that this data is always retained, will shared preferences do this or do I need to use something else?

A:
Will this shared preference persist even after the user exits the application?

yes!

How do I ensure that this data is always retained, will shared
  preferences do this or do I need to use something else?

See documentation

A: Yes, shared preferences are stored until the app is uninstalled or the user clears app data.
See storage options for details on different methods of persisting data.

A: Please see below link for complete infomation of shared preferences, it will solve your problem.
Android Shared Preferences


text:
Q: passing mysql account to remote server i've got to connect 2 php pages on 2 different servers,
in the first server there's the DB (mysql) with an "email" table, generated by a php page..
in the second server there's a php file wich needs to read the "email" table...
the second php page doesn't need to be opened by the user
the fact is that i need to make this work with lots of DB, not just one
so i can't store the mysql connection params in the php page on the 2nd server and just open it... i've got to pass the connection params every time
For now i use something like this, on the 1st server php page:
$socketcon = fsockopen("http://www.server2.com",80,$errorno,$errorstr,10);

if($socketcon) {
  $socketdata = "GET page2.php?dbuser=xxx&dbpass=xxx&db=xxx  HTTP/1.0\r\nHost: http://www.server2.com\r\nConnection: Close\r\n\r\n";
  fwrite($socketcon,$socketdata);
  fclose($socketcon);
}

but i fear that putting the params in URL is soooo bad....
any idea ?

A: One way to do is to create a "public" webservice with PHP that will receive credentials. If the credentials match you reply with the data you need (maybe in XML format). Of course all of this is over HTTPS. You can then "talk" with the service with CURL to create you DB connexion.


text:
Q: How to enable shortcuts in child form I have wrote a frame application, it's a windows form app as parent form.When it starts, it will find dlls in /modules and load them as extensions. And when I click the menuItem in the parent form, the specific dll will work.If the dll is a Form app, it will show.But when i try to use shortcuts(only build-ins,eg : CTRL-C...) in the childForm ,the hotkeys does not work. Anyone kindly tell me why and how can i fix the issue? Here's my code:
//parent.exe--ModuleEntrance.cs
public abstract class ModuleEntrance {
  public abstract string[] GetMenuNames();
  public abstract string[] GetMenuItemNames();
  public abstract EventHandler[] GetEventHandlers();
}
//parent.exe--ParentForm.cs
public partial class MDIParent : Form {
  public MDIParent() { //CTOR
    InitializeComponent();
    ModuleEntrance oneEntrance;
    string oneMenuName, oneMenuItemName;
    ToolStripMenuItem theMenu, theMenuItem;
    for(){ //iterate dlls in /modules, if it implement ModuleEntrance, load it.
          //And 1)load menu&menuItem.
          //2) connect handler to menuItem.click through
        //<code:theMenuItem.Click += new EventHandler(oneEntrance.GetEventHandlers()[i]);>
    }
}

//--------------
//child.dll-- EntranceImp.cs  //implement AC
public class EntranceImp : ModuleEntrance {
  public override string[] GetMenuNames() {
    return new string[] { "MENU"};
  }
  public override string[] GetMenuItemNames() {
    return new string[] { "OpenChildForm"};
  }
  public override EventHandler[] GetEventHandlers() {
    return new EventHandler[]{
      (EventHandler)delegate(object sender, EventArgs e) { //Anonymous method
        childForm form = new childForm();
        //find MDIparent and connect them
        ToolStripMenuItem mi = (ToolStripMenuItem)sender;
        form.MdiParent = (Form)(mi.OwnerItem.Owner.Parent);  //It works!
        form.Show();
      }
    };
  }
}
//child.dll--childForm.dll
//...

A: The child form has to notify the parent form about the key-down events somehow.
A way to do this is to have the child form expose key-down events that the parent form can listen to.  Remember to remove the parent event handlers every time that you change child form, or you'll end up with a memory leak since objects are not garbage collected until you release all references to them, including event handlers.
class Parent
{
    KeyEventHandler KeyDownHandler;

    public Parent()
    {
        KeyDownHandler = new KeyEventHandler(form_TextBoxKeyDown);
    }

    void SetChildForm(Child form)
    {
        form.TextBoxKeyDown += KeyDownHandler;
    }

    void RemoveChildForm(Child form)
    {
        form.TextBoxKeyDown -= KeyDownHandler;
    }

    void form_TextBoxKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control)
        {
            switch (e.KeyCode)
            {
                case Keys.C:

                    break;
                case Keys.X:

                    break;
                case Keys.V:

                    break;
            }
        }
    }
}

class Child
{
    TextBox txtBox;

    public event KeyEventHandler TextBoxKeyDown;

    internal Child()
    {
        txtBox.KeyDown += new KeyEventHandler(txtBox_KeyDown);
    }

    void txtBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (TextBoxKeyDown != null)
            TextBoxKeyDown(sender, e);
    }
}


text:
Q: Show/Hide Divs in jQuery I have this JSFiddle for reference: http://jsfiddle.net/422MP/38/
The green boxes are floating right, therefore I only want them to show when its parent div is expanded. If another div is clicked, I want the previous div's green box to hide and the new div's to show. Any ideas on this? Here is the js:
$('.sidebar').on('click', function() {
    $('.sidebar').not(this).animate({width: 50}, 400);
    if ($(this).width() == 50)
        $(this).animate({width: 150}, 400);
    else
        $(this).animate({width: 50}, 400);
});

A: Try to position it using absolute position
.inner {
    width: 50px;
    height: 50px;
    background-color: green;
    position: absolute;
    left: 100px;
}
.sidebar {
    height: 300px;
    width: 50px;
    display: inline-block;
    position: relative;
    overflow: hidden;
    /* left: 565px;*/
    /*position: relative;i*/
    margin:0 0px 0 10px;
}

Demo: Fiddle

A: Please try this
$('.inner').hide();
$('.sidebar').on('click', function() {
    $('.inner').hide();
    $('.sidebar').not(this).animate({width: 50}, 400);
    if ($(this).width() == 50){
        $(this).animate({width: 150}, 400);
        $(this).find('.inner').show();
    }
    else{
        $(this).animate({width: 50}, 400);
    }
});

Please see the fiddle

A: Why not add display: none for the inner class definition and then do something like this with the jQuery:
$('.sidebar').on('click', function() {
    //$('.sidebar').animate({width: 50}, 400);
    if ($(this).width() == 50)
        $(this).animate({width: 150}, 400).children(".inner").show();
    else
        $(this).animate({width: 50}, 400).children(".inner").hide();
});

jsFiddle

A: css:
.inner{display:none;}

javascript:
$('.sidebar').on('click', function() {
    $('.sidebar').not(this).animate({width: 50}, 400);
    if ($(this).width() == 50){
        $(this).animate({width: 150}, 400);
        $(".inner").fadeOut();
        $(this).children(".inner").fadeIn();
    }
    else{
        $(this).animate({width: 50}, 400);
        $(".inner").hide();
    }
});

A: First hide all the inner divs and show the child inner of current sidebar
Add twol lines of code with your js
$('.sidebar').on('click', function() {

$(".inner").hide();  $(this).children('.inner').show();
$('.sidebar').not(this).animate({width: 50}, 400);
if ($(this).width() == 50)
    $(this).animate({width: 150}, 400);
else
    $(this).animate({width: 50}, 400);

});


text:
Q: how swap an image to another in a slider with a function that compare the browser window's size? I have the html that is like this:

and I have to set a really easy function, like this but surely this is wrong:

How can I fix it?

A: You are assigning your nth-child in a wrong way try it like this change the width of the body to see the change. Use nth-child like this Fiddle
 $(".slide:nth-child(1) img").attr("src","http://placekitten.com/300/305");

$(window).width(function(){
            var win = $('body').width();
            if(win < 650) {
                $(".slide:nth-child(1) img").attr("src","http://placekitten.com/300/305");
                $(".slide img:nth-child(2)").attr("src","http://placekitten.com/300/306");
                $(".slide img:nth-child(3)").attr("src","http://placekitten.com/300/307");
                $(".slide img:nth-child(4)").attr("src","http://placekitten.com/300/308");
            }
            if(win >= 650) {
                $(".slide:nth-child(1) img").attr("src","http://placekitten.com/300/309");
                $(".slide img:nth-child(2)").attr("src","http://placekitten.com/300/310");
                $(".slide img:nth-child(3)").attr("src","http://placekitten.com/300/311");
                $(".slide img:nth-child(4)").attr("src","http://placekitten.com/300/312");
            }

        });
body{
    width:600px;

}

A: You cannot assign width to window variable. Because it's a reserved word. Try using some other variable name.
Other issue with your code is that you are using wrong selector. :nth-child can be used to selected a child, not the nth numbered element. You need to use $(".slide img:nth(1)") for second element.
Correct example :

Demo: jsFiddle


text:
Q: Closed bounded nonempty subset of R^2 I found two sets that are both open and closed in $\mathbb{R}^2: \emptyset$ and $\mathbb{R}^2$.
And I also found a closed but not open set in $\mathbb{R}^2$:
$B(0,1)=\{x \in \mathbb{R}^2 :  \|x\|≤ 1\}$
Now I have to find a closed, bounded, non-empty subset of $\mathbb{R}^2$.
My thought was $C[0,1]$?


text:
Q: reset email adress by using updateEmail(auth.currentUser, "user@example.com"); reactJS/firebase Im new at react and firebase, I set a const triggerResetEmail for the reset button. After my verification, the trigger is indeed awakened, but the command updateEmail(auth.currentUser, "user@example.com") has no effect at all. auth.currentUser also exists, because I used sendPasswordResetEmail(auth, email) in another function, and the function sendPasswordResetEmail was executed successfully.
And I tried most of the methods of google, such as signinwithemailandpassword, which have no effect.
Tnank u for ur reply.
Here is my code:
enter image description here


text:
Q: LLBLGen Pro Self Join with Query Spec I have a simple Entity
public Employee
    {
      public int Id {get; set;}
      public string Name {get; set;}
      public int ManagerId {get; set;}
    }

then I have an LLBLGen Query
var employeeQuery = qf.Create()
            .From(qf.Employee
                .LeftJoin(EmployeeEntity.Relations.EmployeeEntityUsingManagerId))
                .Select(()=> new RptEmployee()
                  {
                     Id = EmployeeFields.Id.ToValue<int>(),
                     EmployeeName = EmployeeFields.Name.ToValue<string>(),
                     ManagerName = HOW?
                  });

How do I get the managername from the self joined query?

A: In this case you must use aliases. Approx code:
var employeeQuery = qf.Create()
    .From(qf.Employee
    .LeftJoin(EmployeeEntity.Relations.EmployeeEntityUsingManagerId, "emp", "man"))
    .Select(() => new RptEmployee()
        {
            Id = EmployeeFields.Id.Source("emp").ToValue<int>(),
            EmployeeName = EmployeeFields.Name.Source("emp").As("EmployeeName").ToValue<string>(),
            ManagerName = EmployeeFields.Name.Source("man").As("ManagerName").ToValue<string>()
        });


text:
Q: Add multiple prefix and namespace to XML tags using XSL Sample request
<execute>
        <XYZ>123</XYZ>
        <commands>
            <Id>
                <name>ABC</name>
            </Id>
            <Level>33</Level>
        </commands>
        <commands>
            <Point>See</Point>
            <method>No</method>
            <No>2</No>
</execute>

Required Output:
<ns2:execute xmlns:ns2="http://namespace">
        <ns2:XYZ>123</XYZ>
        <ns2:commands>
            <ID  xmlns="https://differentnamespace">
                <name>ABC</name>
            </ID>
            <ns1:Level xmlns="https://thireddifferentnamepsace">33</Level>
            <ns1:Channel>Sky</ns1:Channel>
        <ns2:/commands>
        <ns2:commands>
            <ns1:Point>See</Point>
            <ns1:method>No</method>
            <ns1:No>2</No>
<ns2:/execute>

Can I do this with XSL? I did try but having problem with multiple prefix and in some tags there should be no prefix.


text:
Q: Proper Maths way to write nested fractions My question concerns more the Maths field rather then the LaTeX one ...
in fact it's about writing mathematical equations correctly.
I was looking for a way to be able to write a fraction nested in another fraction (at the numerator) in a larger font size.
I came across this question and asked myself: is this correct in mathematical terms?
I should premise that I'm not a Math student, so I'm not that familiar with certain formalisms.
But let's take the following MWE
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}
\begin{document}
    \[
        \frac{\lvert \, x - fl^t(x) \, \rvert}{\lvert \, x \, \rvert} \, \le \, \frac{\cfrac{b^{p-t}}{2}}{b^{p-1}}
        \,=\, \frac{b^{p-t+1-p}}{2} \,=\, \frac{b^{1-t}}{2} \,=\, \varepsilon_M
    \]
\end{document}

If I had to choose according to my 'personal taste', I would say that I prefer this first version over the following one.
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}
\begin{document}
    \[
        \frac{\lvert \, x - fl^t(x) \, \rvert}{\lvert \, x \, \rvert} \, \le \, \frac{\frac{b^{p-t}}{2}}{b^{p-1}}
        \,=\, \frac{b^{p-t+1-p}}{2} \,=\, \frac{b^{1-t}}{2} \,=\, \varepsilon_M
    \]
\end{document}

And their respective outputs are these:

But is this correct?
Thanks in advance!

A: Nesting \cfrac inside \frac doesn't make suitable sizes at all, If you really have to nest I would use \frac here but I'd avoid nesting if possible.

\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}
\begin{document}

eek (cfrac)
    \[
        \frac{\lvert  x - fl^t(x)  \rvert}{\lvert  x  \rvert}  \le  \frac{\cfrac{b^{p-t}}{2}}{b^{p-1}}
        = \frac{b^{p-t+1-p}}{2} = \frac{b^{1-t}}{2} = \varepsilon_M
    \]

 (frac)
    \[
        \frac{\lvert  x - fl^t(x)  \rvert}{\lvert  x  \rvert}  \le  \frac{\frac{b^{p-t}}{2}}{b^{p-1}}
        = \frac{b^{p-t+1-p}}{2} = \frac{b^{1-t}}{2} = \varepsilon_M
    \]

(rearranged)
    \[
        \frac{\lvert  x - fl^t(x)  \rvert}{\lvert  x  \rvert}  \le \frac{b^{p-t}}{2b^{p-1}}
        = \frac{b^{p-t+1-p}}{2} = \frac{b^{1-t}}{2} = \varepsilon_M
    \]
\end{document}


text:
Q: Apache beam GroupByKey duplicate events I have a apache beam pipeline in java that looks like this:
        pipeline
        .apply("Read pubsub",PubsubIO.readStrings()
                .fromTopic(inputTopic)
        )
        .apply(window)
        .apply(ParDo.of(new OrderCodeKey()))
        .apply(GroupByKey.<String, RawBsonDocument>create())
        .apply(ParDo.of(new GetLastOrder()))
        .apply(ParDo.of(new ShopIDKey()))
        .apply(GroupByKey.create())
        .apply(ParDo.of(new CountShopOrder()))
        ;

Problem description: I need to stream events of orders from a pubsub topic, each event is of type "update" or "insert" and corresponding to an update/insert operation in mongodb for an order. In each event there are some notable fields:

*

*clusterTime -> the time at which the operation happens

*order_code -> order's code

*shop_id -> the shop which the order belongs to.

My goal is to compute the total orders per shop.
Detail of pipeline:

*

*Read from pubsub topic

*Create key-value pair (for subsequent GroupByKey) key is order code and value is the document

  public static class OrderCodeKey extends DoFn<String, KV<String, RawBsonDocument>>{
       @ProcessElement
       public void processElement (@Element String order, OutputReceiver<KV<String, RawBsonDocument>> out) throws ParseException {
           // Parse JSON
           RawBsonDocument document = RawBsonDocument.parse(order);
           BsonDocument fullDocument = document.getDocument("fullDocument");
           String orderCode = fullDocument.getString("order_code").getValue();
           //Integer orderCode = 0;
           out.output(KV.of(orderCode, document));
       }
   }

*

*GroupByKey (group by order_code)

*Combine events with same order_code to get the latest order (the one with the biggest clusterTime)

public static class GetLastOrder extends DoFn<KV<String, Iterable<RawBsonDocument>>, KV<String, BsonDocument>>{
        @ProcessElement
        public void processElement (@Element KV<String, Iterable<RawBsonDocument>> orders, OutputReceiver<KV<String, BsonDocument>> out) throws ParseException, java.text.ParseException {
            List<RawBsonDocument> docs = Lists.newArrayList(orders.getValue());
            Collections.sort(docs, new Comparator<RawBsonDocument>(){
                @Override
                public int compare(RawBsonDocument o1, RawBsonDocument o2) {
                    BsonTimestamp t1 = o1.get("clusterTime").asTimestamp();
                    BsonTimestamp t2 = o2.get("clusterTime").asTimestamp();
                    return t2.compareTo(t1); // sort desc
                }
            });
            RawBsonDocument document = docs.iterator().next();
            out.output(KV.of(orders.getKey(), document.getDocument("fullDocument")));
        }

*

*Create new key (key= shop_id) for subsequent GroupByKey

public static class ShopIDKey extends DoFn<KV<String, BsonDocument>, KV<Long, BsonDocument>>{
        @ProcessElement
        public void processElement (@Element KV<String, BsonDocument> order, OutputReceiver<KV<Long, BsonDocument>> out) throws ParseException {
        Long shopId =  Long.valueOf(order.getValue().getInt32("shop_id").getValue());
        out.output(KV.of(shopId, order.getValue()));
        }
    }

*

*GroupByKey (group by shop_id)

*Count number of orders per shop

public static class CountShopOrder extends DoFn<KV<Long, Iterable<BsonDocument>>, Shop>{
        @ProcessElement
        public void processElement (@Element KV<Long, Iterable<BsonDocument>> orders, OutputReceiver<Shop> out) throws ParseException, java.text.ParseException {
            List<BsonDocument> docs = Lists.newArrayList(orders.getValue());
            Long countOrder = Long.valueOf(docs.size());
        }
    }

In the last step, I assume that the input Iterable orders will contain only unique  orders (because after the GroupByKey-GetLastOrder, only the latest event is kept). However, When I debug I received events with the same order_code - which I have already reduced by GetLastOrder ParDo. Here is the window and trigger I use:
Window<String> window = Window.<String>into(
                FixedWindows.of(Duration.standardMinutes(60))
                )
                .triggering(
                        AfterWatermark.pastEndOfWindow()
                        .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane())
                )
                .withAllowedLateness(Duration.standardSeconds(0))
                .accumulatingFiredPanes();

I would appreciate any comment/help on this. Thank you in advance!

A: If you don't need intermediate results but just want hourly summary of unique orders per shop, early triggering is unnecessary.
When you use .withEarlyFirings(AfterProcessingTime.pastFirstElementInPane()), each pane will process only a subset of data after the first data is arrived in the pane. With .accumulatingFiredPanes(), you will see the accumulated result from the previous pane, so the same data appear multiple times across the different panes for the same window.
Please see https://beam.apache.org/documentation/programming-guide/#setting-a-trigger for the details.


text:
Q: Where is the start menu folder for Windows 7 It's not "c:\Users\MyUserName\Start Menu\"

A: All Users
%SystemDrive%\ProgramData\Microsoft\Windows\Start Menu

Per Profile (unless redirected)
%SystemDrive%\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu


text:
Q: Включение в запрос полей из различных таблиц Как добавить в этот запрос: следующие поля:

*

*name, surname из таблицы datacenter и

*nane_avatar и has_avatar из таблицы photo.

в имеющийся запрос?
mysql_query("SELECT sender_id, content FROM massage WHERE recipient_id = '$id'");

A: Выражение "A LEFT JOIN B" в MySQL реализовано следующим образом:

*

*Таблица B устанавливается как зависимая от таблицы A и от всех таблиц, от которых зависит A.

*Таблица A устанавливается как зависимая ото всех таблиц (кроме B), которые используются в условии LEFT JOIN.

*Все условия LEFT JOIN перемещаются в предложение WHERE.

*Выполняются все стандартные способы оптимизации соединения, за исключением того, что таблица всегда читается после всех таблиц, от которых она зависит. Если имеется циклическая зависимость, MySQL выдаст ошибку.

*Выполняются все стандартные способы оптимизации WHERE.

*Если в таблице A имеется строка, соответствующая выражению WHERE, но в таблице B ни одна строка не удовлетворяет условию LEFT JOIN, генерируется дополнительная строка B, в которой все значения столбцов устанавливаются в NULL.

*Если LEFT JOIN используется для поиска тех строк, которые отсутствуют в некоторой таблице, и в предложении WHERE выполняется следующая проверка: column_name IS NULL, где column_name - столбец, который объявлен как NOT NULL, MySQL пререстанет искать строки (для отдельной комбинации ключа) после того, как найдет строку, соответствующую условию LEFT JOIN.

RIGHT JOIN реализован аналогично LEFT JOIN.
При указании жесткого порядка чтения таблиц в LEFT JOIN и STRAIGHT JOIN оптимизатор связей (который определяет, в каком порядке таблицы должны быть связаны) будет выполнять работу намного быстрее, так как ему потребуется проверять меньшее количество перестановок таблиц.
Обратите внимание: отсюда следует, что если выполняется запрос типа
SELECT * FROM a,b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key)
         WHERE b.key=d.key

MySQL будет делать полный просмотр таблицы b, поскольку LEFT JOIN заставит его читать эту таблицу перед d.
В этом случае, чтобы предотвратить полный просмотр таблицы b, нужно изменить запрос таким образом:
SELECT * FROM b,a LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key)
         WHERE b.key=d.key

Взято с Как MySQL оптимизирует LEFT JOIN и RIGHT JOIN

A: SELECT
  message.sender_id, message.content,
       senderInfo.name, senderInfo.surname,
       photo.name_avatar, photo.has_avatar

         FROM massage

             LEFT JOIN datacenter AS senderInfo ON message.sender_id = senderInfo.id
             LEFT JOIN photo ON message.sender_id = photo.id

                 WHERE message.recipient_id = '$id'


text:
Q: How to Bind and Display a Collection in a Data list or Grid View I have three classes for my page. Products are displayed on the page and are added to the basket.
The added products are displayed in a list box through a listbox.
I cannot figure out how to bind and display the collection in a data list or grid view so I have more control over the layout and any additional functionality I might like to add.For example adding removing items etc.
Here are the classes:
public class Product
{
    public string ProductID { get; set; }
    public string Name { get; set; }
    public string ShortDescription { get; set; }
    public string LongDescription { get; set; }
    public decimal UnitPrice { get; set; }
    public string ImageFile { get; set; }
}

public class CartItem
{
    public CartItem() {}

    public CartItem(Product product, int quantity)
    {
        this.Product = product;
        this.Quantity = quantity;
    }

    public Product Product { get; set; }
    public int Quantity { get; set; }

    public void AddQuantity(int quantity)
    {
        this.Quantity += quantity;
    }

    public string Display()
    {
        string displayString =
            Product.Name + " (" + Quantity.ToString()
            + " at " + Product.UnitPrice.ToString("c") + " each)";
        return displayString;
    }
}

public class CartItemList
{
    private List<CartItem> cartItems;

    public CartItemList()
    {
        cartItems = new List<CartItem>();
    }

    public int Count { get { return cartItems.Count; } }

    public CartItem this[int index]
    {
        get { return cartItems[index]; }
        set { cartItems[index] = value; }
    }

    public CartItem this[string id]
    {
        get {
            foreach (CartItem c in cartItems)
                if (c.Product.ProductID == id) return c;
            return null;
        }
    }

    public static CartItemList GetCart()
    {
        CartItemList cart = (CartItemList) HttpContext.Current.Session["Cart"];
        if (cart == null)
            HttpContext.Current.Session["Cart"] = new CartItemList();
        return (CartItemList) HttpContext.Current.Session["Cart"];
    }

    public void AddItem(Product product, int quantity)
    {
        CartItem c = new CartItem(product, quantity);
        cartItems.Add(c);
    }

    public void RemoveAt(int index)
    {
        cartItems.RemoveAt(index);
    }

    public void Clear()
    {
        cartItems.Clear();
    }
}

On my page, the products are displayed in a datalist from the database. Binding is done through sqldatasource.
This is the add method which adds the product to the listbox and simply adds and displays the string returned from the display() method in the class.
I'd like to figure out how to display the items in something like a label control etc.
protected void add(object sender, EventArgs e)
{
    Product p = new Product();
    LinkButton BuyNowButton = (LinkButton)sender;
    DataListItem item = (DataListItem)BuyNowButton.NamingContainer;
    Label IdLabel = (Label)item.FindControl("productidLabel");
    Label NameLabel = (Label)item.FindControl("productnameLabel");
    Label ValueLabel = (Label)item.FindControl("productpriceLabel");
    p.ProductID = IdLabel.Text;
    p.ProductName = NameLabel.Text;
    p.ProductPrice =Convert.ToDecimal(ValueLabel.Text);

    CartItemList cart = CartItemList.GetCart();
    CartItem cartItem = cart[p.ProductID];
    //if item isn't in cart, add it; otherwise, increase its quantity
    TextBox tb = (TextBox)item.FindControl("TextBoxQuantity");
    int quantity = Convert.ToInt16(tb.Text);
    if (cartItem == null)
    {
        cart.AddItem(p,quantity);
        total += Math.Round(p.ProductPrice * quantity, 2);
    }
    else
    {
        cartItem.AddQuantity(quantity);
        total += Math.Round(p.ProductPrice * quantity, 2);
    }

    displayList();
}

And here is the method that displays the basket:
protected void displayList()
{
    CartItemList cart = CartItemList.GetCart();
    CartItem item;

    for (int i = 0; i < cart.Count; i++)
    {
        item = cart[i];
        ListBox1.Items.Add(item.Display());
    }

    Label3.Text = "Total : " + total.ToString();
}

How do I display my data from either database or something like an arraylist on my page in a way that is very customizable as in add "addquantity" "remove" "display message once order total is over certain amount etc."?
So far I've just been binding it to gidviews or datalists or listboxes but that doesn't quite let me present it the way I would like to.
What's happening behind the scenes at websites basket ordering systems such as here https://takeaway.nandos.co.uk/Menu/Appeteasers


text:
Q: Stylelint Nesting Declaration Order Arrays In stylelint is it possible to nest arrays for the rule declaration-block-properties-order? I'm curious because I'd really like to have it enforce a declaration order similar to Nicolas Gallagher's Idiomatic CSS. However I don't really care if padding or margin come first.
I know I can do this easily by having this rule...
"declaration-block-properties-order":
    [
      {
        properties: [
          "position",
          "top",
          "right",
          "bottom",
          "left",
          "z-index"
        ],
      },
      {
        order: "flexible",
        properties: [
          "padding",
          "margin"
        ],
      },
    ]

However... what I'm looking to do is specify the order for padding and margin groups, so margin, margin-top, margin-right, margin-bottom, and margin-left can only come in this order, same for padding.. but not care which group is first. I've tried nesting the arrays but I'm not sure if this is possible or my syntax was wrong.
"declaration-block-properties-order":
    [
       {
        order: "flexible",
        properties: [
          {
            properties: [
              "margin",
              "margin-top",
              "margin-right",
              "margin-bottom",
              "margin-left"
            ],
          },
          {
            properties: [
              "padding",
              "padding-top",
              "padding-right",
              "padding-bottom",
              "padding-left"
            ],
          },
        ],
      },
    ]

but I don't want it to accept margin, margin-top, padding, margin-right, padding-right. I want the two groups to be organized but not care if the padding or margin group is first.

A:
In stylelint is it possible to nest arrays for the rule declaration-block-properties-order?

No, it is not possible.  You have two options:

*

*Write a plugin that offers this flexibility.

*Require that margin must come before padding, or vice versa, in your CSS code.

I'd recommend the latter option as the more specific your order of properties, the easier it is for team members to know where to look to see if a property is being used within a declaration block.


text:
Q: Telegram constantly send requests to the server I am working with telegram-bot.
I registered my bot in BotFather, established "server" on Google Cloud, setup webHook.
My bot is working okay, when I send some command to my bot it replies expected way. The thing that I cannot understand is messages from my 'server' (google cloud).
When I analyze it I have a feeling that telegram constantly sends requests to my API and not every message I previosly send but some of them.
This is log:
2019-04-28 07:47:51 default[20190428t121301]  [2019-04-28 07:47:51,838] ERROR in app: Exception on /telegram_notification [POST]
2019-04-28 07:47:51 default[20190428t121301]  Traceback (most recent call last):    File "/env/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app      response = self.full_dispatch_request()    File "/env/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request      rv = self.handle_user_exception(e)    File "/env/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception      reraise(exc_type, exc_value, tb)    File "/env/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise      raise value    File "/env/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request      rv = self.dispatch_request()    File "/env/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request      return self.view_functions[rule.endpoint](**req.view_args)    File "/home/vmagent/app/main.py", line 96, in telegram_notification      chat_id = data['message']['chat']['id']  KeyError: 'message'
2019-04-28 07:47:53 default[20190428t121301]  {'update_id': ...., 'edited_message': {'message_id': 360, 'from': {'id': ..., 'is_bot': False, 'first_name': '...', 'language_code': 'ru'}, 'chat': {'id': ..., 'first_name': '...', 'type': 'private'}, 'date': 1556389741, 'edit_date': 1556389827, 'text': '.......'}}
2019-04-28 07:47:53 default[20190428t121301]  [2019-04-28 07:47:53,191] ERROR in app: Exception on /telegram_notification [POST]
2019-04-28 07:47:53 default[20190428t121301]  Traceback (most recent call last):    File "/env/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app      response = self.full_dispatch_request()    File "/env/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request      rv = self.handle_user_exception(e)    File "/env/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception      reraise(exc_type, exc_value, tb)    File "/env/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise      raise value    File "/env/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request      rv = self.dispatch_request()    File "/env/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request      return self.view_functions[rule.endpoint](**req.view_args)    File "/home/vmagent/app/main.py", line 96, in telegram_notification      chat_id = data['message']['chat']['id']  KeyError: 'message'
2019-04-28 07:47:54 default[20190428t121301]  {'update_id': ....., 'edited_message': {'message_id': 360, 'from': {'id': ..., 'is_bot': False, 'first_name': '....', 'language_code': 'ru'}, 'chat': {'id': ...., 'first_name': '....', 'type': 'private'}, 'date': 1556389741, 'edit_date': 1556389812, 'text': 'Сафмуллин Данил: 3400.0,\nРаевская Вероника: 4000.0'}}fa
2019-04-28 07:47:54 default[20190428t121301]  [2019-04-28 07:47:54,123] ERROR in app: Exception on /telegram_notification [POST]
2019-04-28 07:47:54 default[20190428t121301]  Traceback (most recent call last):    File "/env/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app      response = self.full_dispatch_request()    File "/env/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request      rv = self.handle_user_exception(e)    File "/env/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception      reraise(exc_type, exc_value, tb)    File "/env/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise      raise value    File "/env/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request      rv = self.dispatch_request()    File "/env/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request      return self.view_functions[rule.endpoint](**req.view_args)    File "/home/vmagent/app/main.py", line 96, in telegram_notification      chat_id = data['message']['chat']['id']  KeyError: 'message'
2019-04-28 07:48:00 default[20190428t121301]  {'update_id': 448395744, 'message': {'message_id': 490, 'from': {'id': ..., 'is_bot': False, 'first_name': '...', 'language_code': 'ru'}, 'chat': {'id': ..., 'first_name': '...', 'type': 'private'}, 'date': 1556430040, 'voice': {'duration': 1, 'mime_type': 'audio/ogg', 'file_id': 'AwADAgADFgMAAjgJKEqOtfGGrxO9KgI', 'file_size': 4400}}}
2019-04-28 07:48:00 default[20190428t121301]  [2019-04-28 07:48:00,395] ERROR in app: Exception on /telegram_notification [POST]
2019-04-28 07:48:00 default[20190428t121301]  Traceback (most recent call last):    File "/env/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app      response = self.full_dispatch_request()    File "/env/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request      rv = self.handle_user_exception(e)    File "/env/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception      reraise(exc_type, exc_value, tb)    File "/env/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise      raise value    File "/env/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request      rv = self.dispatch_request()    File "/env/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request      return self.view_functions[rule.endpoint](**req.view_args)    File "/home/vmagent/app/main.py", line 97, in telegram_notification      text = data['message']['text']  KeyError: 'text'

As you can see, some messages send infinity number of times, and sometimes requests just drop and I got a Traceback KeyError.
I do not understand that behaviour.
1) Why I am getting some same messages ?
I am not sending it to my bot myself. Noone else can send it, since there is check for chat_id.
2) Why there are some Traceback with KeyError?
I think, according to API-telegram docs, that Webhook allows to send request only when some users send message? And here it is like Telegram is constantly sending request to my server..
@app.route('/telegram_notification', methods=['POST'])
def telegram_notification():
    if request.method == "POST":
        data = request.get_json()
        print(data)
        if data is None:
            return jsonify({'success': True})
        # structure of data
        # {'update_id': <int>,
        # 'message':
        #           {'message_id': 138,
        #           'from':
        #               {'id': <int>,
        #               'is_bot': False,
        #               'first_name': '<str>',
        #               'language_code': 'ru'},
        #           'chat':
        #               {'id': <int>,
        #               'first_name': '<str>',
        #               'type': 'private'},
        #           'date': 1556302822,
        #           'text': 'hi'}
        #  }
        # print(data)
        chat_id = data['message']['chat']['id']
        text = data['message']['text']
        if chat_id == <int>:
            # processing
        return jsonify({'success': True})

Also, I do not understand, why when I delete Webhook and then set it again, then restart my 'server', I received instantly dozen of messages from my bot..
EDIT ONE
In my  telegram_notification() under the section # proccessing I am requesting external APIs

A: I think I got the point here.
The problem was as follows. I had connection with external APIs in telegram_notification(), and when I sent message to my bot, which then led to requesting external API, I expected the response, but external APIs sometimes returned 500 error or 404 error and requests dropped.
I thought that Telegram gives up after reasonable numbers of tries and stopped requesting my Server of Google Cloud, but Telegram kept on trying and sending requests, they dropped and I got nothing in return in  telegram_notification().
Because of that I was getting KeyError and Telegram constantly sent requests to the server, until server responses correctly.
Now I fixed the external APIs I got dozens of messages from my bot.
At the current time I see the expected behaviour.


text:
Q: Gathering Largest and Smallest Numbers in C-String C++ my goal for my homework project was to create a program that accepts a series of integers with no spaces in-between as a string. Then to add it up and display the lowest and largest values in the string. I did get my sum and my largest value to work, but for whatever reason, the part of my program that is suppose to get the smallest value is not working, and when I attempt to cout the value, I get nothing.
For example, I enter 1234, I get
"The sum of all numbers within the string you input is 10
The largest value in this series of integers is 4, whilst the smallest value is" ,
Here is my full program. Any help is appreciated (:
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
//Declaring Variables & Character Array:
int size = 100;
char integers[size];

//Small and Large Numbers:
char small = '9';
char large = '0';

//Gathering Integers:
cout << "Please enter a series of integers with nothing between them.";
cin >> integers;

//Gathering Size of String:
size = (strlen(integers) + 1);

//Initializing Sum Variable:
int sum = 0;

//Gathering Sum of All Integers in String:
for(int i = 0; i < size; i++)
{
    if(integers[i] >= '0' && integers[i] <= '9' && integers[i] != '\0')
    {
        if(integers[i] == '0')
            sum += 0;
        if(integers[i] == '1')
            sum += 1;
        if(integers[i] == '2')
            sum += 2;
        if(integers[i] == '3')
            sum += 3;
        if(integers[i] == '4')
            sum += 4;
        if(integers[i] == '5')
            sum += 5;
        if(integers[i] == '6')
            sum += 6;
        if(integers[i] == '7')
            sum += 7;
        if(integers[i] == '8')
            sum += 8;
        if(integers[i] == '9')
            sum += 9;
    }
}

//Gathering Largest Value:
for(int j = 0; j < size; j++)
{
    if(integers[j] > large)
        large = integers[j];
}

//Gathering Smallest Number
for(int j = 0; j < size; j++)
{
    if(integers[j] < small)
        small = integers[j];
}

//Outputting Values:
cout << "The sum of all numbers within the string you input is " << sum << endl;
cout << "The largest value in this series of integers is " << large << ", whilst the smallest value is " << small << endl;

return 0;
}

A: The error is here
//Gathering Size of String:
size = (strlen(integers) + 1);

This is incorrect, it should be
size = strlen(integers);

Because you have the size incorrect you are processing the nul character at the end of a string, and this is messing up your smallest calculation (because the nul character is the smallest character).

A: The final result of small is \0, since you' ve scanned the null character, And its value is smallest.
See this: https://ideone.com/6sLWJV
And, as a suggestion. If you guarantee that your input won't surpass the size of the array, stop iteration by judging whether the current character is \0, rather than calculating the iteration time and compare it with the size of array.


text:
Q: Getting models in nested collections in Backbonejs I'm working in a collection that contains a model with collections of "itself". For example:
[{
     id: 1
     name: "John",
     children: [
         {
              id: 32
              name: "Peter",
              children: []
         },
         {
              id: 54
              name: "Mary",
              children: [
                  {
                      id:12,
                      name: "Kevin"
                  }
         ]
         },
     ]
}]

Let say that I want to get the Kevin "user" by its Id. But all that I have is the "first collection". How can I do that?? And about setting a user within a collection? Another thing: Its possible to get all the Kevin "parents" from him? Like Mary and John?
Does anyone has come to a issue like that?
Thanks a LOT

A: Underscore (which is a Backbone dependency, so you already have it) is great for this sort of thing; if you use its "map" function (which Backbone provides as a method on Collection) with its find function, you can do the following:
findPersonInPeopleCollection: function(nameWeAreLookingFor) {
    function findChildren(person) {
        if (!person.children) return [person];
        var children = _.map(person.children, function(child) {
            foundPeople.push(findChildren(child);
        })
        return _.flatten(children);
    }
    var allPeople = _.flatten(myCollectionOfPeople.map(findChildren));
    return _(allPeople).find(function(person) {
        return person.get('name') == nameWeAreLookingFor;
    }
}

If you wanted to store the parents initially you could either add logic to your "Person" model class's initialize function, eg.
var Person = Backbone.Model.extend({
    initialize: function() {
        _.each(this.get('children'), function(child) {
            child.parent = this;
        }, this);
    }
 });

You could also do something similar by overriding your collection's add method, or adding an event handler to it that triggers after people get added.

A: Well I've made a recursive function on the User's Collection that seems to solved the problem for now ( the best of this is that I can use for retrieve a "deep" model and change it.). Something like that ( if someone has any suggestions, be free to give it a opinion ):
findUserById: function(id) {
        var self = new Backbone.Collection(this.toJSON());

        return thisCollection(id, this);

        function thisCollection(id, collection, array) {
            var innerSelf = collection || this;
            var thisArray = array || [];
            for(var i = innerSelf.models.length; i--;) {
                if(innerSelf.models[i].get('id') == id) {
                    return [innerSelf.models[i]].concat([thisArray]);
                }else {
                    if(innerSelf.models[i].get('children').length > 0) {
                        thisArray.push(innerSelf.models[i]);
                        return thisCollection(id, innerSelf.models[i].get('children'), thisArray);
                    }else {
                        innerSelf.remove(innerSelf.models[i]);
                        return thisCollection(id, self, []);
                    }

                }
            }
        }

    }

Basically I return an array with 2 items. The first is the record that I'm looking for and the second is an array with the parents of this user.


text:
Q: How to match the variable of JQuery to PHP dropdownlist The result of dropdownlist is did not match what I wanted the data that has been selected. I would like to know how to pass the jquery or javascript variable to php or that is another to way to match the dropdownlist data?
    function editbtn(id){

        $('#employee_id_edit').val(id);

        var invoice_id = $('#user-user-list').find("#row_"+id).find("td:eq(1)").text();
        var payment_id = $('#user-user-list').find("#row_"+id).find("td:eq(2)").text();
        var category = $('#user-user-list').find("#row_"+id).find("td:eq(3)").text();
        var sale_person = $('#user-user-list').find("#row_"+id).find("td:eq(4)").text();
        var amount = $('#user-user-list').find("#row_"+id).find("td:eq(5)").text();

        $('#invoice_id_edit').val(invoice_id);
        $('#payment_id_edit').val(payment_id);
        $('#product_type_edit').val(category);
        $('#employee_edit').val(sale_person);
        $('#amount_edit').val(amount);

    }

              <label for="employee">Sale Person</label>
              <select id="employee_edit" name="employee_edit" class="form-control" autocomplete="off">
                        <?php
                        $employee_model = $registry->get('loader')->model('user');
                        $employee = $employee_model->getEmployee();
                        if(null !== $employee) {
                            foreach ($employee as $employee) {
                                ?>
                                <option  value="<?php echo $employee['username'];?>" selected><?php echo $employee['username']; ?></option>
                                <?php
                            }
                        } else {
                            ?>
                            <option>No Employee Available</option>
                            <?php
                        }
                        ?>
              </select>

A: I think you should use jquery plugins like 'jquery select2'(https://select2.org/)  or create some custom ajax request to send data from js to PHP backend and then get and handle a response from js part.


text:
Q: Which has better performance? I am thinking of database schema for post and its comments, in context of a social networking application and im wandering which of these two would give better performance:
I am storing comments of a post in "Comments" Table and posts in the "Posts" Table.
Now my schema for the comments table looks like this:
postId  commentId  postedBy  Date   CommentBody
Since in order to retrieve the comments of a post I would be required to search all posts whose postId matches postId of this specific post and even my postId could not become primary key since the postId would be non unique within the column(since several comments for a single post), therefore I was thinking if I could merge postId and commentId into one single commentId (this becomes primary key) using which postId could also be retrieved. This is how I am thinking:
CommentId would be generated as postId*100+i (where i is the ith comment on the post)
thus in order to retrieve comments for a post(say with postId=8452 ) I would search all posts with commentId(that would be primary key), lying between 845200 & 845299.. instead of searching all comments with postId=8452.. (of course this limits the maximum no of comments to 100). But will this lead to any performance gains?

A: Here's what you do. Load up a database with representative data at (for example) twice the size you ever expect it to get.
Then run your queries and test them against both versions of the schema.
Then, and this is the good bit, retest this every X weeks with new up-to-date data to ensure the situation hasn't changed.
That's what being a DBA is all about. Unless your data will never change, database optimisation is not a set-and-forget operation. And the only way to be sure is to test under representative conditions.
Everything else is guesswork. Educated guesswork, don't get me wrong, but I'd rather have a deterministic answer in preference to anyone's guess, especially since the former will adapt to changes.
My favorite optimisation mantra is "Measure, don't guess!"

A: I'd recommend:

*

*Use two-table structure with composite key in comments for best uniquness in index.

*100 comments per article is a bad limition that may hit you in the back.

*Dont use different tables for comments regarding video/pictures etc.

*If huge amounts of comments, add an comment-archive table and move old comments
there. Most requested comments (newest) will have a smaller and more efficient table.

*Do save blobs (pictures and videos) on different partition and not in db. Db will be smaller and less fragmented at file level.
regards,
/t

A: If you gonna get big volume you should make a table Post and a table Comments in order to have smaller table :). And don't forget to use index and partitions on them.

A: If CommendId is not unique, you can create a composite PRIMARY KEY on (postId, CommentID):
CREATE TABLE Comment
        (
        postId INT NOT NULL,
        commentId INT NOT NULL,
        …,
        PRIMARY KEY (postId, commentId)
        )

If your table is MyISAM, you can mark commentId as AUTO_INCREMENT, which will assign it with a per-post UNIQUE incrementing value.
If it is unique, you can create a PRIMARY KEY on CommentId and create a secondary index on (PostId, CommentId):
CREATE TABLE Comment
        (
        commentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        postId INT NOT NULL,
        …,
        KEY (postId, commentId)
        )

A: Use a composite key. Or, if you're using some framework that only allows single-column keys, a secondary index on postId

A:
CommentId would be generated as postId*100+i (where i is the ith comment on the post)
thus inorder to retrieve comments for a post(say with postId=8452 ) I would search all posts with commentId(that would be primary key), lying between 845200 & 845299.. instead of searching all comments with postId=8452.. (ofcourse this limits the maximum no of comments to 100). But will this lead to any performance gains ??

This will likely give much worse performance than a query based on a postId foreign key column, but the only way to be sure is to try both techniques (as suggested by paxdiablo) and measure the performance.


text:
Q: Total variation distance of $B(n,p)$ and $B(n+1,p)$ How can one prove that $B(n,p)$ and $B(n+1,p)$ have distance $= \Omega (1/n)$?
My professor claimed that it does not need any tedious calculation. So I prefer to solve it without summation over the difference of Binomial coefficient. Can someone help me to do it?

A: Assume that someone has coupled $X \sim Bin(n,p)$ and $Y \sim Bin(n+1,p)$.
Calculate Expectations of $X,Y$ ,which are actually $np$ and $(n+1)p$ in this way:
$$\mathbb{E}X=\mathbb{E}[X|X=Y]\times \mathbb{P}[X=Y]+\mathbb{E}[X|X \ne Y]\times \mathbb{P}[X\ne Y]$$
$$\mathbb{E}Y=\mathbb{E}[Y|X=Y]\times \mathbb{P}[X=Y]+\mathbb{E}[Y|X \ne Y]\times \mathbb{P}[X\ne Y]$$
by setting $\mathbb{P}[X \ne Y]=q$ and subtracting these two equation we get:
$$p=q\times (\mathbb{E}[Y|X \ne Y]-\mathbb{E}[X|X \ne Y])$$
So
$$q=\frac{p}{\mathbb{E}[Y|X \ne Y]-\mathbb{E}[X|X \ne Y]}$$
Now to minimizing $q$ you need to maximize the denominator Which is at most $n+1$
Hence
$$q \ge \frac{p}{n+1}$$as you want.


text:
Q: Probability to find treasure You have a metal detector that will beep 99 times out of 100 if it contains buried treasure within a metre squared. It will also beep 1 time in a 100 if it does not contain buried treasure. I'm searching an island containing John last hidden treasure. You have divided the island up into 1,001 1 metre by 1 metre squares which you plan to test individually. On the first square the metal detector beeps. What is the chance that you've discovered the treasure?
I have no idea how to tackle this problem. Would you like to help me please?

A: Guide:
Let $B$ denotes the event that the metal detector beeps.
Let $T$ denote the event that there is treassure.
Now apply Bayes rule on $P(T|B)=\frac{P(T)P(B|T)}{P(B)}=\frac{P(T)P(B|T)}{P(T)P(B|T)+P(T^c)P(B|T^c)}$.
You will have to make some assumption, such as the treassure only appears in exactly one of the squares.


text:
Q: How do I target the last N sibling elements only when there are Y siblings in CSS? Is it possible to target the last N sibling elements when there are Y siblings?
For example I have list of items, if and only if there are exactly 8, 11, 14... etc sibling elements I want the last two to look different (so 8 + 3n).
If there is any other amount of children I want them all to look the same.

A: The easiest way by far is to target each of the 2 elements you want to style with its own set of pseudo-classes.
The last child, as you state, is represented by 3n+8 (8, 11, 14...). It then follows that the penultimate child is 3n+7 (7, 10, 13...).

li:nth-last-child(1):nth-child(3n+8),
li:nth-last-child(2):nth-child(3n+7) {
  color: red;
}

ul { counter-reset: item; list-style-type: none; }
li { display: inline; padding: 0.25em; }
li::before { content: counter(item); counter-increment: item; }

You can also do this with one complex selector using the technique from Can CSS detect the number of children an element has?, substituting 3n+8 for the :nth-last-child() argument, and using an additional :nth-last-child(-n+2) to target the last two elements with one pseudo-class:

li:first-child:nth-last-child(3n+8) ~ li:nth-last-child(-n+2) {
  color: red;
}

ul { counter-reset: item; list-style-type: none; }
li { display: inline; padding: 0.25em; }
li::before { content: counter(item); counter-increment: item; }

A: Based on

If and only if there are 8 elements I want the last two to look different.

You'll get this:

li:nth-child(7):nth-last-child(2),
li:nth-child(8):nth-last-child(1) {
  color: red;
}
Will colorize 7 and 8

1

2

3

4

5

6

7

8

Will colorize nothing since it has more then 8 elements

1

2

3

4

5

6

7

8

9

10

A:
Is it possible to target the last N sibling elements when there are Y
  siblings?

Yes, you can chain pseudo-classes so that they have to match a count from the beginning and a count from the end:
ol li:nth-of-type(3n + 8):nth-last-of-type(1),
ol li:nth-of-type(3n + 7):nth-last-of-type(2) {
color: rgb(255,0,0);
}

Example:

ol {
float:left;
width:80px;
}

ol li:nth-of-type(3n + 8):nth-last-of-type(1),
ol li:nth-of-type(3n + 7):nth-last-of-type(2) {
color: rgb(255,0,0);
}

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element

Element


text:
Q: Android: Unable to display thumbnail of video I am trying to display thumbnail of a video but I am not able to generate the thumbnail for the video.
My activity_main contains
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<ImageView
android:id="@+id/Thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>

My Main Activity has the following code
package com.example.video1;

import android.app.Activity;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.provider.MediaStore.Video.Thumbnails;
import android.widget.ImageView;

public class MainActivity extends Activity {

    String filePath = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        ImageView thumbnail_mini = (ImageView) findViewById(R.id.Thumbnail);

        Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath,
                Thumbnails.MINI_KIND);

        thumbnail_mini.setImageBitmap(bmThumbnail);

    }
}

Its displaying nothing . How can I display the thumbnail of video?

A: You can't get the thumbnail from a link with the android SDK. You would have to download it locally and then use the thumbnail.utils


text:
Q: How to make a custom stack on Eclipse-Che for Node-Red module? I want to make a custom stack for eclipse che for node-red.
Can anybody tell me the detailed procedure?

A: The stack notion was used for old Che 6.x.
For Che 7.x it is a devfile [1]
Read the doc how to configuring your workspace using a devfile [2]
[1] https://redhat-developer.github.io/devfile/
[2] https://www.eclipse.org/che/docs/che-7/configuring-a-workspace-using-a-devfile/


text:
Q: How do I uncheck all "md-checkboxes" (NOT real checkboxes) on a HTML page from a Greasemonkey script? After wasting countless sweaty hours, swearing and cursing the name of the only food store I can use and how they keep checking their user-hostile options every single pageload, no matter how many times I uncheck them, and no matter how many times I report this "bug" (it's deliberate), I am simply forced to ask you experts for help.
The webpage doesn't use real HTML checkboxes, but instead something they call "md-checkboxes". It's an "AngularJS" thing. The AngularJS manual doesn't explain anything whatsoever, and neither does any of the numerous webpages (including Stack Overflow questions) I've been plowing through. None of the seemingly relevant code snippets do anything but dump various errors in the console.
This is the overall structure I have:
function turn_the_damn_things_off()
{
    var checkboxes = document.getElementsByTagName('md-checkbox');

    for (var i = 0; i < checkboxes.length; i++)
    {
        // I have tried countless things here, but nothing works. The checkboxes are never unchecked. I am, however, certain that the code here executes.
    }
}

setInterval(turn_the_damn_things_off, 500);

The reason I do this in an interval is that they seem to be re-checked not right away but after about a second after the page has been loaded.

A: for (var i = 0; i < checkboxes.length; i++)
{
  let x = checkboxes[i];
  if(x.getAttribute("aria-checked") === "true")
    x.classList.toggle("md-checked");
}