text:
Q: confusion on using nodejs within an actual web application or ide I am new to using nodejs completely, and it seems to be pretty much the go to thing for everything right now. But I program in Visual Studio, and I'm a bit confused about how this works. I will cite an example;
One task I want to do is to get a list of all the files in a directory and all of its sub-directories, and return them as a string[] for a javascript .config file. I started searching for that and found a lot of answers, but they all kept going back to nodejs, for instance, this one, and this one, and this one.
I really wasn't looking for anything having to do with nodejs, it just seems to be part of every solution out there. I've installed it, and gotten it to where I can do some simple things like create a very basic server that listens to a port - thanks to simple tutorials written for a moron like me - but I'm having a hard time figuring out how to use these kinds of things in my real programs - specifically ASP.NET MVC. I've searched pretty hard on this topic too, and discovered things like iisnode and the like that do some partial integration.
But even with all of this, this wealth of information, I am extremely confused.
I understand that I can use it from a command line, like PowerShell, I can run commands from a terminal, and install packages into projects, but I'm having a hard time seeing and finding how this actually translates into literal, real usage in an existing application. I have scoured around for days and days for examples, I've read at least 3 books on nodejs, The Node Beginner Book, What is Node, and Professional Node.js and to be very honest I am still as lost as ever.
Everything I read keeps assuming I am doing things from the command line or a terminal, but all of the applications I see for node assume you're writing a web application. I'm having a really hard time wrapping my head around how you use it within an application. Can anyone assist me with this? Perhaps a working example of an actual program that uses node? I'll take almost anything at this point, though ASP.NET MVC is my core system of choice.
I was originally going to post this on StackOverflow, but someone suggested that this community was more appropriate for this question.
Update
I want to make a more clear example of what is confusing me, I'm already learning because of the 1 proposed answer, but let me give more examples.
I program in Visual Studio, it has no real concept of node.js - in fact, if I try to do things that will run against node, it gives me problems. I often have to code anything related to node in WebStorm from JetBrains.
I understand that I can 'compile' things with node, what I don't understand is how I can invoke it within my program, not inside of a command line. For example let's say there is a node module that takes an array and does something to it - for sake of example let's say that it sorts everything in the array alphabetically, and it is a module called supersort.
So if I were at the console, I would just type in ...

node supersort.js

Okay, but now I'm not at the command line. I have published my web application. My user is at a page, let's say /account/history and they are seeing a list of every product they have bought. For the sake of argument, say I've got that list as a object[] or string[] - I realize that is completely absurd and it would be far more complex, but just jive with me.
I want to run supersort on this page. But it's live! How do I do it? How do I run this module on their live, active data without manually being there at the console? Is there a set of javascript files I'm supposed to download and call http requests a certain way? Do I wire up a special IHttpHandler in IIS? I think you can start to see where I am lost.
Update 2
Attempting to further emphasize my question, I'll try and cite a more specific example. I want to use the library Q.js in my ASP.NET MVC application. Now, there is a version 1 that I can seem to run out of the box, but I want to try out version 2 - you can find it linked Q.js v2 (beta)
So I am using Visual Studio, and I'll download the q.js file and load it up, but immediately we already have trouble now - if you look at the file's source code right away I see this.
require("collections/shim");
var WeakMap = require("collections/weak-map");
var Iterator = require("collections/iterator");
var asap = require("asap");

Now I certainly don't have folders with those names in my application - and even though I have node.js installed, putting this file in a <script> tag does not work, as it says it cannot find the specific libraries. If I go to a console explicitly and type in npm install -g q@~2, it will create a folder called node_modules/q in my AppData/Roaming/npm folder, and this one does have folders for those other libraries.
So what is the right way to do this? It's clear that just having node installed doesn't make node commands work when I try to run the page in ASP.NET MVC - but I also don't understand how to get to the final version of the library that I can include on my application like a normal javascript file and use across the program.

A: node.js (not nodejs, as you seem to put it), is a server side technology.
In that respect, it is like Apache or IIS - web servers.
It can and mostly is used as a backend for web applications (and web based APIs) - it serves up whatever it is coded to serve up (in that respect, no different from Apache and IIS).
If you code up a web application (serving HTML and whatever else is involved in writing a web application) in node, that's what it would be serving, a web application.
The reason you see a lot of discussion of the command line/terminal is that there is no GUI for node. One is expected to use an editor to write the node application and run it from the command line. It is not wrapped up in a service for you, like IIS.

A: It seems to me that you've gone down a rabbit hole. If you're writing an application in ASP.Net, why not just research how to solve a particular problem in that platform? I'd need to have a pretty damn good reason to add another tool/language/platform to my solution, and I don't get the impression that such a compelling reason exists for you. Node.js may be the hip thing right now and offer some pretty neat ways to solve problems, but you probably could have solved your problem natively 10 times over by now. That's just my two cents.


text:
Q: jpa, eclips-link 2.5.1: OneToMany not working on columns not primary key I have these two entities:
Anagrafica
  @Entity
    @Access(AccessType.FIELD)
    @Table(name = "S_MC_CC_USER")
    @SequenceGenerator(name = "SEQ_ID", sequenceName = "SEQ_ID", allocationSize = 1)
    public class Anagrafica implements Serializable{
        private static final long serialVersionUID = 332466838544720886L;

        @EmbeddedId
        private AnagraficaId anagraficaId;

        @Column(name = "USER_ID")
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ID")
        private Long userId;

        @OneToMany(cascade = CascadeType.ALL)
        @JoinColumn(name = "USER_ID", updatable = false, insertable = false)
        private List<Mobile> mobiles;

/**
     * La classe di dominio che modella la chiave primaria di un {@link Anagrafica}
     *
     * @author Massimo Ugues
     *
     */
    @Embeddable
    static public class AnagraficaId implements Serializable {
        private static final long serialVersionUID = -54640203292300521L;

        @Column(name = "ANAG_UTENTE")
        private String bt;

        @Column(name = "COD_ABI")
        private String abi;

        public AnagraficaId() {
            super();
        }

Mobile
@Entity
@Table(name = "S_MOBILE")
@SequenceGenerator(name = "SEQ_MOBILE", sequenceName = "SEQ_MOBILE", allocationSize = 1)
public class Mobile implements Serializable{
    private static final long serialVersionUID = 5999493664911497370L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_MOBILE_DEVICE_REGISTRY")
    @Column(name = "ID_MOBILE")
    private Long mobileId;

    @Column(name = "DEVICE_TOKEN")
    private String deviceToken;

    @Column(name = "DATA_INSERIMENTO")
    @Temporal(TemporalType.TIMESTAMP)
    private Calendar dataInserimento = Calendar.getInstance();

With eclispe-link 2.1.2 all works great, but with eclispe-link 2.5.1 I got this exception:
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [persistence-unit] failed.
Internal Exception: Exception [EclipseLink-7220] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The @JoinColumns on the annotated element [field mobiles] from the entity class [class com.intesasanpaolo.domain.entities.sub.Anagrafica] is incomplete. When the source entity class uses a composite primary key, a @JoinColumn must be specified for each join column using the @JoinColumns. Both the name and the referencedColumnName elements must be specified in each such @JoinColumn.
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:1954)
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1945)
    at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:322)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    ... 40 more

The problem is the OneToMany association based on a foreign key that is not primary key.
Since I cannot change the database model how can I make it work?
Kind regards
Massimo

A: The reason it worked in a prior version was that it EclipseLink doesn't look at the fields in the mapping, but with JPA adding derived Id support, EclipseLink now validates the number of foreign keys match the number of ID fields.
James' answer here
JPA @JoinColumn issues while joining on non primary key columns
explains it that you'll need to use a descriptorCustomizer to change the JPA mapping.  So you would either not map the field in JPA (mark it as @Transient) and then add a mapping in the customizer, or have the JPA mapping to use all primary key fields and then change the mapping in the customizer to only use the USER_ID->USER_ID fields.
EclipseLink customizers are shown here:
http://eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_customizer.htm

A: Ok, this is the Customizer I created:
public void customize(ClassDescriptor descriptor) throws Exception {
        // handle the oneToManyMapping to non foreign keys
        ManyToManyMapping mapping = (ManyToManyMapping) descriptor.getMappingForAttributeName("mobileDevices");
        ExpressionBuilder builder = new ExpressionBuilder();
        mapping.setSelectionCriteria(builder.getField("USER_ID").equal(builder.getParameter("USER_ID")));

        // handle the insert statement
        mapping.setInsertCall(new SQLCall(""));
    }

As suggested from Chris this works great with the selection.
I had to modify the Insert Call since eclipse-link tried to create and insert statement on a mapping table that I haven't.
The problem now is on the delete: when I try to delete the collection from the source association (i.e. Cliente) as described here
Cliente.ClienteId id = new Cliente.ClienteId(abi, bt);
Cliente cliente = clienteRepository.findOne(id);
cliente.setMobileDevices(null);

I need eclipse link to delete the orphan.
The dml generated is the following:
DELETE FROM S_MC_CC_CLIENTI_S_MOBILE_DEVICE_REGISTRY WHERE ((mobileDevices_ID_MOBILE_DEVICE_REGISTRY = 13) AND ((ANAG_UTENTE = '71576493') AND (COD_ABI = '01025')))

Since I haven't the mapping table I modified the customizer adding a setDeleteCall statement    :
mapping.setDeleteCall(new SQLCall("DELETE FROM S_MOBILE_DEVICE_REGISTRY WHERE USER_ID = #USER_ID"));

In this way eclipse link generates 2 dml:
DELETE FROM S_MOBILE_DEVICE_REGISTRY WHERE USER_ID = NULL
DELETE FROM S_MOBILE_DEVICE_REGISTRY WHERE (ID_MOBILE_DEVICE_REGISTRY = 13)

The first is the translation of my SQLCall, but without the correct parameter: any idea how to generate only the correct delete statement?
Kind regards.
Massimo

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use the compass sprite production RWD, do not compile without pictures? My folder has a.png and b.png two pictures, and this is my scss code:
@import "icon/*.png";
@include all-icon-sprites(true);

Compile results:
.icon-sprite, .icon-a, .icon-b{
   background: url('/images/icon-s351f62e8ff.png') no-repeat;
}
.icon-a {
 background-position: 0 0;
 height: 138px;
 width: 170px;
}
.icon-b {
 background-position: 0 -138px;
 height: 44px;
 width: 113px;
}

When I use the media query produced RWD, only b.png make changes, and put under another tablet icon Data folder, as follows:
@media only screen and (min-width : 768px) and (max-width : 1024px) {
  @import "tablet/icon/*.png";
  @include all-icon-sprites(true);
}

Compile results:
 @media only screen and (min-width : 768px) and (max-width : 1024px) {
  .icon-sprite, .icon-a, .icon-b {
   background: url('/images/tablet/icon-s26eab31296.png') no-repeat;
  }
}

But I do not want to compile .icon-a of this class, there is no a.png folder inside the file, how do I get it to compile the results as follows:
 @media only screen and (min-width : 768px) and (max-width : 1024px) {
  .icon-sprite, .icon-b {
   background: url('/images/tablet/icon-s26eab31296.png') no-repeat;
  }
}

Thank you:)

A: Maybe, this can help you:
@media only screen and (min-width : 768px) and (max-width : 1024px) {
  @import "tablet/icon/*.png";
  @include icon-sprites(b);
}

where b - name of your b.png
more information you can find here: http://compass-style.org/help/tutorials/spriting/
chapter: "Selector Control"

A: I tried the way you offer, but after compiling still produces other class.
My final solution is still to create a tablet-icon folder, in addition to compile it and add a class to each state in html, and no way to continue with the same class do different css sprite.
Thank you for giving me some ideas:)


text:
Q: Tikz graphdrawing trees layout: center second child I have created following tree/graph:
%! TEX program = lualatex
\documentclass[]{scrartcl}
\usepackage{tikz}

\usetikzlibrary{
  graphs,
  graphdrawing,
  quotes,
}
\usegdlibrary{trees}

\begin{document}

{\footnotesize
\begin{tikzpicture}[
  every node/.style={align=center},
]

\graph[
    tree layout,
    minimum number of children=3,
    missing nodes get space=false,
    edge quotes={anchor=center, align=center},
    edges={nodes={fill=white}},
    sibling distance=28mm,
    level distance=28mm,
  ]{

  % % level 1:
  %   a/"$P4/m2/m/2/m$";
  % % level 2:
  %   b/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  % % level 3:
  %   c/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  %   d/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  % % level 4:
  %   e/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  %   f/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  %   g/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  % % level 5:
  %   h/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  %   i/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  % % level 6:
  %   j/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  %   k/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  %   l/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";
  % % level 7:
  %   m/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}";

  a ->
  b[second] ->  {  c[first] -> {e[first], , }, d[second]->{f[first] -> h[second] -> {, j[second],k[third] -> m}, ,g[third] -> i[second] -> l[second] -> m}, };
};

\end{tikzpicture}
}
\end{document}

The result looks just like I want it:

However, if I uncomment the code block, the second children are no longer at centered positions:

How can I force tikz graphdrawing to stick to the same positioning as for the single letter node labels.
Related question seem to be Centering children of tikz tree layout
The only answer recommends to switch to the forest package. However, I would be happy if I could stay with the tikz graphdrawing library. I am also not sure whether the forrest package actually allows to draw a graph not only trees.

A: This solution uses numerous post-anchoring adjustments to position nodes in their desired positions on the canvas. This is done using the regardless at key (see p380 of TikZ manual). The result is that rather than nodes being placed at locations determined by the graph drawing algorithm, the nodes are placed at the nominated coordinates.
In an instance like this, where the location of the nodes is known, and they have a symmetrical layout, my preference would be to use either a matrix of nodes, or the features of the positioning library to place nodes appropriately, without the need to invoke any graph drawing algorithm. Nevertheless, the question asks for a solution using graph drawing syntax, so maybe this will be useful.
To make it easier to follow the code and the graph it generates, the nodes are identified with a name (a through m), together with the labels given by the OP. This is done with a command \lb. The background grid is from  How can I show coordinates by grid in TikZ automatically?
This is the result:

This is the code:
%! TEX program = lualatex
\documentclass[tikz,border=3pt]{standalone}

\usetikzlibrary{
  graphs,
  graphdrawing,
}
\usegdlibrary{
layered}

\pagestyle{empty}

% https://tex.stackexchange.com/a/39698
\makeatletter
\def\grd@save@target#1{%
    \def\grd@target{#1}}
\def\grd@save@start#1{%
    \def\grd@start{#1}}
\tikzset{
    grid with coordinates/.style={
        to path={%
            \pgfextra{%
                \edef\grd@@target{(\tikztotarget)}%
                \tikz@scan@one@point\grd@save@target\grd@@target\relax
                \edef\grd@@start{(\tikztostart)}%
                \tikz@scan@one@point\grd@save@start\grd@@start\relax
                \draw[minor help lines] (\tikztostart) grid (\tikztotarget);
                \draw[major help lines] (\tikztostart) grid (\tikztotarget);
                \grd@start
                \pgfmathsetmacro{\grd@xa}{\the\pgf@x/1cm}
                \pgfmathsetmacro{\grd@ya}{\the\pgf@y/1cm}
                \grd@target
                \pgfmathsetmacro{\grd@xb}{\the\pgf@x/1cm}
                \pgfmathsetmacro{\grd@yb}{\the\pgf@y/1cm}
                \pgfmathsetmacro{\grd@xc}{\grd@xa + \pgfkeysvalueof{/tikz/grid with coordinates/major step}}
                \pgfmathsetmacro{\grd@yc}{\grd@ya + \pgfkeysvalueof{/tikz/grid with coordinates/major step}}
                \foreach \x in {\grd@xa,\grd@xc,...,\grd@xb}
                \node[anchor=north,color=blue] at ([yshift=-0.15cm]\x,\grd@ya) {\pgfmathprintnumber{\x}};
                \foreach \y in {\grd@ya,\grd@yc,...,\grd@yb}
                \node[anchor=east,color=blue] at ([xshift=-0.15cm]\grd@xa,\y) {\pgfmathprintnumber{\y}};
            }
        }
    },
    minor help lines/.style={
        help lines,
        step=\pgfkeysvalueof{/tikz/grid with coordinates/minor step},
        minor line width/.initial=0.25pt,
    },
    major help lines/.style={
        help lines,
        line width=\pgfkeysvalueof{/tikz/grid with coordinates/major line width},
        step=\pgfkeysvalueof{/tikz/grid with coordinates/major step},
        line cap=round,
        color=lightgray,
    },
    grid with coordinates/.cd,
    minor step/.initial=1, % just use major
    major step/.initial=1,
    major line width/.initial=0.5pt,
}
\makeatother
\newcommand{\lb}[3]{{\begin{tabular}{c}#1\\#2\\\fbox{#3}\end{tabular}}}

\begin{document}

\begin{tikzpicture}[
font=\normalsize\bfseries
]

\draw (-14,-20) to[grid with coordinates] (8,1);

\graph[
    layered layout,
    sibling distance=50mm,
    level distance=30mm,
  ]{
      a/\lb{a}{$P4/m2/m/2/m$}{} -> b/\lb{b}{$P4/n2_1/m2/m$}{$HT-WO_3$} -> d/\lb{d}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(0,-6)}],
%%
      d -> {f/\lb{f}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(-6,-9)}],g/\lb{g}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(6,-9)}]},
%%
      f -> h/\lb{h}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(-6,-12)}] -> j/\lb{j}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(-6,-15)}],
      g -> i/\lb{i}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(6,-12)}] -> l/\lb{l}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(6,-15)}] -> m/\lb{m}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(6,-18)}],
      h -> k/\lb{k}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(0,-15)}],
      k -> m,
%%
      b -> c/\lb{c}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(-6,-6)}] -> e/\lb{e}{$P4/n2_1/m2/m$}{$HT-WO_3$}[regardless at={(-12,-9)}]
  };

\end{tikzpicture}

\end{document}

A: Use calculated coordinates from first run
%! TEX program = lualatex
\documentclass[]{scrartcl}
\usepackage{tikz}

\usetikzlibrary{
  calc,
  graphs,
  graphdrawing,
  quotes,
}
\usegdlibrary{trees}

\makeatletter
\def\extractcoord#1#2#3{
  \path let \p1=(#3) in \pgfextra{
    \pgfmathsetmacro#1{\x{1}/\pgf@xx}
    \pgfmathsetmacro#2{\y{1}/\pgf@yy}
    \xdef#1{#1} \xdef#2{#2}
  };
}
\makeatother

\begin{document}

{\footnotesize
\begin{tikzpicture}[
  every node/.style={align=center},
]

\graph[
    tree layout,
    minimum number of children=3,
    missing nodes get space=false,
    edge quotes={anchor=center, align=center},
    edges={nodes={fill=white}},
    sibling distance=28mm,
    level distance=28mm,
  ]{

    % % copy `nail at` from log file
    % a/"$P4/m2/m/2/m$"                    [nail at={(TO BE DETERMINED)}];
    % b/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % c/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % d/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % e/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % f/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % g/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % h/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % i/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % j/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % k/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % l/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];
    % m/"$P4/n2_1/m2/m$\\\fbox{$HT-WO_3$}" [nail at={(TO BE DETERMINED)}];

  a ->
    b[second] ->  {
    c[first] -> { e[first], , },
    d[second]->{
      f[first] -> h[second] -> {,
        j[second],
        k[third] -> m
      }, ,
      g[third] -> i[second] -> l[second] -> m
    },
  };
};

\extractcoord\xa\ya{a}\typeout{[nail at={(\xa,\ya)}];}
\extractcoord\xb\yb{b}\typeout{[nail at={(\xb,\yb)}];}
\extractcoord\xc\yc{c}\typeout{[nail at={(\xc,\yc)}];}
\extractcoord\xd\yd{d}\typeout{[nail at={(\xd,\yd)}];}
\extractcoord\xe\ye{e}\typeout{[nail at={(\xe,\ye)}];}
\extractcoord\xf\yf{f}\typeout{[nail at={(\xf,\yf)}];}
\extractcoord\xg\yg{g}\typeout{[nail at={(\xg,\yg)}];}
\extractcoord\xh\yh{h}\typeout{[nail at={(\xh,\yh)}];}
\extractcoord\xi\yi{i}\typeout{[nail at={(\xi,\yi)}];}
\extractcoord\xj\yj{j}\typeout{[nail at={(\xj,\yj)}];}
\extractcoord\xk\yk{k}\typeout{[nail at={(\xk,\yk)}];}
\extractcoord\xl\yl{l}\typeout{[nail at={(\xl,\yl)}];}
\extractcoord\xm\ym{m}\typeout{[nail at={(\xm,\ym)}];}

\end{tikzpicture}
}

\end{document}

Now you can find in the log file following code snippet
[nail at={(0.0,0.0)}];
[nail at={(0.0,-2.8)}];
[nail at={(-2.8,-5.6)}];
[nail at={(0.0,-5.6)}];
[nail at={(-5.6,-8.40001)}];
[nail at={(-2.8,-8.40001)}];
[nail at={(2.8,-8.40001)}];
[nail at={(-2.8,-11.2)}];
[nail at={(2.8,-11.2)}];
[nail at={(-2.8,-14.0)}];
[nail at={(0.0,-14.0)}];
[nail at={(2.8,-14.0)}];
[nail at={(2.8,-16.8)}];

You can insert this into the main document and uncomment the full vertex labels.


text:
Q: One column with autfit to jqgrid size I have jqGrid with 2 columns, 1 is hidden and I want to make the width of 2nd column to autofit to grid size.
can anybody help me?
I have highlighted the empty area.
  SelectedContactPerson = xmlString;
$("#ContactPersons").jqGrid({
    datatype: 'xmlstring',
    datastr: xmlString.XmlToString(),
    mtype: 'POST',
    beforeRequest: function () {
        //alert('beforeRequest');
    },
    loadError: function (xhr, status, error) {
        $(this).HideBusy();
        //   alert(status);
        //     alert(error);
        alert(xhr.responseText);
    },
    onSelectRow: function (id) {
        var CntctCode = $("#ContactPersons").jqGrid('getCell', id, 'CntctCode');
        SelectedContactPerson.find("OCPR>row").each(function (index) {
            if ($(this).find('CntctCode').text() == CntctCode) {
                var v1 = $(this).XmlToString();
                var v2 = '<OCPR>' + v1 + '</OCPR>';
                $(this).SetValuesToControl("BusinessPartner #CP", $($.parseXML(v2)));
            }
        });
    },
    loadComplete: function (data) {
        var top_rowid = $('#ContactPersons tr:nth-child(2)').attr('id');
        $("#ContactPersons").setSelection(top_rowid, true);
        $(this).HideBusy();
    },
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
    xmlReader: { repeatitems: false, root: "OCPR", row: 'row' },
    colNames: ['CntctCode', 'Name'],
    colModel: [
                        { name: 'CntctCode', key: true, index: 'CntctCode asc', hidden: true },
                        { name: 'Name', index: 'Name', sortable: false, align: "left"  }
           ],
    viewrecords: true,
    gridview: true,
    autowidth:true,
     shrinkToFit:false,
    height: 150,
    width: 100
}).jqGrid('navGrid', '', { edit: false, add: false, del: false, searchOnEnter: false, search: false }, {}, {}, {}, { multipleSearch: false });

I am expecting the highlighted column must be hidden

A: looking at your code I can say that your first column is hidden.. The space which you have highlighted is not because of that hidden column.. its the space allocated for scrollbar. When you will have more records the scrollbar will be visible.
have a look at jqgrid remove empty header cell after the last column
Hope this will help you.


text:
Q: Liferay ADT - Freemarker Call Function From A Local Form I am currently struggling with Liferay ADT, using freemarker language. What i want to do is simple. I just want to change a boolean field in a web content structure from true to false and vice versa.
I have achieved that by utilizing this code :
<#function expire>
<#assign isActiveNode = docXml.selectSingleNode("//dynamic-element[@name='isActive']/dynamic-content") />
    <#assign journalArticleLocalService = serviceLocator.findService("com.liferay.portlet.journal.service.JournalArticleLocalService")>
    <#assign expireArticle = isActiveNode.setText("false") />
    <#assign expireArticle = article.setContent(docXml.asXML()) />
    <#assign expireArticle = journalArticleLocalService.updateJournalArticle(article) />
</#function>

I know the code worked because i tried it without using function. But i want the whole activity to be triggered by a click of a button. So what i want to do is to call that function from a form or a button. I can't seem to be able to do this :
<form action="${expire}" method="post">
<input type="submit" value="Expire" class="btn btn-success"/>
</form>

Calling it from button onclick event wont help either.
It says :

Expecting a string, date or number here, Expression expire is instead
  a freemarker.core.Macro

So how do i call that "expire" function from a html tag?
Any thoughts would be greatly appreciated.

A: As expire is a function, you should call it like ${expire()}. However, your function has no return value (no <#return someValue>), so that will also cause an error. I'm not sure what do you expect to be inserted at that ${...}, but #return it at the end of the #function.
Also it's pointless to re-assing to the expireArticle variable again and again; you just overwrite the old value. Also, for variables that you only need inside the function it's cleaner to use <#local someVar = someValue>.


text:
Q: 404 Error The requested URL was not found on the server I have a app base on miguelgrinberg tutorial, it's contains of:
flask
 run.py
 config.py
 db_migrate.py
 db_craete.py
 db_repository
 app
     __init__.py
     viw.py
     model.py
     form.py
     tmp
     static

I put some changes for model and then use ./db_migrate.py to update data base But I got this error
Traceback (most recent call last):
  File "run.py", line 2, in <module>
    from app import app
  File "/home/peg/flask/app/ __ init __.py", line 13, in <module>
    from app import view, model

so I delete from app import view, model line in  (__ init __.py ) and run db_migrate.py But when I run the app got 404 error so where is the problem and how can I solve it?

__ init __.py

#!flask/bin/python
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'

from app import view, model # should delete this line to solve error Traceback

db_migrate.py

  #!flask/bin/python
    import imp
    from migrate.versioning import api
    from app import db # Error here for traceback
    from config import SQLALCHEMY_DATABASE_URI
   .... other stuff....

..

view.py

@lm.user_loader
def load_user(id):
    return User.query.get(int(id))

@app.before_request
def before_request():
    g.user = current_user

@app.route('/')
@app.route('/index')
@login_required
def index():
    user = g.user
    return render_template('index.html',
            user = user,
            title ='Home')

A: Try changing the directory from "tmp" to the Flask default "templates".
If you must you can override Flask's default templates directory name like this.
In your __init__.py File
app = Flask(__name__, template_folder='tmp')

source | Flask API .10  - Application Object


text:
Q: I want to access data in a Method(Test) under the Class(Profile) using Ajax, jQuery and CodeIgniter I want to access data by "Test" method under the "Profile" class. But data does not come on "Test" method. I'm using jquery, ajax and CodeIgniter. Can anyone help me ?
jQuery and Ajax functionality.
<script>
    $(document).ready(function(){
        function hideResponse(){
            setTimeout(function(){
                $("#response").slideUp("slow", function(){});
        }, 2000);
    }

    $("#response").hide();

    $(function(){
        $("#list .sections").sortable({ opacity: 0.5, cursor: 'move', update: function(){
            var data = $(this).sortable("serialize");
            $.ajax({
                url: 'Profile/Test',  //'Profile' class and 'Test' method.
                type: 'POST',
                data: data,
                success: function(response) {
                    $("#response").html(response);
                    $("#response").slideDown('slow');
                    hideResponse();
                },
                error: function() {
                    alert('Fail');
                }
            });
        } });
    });
});
</script>

Here "Test" method under the "Profile" class.
public function Test()
{
    if(isset($_REQUEST['data']))
    {
        $data = $_REQUEST['data'];

        parse_str( $data, $str );

        print_r($str);  // here data does not come
    }
}

A: Hope you have made the Profile class in the controller file(Controller folder): Profile.php(CI 3) and for profile.php( CI 2 )
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Profile extends CI_Controller {
 public function Test()
     {
          // your code
        }
}

Then in the ajax call:
url: '<?php echo base_url("profile/test"); ?>',
//'Profile' class and 'Test' method.

Hope this solves your problem. Thanks.


text:
Q: Asynchronous looping through array with an object carrying another array I have the following array, which consists of some properties and an array with a few more objects.
var array = [
    {
        prop1Name: 'Thing',
        prop2ID: 1
        propArray: [
            {
                innerProp1Name: 'Name 1',
                innerProp2ID: 1
            },
            {
                innerProp1Name: 'Name 2',
                innerProp2ID: 2
            },
        ]
    },
    {
        prop1Name: 'Thing 2',
        prop2ID: 2
        propArray: [
            {
                innerProp1Name: 'Name 1',
                innerProp2ID: 1
            },
            {
                innerProp1Name: 'Name 2',
                innerProp2ID: 2
            },
        ]
    }
]

Now, my goal is to insert this into a database, through a Node.JS API. I've dabbled with async.js, but I'm wondering whether or not async.each() inside of an async.each() is the way to go here. Maybe I could define it inside of the iterator function for the first async.each().
The table needs the ID of the outer property on each of the entries within propArray. PropArray controls the rows to add.

A: Loop through nested array and do db insert for every entry is very expensive when array and nested arrays are large. if db driver allows you to do array insert (which most do), it's less expensive to flatten it out with regular for loops and do 1 db insert.  something like this:
var array = [ ... ];  // your array
var i, j, outLen, inLen, item, innerItem;
var result = [];

for (i = 0, outLen = array.length; i < outLen; i++) {
  item  = array[i];
  for (j = 0, inLen = item.propArray.length; j < inLen; j++) {
    innerItem = item.propArray[j];
    result.push({
      prop1Name: item.prop1Name,
      prop2ID: item.prop2ID,
      innerProp1Name: innerItem.innerProp1Name,
      innerProp2ID: innerItem.innerProp2ID
    });
  }
}

db.collection.insert(result, ...);

This doesn't have any error checking and existence of inner array. You might want to do that.


text:
Q: MySql on what cols should I put indexes? I have this query:
SELECT Concat(f.name, ' ', f.parent_names) AS FullName,
       stts.name                           AS 'Status',
       u.name                              AS Unit,
       city.name                           AS City,
       (SELECT Group_concat(c.mobile1)
        FROM   contacts c
        WHERE  c.id = f.husband_id
                OR c.id = f.wife_id)       AS MobilePhones,
       f.phone                             AS HomePhone,
       f.contact_initiation_date           AS InitDate,
       f.status_change_date                AS StatusChangeDate,
       cmt.created_at                      AS CommentDate,
       cmt.comment                         AS LastComment,
       f.reconnection_date                 AS ReconnectionDate,
       (SELECT Group_concat(t.name, ' ')
        FROM   taggings tgs
               JOIN tags t
                 ON tgs.tag_id = t.id
        WHERE  tgs.taggable_type = 'family'
               AND tgs.taggable_id = f.id) AS HandlingStatus
FROM   families f
       JOIN categories stts
         ON f.family_status_cat_id = stts.id
       JOIN units u
         ON f.unit_id = u.id
       JOIN categories city
         ON f.main_city_cat_id = city.id
       LEFT JOIN comments cmt
              ON f.last_comment_id = cmt.id
WHERE  1 = 0
        OR ( u.is_busy = 1 )
        OR ( f.family_status_cat_id = 1423 )
        OR ( f.family_status_cat_id = 1422
             AND f.status_change_date BETWEEN '2011-03-21' AND '2012-03-13' )

My problem is very specific. It is regarding the line:
 SELECT GROUP_CONCAT( c.mobile1 )
    FROM contacts c
    WHERE c.id = f.husband_id
    OR c.id = f.wife_id
    ) AS MobilePhones

When I use EXPLAIN, it seems that this query is bad. I get for this table (c = contacts): 38307 rows.
On what columns should I put the index according to the query?
I tried mobile1 - but no improvement (BTW - family_id is indexed in the contacts table).
I attach the image of the explain result:

Or maybe someone can help me optimize the query...

A: Any column you'll be searching on, to speed up the process. Keep in mind that keys are already indexed.

A: Well, it seems that using the GROUP_CONCAT is the problem.
I just seperated the wife and husband mobile to be 2 different columns.
First, I thought that using the GROUP_CONCAT will be faster, but it proved to be VERY WRONG.

A: Just out of my curiosity, what is the performance of the query
SELECT GROUP_CONCAT( c.mobile1 )
    FROM contacts c
    WHERE c.id IN(f.husband_id, f.wife_id)
    ) AS MobilePhones


text:
Q: Codeigniter: Selecting different columns from 3 tables Today i encountered a problem developing my app.
I restructured my database.
I have 3 tables for posts, photos, and for the tags of the posts.
I joined the two other tables(photos, tags).
I would like to query the first 3 post with only one SELECT with photos and tags, but only the first row showing up from the results.
Heres is my code:
$this->db->select('owner, title, time, LEFT(content, 75) as content, category, url, price, county');

$this->db->from(POSTS_TABLE);

$this->db->join(PHOTOS_TABLE, PHOTOS_TABLE.'.post_id = '.POSTS_TABLE.'.url');

$this->db->join(TAGS_TABLE, TAGS_TABLE.'.post_url = '.POSTS_TABLE.'.url');

$this->db->order_by('time', 'desc');

$this->db->limit(3);

$query = $this->db->get();

$posts = $query->result();

My DB structure:
posts table:
id, owner, title, content, url

tags table: id, post_id (same as the url column from the posts table), photo (the link to the photo)
tags table:
 id, post_url (same as the url column from the posts table), tag.

Please help.How can i achieve that with only one SELECT and showing up the correct results ?
I cannot use the WHERE clause, since i dont know the exact post_url

A: Considering column name 'url' is the id of the row
Try:
// Code before
$this->db->join('PHOTOS_TABLE', 'PHOTOS_TABLE.post_id = POSTS_TABLE.url');
$this->db->join('TAGS_TABLE', 'TAGS_TABLE.post_url = POSTS_TABLE.url');
// Code After


text:
Q: How to calculate time with a php force download script? I have a rather simple force download script:
$thefile = $_GET['id'];
$file = 'http://www.mywebsite.com/test/'.$thefile;
header('Content-Disposition: attachment; filename='.$thefile);
header("Content-Type: application/force-download");
@readfile($file);

And it works nicely, except it does not show how much time is remaining ("could not calculate time").
I found someone with a similar problem here, by using this code:
# for URL paths that begin with "/foo/bar/"
SetEnvIf Request_URI ^/foo/bar/ no-gzip=1

# for files that end with ".py"
<FilesMatch \.py$>
    SetEnv no-gzip 1
</FilesMatch>

But alas, I can not get that to work. My files are media files (avi, wmv, mp4 and so forth), so I assumed I would have to modify the code along these lines:
SetEnvIf Request_URI ^/test/ no-gzip=1

<FilesMatch "\.(avi|wmv|mp4|mpg|mpeg|m4v)$">
    SetEnv no-gzip 1
</FilesMatch>

I have also changed the path to a simple test folder, but time is still not being displayed.
How to?

A: You should add content-length header, for your browser to know total file size.
header("Content-Length: " . filesize($file));

Take a look at this example.


text:
Q: I have this Error - jquery.min.js: 2 Uncaught TypeError: Illegal invocation django I am trying to save the order details data, however I get this error.
jquery.min.js: 2 Uncaught TypeError: Illegal invocation

I am still in the process of sending that data to the database, I just want to see if it is working correctly with this line of code:
vents = request.POST['ventas']

JS
    $('form').on('submit', function (e) {
        e.preventDefault();
        var parametros = new FormData();
        parametros.append('action', $('input[name="action"]').val());
        parametros.append('ventas', JSON.stringify(ventas.items));
        submit(window.location.pathname, parametros, function(){
            location.href = "{% url 'Venta' %}";

        });
    });

VIEWS
def post(self, request, *args, **kwargs):
        data = {}
        try:
            action = request.POST['action']
            if action == 'autocomplete':
                productos = Producto.objects.filter(nombre__icontains=request.POST['term'])[0:10]
                for i in productos:
                    data = []
                    item = i.toJSON()
                    item['value'] = i.nombre
                    data.append(item)
            elif action == 'add':
                vents = request.POST['ventas']
            else:
                data['error'] = 'No ha ingresado a ninguna opción'
        except Exception as e:
            data['error'] = str(e)
        return JsonResponse(data,safe=False)

A: In your js do:
       $('form').on('submit', function (e) {
        e.preventDefault();
        var parametros = new FormData();
        parametros.append('action', $('input[name="action"]').val());
        parametros.append('ventas', JSON.stringify(ventas.items));
        submit(window.location.pathname, parametros, function(){
            location.href = "{% url 'Venta' %}";

        });
    })

Just get rid of the trailing ';' at the last ')' closing.Worked for me when I run into this problem!


text:
Q: Mapbox - Changing map style causes Directions to not work properly Having an issue with getting Directions to work in MapBox web application issue happens when I change the map style. This question has been asked in github, but has not received been resolved yet. (From 2018) Hoping that by now there is a solution to why this is happening.
If you change a maps style with directions already rendered you end up with: Error: The layer 'directions-route-line-alt' does not exist in the map's style and cannot be queried for features.
(From github question - link below)
This example was generated from the directions example: https://www.mapbox.com/mapbox-gl-js/example/mapbox-gl-directions/
Example of issue:
https://plnkr.co/edit/M8mj1WTH1KjDa1dhiUKw?p=preview&preview

Git hub original post:
https://github.com/mapbox/mapbox-gl-js/issues/7019
My Code:
https://github.com/juanmguevara/MapBoxMapping
Thanks for the help!

A: When you add the MapboxDirections control to the map, it adds an extra layer or two.
When you "change a map's style", you're essentially removing all the existing sources and layers, and adding new ones.
So it is removing the layers you added at the start, which then causes the error you see.
After you change the map's style, you should remove and re-add the MapboxDirections control.


text:
Q: Js Helper submit issue on cakephp 2.x I am using JS Helper submit in my cakephp 2.x version.
My code is fine as function is called.
<?php  echo $this->Js->submit("Apply", array(
'div' => false,
'class' => 'general_button',
'style' => array('float:none;', 'margin: 10px;'),
'url' => array('controller' => 'poets', 'action' => 'index', 'field' => $search_term, 'value' => $search_value),
'update' => '#listID',
'confirm' => 'Are you sure you want to apply action to selected records ??',
'before' => "return isAnySelect(this.form);",
'success' => 'myShowMessage();')); ?>

Though function isAnySelect(this.form) is called but my function this.form returns undefined wats the issue with this code .. Please explain.
My function
function isAnySelect(frmObject) {
console.log(frmObject);
return false;
varAllId = "";

for (i = 1; i < frmObject.chkRecordId.length; i++) {
    alert('Hiii');
    alert(varAllId + "xs");
    if (frmObject.chkRecordId[i].checked == true) {
        if (varAllId == "") {
            varAllId = frmObject.chkRecordId[i].value;
        } else {
            varAllId += "," + frmObject.chkRecordId[i].value;
        }
    }
}
if (varAllId == "") {
    alert("Please select atleast one record !!");
    return false;
} else {
    document.getElementById('idList').value = varAllId;
    return true;
}
}

Though function is called but it output undefined on console.


text:
Q: Automatically determine minimum WordPress version required for a plugin? When developing a plugin, is there a way to automatically determine the minimum version of WordPress that's required to run it? I want to make sure that the Requires header is accurate, but manually checking every time I call a new core function is tedious and error-prone.
I'm thinking a script could figure it out easily enough:

*

*Scan all the files in a plugin.

*Parse out all the class instantiations and function calls based on the new foo( [...] ), foo::bar( [...] ), bar( [...] ), call_user_func( [...] ), etc syntax.

*Parse the WP source to determine when each of those classes/functions were added to WordPress, using the @since phpDoc tag.

*Generate a report listing each class/function and the version it was added, along with the earliest version of WordPress that includes all of the classes/functions.

I've looked around but couldn't find anything like it, and don't have the time to write it myself. Does anyone know of an existing solution?

A: Well, this is more of a starting point, but there is this nice list of WP functions and the versions they were added/removed here.  Unfortunately, it only goes up to WP 3.0.1, but if you're shooting for 3.0 as a baseline it will at least help - if it's not in the list, it was added later.  You might want to email Ozh and ask him to update the list, and if one of us gets the gumption someone can make a plugin to check (like a reverse deprecation checker).
ETA: Per @mrwweb - Adam Brown's Hook List!  Current to 3.3 and goes waaaaay back to 1.2.1, which no one in their right mind would be running anymore (release date Oct. 6, 2004).

A: I found a solution as an automated service over at http://wpseek.com/pluginfilecheck/
It's does exactly, what was asked for including the generation of list of used functions and giving a suggestion for the Plugin-Header comments.

A: I think the answer does lie in the deprecated notices - you should be developing with WP_DEBUG true - whether you display or log them is your call, but WP will notify you if you use a deprecated function.
It would be possible to parse @since as you say, but tools can only take you so far - familiarity with the codebase and manual checking may be the way to go.


text:
Q: Paint a parabola using JTextField values in Java The program consists of drawing a parabola using the values from the A, B and C jtextfields every time the button is pressed:

It also has to be on two separate classes, the View which displays the menu and the Controller which takes the inputs from the first class and paints the parabola.
My actual code:
public static void main(String[] args) {
    JFrame frame = new JFrame("Parabola");
    frame.getContentPane().setLayout(new BorderLayout());

    JPanel panel1 = new JPanel();
    panel1.setPreferredSize(new Dimension(50, 50));

    JLabel labelA = new JLabel();
    labelA.setText("a");
    JTextField textA = new JTextField("0",3);
    JLabel labelB = new JLabel();
    labelB.setText("b");
    JTextField textB = new JTextField("0",3);
    JLabel labelC = new JLabel();
    labelC.setText("c");
    JTextField textC = new JTextField("0",3);

    JButton draw = new JButton();
    draw.setText("Draw");
    draw.addActionListener( new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            textA.getText();
            textB.getText();
            textC.getText();

        }
    });

    panel1.add(labelA);
    panel1.add(textA);
    panel1.add(labelB);
    panel1.add(textB);
    panel1.add(labelC);
    panel1.add(textC);
    panel1.add(draw);

    JPanel panel2 = new JPanel(){

        double a=2, b=1, c=0;

        public void section (Graphics g){
            g.setColor(Color.blue);
            g.drawLine(200,0,200,400);
            g.drawLine(0,200,400,200);
            for (int x=0; x<=400; x= x +40){
                g.drawLine(x,195,x,205);
            }
            for (int y=0; y<=400; y=y+40){
                g.drawLine(195,y,205,y);
            }
        }

        public void graphic(Graphics g) {
            g.setColor(Color.red);
            for (double x=-100;x<=100;x = x+0.1){
            double y = a * x * x + b * x + c;
            int X = (int)Math.round(200 + x*20);
            int Y = (int)Math.round(200 - y*20);
            g.fillOval(X-2,Y-2,4,4);
            }
        }

        public void paint (Graphics g){
            section(g);
            graphic(g);
        }
    };
    panel2.setBackground(Color.WHITE);

    frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
    frame.getContentPane().add(panel2, BorderLayout.CENTER);

    frame.pack();
    frame.setVisible(true);
    frame.setSize(420,490);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

I`ve managed to do it in one class without the textfields working and have no idea how to separate the graphic into another class so it can do the operations and send them back to the view class again.

A: Solved it:
Class View
public class View extends JFrame {

public View() {

    JFrame frame = new JFrame("Equation");
    frame.getContentPane().setLayout(new BorderLayout());

    JPanel panel1 = new JPanel();
    panel1.setPreferredSize(new Dimension(50, 50));

    JLabel labelA = new JLabel();
    labelA.setText("a");
    JTextField textA = new JTextField("0",3);
    JLabel labelB = new JLabel();
    labelB.setText("b");
    JTextField textB = new JTextField("0",3);
    JLabel labelC = new JLabel();
    labelC.setText("c");
    JTextField textC = new JTextField("0",3);

    JButton draw = new JButton();
    draw.setText("Draw");
    draw.addActionListener( new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            Controller.a = Double.parseDouble(textA.getText());
            Controller.b = Double.parseDouble(textB.getText());
            Controller.c = Double.parseDouble(textC.getText());

            repaint();
            frame.pack();
            frame.setSize(420,490);
        }
    });

    panel1.add(labelA);
    panel1.add(textA);
    panel1.add(labelB);
    panel1.add(textB);
    panel1.add(labelC);
    panel1.add(textC);
    panel1.add(draw);

    JPanel panel2 = new JPanel(){

        public void paint(Graphics g){
            super.paint(g);
            Controller.grid(g);
            Controller.Graphic1(g);
        }
    };

    panel2.setBackground(Color.WHITE);

    frame.getContentPane().add(panel1, BorderLayout.PAGE_START);
    frame.getContentPane().add(panel2, BorderLayout.CENTER);

    frame.setVisible(true);
    frame.setSize(420,490);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                View frame = new View();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
}

Class Controller
public class Controller {

static double a=2, b=1, c=0;

public static void grid (Graphics g){
            g.setColor(Color.blue);
            g.drawLine(200,0,200,400);
            g.drawLine(0,200,400,200);
            for (int x=0; x<=400; x= x +40){
                g.drawLine(x,195,x,205);
            }
            for (int y=0; y<=400; y=y+40){
                g.drawLine(195,y,205,y);
            }
}

public static void Graphic1(Graphics g) {
            g.setColor(Color.red);
            for (double x=-100;x<=100;x = x+0.1){
                double y = a * x * x + b * x + c;
                int X = (int)Math.round(200 + x*20);
                int Y = (int)Math.round(200 - y*20);
                g.fillOval(X-2,Y-2,4,4);
            }

}

}


text:
Q: addEventListener() not working Ok, so I tried to make this page with an addEventListener function, to address the clicking of a button; It didn't work. I narrowed it down by deleting everything but the basic elements needed for the listener, and am left with the following:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function init(){
    document.getElementById("test").addEventListener("mousedown", function(){
        alert("Test successful");
    });
}
body.onload = init();
</script>
</head>
<body>
<button id="test">Click</button>
</body>
</html>

which didn't work either, so I know the issue is in my syntax of the above. Mind you, when I took away body.onload = init(); and instead put onload="init()" into the body tag, it did work :O Problem is, I don't want to have it inline. Any suggestions?
Note: Do bear in mind that this question is not about how there is a bug in JS, even if the title may suggest so, it is about how I can't get it to work since I've probably got the syntax wrong. Please feel free to rename it if you wish.

A: body.onload = init();
Not the way to refer to body, use window instead-
and don't call the method there, reference it (without parentheses)
window.onload=init;
Pass the third argument, even if it is false-
function init(){
     document.getElementById("test").addEventListener("mousedown", function(){
         alert("Test successful");
     },false);
}

And note that IE before version #9 does not support addEventListener.

A: First of all, you should access the body element through document.body. However, onload is defined on window, so you actually need:
window.onload = init();

However, that would execute the init() method and store the return value in window.onload. Obviously, that's not what you want: you want the init function to act as onload handler. Therefore, you should have written:
window.onload = init;

Although I'd recommend using addEventListener for that as well:
window.addEventListener("load", init);

A: It happens because body is not defined, the correct is document.body.
Also, maybe the document.body is not defined yet because the head tag is rendered before the body tag, so the better is to check when the window or the document is loaded.
Try this code:
function init(){
    document.getElementById("test").addEventListener("mousedown", function(){
        alert("Test successful");
    });
}
document.addEventListener('load',init);//Or also, window.addEventListener

A: <script>
        window.addEventListener('load', () => {
            document.getElementById('test').addEventListener("mousedown", (e) => {
                alert("Test successful");
            });
        })
</script>


text:
Q: SSRS gauge component stop working with error in designer but work in preview In ssrs 2012 everything was ok.
But one day, when I drag Gauge from toolbox the components, I get an error like

*

*SQL Server edition is 2012

*SQL Server data tool is 2010

I try to reinstall SQL Server Data Tools 2012 and again I get this error.
I try install SQL Server Data Tools for Visual Studio 2012 and again error.
The gauge that I created before give me this errore in designer but work in preview - what's the problem? How can I fix this problem?


text:
Q: C# - How to detect + and = pressed characters I was testing keys and I got that = and Shift+= (+) have the same code: 187
And the expression e.KeyValue == 187 works in the both cases. How to verify the real key? Thanks

A: Examining the documentation for System.Windows.Forms.KeyEventArgs, which it seems you're using here, you'll discover several documented properties which give you "the rest of the story".
What you're interested in is the Shift property. For example:
if ( e.Shift )  { /* the key is + */ }
           else { /* the key is = */ }

Note, too, that just examining the Shift property doesn't account for the possibility that the user has also held down the Alt key, or the Control key, which are reflected similarly in the properties Alt and Control
Also, you may need to understand the Modifiers property, which is a bit field indicating all of the modifier key states (Atl, Control and Shift) at once.
Further, you will want to investigate the difference between KeyValue, KeyCode and KeyData.
KeyValue is defined as a raw numeric value, which as you discovered ignores shift states, so it can't distinquish between lower and upper case, or between + and =.

A: You can read here that via the event args you can verify if shift is pressed or not, for intense:
if ( e.Shift )
{
   // the key is +
}
else
{
  //  the key is =
}


text:
Q: How to removeListener in reactjs es6 I use es6 in project of react.
componentDidMount() {
        userStore.addListener(ViewUpdateTypes.USER_UPDATE,(data)=>this._onChange(data));
        userStore.addListener(ViewUpdateTypes.FD_MENU_UPDATE,(data)=>this._onChange(data));
};

Now I want removeListener,What should I do.

A: You can do constructor and Function.prototype.bind like this.
constructor(props) {
    super(props);
    this._onChange = this._onChange.bind(this);
}
componentDidMount() {
    userStore.addListener(ViewUpdateTypes.USER_UPDATE, this._onChange);
    userStore.addListener(ViewUpdateTypes.FD_MENU_UPDATE, this._onChange);
}
componentWillUnmount() {
    userStore.removeListener(ViewUpdateTypes.USER_UPDATE, this._onChange);
    userStore.removeListener(ViewUpdateTypes.FD_MENU_UPDATE, this._onChange);
}


text:
Q: Ionic 3 background mode return as false I use Ionic 3 and I want my app to work in the background as well, and now I try to use background mode of Ionic 3 in app.component, using this.backgroundMode.enable() and then use method isEnable() but when I use isEnable() it return as false. What did I do wrong, why is it return as false? Please help me
import { BackgroundMode } from '@ionic-native/background-mode';
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';

@Component({
  templateUrl: 'app.html'
})

export class MyApp {
  rootPage: any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private backgroundMode: BackgroundMode) {
    platform.ready().then(() => {

      this.backgroundMode.enable()
      var bgmStatus = this.backgroundMode.isEnabled();
      console.log(bgmStatus);

      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}

    import { BackgroundMode } from '@ionic-native/background-mode';
    import { Component } from '@angular/core';
    import { Platform } from 'ionic-angular';
    import { StatusBar } from '@ionic-native/status-bar';
    import { SplashScreen } from '@ionic-native/splash-screen';
    import { HomePage } from '../pages/home/home';

    @Component({
      templateUrl: 'app.html'
    })

    export class MyApp {
      rootPage: any = HomePage;

      constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private backgroundMode: BackgroundMode) {
        platform.ready().then(() => {

          this.backgroundMode.enable()
          var bgmStatus = this.backgroundMode.isEnabled();
          console.log(bgmStatus);

          statusBar.styleDefault();
          splashScreen.hide();
        });
      }
    }


text:
Q: Python post request with wrong form [no "action", "method", or "value attribute"] Want
Make Python submit an address on https://boligejer.dk/ and collect the response.
Specifically, I want to get the response from submitting "Ved Stranden 1, 3220 Tisvildeleje" - shown in first picture. And then collect the response (https://boligejer.dk/ejendomsdata?knr=0270&enr=027002) - shown in second picture
Submitting an address
Response page after submitting the address
Have
Followed recipe from: Python post request for USPTO site scraping. However, I am not getting my form correct. Any suggestions or input on how to nail this?
from bs4 import BeautifulSoup
import requests
import re

#Methods
def make_soup(url):
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')
return soup

def get_forms(soup):
    form = soup.find_all("form")
    return form

def get_form_data(form,address):
    data = {}
    for inp in form('input'):
     # if the value is None, we put the address to this field
     data[inp['name']] = inp['value'] or address

return data

#Values
url               = 'https://boligejer.dk/'
form_name         = 'content-banner__form mt-3'
address_wanted    = "Ved Stranden 1, 3220 Tisvildeleje"

soup               = make_soup(url)
all_forms          = get_forms(soup)
form               = all_forms[1]

#Method does not inject address, as there is no value with none
#data               = get_form_data(form,address)
data               = {'input aria-autocomplete=':"list","aria-label":address_wanted,
                 "autocomplete":"off","class":"form-control","id":"dawa-autocomplete-
                   input","placeholder":"Indtast adresse","type":"text"}

request_with_form    = requests.post(url, data=data)

print('_______________Form from web
page__________________________________________________________________________')
print(form)
print('_____________inputs of the form
______________________________________________________________________')
print(form('input'))
print('_____________Data
______________________________________________________________________')
print(data)
print('_____________Reponse with form
______________________________________________________________________')
BeautifulSoup(request_with_form.content, 'html.parser' )

Failed output

_______________Form from web page__________________________________________________________________________
<form class="content-banner__form mt-3">

<input aria-autocomplete="list" aria-label="Indtast adresse" autocomplete="off" class="form-control" id="dawa-autocomplete-input" placeholder="Indtast adresse" type="text"/>

<button class="btn btn-secondary btn-lg btn-icon" id="ejdsearch" type="submit">

<svg focusable="false"><use xlink:href="/themes/custom/newerst/dist/svg/svg-sprite.svg#arrow-line-right"></use></svg>

</button>

</form>
_____________inputs of the form ______________________________________________________________________
[<input aria-autocomplete="list" aria-label="Indtast adresse" autocomplete="off" class="form-control" id="dawa-autocomplete-input" placeholder="Indtast adresse" type="text"/>]
_____________Data ______________________________________________________________________
{'input aria-autocomplete=': 'list', 'aria-label': 'Ved Stranden 1, 3220 Tisvildeleje', 'autocomplete': 'off', 'class': 'form-control', 'id': 'dawa-autocomplete-input', 'placeholder': 'Indtast adresse', 'type': 'text'}
_____________Reponse with form ______________________________________________________________________

<!DOCTYPE html>

<meta charset="utf-8"/>
<link href="https://boligejer.dk/" rel="canonical"/>
<meta content="BOLIGEJER.DK Boligejer skaber overblik, indeholder guides og tilbyder relevante værktøjer til dig, der skal købe eller sælge en bolig." name="description"/>
<meta content="width" name="MobileOptimized"/>
<meta content="true" name="HandheldFriendly"/>
<meta content="width=device-width, initial-scale=1, minimal-ui" name="viewport"/>
<meta content="frontpage" name="ERST.ContentType"/>
<meta content="3. januar 2022" name="ERST.ContentDate"/>
<meta content="FORSIDE" name="ERST.ContentLabel"/>


text:
Q: Rails converts empty arrays into nils in params of the request I have a Backbone model in my app which is not a typical flat object, it's a large nested object and we store the nested parts in TEXT columns in a MySQL database.
I wanted to handle the JSON encoding/decoding in Rails API so that from outside it looks like you can POST/GET this one large nested JSON object even if parts of it are stored as stringified JSON text.
However, I ran into an issue where Rails magically converts empty arrays to nil values. For example, if I POST this:
{
  name: "foo",
  surname: "bar",
  nested_json: {
    complicated: []
  }
}

My Rails controller sees this:
{
  :name => "foo",
  :surname => "bar",
  :nested_json => {
    :complicated => nil
  }
}

And so my JSON data has been altered..
Has anyone run into this issue before? Why would Rails be modifying my POST data?
UPDATE
Here is where they do it:
https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/request.rb#L288
And here is ~why they do it:
https://github.com/rails/rails/pull/8862
So now the question is, how to best deal with this in my nested JSON API situation?

A: You can re-parse the parameters on your own, like this:
class ApiController
  before_filter :fix_json_params    # Rails 4 or earlier
  # before_action :fix_json_params  # Rails 5

  [...]

  protected

  def fix_json_params
    if request.content_type == "application/json"
      @reparsed_params = JSON.parse(request.body.string).with_indifferent_access
    end
  end

  private

  def params
    @reparsed_params || super
  end
end

This works by looking for requests with a JSON content-type, re-parsing the request body, and then intercepting the params method to return the re-parsed parameters if they exist.

A: After much searching, I discovered that you starting in Rails 4.1 you can skip the deep_munge "feature" completely using
config.action_dispatch.perform_deep_munge = false

I could not find any documentation, but you can view the introduction of this option here:
https://github.com/rails/rails/commit/e8572cf2f94872d81e7145da31d55c6e1b074247
There is a possible security risk in doing so, documented here: https://groups.google.com/forum/#!topic/rubyonrails-security/t1WFuuQyavI

A: I ran into similar issue.
Fixed it by sending empty string as part of the array.
So ideally your params should like
{
  name: "foo",
  surname: "bar",
  nested_json: {
    complicated: [""]
  }
}

So instead of sending empty array I always pass ("") in my request to bypass the deep munging process.

A: Here's (I believe) a reasonable solution that does not involve re-parsing the raw request body.  This might not work if your client is POSTing form data but in my case I'm POSTing JSON.
in application_controller.rb:
  # replace nil child params with empty list so updates occur correctly
  def fix_empty_child_params resource, attrs
    attrs.each do |attr|
      params[resource][attr] = [] if params[resource].include? attr and params[resource][attr].nil?
    end
  end

Then in your controller....
before_action :fix_empty_child_params, only: [:update]

def fix_empty_child_params
  super :user, [:child_ids, :foobar_ids]
end

I ran into this and in my situation, if a POSTed resource contains either child_ids: [] or child_ids: nil I want that update to mean "remove all children." If the client intends not to update the child_ids list then it should not be sent in the POST body, in which case params[:resource].include? attr will be false and the request params will be unaltered.

A: Looks like this is a known, recently introduced issue: https://github.com/rails/rails/issues/8832
If you know where the empty array will be you could always params[:...][:...] ||= [] in a before filter.
Alternatively you could modify your BackBone model's to JSON method, explicitly stringifying the nested_json value using JSON.stringify() before it gets posted and manually parsing it back out using JSON.parse in a before_filter.
Ugly, but it'll work.

A: I ran into a similar issue and found out that passing an array with an empty string would be processed correctly by Rails, as mentioned above.
If you encounter this while submitting a form, you might want to include an empty hidden field that matches the array param :
<input type="hidden" name="model[attribute_ids][]"/>

When the actual param is empty the controller will always see an array with an empty string, thus keeping the submission stateless.


text:
Q: Problems with this stack implementation where is the mistake?
My code here:
 typedef struct _box
    {
        char *dados;
        struct _box * proximo;
    } Box;

    typedef struct _pilha
    {
        Box * topo;
    }Stack;

void Push(Stack *p, char * algo)
{
    Box *caixa;
    if (!p)
    {
        exit(1);
    }

    caixa = (Box *) calloc(1, sizeof(Box));
    caixa->dados = algo;
    caixa->proximo = p->topo;
    p->topo = caixa;
}

char * Pop(Stack *p)
{
    Box *novo_topo;
    char * dados;
    if (!p)
    {
        exit(1);
    }

    if (p->topo==NULL)
        return NULL;

    novo_topo = p->topo->proximo;

    dados = p->topo->dados;

    free(p->topo);
    p->topo = novo_topo;

    return dados;
}

void StackDestroy(Stack *p)
{
    char * c;
    if (!p)
    {
        exit(1);
    }
    c = NULL;
    while ((c = Pop(p)) != NULL)
    {
        free(c);
    }
    free(p);
}

int main()
{
int conjunto = 1;
char p[30], * v;
int flag = 0;

Stack *pilha = (Stack *) calloc(1, sizeof(Stack));

FILE* arquivoIN = fopen("L1Q3.in","r");
FILE* arquivoOUT = fopen("L1Q3.out","w");

if (arquivoIN == NULL)
{
    printf("Erro na leitura do arquivo!\n\n");
    exit(1);
}

fprintf(arquivoOUT,"Conjunto #%d\n",conjunto);

while (fscanf(arquivoIN,"%s", p) != EOF )
{
    if (pilha->topo == NULL && flag != 0)
    {
        conjunto++;
        fprintf(arquivoOUT,"\nConjunto #%d\n",conjunto);
    }

    if(strcmp(p, "return") != 0)
    {
        Push(pilha, p);
    }

    else
    {
        v = Pop(pilha);

        if(v != NULL)
        {
            fprintf(arquivoOUT, "%s\n", v);
        }
    }
    flag = 1;
}

StackDestroy(pilha);

return 0;

}
The Pop function returns the string value read from file.
But is not correct and i don't know why.

A: You're not allocating any storage for the strings pointed to by dados - you're just re-using one string buffer (p) and passing that around, so all your stack elements just point to this one string.


text:
Q: Comparing two JPEG images in iOS I have images that I upload to a server using Amazon S3. I convert them to NSData, using UIImageJPEGRepresentation with 0.75f compression quality. Now I'd like to compare them and see if they are equal.
With PNG, it's easy, all I had to do is this:
if (UIImagePNGRepresentation(self.pictureImageView.image) isEqual:
             UIImagePNGRepresentation(manageItemVC.pictureImage)]) {}

as stated here. And that would work, but now the images are JPEG, and the comparison isn't working (most likely due to compression), even if I use UIImageJPEGRepresentation.
self.pictureImageView.image is the image from the server that I've loaded into an UIImageView, and manageItemVC.pictureImage is an image that the user picked from the photo library.
Anyone know how to compare JPEG images?

A: You can check data's length of two image and compare it.
With my suggestion, i check if two data different about 10000 => two image different.


text:
Q: I am getting error while using sessions in asp.net I have 2 tables Users and Hobbies. userIdis primary key inUserstable and it is foreign key inHobbiestable. I want sameuserIdin both tables. When user logged in he getsuserId. On next page there is hobbies page where user have to fill info and the sameuserId` should get saved into Hobbies table. I am using session for this, but it is giving exception as
"Error converting datatype object to int."
My code is:
this is a code on Users Page
protected void loginbtn_Click(object sender, EventArgs e)
{
    SqlCommand cmd1 = new SqlCommand("select UserId from Users where username=@username and password=@password",con);
    Session["ID"] = cmd1;
}

and this is the code on hobbies:
protected void Button4_Click(object sender, EventArgs e)
{
    int id= Convert.ToInt32(Session["ID"]);
    cmd.Parameters.AddWithValue("@UserId",id);
    con.Open();
    cmd.ExecuteNonQuery();
}

I am new to sessions and stored procedure. This is my first web app. Please help me to improve.

A: You shouldn't store a command in a session let along convert it to a integer.
loginbtn_Click
protected void loginbtn_Click(object sender, EventArgs e)
{
    string conString = "xxxxxxxxxxxxxxxxxxxxxxxx";
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (var cmd = new SqlCommand(
        "select UserId from Users where username=@username and password=@password",
        con))
        {
            cmd.Parameters.AddWithValue("@username", username.Text);
            cmd.Parameters.AddWithValue("@password", password.Text);
            var id = cmd.ExecuteScalar();
            Session["ID"] = id;

        }
    }
}

Button4_Click
protected void Button4_Click(object sender, EventArgs e)
{
    string conString ="xxxxxxxxxxxxxxxxxxxxxxxxxx";
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (var cmd = new SqlCommand("select * from Users where UserId=@UserId",con))
        {
            var id= Convert.ToInt32(Session["ID"]);
            cmd.Parameters.AddWithValue("@UserId",id);
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                //get the data
            }
        }
    }
}

A: You need to execute the SQLCommand first to get the value of your UserID. Right now, you are passing an SQLCommand object, which obviously isn't an integer value. To fix the error, you would need to do something like this:
using (SqlConnection con = new SqlConnection (connectionstring))
{
 SqlCommand cmd1 = new SqlCommand("select UserId from Users where username=@username and password=@password",con);
 cmd.Parameters.AddWithValue("@username", username.Text);
 cmd.Parameters.AddWithValue("@password", password.Text);
 con.Open();
 int UID = (int)cmd1.ExecuteScalar(); //Execute command and assign value
 Session["ID"] = UID; //Now set session variable
}

Of course, you need to handle exceptions and so on, but this should get you started.

A: First i want to notify you that you are storing the command object into the Session and not the UserID. so you are getting this error!
On Users.aspx Page:
Storing UserID in session:
 using (SqlConnection con = new SqlConnection (yourConnectionString))
    {
     SqlCommand mycmd = new SqlCommand("select UserId from Users where  username=@username and password=@password",con);
    //add parameters to pass the username & password here
      mycmd.Parameters.AddWithValue("@username", username.Text);
      mycmd.Parameters.AddWithValue("@password", password.Text);
     if (con.State != ConnectionState.Open)
      {
           con.Close();
           con.Open();
      }

     int userID = (int)mycmd.ExecuteScalar();
     Session["UserID"] = userID; //Store USerID in session
     con.Close();
    }

The reason I'm not simply using:
if (con.State == ConnectionState.Closed)
{
    con.Open();
}

Is because the ConnectionState can also be:
Broken, Connnecting, Executing, Fetching

Additionally Microsoft states that Closing, and then Re-opening the connection "will refresh the value of State." More Details
On Hobbies.aspx Page:
Using Session UserID:
if(Session["UserID"]!=null)
{
int userID=Convert.ToInt32(Session["UserID"])
//do other stuff
}

Insert Into Hobbies table:
private void btnInsertHobbies_Click(object sender, EventArgs e)
    {
        int userID=0;
        if(Session["UserID"]!=null)
        {
          userID=Convert.ToInt32(Session["UserID"]);
        }

        //add Here fields of hobbies table
        string hobby1= textBox2.Text;
        string hobby2= textBox3.Text;
        if (conn2.State != ConnectionState.Open)
        {
           conn2.Close();
           conn2.Open();
        }

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn2;
        cmd.CommandText = "INSERT INTO Hobbies(userID, hobby1, hobby2)   VALUES(@userID,@hobby1,@hobby2)";

        cmd.Parameters.AddWithValue("@userID", userID);
        cmd.Parameters.AddWithValue("@hobby1", hobby1);
        cmd.Parameters.AddWithValue("@hobby2", hobby2);

        cmd.ExecuteNonQuery();

        conn2.Close();
    }

NOTE: please make changes according to your table fields and mark as answer if it help you!


text:
Q: Impossible to use virtual keyword on destructor Is there any valid and usable case, that will force you not to use the virtual keyword before the destructor.
class Base {
public:
  virtual ~Base() { ... } // `virtual` causes error (not compile time or syntax) or wrong behaviour
  // could contain other fields

};

// some example

A: It's possible that making the destructor virtual could convert your class from a non-polymorphic type to a polymorphic type.
Note that a polymorphic type is never trivially copyable. So, for example, you could break any use of std::memcpy by the introduction of a virtual destructor.
In some situations - particularly when interoperating with C - that can wreak havoc, as you can no longer assume that the address of an instance of your class is the same as the address of the first member.
Reference: https://en.cppreference.com/w/cpp/types/is_trivially_copyable

A:
Is there any valid and usable case, that will force you not to use the virtual keyword before the destructor.

Yes. If you ever use std::memcpy or std::memcmp with instances of the class or its members, or rely on a pointer to/from an instance being convertible to the first member of the class,or examine common initial sequence of an inactive union member of the class type.
In general: If you rely on the class being a standard-layout type or trivially copyable, then the destructor (as well as all other member functions) must be non-virtual. Most cases of erroneously assuming standard-layoutness or triviality have undefined behaviour. Those properties can be enforced with type traits and static asserts, so that you get a nice compilation error instead.


text:
Q: Fixing the max-height in resizable textarea I want to fix the max height and the max width of my resizable textarea.

textarea {
  width:70%;
  max-width:70%;
  height: 40%;
  max-height:60%;
  }
<textarea></textarea>

The max width is fixed but the height no ! How to fix that using css ?

A: Did you size textarea's main div?
You can find the solution here:

body {
  background:#ddd;
  margin:0;
  padding:0;
}
.getDiv {
  height:200px;
  width:400px;
  background:red;
}
textarea {
  height:25%; /* 50px */
  width:25%; /* 100px */
  max-height:50%; /* 100px */
  max-width:50%; /* 200px */
  }
<body>
 <div class="getDiv">
    <textarea></textarea>
  </div>
</body>

A: This will fix max-width to 500px and max-height to 100px in your resizable textarea.
Change the values of max-width and max-height accordingly.

textarea {
  width: 100%;
  max-width:500px;
  height: 100%;
  max-height:100px;
}
<textarea></textarea>


text:
Q: Output of one request used as a parameter in next request using Asyncio + Aiohttp I'm new to Async programming, Asyncio, Aiohttp world.
I have multiple requests where - output of 1st request is being used as a parameter in 2nd request.
So far I have tried this much -
import aiohttp
import asyncio

async def get_response(session, url, params):
    async with session.get(url=url, params=params) as response:
        response = await response.json()
        return response['output']

async def main():

    tasks = []

    url = "https://example.api.com/"

    url_1 = url + 'path_1'
    url_2 = url + 'path_2'

    params = {'name': "Hello"}

    async with aiohttp.ClientSession() as session:

        a1 = get_response(session, url_1, params)
        tasks.append(a1)

        params = {'name': a1}
        b1 = get_response(session, url_2, params)
        tasks.append(b1)

        responses = await asyncio.gather(*tasks, return_exceptions=True)

        print(responses)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

I'm getting this error which is obvious -
TypeError("Invalid variable type: value should be str, int or float, got <coroutine object get_response at 0x00000000037FA6C0> of type <class 'coroutine'>")

So how do I pass the output of 1st request and not the coroutine object to the 2nd request -
params = {'name': a1}
b1 = get_response(session, url_2, params)

A: If the result of the first coroutine is needed for the second one, then you cannot run both coroutines in parallel, you will need to await the response of the first one. For example:
async def get_both(session, url_1, url_2, params_1):
    a1 = await get_response(session, url_1, params_1)
    params_2 = {'name': a1}
    b1 = await get_response(session, url_2, params_2)
    return a1, b1  # or just b1 if you don't need a1

Your main() would then look like this:
async def main():
    url = "https://example.api.com/"
    url_1 = url + 'path_1'
    url_2 = url + 'path_2'
    params = {'name': "Hello"}

    async with aiohttp.ClientSession() as session:
        responses = await get_both(session, url_1, url_2, params)
        print(responses)

Of course, you don't get parallel fetching, but that's a direct consequence of the fact that one request depends on the result of the other. What you could easily do is parallelize multiple instances of get_both - e.g. if url_1 and url_2 were lists, you could do this:
async def main():
    url_list_1 = [...]
    url_list_2 = [...]
    params = {'name': "Hello"}

    async with aiohttp.ClientSession() as session:
        coros = [get_both(session, url_1, url_2, params)
                 for url_1, url_2 in zip(url_list_1, url_list_2)]
        all_responses = await asyncio.gather(*coros)
        print(all_responses)


text:
Q: How to send gmail email with asp.net - c#? hi i want to send a some form entries resulting in a  postback to be mailed automatically with my gmail account to the target mail id entered by the user with asp.net - c#?

A: You can send an email using: http://www.systemnetmail.com/
Gmail uses the mail server that you can configure (I forget the exact address, but you can find it on the google site) your web application to use when it sends mail.

A: As gmail lets you send mail var SMTP you should just be able to use the SmtpClient class in the .net framework.
Do you however often have to configure your virus scanner to allow out going emails from the process the Asp.net is running in.


text:
Q: Pass connection string to code-first DbContext How do I pass a connection string to entity framework's code-first DbContext? My database generation works correctly when both DbContext and the connection string in web.config is in the same project and named the same way. But now I need to move the DbContext to another project so I'm testing passing a connection string to it as follows:
Model & Context
public class Dinner
{
    public int DinnerId { get; set; }
    public string Title { get; set; }
}

public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
        : base(connString)
    {
    }
    public DbSet<Dinner> Dinners { get; set; }
}

Action
    public ActionResult Index()
    {
        var db = new NerdDinners(ConfigurationManager.ConnectionStrings["NerdDinnerDb"].ConnectionString);

        var dinners = (from d in db.Dinners
                      select d).ToList();
        return View(dinners);
    }

Web.Config
<connectionStrings>
  <add name="NerdDinnerDb" connectionString="Data Source=|DataDirectory|NerdDinners.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>

If I set a breakpoint in the action an analyze the db, the connection string is there, but it does not create or find the database or anything.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

A: After reading the docs, I have to pass the name of the connection string instead:
var db = new NerdDinners("NerdDinnerDb");

A: Thought I'd add this bit for people who come looking for "How to pass a connection string to a DbContext": You can construct a connection string for your underlying datastore and pass the entire connection string to the constructor of your type derived from DbContext.
(Re-using Code from @Lol Coder)
Model & Context
public class Dinner
{
    public int DinnerId { get; set; }
    public string Title { get; set; }
}

public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
        : base(connString)
    {
    }
    public DbSet<Dinner> Dinners { get; set; }
}

Then, say you construct a Sql Connection string using the SqlConnectioStringBuilder like so:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(GetConnectionString());

Where the GetConnectionString method constructs the appropriate connection string and the SqlConnectionStringBuilder ensures the connection string is syntactically correct; you may then instantiate your db conetxt like so:
var myContext = new NerdDinners(builder.ToString());

A: In your DbContext, create a default constructor for your DbContext and inherit the base like this:
    public myDbContext()
        : base("MyConnectionString")  // connectionstring name define in your web.config
    {
    }

A: I have a little solution example for that problem.
MyDBContext.cs
 public MyDBContext(DBConnectionType ConnectionType) //: base("ConnMain")
  {
      if(ConnectionType==DBConnectionType.MainConnection)
       {
         this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnMain"].ConnectionString;
       }
      else if(ConnectionType==DBConnectionType.BackupConnection)
       {
         this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnBackup"].ConnectionString;
       }
  }

MyClass.cs
public enum DBConnectionType
 {
    MainConnection=0,
    BackupConnection=1
 }

frmMyForm.cs
 MyDBContext db = new MyDBContext(DBConnectionType.MainConnection);
                               //or
//MyDBContext db = new MyDBContext(DBConnectionType.BackupConnection);

A: If you are constructing the connection string within the app then you would use your command of connString. If you are using a connection string in the web config. Then you use the "name" of that string.

A: from here
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
      optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
    }

note you may need to add Microsoft.EntityFrameworkCore.SqlServer

A: A little late to the game here, but another option is:
public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
    {
        this.Database.Connection.ConnectionString = connString;
    }
    public DbSet<Dinner> Dinners { get; set; }
}

A: Check the syntax of your connection string in the web.config.  It should be something like ConnectionString="Data Source=C:\DataDictionary\NerdDinner.sdf"

A: When using an EF model, I have a connection string in each project that consumes the EF model. For example, I have an EF EDMX model in a separate class library. I have one connection string in my web (mvc) project so that it can access the EF db.
I also have another unit test project for testing the repositories. In order for the repositories to access the EF db, the test project's app.config file has the same connection string.
DB connections should be configured, not coded, IMO.

A: Can't see anything wrong with your code, I use SqlExpress and it works fine when I use a connection string in the constructor.
You have created an App_Data folder in your project, haven't you?

A: For anyone who came here trying find out how to set connection string dinamicaly, and got trouble with the solutions above (like "Format of the initialization string does not conform to specification starting at index 0.") when setting up the connection string in the constructor. This is how to fix it:
public static string ConnectionString
{
    get {
        if (ConfigurationManager.AppSettings["DevelopmentEnvironment"] == "true")
            return ConfigurationManager.ConnectionStrings["LocalDb"].ConnectionString;
        else
            return ConfigurationManager.ConnectionStrings["ExternalDb"].ConnectionString;
    }
}

public ApplicationDbContext() : base(ConnectionString)
{
}


text:
Q: Bootstrap progress bar called from javascript error I have a progress bar defined like this:

I am using a javascript code to change the length of the bar simultaneously. Here is the code
            var progress = setInterval(function() {
                var percent=(($scope.subcategory.planned2+$scope.subcategory.completed2)/($scope.subcategory.required2)*100);
                var $bar = $('.bar');
                $bar.width($bar.width()+percent);
                $bar.text(percent + "%");
            });

I am getting the value of the bar correctly when i run my program but for some reason the bar does not show. It shows an empty progress bar but the value of the $bar.text still shows up.

A: Have you updated from bootstrap 2 to bootstrap 3?  If so the inner class is wrong, you'll want to use progress-bar instead of bar.


text:
Q: Passing dynamic array of structs to GPU kernel I try to pass my dynamic array of structs to kernel but it doesn't works. I get - "Segmentation fault (core dumped)"
My code - EDITED
#include <stdio.h>
#include <stdlib.h>

struct Test {
    unsigned char *array;
};

__global__ void kernel(Test *dev_test) {
}

int main(void) {

    int n = 4;
    int size = 5;
    unsigned char *array[size];
    Test *dev_test;

    //   allocate for host
    Test *test = (Test*)malloc(sizeof(Test)*n);
    for(int i = 0; i < n; i++)
    test[i].array =  (unsigned char*)malloc(size);

    //  fill data
    for(int i=0; i<n; i++) {
        unsigned char temp[] = { 'a', 'b', 'c', 'd' , 'e' };
        memcpy(test[i].array, temp, size);
    }

    //  allocate for gpu
    cudaMalloc((void**)&dev_test, n * sizeof(Test));
    for(int i=0; i < n; i++) {
        cudaMalloc((void**)&(array[i]), size * sizeof(unsigned char));
        cudaMemcpy(&(dev_test[i].array), &(array[i]), sizeof(unsigned char *), cudaMemcpyHostToDevice);
    }

    kernel<<<1, 1>>>(dev_test);

    return 0;
}

How correctly I should allocate gpu memory and copy data to this memory?

A: You need to allocate memory for struct member array.
Test *test = malloc(sizeof(Test)*n);
for(int i = 0; i < n; i++)
    test[i]->array =  malloc(size);

I would suggest to read this answer to cope up with other issues after this fix.

A: what is your card ? if your card support compute capability >= 3.0, try the unified memory system , to have same data in host/device memory
you can have a look here :
it should maybe look like this one :
    int main(void) {
int n = 4;
int size = 5;
Test *test;
cudaMallocManaged(&test, n * size);
unsigned char values[] = { 'a', 'b', 'c', 'd' , 'e' };
for(int i=0; i<n; i++)
{
    unsigned char* temp;
    cudaMallocManaged(&temp, size*sizeof(char) );
    memcpy(temp, values, sizeof(values) );
}
// avoid copy code, makes a deep copy of objects
kernel<<<1, 1>>>(test);
return 0;
    }

And i hope you know it, but Don't forget do call cudaFree & delete/free on allocated memory. (better to use std::vector and use data() to access to raw pointer)


text:
Q: How to take an entire column of a database and turn it into a String array? I'm trying to take an entire column from a table in my DB and store all the entries into a String array Below you have my code:
    public Cursor fetchAllBarcodeEntries(){
    return db.query(BARCODE_TABLE, new String[] {KEY_BARCODE_ID, KEY_BARCODE_NUMBER, KEY_BARCODE_PRODUCT, KEY_BARCODE_PRODUCT_DESC}, null, null, null, null, null);
}

I'm calling and using the function like this:
    Cursor c = dbAdapter.fetchAllBarcodeEntries();

    for(int i = 0; i < c.getCount(); i++){
        stringArray[i] = c.getString(c.getColumnIndex(dbAdapter.KEY_BARCODE_PRODUCT);
    }

This is part of the error log that I'm getting
01-26 23:15:02.434: E/AndroidRuntime(787): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

Any help would this would be greatly appreciated...

A: The answer is here
ArrayList<String> columnArray1 = new ArrayList<String>();
ArrayList<String> columnArray2 = new ArrayList<String>();
ArrayList<String> columnArray3 = new ArrayList<String>();
if(mCursor.moveToFirst()!=null){
  do{
    columnArray1.add(mCursor.getString(COLUM_INDEX1));
    columnArray2.add(mCursor.getString(COLUM_INDEX2));
    columnArray3.add(mCursor.getString(COLUM_INDEX3));
  } while (mCursor.moveToNext()!=null);
}

Afterwards you can convert the ArrayList into a String array:
String[] colStrArr1 = (String[]) columnArray1.toArray(new String[columnArray1.size()]);

A: You should check the return value of c.getColumnIndex(). It is probably returning -1 because the given column (dbAdapter.KEY_BARCODE_PRODUCT) does not exist in that table, possibly due to an error on your database.
Also, what's Toast.LENGTH_SHORT doing there?
It seems something is missing from the code you posted...

A: You may try something like this below:
Cursor c = dbAdapter.fetchAllBarcodeEntries();

int columnCnt = c.getColumnCount ();

String[] stringArray = new String[columnCnt];
c.moveTofirst();

    for(int i = 0; i < columnCnt ; i++){

        stringArray[i] = c.getString(i);
}

Note: I don't have IDE handy, there may be syntax errors.


text:
Q: Absolute Path Not working for create react app with typescript If I use absolute path which configured with typescript it doesn't work. After adding config in tsconfig file I can navigate to the file in vscode by clicking on component. But Project doesn't run. Please help me if there any issue with my config.
tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "~/*": ["./*"]
    },
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "exclude": ["node_modules", "build"]
}

Here is my main route file
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import { Login, Movie } from '~/pages';

const AppRouter: React.FC = (props) => {
  return (
    <Routes>
      <Route path="" element={<Movie />} />
      <Route path="login" element={<Login />} />
    </Routes>
  );
};

export default AppRouter;

When I click on component it goes to the file successfully. But when I run the project. It show me error message
Failed to compile.

Module not found: Error: Can't resolve '~/pages' in '/Volumes/Workplace/ababa_tech_task/frontend/src/routes'
ERROR in ./src/routes/index.tsx 6:0-39
Module not found: Error: Can't resolve '~/pages' in '/Volumes/Workplace/ababa_tech_task/frontend/src/routes'

webpack compiled with 1 error
Files successfully emitted, waiting for typecheck results...
Issues checking in progress...
No issues found.

It work like this ->
...
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "pages": ["src/pages"]
    },
}

import React from 'react';
import { Route, Routes } from 'react-router-dom';
import { Login, Movie } from 'pages'; // pages instead of ~/pages working

const AppRouter: React.FC = (props) => {
  return (
    <Routes>
      <Route path="" element={<Movie />} />
      <Route path="login" element={<Login />} />
    </Routes>
  );
};

export default AppRouter;

But I don't want to keep like this. Because It will confusing. direct module path means comes from node_modules and I want to keep ~/* which means comes from src folder
I used other project with react-rewired-app which worked. but I don't want to do like this.

A: You gotta check if there's a "type": "module" in your package.json, cause then you'll need to write the ext. in every file you import:
import { Login, Movie } from '~/pages.tsx';

If that's the case, you can simply remove "type": "module"

A: You are using create-react-app so you must follow the pattern set by them.
create-react-app explains in their documentation how to use absolute imports for typescript projects.
If your project looks something like this:
    |- project
    |- src
       |-- components
       |-- pages
            |- index.ts
            |- Login.tsx
            |- Movie.tsx

your import should look like this:
    import {Login, Movie} from 'paths'