text:
Q: How to pass parameters to procedure at DBMS.SUBMIT? I have such a procedure:
    create or replace procedure addJobTest (
  opisArg varchar2
)as

  begin
    insert into JobsTest(opis) values (opisArg);

end addJobTest;

I'm trying to use it with DBMS.SUBMIT passing 'ala123' argument
Declare
jobInsertNo number;
BEGIN
      DBMS_JOB.SUBMIT (number,
                   'addJobTest('||''''||'ala123'||''''||');',
                  SYSDATE,
                  'SYSDATE + (10/(24*60*60))');
  COMMIT;
  END;

but i get an error. It says
ORA-06550: line 5, column 33:
PLS-00103: Encountered the symbol "ALA123" when expecting one of the following:
   ) , * & | = - + < / > at in is mod remainder not rem => ..
   <an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_
   LIKE4_ LIKEC_ between || multiset member SUBMULTISET_
The symbol ", was inserted before "ALA123" to continue.
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

How should I pass a varchar argument to addJobTest procedure at DBMS.SUBMIT?

A: I've found a small typo in your PL/SQL block but other than that your code works:
SQL> CREATE TABLE JobsTest (opis VARCHAR2(20));

Table created

SQL> CREATE OR REPLACE PROCEDURE addJobTest(opisArg VARCHAR2) AS
  2  BEGIN
  3     INSERT INTO JobsTest (opis) VALUES (opisArg);
  4  END addJobTest;
  5  /

Procedure created

SQL> DECLARE
  2     jobInsertNo NUMBER;
  3  BEGIN
  4     DBMS_JOB.SUBMIT(jobInsertNo, /* instead of number */
  5                     'addJobTest('||''''||'ala123'||''''||');',
  6                     SYSDATE,
  7                     'SYSDATE + (10/(24*60*60))');
  8     COMMIT;
  9  END;
 10  /

PL/SQL procedure successfully completed

SQL> select * from jobstest;

OPIS
--------------------
ala123

A: DECLARE
     jobInsertNo NUMBER;
  BEGIN
     DBMS_JOB.SUBMIT(jobInsertNo, /* instead of number */
                     q'{addJobTest('ala123');}',
                     SYSDATE,
                     'SYSDATE + (10/(24*60*60))');
  COMMIT;
END;


text:
Q: How to get the uid of a registered user with ionic and firebase I'm trying to register a user with firebase, once the user is registered, I would like to add them to the firestore database but I can't access the uid of the user that just registered.
registerUser(name: string, email: string, password: string): Promise<any> {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password).then((newUser:any) => {
    console.log(newUser.uid)
});
}

newUser.uid is undefined, how do I access this value?
Thanks

A: according to the documentation here - https://firebase.google.com/docs/reference/js/firebase.auth.Auth#createUserWithEmailAndPassword
the function returns "returns firebase.Promise containing non-null firebase.auth.UserCredential"
console.log(newUser.user.uid)

redpajama_set_name: RedPajamaStackExchange


text:
Q: According to Faraday's law, does a magnet need to accelerate to cause an induced voltage or can the magnet be stationary? I'm trying to design an experiment around Faraday's law for an assignment in school. I want to do something similar to what is in this video https://youtu.be/vwIdZjjd8fo. I wanted to only change the loops in the wire to see if induced voltage was proportional to the number of loops in the wire. I want to keep velocity constant in the trials. Will a voltage still be induced at a constant velocity or do I have to accelerate the magnet?

A: Let's recall that the induced current due to the motion of a magnet is proportional to the rate of change of the magnetic flux. Meaning that a magnet moving, at a constant velocity, will induce a voltage in the coil. Additionally, the higher the velocity, the higher the absolute value of voltage induced.
It's important to note that the energy deposited into the circuit is directly subtracted from the kinetic energy of the magnet. That's why, when you drop a magnet through a coil, the magnet takes longer to hit the ground than if you were to drop it in the absence of a coil.
The question you asked in the title is also slightly different from what you had asked in the question body. Typically, a stationary magnet cannot induce a voltage in a coil since there is no change in the magnetic flux over time. This is based on the assumption that you can't somehow manipulate the orientation of the magnetic field of the magnet itself without moving it mechanically.

A: The induced emf is proportional to the rate of change of magnetic flux which in turn will be related to the speed of the magnet.
If the speed is increasing and all other things are equal then the emf will increase.
I'm trying to design an experiment around Faraday's law for an assignment in school. I want to do something similar to what is in this video . . . . . . which consists of a magnet being moved into a coil, with a variable number of tuns, connected to a moving coil ammeter.
This is a often used demonstration of Faraday's law which illustrates the idea but can be improved.
The first thing to note from the video is that the coils which are being used have differing resistances because the lengths of the wires are not the same.
So better to have a long piece of wire and altering the number of turns with the rest of the wire which is not part of the coil being connecting leads.
Next there is a problem with the damping in the circuit which can often be illustrated by adding resistance in the coil and ammeter circuit and noting that the deflection shown on the ammeter is larger!
The ammeter coil is designed to be critically damped so that the pointer reaches a reading without overshoot and in the shortest time possible.
With a small resistance coil across the terminals the damping is increased and so when the emf is generated over a short period of time the coil (and pointer) are more sluggish in its response resulting in a smaller reading.
Another problem is that keeping "all other things are equal" requires you to move the magnet at the same speed for each part of the experiment.
A possible way out of this is to have the coil in a horizontal plane and connect to either a data logger of a cathode ray oscilloscope and dropping the magnet from the same position relative to the coil every time and noting the maximum and minimum readings.
With this arrangement the damping of the ammeter is avoided and it is possible to take readings which show a proportionality between induced voltage and number of turns.
With the coil and the magnets you will probably be using the effect of the induced voltage producing an induced current which retards the passage of the magnet will probably be very small as the induced current will be very small due to the input resistance of the data logger or the CRO being very high.


text:
Q: how to get some data from the type any in swift I have a variable with a type of Any, when I print the variable it looks like I have a json object like below:
var machineNumber: Any

NSLog("Machine number: \(machineNumber)")

the result is :
Machine number: {length = 29, bytes = 0xab002a05 0803073c 6b43fefe 6b3c0000 ... 00000000 00000000 }

my question is, how can I get the bytes out of the variable with the type Any.
Any help is appreciated!

A: This is the string format you would get for an NSData. Assuming it really is an NSData, you would convert it to a Data. (And then, ideally, replace Any with Data in your definition. Any types a major pain to work with.)
if let data = machineNumber as? Data {
    // use `data` for the bytes
}


text:
Q: OSError : no Such file or directory I have the following piece of code to check if a file exists in my s3 bucket. I give the program a directory and I am trying to upload all the files in that directory. However I have no idea why I keep running into the OSError: [Errno 2] No such file or directory: 'foo.txt' error. This is my code
def s3_has_uptodate_file(bucket, transfer_file, source_size):

    bucket = Bucket(conn, default_bucket)
    s3_key = bucket.get_key(os.path.basename(transfer_file))
    if s3_key:
        s3_size = s3_key.size
        local_size = source_size
        s3_time = rfc822.mktime_tz(rfc822.parsedate_tz(s3_key.last_modified))
        local_time = os.path.getmtime(os.path.basename(transfer_file)) #fails here
        return s3_size == local_size and s3_time >= local_time
    return False

I check my stackdata and my bucket has the right bucket name, transfer file is /Users/merlin/Desktop/test_folder/foo.txt and source size is 141 (correct size).
I put the following lines of code into a  new file to test it out and it runs perfectly.
import os
transfer_file = '/Users/merlin/Desktop/test_folder/foo.txt'
local_time = os.path.getmtime(os.path.basename(transfer_file))
print local_time

A: os.path.basename(transfer_file) will return just the file name off a path. This is a relative path from the prospective of any os.path methods. Unless you are running the program from the directory in which "foo.txt" lives in, os.path.getmtime will most certainly fail. You need to pass the absolute path to "foo.txt". You probably just want to use os.path.getmtime(transfer_file).


text:
Q: Way to find real roots in 5th polynomial equation which some constant is 2D array My equation is like this:
A x**5 + B x**4 + C x**3 +  D x**2 + E[i][j] x + F[i][j] = 0
I want to find real roots. Constant E and F are matrix (2D array) size 80x100. My guessing code for solution of this problem is:
p = [A, B, C, D, E[i][j], F[i][j]]
u_cr2 = np.roots(p)
u_cr2 = u_cr2[np.isreal(u_cr2)]
print(u_cr2)

If I exchange [i][j] with first elements of matrix [0][0] I will get the real root for that first element of the matrix. So that tells me that the logic for this problem is pretty much okay. But how I to iterative this problem to get full solution, to get 2D array of real roots size 80x100? It doesn't works if I leave code like this.


text:
Q: Why late materialization is not triggered for insert queries? Assume I have table t with columns c1,c2,c3. (not so many records, ~10k) and an empty table tmp_table with same structure.
Talking about columnar store, I want to understand when does it make sense to apply late materialization/projection.
I wrap query q2 inside insert and suddenly late materialization is not triggered anymore, why ?
select * from t where c2 = 4; -- q1: late projection is applied

insert into tmp_table (select * from t where c2 = 4); -- q2: late projection NOT applied

A similar question I found on: https://answers.sap.com/questions/699087/late-materialization-insert-processing.html
But the answer is revolves around OUT OF MEMORY exception while I have little data that fits inside main memory.


text:
Q: Android Webview SwipeRefreshLayout Is it possible to refresh WebView current page using SwipeRefreshLayout? If it is can you show me how to do that?

A: Wrap your webview inside SwipeRefreshLayout and override the onRefresh() method of SwipeRefreshLayout.
In onRefresh() method you can do whatever you want.


text:
Q: Approximate the largest and the smallest values of the integral How do I solve this:approximate the largest and the smallest values of the integral

for

A: Please note that some illustration of your efforts to  solve this problem with Mathematica is regarded as a minimum requirement for questions. This aids your skills and facilitates assistance.
For motivation:
Plot[t/Sqrt[2 + t^3], {t, -1, 3}, Filling -> Axis]

For the interval of interest the function is positive and close to constant. The integral of the function will be monotone increasing  (and close to linear ), hence the minimum and maximum will be the end points of the interval.
I suggest you program using NIntegrate or Integrate.
Just for 'fun', you can use new functions in v10:
ir0 = ImplicitRegion[0 > y > x/Sqrt[2 + x^3] && -1 < x < 0, {x, y}];
irf[u_] :=
 ImplicitRegion[0 < y < x/Sqrt[2 + x^3] && 0 < x < u, {x, y}]
func[v_] := N[RegionMeasure[irf[v]] - RegionMeasure[ir0]]

Confirming the qualitative observation:
Plot[func[v], {v, 1, 3}]

You can now answer your minimum, maximum question.


text:
Q: How to save multiple records using Ajax in JSP I want to save multiple records in database without refreshing the page. For that I am using Ajax. But It saves only one record at a time.
My JSP code (CustomerInvoice.jsp):
<%@ page import="java.sql.Statement" import="java.sql.ResultSet" import="java.sql.Connection" import="java.util.*" %>
<%@page import="connection.DBConnection"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer Invoice wise </title>

 Customer Invoice wise outstanding

<form name="bankledgerreport" action="CustomerInvoiceServlet1" method="get" >

Date
Invoice Number
Invoice Amount
Amount Adjusted
Balance Amount

<%  DBConnection dbc=new DBConnection();
            Connection con=dbc.getNewConnection();
            Statement st = null;
            ResultSet rs = null;
            String selectedcustcode = request.getParameter("acc");

            ///int count=1;
            double debtors=0, creditors=0, cashbank=0, fixedassets=0, other=0, capital=0, otherexpenses=0, sellingandmarketing=0, salaryandwages=0, administrativecharges=0, provision=0, unsecuredloans=0, securedloans=0, investments=0, closingstock=0, openingstock=0, loansandadvances=0, indirectincome=0, bankchargesandinterest=0, depreciation=0; //trial balance
            //out.println(selectedcustcode);
            double bal=0.0,in=0.0,adj=0.0,bal1=0.0,bal2=0.0;

            String dte="",nm="",cd="",inn="",inn1="";
            List li=new ArrayList();
            %>

            <%
            try
            {
                  st=con.createStatement() ;

                          rs=st.executeQuery("SELECT innum,date,svname,ccode,balance,scred FROM salesinvoiceoutstanding WHERE  EXISTS (SELECT  innum FROM salesvoucher2  WHERE  salesinvoiceoutstanding.innum = salesvoucher2.innum ) and ccode='"+selectedcustcode+"'");
                          while(rs.next())
                          {

                              inn=rs.getString(1);
                                dte=rs.getString(2);
                                nm=rs.getString(3);
                                cd=rs.getString(4);
                                 bal=rs.getDouble(5);
                                 bal1=bal1+bal;
                                 int cred=rs.getInt(6);
                                 %>
                                    <input type=hidden name=cname id=cname class=cname value="<%=nm%>"/>
                  <input type=hidden name=ccd id=ccd class=ccd value="<%=cd%>"/>
                <input type=hidden name=cred id=cred class=cred value="<%=cred%>"/>

             <input type=hidden id=dte name=dte class=dte value="<%=dte %>"/><%=dte %>

             <input type=hidden id=inn name=inn class=inn value="<%=inn %>"/><%=inn %>

            <input type=hidden  name=innamt id=innamt class=innamt value="<%=bal %>"/><%=bal %>
             <input type=text name=amtadjust id=amtadjust class=amtadjust value="0"  />
             <input type=text name=balamt id=balamt class=balamt value="<%=bal %>" />

          <%}
                          rs=st.executeQuery("SELECT innum,date,scname,ccode,stota,scredlim FROM salesvoucher2 WHERE not EXISTS (SELECT  innum FROM salesinvoiceoutstanding  WHERE  salesinvoiceoutstanding.innum = salesvoucher2.innum ) and (ccode='"+selectedcustcode+"' and status=1)");
                          while(rs.next())
                          {

                              inn=rs.getString(1);
                                dte=rs.getString(2);
                                nm=rs.getString(3);
                                cd=rs.getString(4);
                                 in=rs.getDouble(5);
                                 bal2=bal2+in;
                                 int cred=rs.getInt(6);

                        %>
                        <input type=hidden name=cname id=cname class=cname value="<%=nm%>"/>
                  <input type=hidden name=ccd id=ccd class=ccd value="<%=cd%>"/>
                <input type=hidden name=cred id=cred class=cred value="<%=cred%>"/>

             <input type=hidden id=dte name=dte class=dte value="<%=dte %>"/><%=dte %>

             <input type=hidden id=inn name=inn class=inn value="<%=inn %>"/><%=inn %>
            <input type=hidden  name=innamt id=innamt class=innamt value="<%=in %>"/><%=in %>
             <input type=text name=amtadjust id=amtadjust class=amtadjust value="0"  />
             <input type=text name=balamt id=balamt class=balamt value="<%=in %>" />

<%
            }}
               catch(Exception e)
               {} %>
               <% double amount=bal1+bal2; %>

	Advanced Received		<input type=text name=advance id=advance value="0"/>

	Total		<input type=text name=total id=total value="0" onblur="sub()" />	<input type="text" name="totamt" value="<%=amount %>"  />

 <input type=button name="customersubmit" id="customersubmit" value=Save>
        </form>

In above image, I have to save those two records that are SV2 and SV3 (Invoice number) in database using Ajax.
My servlet code:(CustomerInvoiceServlet1.java)
package com;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import connection.DBConnection;

/**
 * Servlet implementation class CustomerInvoiceServlet1
 */
public class CustomerInvoiceServlet1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public CustomerInvoiceServlet1() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        String dt1="",nm1="",cd1="",in1="",amt1="",amtadj1="",balamt1="",cr1="";
        int crd[] = null;
        //int cr1=0;
        DBConnection dbc=new DBConnection();
        Connection con=dbc.getNewConnection();
        Statement st = null;
        ResultSet rs=null;
        String dt[] = request.getParameterValues("dte");
        String nm[]=request.getParameterValues("cname");
        String cd[]=request.getParameterValues("ccd");
        String cr[]=request.getParameterValues("cred");
        String in[]=request.getParameterValues("inn");
        //int count[]=Integer.parseInt(request.getParameterValues("cnt1"));
        String amt[]=request.getParameterValues("innamt");
     String amtadj[]=request.getParameterValues("amtadjust");
    String balamt[]=request.getParameterValues("balamt");

    String  query="";
     double pyamt=0.0;

  try{
     st=con.createStatement();
    for (int i=0;i<in.length;i++)
    {
        cd1=cd[i];
        String  query1="delete from salesinvoiceoutstanding where ccode = '"+cd1+"';";
        st.executeUpdate(query1);
    }

  for (int i=0;i<in.length;i++) {

      dt1=dt[i];
     nm1=nm[i];
     cd1=cd[i];
     cr1=cr[i];
     in1=in[i];
     amt1=amt[i];
     amtadj1=amtadj[i];
     balamt1=balamt[i];

     query="INSERT INTO salesinvoiceoutstanding(date,innum,svname,ccode,svamount,adjamount,balance,scred) VALUES('"+dt1+"','"+in1+"','"+nm1+"','"+cd1+"','"+amt1+"','"+amtadj1+"','"+balamt1+"','"+cr1+"')";
    int j=st.executeUpdate(query);

    }

    con.close();

}catch(Exception e){
  e.printStackTrace();
}

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

Above all coding saves only first record i.e. SV2.
So My question is how can I save those two records(SV2 and SV3) or more records  in database at a time using Ajax.

A: You can do a query of the following form to INSERT multiple records with one query in MySQL:
INSERT INTO salesinvoiceoutstanding (date,innum,...) VALUES(dt1,in1,...),(dt2,in2,...),(dt3,in3,...);

Here is some sample code which will allow you to handle an arbitrary number of INSERTs coming from your AJAX call:
String query = "INSERT INTO salesinvoiceoutstanding(date,innum,svname,ccode,svamount,adjamount,balance,scred) ";
for (int i=0; i<in.length; ++i) {

    dt1=dt[i];
    nm1=nm[i];
    cd1=cd[i];
    cr1=cr[i];
    in1=in[i];
    amt1=amt[i];
    amtadj1=amtadj[i];
    balamt1=balamt[i];

    if (i > 0) {
        query += ",";
    }

    query += "VALUES('"+dt1+"','"+in1+"','"+nm1+"','"+cd1+"','"+amt1+"','"+amtadj1+"','"+balamt1+"','"+cr1+"')";
}

query += ";"; // don't forget the semi-colon at the end of the query

int j=st.executeUpdate(query);

By the way, you should be really careful about SQL injection attacks with your code.


text:
Q: Validating Docbook 5.0, link/linkend I am wondering why this Docbook 5.0 document is not valid:
<?xml version='1.0' encoding='utf-8'?>

<title>This is a title</title>
<para>
Blah <link linkend='H_0'>This is a link</link>blah blah blah.</para>

Here is what I get from xmlstarlet:
$ xmlstarlet val --err --xsd /usr/share/xml/docbook/schema/xsd/5.0/docbook.xsd test.xml
test.xml:3.22: Element '{http://docbook.org/ns/docbook}section', attribute '{http://www.w3.org/XML/1998/namespace}id': '' is not a valid value of the atomic type 'xs:ID'.
test.xml:6.25: Element '{http://docbook.org/ns/docbook}link', attribute 'linkend': '' is not a valid value of the atomic type 'xs:IDREF'.
test.xml - invalid

I just want internal links in the document, to the sections.
Addition: maybe this is an xmlstarlet problem, as other tools happily process the files. Anyway, I'd be glad if somebody could explain the problem.

A: Maybe it's a bug in the version of xmlstarlet you have installed? It works for me on Debian:
$ xmlstarlet val --err --xsd /usr/share/xml/docbook/schema/xsd/5.0/docbook.xsd -
<?xml version='1.0' encoding='utf-8'?>

<title>This is a title</title>
<para>
Blah <link linkend='H_0'>This is a link</link>blah blah blah.</para>

- - valid
    ^^^^^

Here's my xmlstarlet version info:
$ xmlstarlet --version
1.6.1
compiled against libxml2 2.9.4, linked with 20904
compiled against libxslt 1.1.29, linked with 10129

Incidentally, though, the DocBook document in the question isn't actually valid—because a DocBook article element must have either a title or info child:
$ cat > test.xml
<?xml version='1.0' encoding='utf-8'?>

<title>This is a title</title>
<para>
Blah <link linkend='H_0'>This is a link</link>blah blah blah.</para>

$ java -jar /usr/share/java/jing.jar \
    /usr/share/xml/docbook/schema/rng/5.0/docbook.rng test.xml
test.xml:3:23: error: element "section" not allowed yet; expected element "info",
"subtitle", "title" or "titleabbrev"

See http://tdg.docbook.org/tdg/5.0/article.html:

article — An article.
Synopsis
Sequence of:

*

*One of:

*

*Sequence of:

*

*Interleave of:

*

*title

*titleabbrev?

*subtitle?

*info? (db.titleforbidden.info)

*info (db.titlereq.info)

The lack of a ? question mark after title and info there, combined with the One of means that one or the other of title or info is required.
I'm surprised the XSD schema doesn't catch that. But I guess maybe it's an indication that to make sure your DocBook documents actually are valid, you probably want to consider validating against the RelaxNG schema (/usr/share/xml/docbook/schema/rng/5.0/docbook.rng file) instead.


text:
Q: Creating lists of lists (Structs) I am doing a programming assignment at the moment and I dont really have a full grasp of linking as we havent covered it yet. However I feel I need it to do what I want as arrays are not sufficent
I have created a struct as follows
struct node
{
float coef;
int expo;
struct node *link;
};

from this I can create pointers to the struct each with different names, however the problem I encountered is that I want user input to determine the amount I structs. I also want the ability to add and create the different structs.

A: You need to create a head pointer to keep track of your list.
This might be helpful:
struct list
{
    struct node *head;
    int count;
};

And you need to allocate memory for each new node and move the head to the newly created one.
struct node *add_node(struct list *pList, float coef, int expo)
{
    if (pList == NULL)
    {
        return NULL;
    }

    struct *node pNode = (struct node*)malloc(sizeof(struct node));

    if (node == NULL)
    {
        return NULL;
    }

    pNode->coef = coef;
    pNode->expo = expo;
    pNode->link = pList->head;

    pList->head = pNode;
    pList->count++;

    return pNode;
}

To delete an element you need to move the head forward and then free it previous memory.
void *delete_node(struct list *pList, float coef, int expo)
{
    if (pList == NULL)
    {
        return NULL;
    }

    struct node *tmp = pList->head;

    pList->head = pList->head->link;

    free(tmp);

    pList->count--;
}

Note:
This is not the ultimate version. I'm just pointing my fingers to what should be done.

A: I would try something like this as your data structure
struct node
{
    float coef;
    int expo;
    struct node *link;
};

struct poly
{
    node *value;
    struct poly *link
}

Maintain a linked list of polys, each of which contains a linked list of nodes.


text:
Q: Auto margin for input float left

<input type="text"><input type="text"><input type="text">

Inputs have width 31% and i will, that they fill the parent div in 100%. Auto margin for first two inputs. Like this:

A: Please see below code.

<input type="text"><input type="text"><input type="text">


text:
Q: Drag Adorner on ListViewItem with a GridView I have a ListView containing objects and I have used a GridView to display the properties:
       <ListView ItemsSource="{Binding Path=Fields}">
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <EventSetter Event="PreviewMouseLeftButtonDown" Handler="s_PreviewMouseLeftButtonDown" />
                    <EventSetter Event="PreviewMouseLeftButtonUp" Handler="s_PreviewMouseLeftButtonUp" />
                    <EventSetter Event="MouseMove" Handler="MouseMoveHandler" />
                </Style>
            </ListView.ItemContainerStyle>

            <ListView.View>
                <GridView >
                    <GridViewColumn Header="1" >
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Textbox text={binding} />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

Then I have a drag and drop behavior set up on the ListView so that when an ListViewItem is dragged, I clone the controls template which becomes the drag adorner:
 private static ContentControl CreateClone(ListViewItem element)
 {
     ListViewItem control = new ListViewItem();
     if (element != null)
     {
         control.Content = element.Content;
         control.ContentTemplate = element.ContentTemplate;
         control.Template = element.Template;
         control.Style = element.Style;
         control.Background = Brushes.LightGray;
         control.Width = element.ActualWidth;
         control.Height = (element.ActualHeight);
         control.VerticalAlignment = VerticalAlignment.Top;
         control.VerticalContentAlignment = VerticalAlignment.Stretch;
         control.HorizontalContentAlignment = HorizontalAlignment.Stretch;
         control.Opacity = .70;
     }

     return control;
 }

My problem is that the ListViewItem does not have a ContenetTemplate, because im assuming it is defined by the GridView, So I end up with a blank adorner with no columns in it. Do I need to also define a template in the ItemContainerStyle?


text:
Q: building from source Qpid Messaging API (C++, bindings) [Qpid C++ 1.37.0] - missing files I am trying to build from sources Qpid Messaging API (C++, bindings).
Build is triggered on RHEL and all prerequisites mentioned on link below are installed.
https://git-wip-us.apache.org/repos/asf?p=qpid-cpp.git;a=blob_plain;f=INSTALL.txt;hb=HEAD
yet when reaching step: make all
what i get is this
error:
Linking CXX shared library libqpidclient.so
[ 86%] Built target qpidclient
Scanning dependencies of target qpidmessaging
[ 86%] Building CXX object src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o
In file included from /home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/AddressHelper.cpp:22:0:
/home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/PnData.h:27:27: fatal error: proton/engine.h: No such file or directory
 #include <proton/engine.h>
                           ^
compilation terminated.
make[3]: *** [src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o] Error 1
make[2]: *** [src/CMakeFiles/qpidmessaging.dir/all] Error 2
make[1]: *** [examples/messaging/CMakeFiles/client.dir/rule] Error 2
make: *** [client] Error 2

that would indicate that "Qpid proton-c " might be missing but its installed....
any ideas ?

A: It worked for me using these steps.
$ wget http://apache.claz.org/qpid/proton/0.18.1/qpid-proton-0.18.1.tar.gz
$ tar -xf qpid-proton-0.18.1.tar.gz
$ cd qpid-proton-0.18.1/
$ mkdir bld
$ cd bld
$ cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/testprefix
$ make -j8
$ make install
$ cd ../..
$ wget http://apache.claz.org/qpid/cpp/1.37.0/qpid-cpp-1.37.0.tar.gz
$ tar -xf qpid-cpp-1.37.0.tar.gz
$ cd qpid-cpp-1.37.0/
$ mkdir bld
$ cd bld
$ cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/testprefix
>>>> Here check for "Found Proton" in the cmake output <<<<
$ make -j8
$ make install

Check that proton/engine.h is where you think it should be.  In your case, it looks like that would be /usr/local/include/proton/engine.h.
You can use the following command to see what your include search path is.
cpp -v /dev/null -o /dev/null

A: As stated in the very INSTALL file you provided the link to:

Note: If Proton is installed in a non-standard location, there are two
ways to locate it:

*

*Recommended: use proton 0.7 or later and use the same install prefix    for both Proton and Qpid.

*Using pkg-config: set the PKG_CONFIG_PATH environment variable to    /lib[64]/pkgconfig before running cmake.

I'd go for method 1 and rebuild Proton specifiyng an install prefix to cmake, this way:
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local

Then use the same prefix for Qpid (i.e. run cmake again, just like the above).


text:
Q: How can I do a recursion on C++ variadic templates? Suppose I want to define a C++ function that has no Input Parameters within bracket, but within the <> argument. I have a Parameter pack as Input Arguments. Meaning that I have to write, for example, a function
int calculate<args...>()
{
   return 1 + calculate<some_arg,args...>();
}

And also a base case implementation I have to give. However, I am confronted with a lot of Compiler Errors, because I don't know how to write such a form of recursion out properly. What I have to write before the above function declaration?
template<int... args>

(if data type of args is int; any other data type is also possible in a similar way)? Or what I have to write to avoid Compiler Errors? I also tried
template<int some_arg,int... args>

But I don't know also how to deal with variadic templates (how to unpack them). Any help?
EDIT:
My attempt for one Special case
template<bool... dg>
int calculate<0>()
{
    return 1;
}

Error message for this is:
error: expected initializer before '<' token

A:
But I don't know also how to deal with variadic templates (how to unpack them). Any help?

As of C++17 you needn't resort to recursion, but can use pack expansion:
#include <iostream>

template<int ...Args>
constexpr int calculate() {
   return (Args + ...);
}

int main() {
    std::cout << calculate<1, 2, 3>();  // 6
}

If you want to allow other types of non-type template parameters, you can make use of a placeholder type (auto) for non-type template parameters, also a C++17 feature:
template<auto ...Args>
constexpr auto calculate() {
   return (Args + ...);
}

As you cannot partially specialize function templates, you will have to use delegation to a class template if you want to provide different implementations for different specializations:
#include <iostream>
#include <ios>

template<auto ...Args>
struct calculate_impl {
    static constexpr auto calc() { return (Args + ...); }
};

template<bool ...Args>
struct calculate_impl<Args...> {
    static constexpr bool calc() { return (Args && ...); }
};

template<auto ...Args>
constexpr auto calculate() {
   return calculate_impl<Args...>::calc();
}

int main() {
    std::cout << calculate<1, 2, 3>();  // 6
    std::cout << std::boolalpha
        << "\n" << calculate<false,true>()  // false
        << "\n" << calculate<true, true>();  // true
}

A: If you're using C++17+: refer to dfrib's answer
Here's how you would implement a function to add the elements of a parameter pack using template recursion
template<int arg>
constexpr int add()
{
    return arg;
}

template<int arg1, int arg2, int... args>
constexpr int add()
{
    return arg1 + add<arg2, args...>();
}

Regarding if you wanted to create a special case
template<int arg>
constexpr int calculate()
{
    return arg;
}

template<> int calculate<0>() { return 1; } // special case

template<int arg1, int arg2, int... args>
constexpr int calculate()
{
    return calculate<arg1>() + calculate<arg2,args...>();
}

This would make it to where every time you have a zero in you argument list, it will add 1 instead of 0

A: Another way to do recursion allows you to do it in a single function, utilizing the sizeof... operator:
template<int lhs, int... rhs>
int add()
{
    if constexpr(sizeof...(rhs))
    {
        return lhs + add<rhs...>();
    }
    else
    {
        return lhs;
    }
}

This also requires C++17 for if constexpr, but it can do things that fold expressions might not be able to.


text:
Q: I already have 3 checkboxes and 1 textbox in asp.net webform when i check 1and 2 checkbox then result in textbox will be 1,2 I already have 3 checkboxes and 1 textbox in asp.net webform when i check 1and 2 checkbox then result in textbox will be 1,2
I have the following code :
<script type="text/javascript">
    function Test(control, value) {
        var str = '';
        if (control.checked) {
          str = value + '\n' + $('#<%=txtTest.ClientID %>').val();
        }
        else {
            str = $('#<%=txtTest.ClientID %>').val().replace(value + '\n', '');
        }
        $('#<%=txtTest.ClientID %>').val(str);
    }
</script>

to do this......
But the problem in this code ...was when i check 3 and 2 checkbox then result in the textbox is 3,2,
But i want it appear as 2,3 only ...
Can anybody reedit this code ....... ??????
I would be thank ful to u ..............

A: What if you just reverse the output?
$('#<%=txtTest.ClientID %>').val().split(",").reverse().join(",");

A: This function is triggered when user clicks check box. So if you click 2 & 3 by this order, them there is everything right?
So user "each" sentence:
<script type="text/javascript">
    function Test(control, value) {
     var str = '';
     $('#<%=txtTest.ClientID %> :checked').each(function() {
       str = str + ', ' $(this).val();
     });
     $('#<%=txtTest.ClientID %>').val(str);

</script>


text:
Q: найти близкое к среднему знач. число, нужно исправить код #include <stdio.h>
#include <math.h>

int main()
{
    int N, i, c, j, sum = 0, array[10000] = { 0 };
    int result;

    scanf("%d", &N);

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

        scanf("%d", &array[i]);

    for (i = 0; i < N; i++)
    {
        sum = sum + array[i];
    }
    sum = sum / N;

    c = sum - array[0];
    result = array[0];

    for (j = 1; j < N; j++)
    {
        if ((sum - array[i]) < c)
        {
            c = sum - array[i];
            result = array[i];
        }
    }

    printf("%d", result);

    return 0;
}

нужно задать длину массива, ввести числа и вывести одно наиболее приближенное к среднему значению число (целочисленное), код выше выводит просто первое число которое я ввел(т.е. назначает его наиболее приближенным к среднему значению), а мне нужно чтобы он проверил все числа и вывел наиболее приближенное к среднему значению число.Если не трудно напишите мне исправленный или подскажите что неправильно и как исправить если не трудно))язык си
пример правильно работающего кода:
длина массива=5;
вводим числа
9,
7,
5,
-3,
-1.
среднее знач=5

A: 3 существенных ошибки:
1) Разница со средним может быть как положительной, так и отрицательной, так что искать нужно минимум абсолютного значения
c = abs(sum - array[0]);

2) Как @AnT подсказал, среднее значение может быть не целым, поэтому следует использовать вещественную переменную.
3) В третьем цикле счётчик j, а индексы i. Чтобы реже допускать такие ошибки, делайте счётчик цикла локальной для блока цикла переменной.
int main()
{
      int N, array[10] = { 0 };
int result;
float c, sum = 0.0;

scanf("%d", &N);

for (int i = 0; i < N; i++)

    scanf("%d", &array[i]);

for (int i = 0; i < N; i++)
{
    sum = sum + array[i];
}
sum = sum / N;

c = fabs(sum - array[0]);
result = array[0];

for (int i = 1; i < N; i++)
{
    if (fabs(sum - array[i]) < c)
    {
        c = fabs(sum - array[i]);
        result = array[i];
    }
}

printf("%d", result);


text:
Q: how to get sum of a column of sub query result column in sql this is my query in this sub query gives some output columns and i want sum of total amount committed
select x.*,sum(x.AmountCommited)
from
(select
a.TrustMemName,
a.DonorFirstName,
a.AmountCommited,
a.YourCommitmentId,
b.AmountFulfilled,
SUM( CASE WHEN a.DateFulfilled1 between "2017-01-01" and "2017-03-31"
      THEN a.AmountFulfilled
 END) as quarter1,
SUM( CASE WHEN a.DateFulfilled1 between "2017-04-01" and "2017-06-30"
      THEN a.AmountFulfilled
 END) as quarter2,
SUM( CASE WHEN a.DateFulfilled1 between "2017-07-01" and "2017-09-30"
      THEN a.AmountFulfilled
 END) as quarter3,
SUM( CASE WHEN a.DateFulfilled1 between "2017-10-01" and "2017-12-31"
      THEN a.AmountFulfilled
 END) as quarter4
 from
 commitmentcomplete as a left join commitmentsummary as b on
  a.YourCommitmentId=b.YourCommitmentId
  where a.TrustId=2521
 group by a.YourCommitmentId
 ) as x

-------------------------out put------------------
  "TrustMemName"        "DonorFirstName"    "AmountCommited"    "YourCommitmentId"  "AmountFulfilled"   "quarter1"          "quarter2"  "quarter3"  "quarter4"
  "nithin"              "xdfcdg"             "4567"                 "171"       "4500"                   "3000"                 "1500"            \N          \N
  "virendra"            "ghgf"              "20000"                 "172" "10000"                               \N       \N     \N       \N
  "virendra"            "ghfgh"            "30000"                  "173"   "15000"                             \N                       "15000"    \N  \N

this is sub query result and i want total sum of amountcommitted

A: create a view of above sub query then join that view with the above sub query we will get the result


text:
Q: Issue sending the information to my email from a contact us form I have a contact us form using a HTML file and a PHP file (sendeamil.php) that is compose by (header.html, footer.html and contentsendemail.php where is my code to send the information to my email.
I have my HTML file with the form:
<form name="htmlform" method="post" action="sendemail.php">

  First Name *

  <input  type="text" name="first_name" maxlength="50" size="30">

  Last Name *

  <input  type="text" name="last_name" maxlength="50" size="30">

  Email Address *

  <input  type="text" name="email" maxlength="80" size="30">

  Telephone Number

  <input  type="text" name="telephone" maxlength="30" size="30">

  Comments *

  <textarea  name="comments" maxlength="1000" cols="25" rows="6">     </textarea>

<input type="submit" value="Submit">   ( HTML Form )

</form>

Then I have my sendemail.php file which is compose by the Header, content and Footer:
<?php
include("templates/header.html");
$action = 'contentsendemail';
$disallowed_paths = array('header', 'footer');
if (!empty($_GET['action'])) {
$tmp_action = basename($_GET['action']);
if (!in_array($tmp_action, $disallowed_paths) && file_exists("templates/{$tmp_action}.php"))
    $action = $tmp_action;
}
include("templates/$action.php");
include("templates/footer.html");
?>

And the my contentsendemail.php file:
<?php
if(isset($_POST['email'])) {

// CHANGE THE TWO LINES BELOW
$email_to = "myemail@gmail.com";

$email_subject = "Subject Here";

function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.

";
    echo $error."

";
    echo "Please go back and fix these errors.

";
    die();
}

// validation expected data exists
if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['telephone']) ||
    !isset($_POST['comments'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required

 $error_message = "";
 $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
 $error_message .= 'The Email Address you entered does not appear to be valid.
';
  }

    $string_exp = "/^[A-Za-z .'-]+$/";
    if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.
';
  }

   if(!preg_match($string_exp,$last_name)) {
   $error_message .= 'The Last Name you entered does not appear to be valid.
';
 }

  if(strlen($comments) < 2) {
  $error_message .= 'The Comments you entered do not appear to be valid.
';
 }
  if(strlen($error_message) > 0) {
  died($error_message);
  }
  $email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";

$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

Thank you for contacting us.

<?php
}
die();
?>

I have 2 questions or issues:

*

*I'm not getting any email. Is anything I need to do in the server or somewhere to have the emails sent? why I'm not getting the emails?

*when I click submit in the contactus.php site and I get the message "Thank you for contacting us." in the sendemail.php I get both the header.html and contentsendemail.php included but not the footer.html.

A: I have two answers to your two issues which both reside in contentsendemail.php

*

*@mail() does not exist in core PHP (and I'm not even sure its a valid function name), you want mail().

*die(); kills the execution of the script at that point, and nothing else is parsed/returned after that line which is executed before the inclusion of the footer.


text:
Q: pointer to string literal char * ptr="coding";
Here ptr is a character pointer which is pointing to the first character of the string enclosed in " ", that is ptr is pointing to address of 'c'.

*

*In pointers-->  * Operator is used to getting the values that are stored on
the address pointed by the pointer variable.

So here
On accessing *ptr --> we get the value which is stored in the address pointed by ptr, as ptr is pointing to address of 'c', so on writing this code
 char * ptr="coding";
 cout<< *ptr;

we get the output: c
on accessing *++ptr --> ++ptr increments the location by 1 , so on accessing *++ptr, we get the value which is stored in next loaction.So on writing this code
char * ptr="coding";
     cout<< *++ptr;

we get the output: o
& operator is used for getting the address that is being pointed by pointer variable, here as ptr is pointing to 'c' so on writing this code :
 const char* str = "Hello";

 cout << &str ;

we get the output: 0x7fff11d19cb0
Now when we write code:
 char * ptr="coding";
         cout<< ptr;

We get the output: coding
How is it printing a whole string, as ptr is only pointing to the address of the first character 'c'.
Where does ptr pointing to?
As ptr is a character pointer.


text:
Q: Breeze manager.createEntity This key is already attached I have a SPA (hot towel template) and use window.localStore for keep data in browser. I used export/import from breeze 1.3.5, but later of use import entities function I need to create an other new entity and use again this line:
manager.createEntity('Project');

And the next error appears:
This key is already attached: Project:#Solution.Project.Models--1

The error only appears when I use import entities function to localStorage before call function createEntity.
Steps of test:

*

*Open browser, create entities

*Import entities to localStorage

*Close browser

*Open browser and load data from localStorage

*Create a new entity and here appears error This key is already attached: Project:#Solution.Project.Models--1
If I didn't close the browser all work fine, but the error appeared when I had closed the browser and opened again, load data from localStorage and create a new entity.
Please, help me with this error.

A: Maybe you have alredy create the entity Project. Try to search in all the solution "createEntity" and see if there's another entity called Project.

A: Not sure, but there was a bug in Breeze related to Export/Import that was just fixed in v 1.3.5.  Can you try that and let us know if that was the issue?

A: ddtere,
We were not able to reproduce the problem here.
Here's the snippet from our Hot Towel test solution:
return manager.executeQuery(query)
    .then(function (data) {
        var newPhysician0 = manager.createEntity('Physician');
        var bundle = manager.exportEntities();
        var em2 = new breeze.EntityManager({
            serviceName: manager.serviceName,
            metadataStore: manager.metadataStore
        });
        em2.importEntities(bundle);
        var newPhysician1 = manager.createEntity('Physician');
        var newPhysician2 = em2.createEntity('Physician');
        var newPhysician3 = manager.createEntity('Physician');
        var newPhysician4 = em2.createEntity('Physician');

        querySucceeded(data);
    })
    .fail(queryFailed);

Can you provide a solution reproducing the issue so we can investigate further? Please keep the solution to a minimum necessary to repro the problem.
Thanks.


text:
Q: Gson failing to parse Month correctly Json Data:
"created_at":"2013-07-24 21:43:52"

Code to parse:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-DD HH:mm:ss").create();
foo mfoo = gson.fromJson(Json, foo.class);

The resulting "created_at" field in the is January instead of July.   (2013-01-24 21:43:52)
What am I doing wrong?

A: DD is day in year. So ... you get Jan 24th.
Change it to dd


text:
Q: Regex to convert string number to currency I have a string filed which holding the dollar amount. What I want to do is process the string and covert in actual currency.
Example:
Possible incoming string;
80
1000.00
1000.0
-100

Desired Outputs are;
100.00
1,000.00
-100.00

How can I format the string with regex and covert it to the output I want?

A: It's not really clear what you mean by actual currency, but I'm assuming you just want a string that looks like the samples you've posted. Keep in mind that the decimal type (the type best suited to represent currency) doesn't have any actual formatting information.
You'll have to parse the string using decimal.Parse, then convert the value back to a string to get it into the desired format.
For example:
public string Format(string input)
{
    decimal value = decimal.Parse(input);

    return value.ToString("#,#.00");
}

// usage: Format("1000.0")

Example: https://dotnetfiddle.net/P7psPC
However if you're dealing with currency you can just use the C format specifier:
value.ToString("C");

This would output the following for your sample inputs:
$80.00
$1,000.00
$1,000.00
($100.00)

A: There isn't a real currency converter in Microsoft .Net Framework, so you have to work within the constraints provided, which is decimal.  The closest you can get to your decimal being defaulted to money would be:
decimal amount = 0.00m

The m at the end is declaring that this decimal will represent money.  Which when added will provide basic rounding as if it were money.
However the easiest approach would be how Andrew Whitaker did the conversion.  The only thing I would add, is that when you utilize:
value.ToString("#,##0.00"); // Output: 0.96
value.ToString("#,#.00");   // Output .96
value.ToString("0.##");     // Output 0.6

To clarify the conversion with ToString(); for the decimal.


text:
Q: scroll on ios in mobile version I have a scroll problem only on iOS in mobile version.
Sometimes I get stuck on the top of my page if I scroll fast.
If you test this page on iphone http://www.espace-piano.ch/ESPACE_PIANO_WEB/FR/cours.awp you will sometimes have the same problem as I have. The problem is often after the page refresh.
If I switch to "computer version" on safari on my iphone, I no longer have a problem.
Is it possible in javascript to force the browser to "computer version".
I already have this code to know if the user is on iphone..., I just miss the code to force in "computer version" on the browser.
let isIOS = /iPad|iPhone|iPod/.test(navigator.platform) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);


text:
Q: Multiple input split into groups So I have this form to add a Report, and my Report hasMany Measures. My problem is, I want to "split" the display of the Measures into groups (a Measure belongsTo a Group).
I have this:
//Controller/Report/add

$measures = $this->Report->Measure->find('list');

and this:
//View/Report/add.ctp

echo $this->Form->input('Measure', array('label' => false, 'multiple' => 'checkbox'));

This outputs:

    <input type="hidden" name="data[Measure][Measure]" value="" id="MeasureMeasure"/>

        <input type="checkbox" name="data[Measure][Measure][]" value="1" id="MeasureMeasure1" />

            ...

      ....

However I need something like:

Measure Group 1

        <input type="hidden" name="data[Measure][Measure]" value="" id="MeasureMeasure"/>

            <input type="checkbox" name="data[Measure][Measure][]" value="1" id="MeasureMeasure1" />

                ...

          ....

Measure Group 2

        <input type="hidden" name="data[Measure][Measure]" value="" id="MeasureMeasure"/>

            <input type="checkbox" name="data[Measure][Measure][]" value="1" id="MeasureMeasure1" />

                ...

          ....

What is the best way to achieve this?

A: It will take a bit of extra work to prepopulate the fields for editing when setting the request data to the view but you could do something like this:
echo $this->Form->input('Measure.Measure.group1', array('options'=>$options, 'label' => false, 'multiple' => 'checkbox'));
echo $this->Form->input('Measure.Measure.group2', array('options'=>$options, 'label' => false, 'multiple' => 'checkbox'));

Should give you something in your controller like this:
pr($this->data['Measure']['Measure']['group1']);

array(
   [0] => someval,
   [1] => some other val
)

A: Ok so I solved it, basically I did:
$this->loadModel('Measuregroup');
$this->Measuregroup->contain();
$measureGroups = $this->Measuregroup->find('all');
foreach ($measureGroups as $measureGroup) {
    $measures[$measureGroup['Measuregroup']['name']] =
        $this->Report->Measure->find('list',
            array('conditions' => array(
                'Measure.measuregroup_id' => $measureGroup['Measuregroup']['id'])));
}

And in the view just this:
echo $this->Form->input('Measure', array('label' => false, 'multiple' => 'checkbox'));


text:
Q: Comparing two hashmaps for equal values and same key sets? How can I best compare two HashMaps, if I want to find out if none of them contains different keys than the other, and if the values of that keys match each other.
Map<objA, objB> mapA = new HashMap<objA, objB>();
mapA.put("A", "1");
mapA.put("B", "2");

Map<objA, objB> mapB = new HashMap<objA, objB>();
mapB.put("D", "4");
mapB.put("A", "1");

When comparing A with B, it should fail due to different keys B and D.
How could I best compare non-sorted hashmaps?

A: Simply use :
mapA.equals(mapB);

Compares the specified object with this map for equality. Returns true
  if the given object is also a map and the two maps represent the same
  mappings

A: Make an equals check on the keySet() of both HashMaps.
NOTE:
If your Map contains String keys then it is no problem, but if your Map contains objA type keys then you need to make sure that your class objA implements equals().

A: /* JAVA 8 using streams*/
   public static void main(String args[])
    {
        Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        map.put(100, true);
        map.put(1011, false);
        map.put(1022, false);

        Map<Integer, Boolean> map1 = new HashMap<Integer, Boolean>();
        map1.put(100, false);
        map1.put(101, false);
        map1.put(102, false);

        boolean b = map.entrySet().stream().filter(value -> map1.entrySet().stream().anyMatch(value1 -> (value1.getKey() == value.getKey() && value1.getValue() == value.getValue()))).findAny().isPresent();
        System.out.println(b);
    }

A: Compare every key in mapB against the counterpart in mapA. Then check if there is any key in mapA not existing in mapB
public boolean mapsAreEqual(Map<String, String> mapA, Map<String, String> mapB) {

    try{
        for (String k : mapB.keySet())
        {
            if (!mapA.get(k).equals(mapB.get(k))) {
                return false;
            }
        }
        for (String y : mapA.keySet())
        {
            if (!mapB.containsKey(y)) {
                return false;
            }
        }
    } catch (NullPointerException np) {
        return false;
    }
    return true;
}

A: public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {

    if (map1 == null || map2 == null)
        return false;

    for (String ch1 : map1.keySet()) {
        if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
            return false;

    }
    for (String ch2 : map2.keySet()) {
        if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
            return false;

    }

    return true;
}

A: if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==
boolean b = map1.entrySet().stream().filter(value ->
            map2.entrySet().stream().anyMatch(value1 ->
            (value1.getKey().equals(value.getKey()) &&
  value1.getValue().equals(value.getValue())))).findAny().isPresent();

System.out.println("comparison  "+b);

A: A simple and good algorithm for such a comparison could be:
    Map<Integer, Boolean> map1 = new HashMap<Integer, Boolean>();
    map1.put(100, false);
    map1.put(101, false);
    map1.put(102, false);

    Map<Integer, Boolean> map2 = new HashMap<Integer, Boolean>();
    map2.put(100, false);
    map2.put(1011, false);
    map2.put(1022, false);

    if (!map1.keySet().equals(map2.keySet())) {
        result = false;
    } else {
        result = map1.keySet()
                .stream()
                .allMatch(key -> map1.get(key).equals(map2.get(key)));
    }

Simply you'll have to compare the set of keys, if they are equal, then compare the values for each key on both maps.


text:
Q: css form - radio button placement I am currently learning html/css and would like to develop my first web form. However, I am having issues placing my radio buttons next to the associated label.
Here is my jsfiddle
I assume I have to create a .radio style in my css. However, I am not certain what to do.
<form id="contactform" class="rounded" method="post" action="">

Equipment Procurement Form

Use this form to submit requests to Medical Physics for new equipment

        Directorate
        <input type="text" class="input" name="Directorate" id="Directorate" />

Enter your directorate.

        Department:
        <input type="text" class="input" name="Department" id="Department" />

Enter your department.

        Equipment Requested:
        <textarea class="input textarea" name="Request" id="Request"></textarea>

Summarise equipment request..

        <input id="Capital" type="radio" name="Capital" value="Capital">
            Capital
                >£5000 (inc VAT)
        <input id="Capital" type="radio" name="Capital" value="Revenue">
        Revenue
            <£5000 (inc VAT)

    <input type="submit" name="Submit" class="button" value="Submit" />
</form>

A: Refer this http://jsfiddle.net/3sPNH/13/ . I hope this is how you want. Just placed the input inside.

A: <form id="contactform" class="rounded" method="post" action="">

Equipment Procurement Form

Use this form to submit requests to Medical Physics for new equipment

    Directorate
    <input type="text" class="input" name="Directorate" id="Directorate" />

Enter your directorate.

    Department:
    <input type="text" class="input" name="Department" id="Department" />

Enter your department.

    Equipment Requested:
    <textarea class="input textarea" name="Request" id="Request"></textarea>

Summarise equipment request..

    <input id="Capital" type="radio" name="Capital" value="Capital">
        Capital
            >£5000 (inc VAT)

        <input id="Capital" type="radio" name="Capital" value="Revenue">
        Revenue
        <£5000 (inc VAT)

<input type="submit" name="Submit" class="button" value="Submit" />

A: You put the radio buttons outside of the label, it will hold them together if you put them in.

        Capital
        <input id="Capital" type="radio" name="Capital" value="Capital">
        >£5000 (inc VAT)

         Revenue
         <input id="Capital" type="radio" name="Capital" value="Revenue">
         <£5000 (inc VAT)


text:
Q: OpenCart 3 + Journal 3, remove email field from guest checkout? I want to remove email field from checkout page for guest, I use OpenCart 3 with theme Journal 3. So what I can do?
I've tried to call out it from guest.php but still not work.

A: You can't just remove email field. A lot of system properties connected to email on checkout, although using journal3 makes more complicated extraction of email.
You can see what fields you can turn on / switch of in Journal Quick Checkout:
Journal > Skins > Checkout

UPDATED
To disable Email only for guests in Journal 3 Quick Checkout:
Go to /catalog/view/theme/journal3/template/journal3/checkout/register.twig
Find
{# customer email #}

  {{ entry_email }}
  <input v-model="order_data.email" type="text" name="email" value="" placeholder="{{ entry_email }}" id="input-email" class="form-control"/>

Adding a check, like for password v-if="account === 'register'". New code is
{# customer email #}

  {{ entry_email }}
  <input v-model="order_data.email" type="text" name="email" value="" placeholder="{{ entry_email }}" id="input-email" class="form-control"/>

Now go to /catalog/controller/journal3/checkout.php and find
    // email
    if ((utf8_strlen(Arr::get($this->request->post, 'order_data.email')) > 96) || !filter_var(Arr::get($this->request->post, 'order_data.email'), FILTER_VALIDATE_EMAIL)) {
        $error['email'] = $this->language->get('error_email');
    } else if (($this->session->data['account'] === 'register') && $this->model_account_customer->getTotalCustomersByEmail(Arr::get($this->request->post, 'order_data.email'))) {
        $error['email'] = $this->language->get('error_exists');
    }

Replace with
    // email
    if ($this->session->data['account'] === 'register') {
        if ((utf8_strlen(Arr::get($this->request->post, 'order_data.email')) > 96) || !filter_var(Arr::get($this->request->post, 'order_data.email'), FILTER_VALIDATE_EMAIL)) {
            $error['email'] = $this->language->get('error_email');
        } else if (($this->session->data['account'] === 'register') && $this->model_account_customer->getTotalCustomersByEmail(Arr::get($this->request->post, 'order_data.email'))) {
            $error['email'] = $this->language->get('error_exists');
        }
    }

A: Additional to the emntioned 3 steps you have to fix the sendmail funtion. One way is mentioned here in 2 more steps:
File: system/library/mail.php
Change:
$this->to = $to;

To:
 if ($to != '') {$this->to = $to;} else { $this->to = 'web-and-seo@itech.bg';}

Change web-and-seo@itech.bg to an e-mail that you will receive the confirmation instead of the customer.

*Then remove the * from the mail field on checkout page

File: catalog/view/theme/journal3/template/journal3/checkout/register.twig
Change:

To:

Good luck.


text:
Q: Hide UISlider track when behind transparent thumb image I'm currently creating a custom UISlider in Xcode. I am setting the thumb Image, min Image, and max Image for the slider. Everything works great. The design calls for the thumb image to be transparent to the background of the view. This is where my problem comes in, you can see the two sides of the slider coming together in the middle of the thumb image. I don't want it to look like this. I want the slider bars to stop a the edge of the thumb image. Any ideas as to how I can accomplish this? Any and all suggestions are welcome. Thanks.
This is the Code I'm using so far.
UIImage *thumbImage = [UIImage imageNamed:@"thumb.png"];
UIImage *minImage = [UIImage imageNamed:@"min.png"];
UIImage *maxImage = [UIImage imageNamed:@"max.png"];

minImage = [minImage resizableImageWithCapInsets:UIEdgeInsetsMake(0,0,0,0)];
maxImage = [maxImage resizableImageWithCapInsets:UIEdgeInsetsMake(0,0,0,0)];

[_slider setMinimumTrackImage:minImage forState:UIControlStateNormal];
[_slider setMaximumTrackImage:maxImage forState:UIControlStateNormal];
[_slider setThumbImage:thumbImageforState:UIControlStateNormal];

I can't Post an image because I don't have enough reputation. I'll try to explain a little better. I have a Thumb Image that is a circle. The center of the circle is transparent and you can see right to the background image of my view. The track for the slider continues all the way to the center of the circle. I'd prefer if the track stopped at the outline of the circle. I hope that makes more sense.

A: I have not received any suggestions as to how to hide the slider track when it is behind the thumb image so I am posting my solution incase someone else has this problem. If anyone has a better way of doing this please let me know.
In order to have a transparent thumb image and not have the track connect in the center of it I had to set the slider track images to blank images and setup my own slider track image that is just going to be resized every time the value of the slider changes. Not only will I be changing the width of the custom slider track but I also will have to update the X position of the image every time I resize it so that it will connect with the end image of my slider track.
In my case I have a slider that is set to 0 and its Max is set to the Width of the slider. My custom slider track is only going to appear on the right side of the thumb image. So as you slide the thumb image to the right the bar shrinks and the left side is clear.
First I setup my Slider Thumb Image and Set the Slider Track to Blank Images.
- (void)viewDidLoad {
[super viewDidLoad];

UIImage *thumbImage =[UIImage imageNamed:@"answerSlider.png"];

[_slider setMinimumTrackImage:[UIImage new] forState:UIControlStateNormal];
[_slider setMaximumTrackImage:[UIImage new] forState:UIControlStateNormal];
[_slider setThumbImage:thumbImage forState:UIControlStateNormal];

thumbImage = nil;

_slider.value = 0;
}

In the ViewWillApear I have a call to setup my custom SLider track that I will create.
- (void)viewDidAppear:(BOOL)animated{
[self updateSlideBarLength];
}

Inside updateSLideBarLength I Use the value of the slider to help determine the width of my slider track Image.
- (void)updateSlideBarLength{
// Get Position Of Slider
CGFloat sliderValue = _slider.value;
CGFloat thumbImageWidth = 58; // this is the width of my thumb image
CGFloat sliderControlWidth = 288.0f; // This is a constant number in my case
CGFloat sliderWidth = sliderControlWidth - thumbImageWidth - sliderValue;

CGFloat sliderBarHeight = 2.0f;

// Reset Width Of aFrame
CGFloat sliderEndY = _sliderEnd.frame.origin.y;
CGFloat sliderEndX = _sliderEnd.frame.origin.x;

CGFloat sliderBarY = sliderEndY + (_sliderEnd.frame.size.height / 2 - 1);
CGFloat sliderBarX = sliderEndX - sliderWidth + (_sliderEnd.frame.size.width/2);

CGRect aframe = CGRectMake(sliderBarX, sliderBarY, sliderWidth, sliderBarHeight);

if (_sliderBar == nil) {
    NSLog(@"Slider Bar Doesnt Exist");
    _sliderBar = [[UIImageView alloc] initWithFrame:aframe];
    _sliderBar.image = [UIImage imageNamed:@"sliderBar.png"];
    [self.view addSubview:_sliderBar];
    [self.view bringSubviewToFront:_sliderBar];
}

_sliderBar.frame = aframe;
}

Lastly I make sure the updateSliderBarLength is called every time the slider value changes.
- (IBAction)sliderMoved:(id)sender {
    [self updateSlideBarLength];
}

This works although I had to adjust the Max value of my slider so that the custom slider track image I created always lines up with the edge of the thumb Image. While sliding the thumb image as the value increased the more the slider track started to infringe on my thumb image. By increasing the slider value I was able to stop this from happening. Again, I'm not convinced this is the best way to do this but it works for me. Later when I have more Rep and can post Pictures I will edit this post to help everyone visualize what I am describing.

A: I did something similar to Sean Marraffa, although I found it easier to subclass UISlider and update the frames of my image views in thumbRectForBounds:trackRect:value using something like this:
var trackHeight: CGFloat = 2

override func thumbRectForBounds(bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect
{
    let superValue = super.thumbRectForBounds(bounds, trackRect: rect, value: value)
    let originY = (bounds.height-trackHeight)/2.0
    minTrackImageView?.frame = CGRectMake(0, originY, superValue.minX, trackHeight)
    maxTrackImageView?.frame = CGRectMake(superValue.maxX, originY, bounds.width-superValue.maxX, trackHeight)
    return superValue
}

minTrackImageView and maxTrackImageView are image views I set up in viewDidLoad.


text:
Q: 20.04 nvidia-driver-470 Failed to load module "nvidia" (module does not exist, 0) After a recent system upgrade Xorg can no longer load the nvidia module.
At first I went to
https://help.ubuntu.com/community/BinaryDriverHowto/Nvidia
ran the
sudo ubuntu-drivers devices

and followed the process of purging the existing drivers and installing the recommended drivers (for me, 470).
After a big long run and reboot, same thing.
tried,
sudo update-initramfs -u

and a reboot, and still no go.
I don't know where X is looking for the driver, or why this process does not appear to be installing the X driver, but I don't know what more to do.

A: It appears the Ubuntu packages don't install the xorg drivers in a place where X will find them. By having
Section "Files"
    ModulePath "/usr/lib/x86_64-linux-gnu/nvidia/xorg/"
    ModulePath "/usr/lib/xorg/modules"
EndSection

in /etc/X11/xorg.conf X is able to find the drivers and load properly.
It's frustrating that the Ubuntu packages are built in a way that this manual intervention is required.


text:
Q: Prevent Firefox from downloading endless JNLP files? Every time I click a Java Webstart button, Firefox downloads the JNLP file and puts it in my Downloads folder. I have over 500 JNLP files from my JWS app called name-123.jnlp and so on. Internet Explorer doesn't do this, is there a way to stop Firefox from doing it ? I'm the app's developer, so server side changes are possible too.
Additional info: I set the mime type correctly on the server.

A: You can try following

*

*In your Firefox browser, go to Edit >> Preferences >> Applications, in Content Type select the option "use other" for jnlp files
2.In the dialog box, select the "javaws" file location (for me, it was located in "/usr/java/jre1.6.0_16/bin")

I have it working on Ubuntu


text:
Q: How is $C(n,r) = C(n-1, r-1) + C(n-1,r)$ How is  $C(n,r) = C(n-1, r-1) +  C(n-1,r)?$ I am watching P & C video from here
I have read that suppose we have n distinct inputs. We have two possibilities:
1) Can select
2) Not select
If I select one from n then I am left with $C(n-1, r-1)$ and if I don't select I am left with $C(n-1, r)$.
I don't understand this $C(n-1, r)$ part. If I don't select how did the total elements turn $n-1$ shouldn't they still remain $n$. Any mathematical proof to prove the equality or understand it better?

A: Here are two proofs of Pascal's Identity.
Algebraic Method:
\begin{align*}
\binom{n - 1}{r - 1} + \binom{n - 1}{r} & = \frac{(n - 1)!}{(r - 1)![n - 1 - (r - 1)]!} + \frac{(n - 1)!}{r!(n - 1 - r)!}\\
& = \frac{(n - 1)!}{(r - 1)!(n - r)!} + \frac{(n - 1)!}{r!(n - r - 1)!}\\
& = \frac{(n - 1)!r}{(r - 1)!(n - r)!r} + \frac{(n - 1)!(n - r)}{r!(n - r - 1)!(n - r)}\\
& = \frac{(n - 1)!r}{r!(n - r)!} + \frac{(n - 1)!(n - r)}{r!(n - r)!}\\
& = \frac{(n - 1)!(r + n - r)}{r!(n - r)!}\\
& = \frac{(n - 1)!n}{r!(n - r)!}\\
& = \frac{n!}{r!(n - r)!}\\
& = \binom{n}{r}
\end{align*}
Combinatorial Method:  A subset of $r$ elements can be selected from a set of $n$ elements in $$\binom{n}{r}$$ ways.  Suppose we wish to select $r$ elements from the set $\{x_1, x_2, \ldots, x_{n - 1}, x_n\}$.  There are two possibilities.  The subset either contains the element $x_n$, or it does not.  If $x_n$ is one of the $r$ elements in the subset, we must select $x_n$ and $r - 1$ elements from the subset $\{x_1, x_2, \ldots, x_{n - 1}\}$, which can be done in $$\binom{1}{1}\binom{n - 1}{r - 1} = \binom{n - 1}{r - 1}$$ ways.  If $x_n$ is not one of the $r$ elements in the subset, we must select $r$ elements from the subset $\{x_1, x_2, \ldots, x_{n - 1}\}$, which can be done in $$\binom{n - 1}{r}$$ ways.  Hence, the number of ways of selecting $r$ elements from a set with $n$ elements is
$$\binom{n}{r} = \binom{n - 1}{r - 1} + \binom{n - 1}{r}$$


text:
Q: How to deploy clustered Kubernetes including an application (ex. nginx) using azure arm template I can create kubernetes cluster on azure using arm template but can not include my application on kubernetes or any other application in the same arm template.
Any idea is that possible or any equivalent solution to delpoying kubernetes clustered containing my application on azure

A: no, this is not possible without hacks, really. you could try and get enrolled into the Azure Terraform Resource Provider Private Preview, but I dont think this is getting anywhere, as its been over a year with no news on this.
And the hacks would be to create an Azure Container Instance and instruct it to talk to the cluster and deploy whatever you need to deploy or doing the same using an Azure Function.


text:
Q: How to detect if the scroll bar reached the end using JavaScript I'm trying to implement a feature in a terms and conditions page where the Agree button will be disabled until the user scrolls over all the conditions till the end. So, I tried to follow an existing example (http://jsfiddle.net/dy8bqzkm/) and change what best fits into my scenario, but I keep facing issues and errors. Any idea on how to implement this feature correctly?
Error message:

HTML code:

        <button type="submit" class="agree w-button" id="AgreeBtn" disabled>I Agree</button>
        <button type="submit" class="cancel w-button" id="CancelBtn">Cancel</button>

JavaSript code:

A: Remove the first select array in your selection elements, and rename "getElementById", change to:
document.getElementById("PolicySection").addEventListener("scroll", checkScrollHeight,
false);

function checkScrollHeight() {
    var policyElement = document.getElementById("PolicySection")
    if ((policyElement.scrollTop + policyElement.offsetHeight) >= policyElement.scrollHeight)
    {
        document.getElementById("AgreeBtn").disabled = false;
    }
}

Suggestion refactor:

const licenseField = document.getElementById("licenseField");

licenseField.onscroll = () => this.checkScrollHeight();

checkScrollHeight = () => {
  const agreeButton = document.getElementById("AgreeBtn");
  const shouldEnableAgreeButton = !((licenseField.scrollTop + licenseField.offsetHeight) >= licenseField.scrollHeight);

  agreeButton.disabled = shouldEnableAgreeButton;
}

License Agreement:

    <textarea id="licenseField" name="licenseAgreement" rows="10" cols="45">This is my long, long license agreement where you agree to all of my demands.

    This is my long, long license agreement where you agree to all of my demands.

    This is my long, long license agreement where you agree to all of my demands.

    This is my long, long license agreement where you agree to all of my demands.

    This is my long, long license agreement where you agree to all of my demands.

    This is my long, long license agreement where you agree to all of my demands.

    This is my long, long license agreement where you agree to all of my demands.

    This is my long, long license agreement where you agree to all of my demands.

    This is my long, long license agreement where you agree to all of my demands.

</textarea>

    <button type="submit" class="agree w-button" id="AgreeBtn" disabled>I Agree</button>
    <button type="submit" class="cancel w-button" id="CancelBtn">Cancel</button>


text:
Q: Ada Program Hangs on Exception, gnatmake I'm having an issue with an ADA program hanging on exception. Below is a test program that I am compiling with
$ gnatmake divide_by_zero.adb
gcc -c divide_by_zero.adb
divide_by_zero.adb:6:19: warning: division by zero
divide_by_zero.adb:6:19: warning: "Constraint_Error" will be raised at run time
gnatbind -x divide_by_zero.ali
gnatlink divide_by_zero.ali

My version of gnatmake is
$ gnatmake --version
GNATMAKE 4.8.3

The contents of divide_by_zero.adb are
$ cat divide_by_zero.adb
procedure divide_by_zero is
   result : Integer;
   denominator : Integer;
   begin
      denominator := 0;
      result := 1 / denominator;
   end divide_by_zero;

The output of program execution is
$ ./divide_by_zero.exe

raised CONSTRAINT_ERROR : divide_by_zero.adb:6 divide by zero
** Program hangs, Ctrl-C does nothing, Ctrl-D does nothing
** I have to go to Task Manager to stop divide_by_zero.exe

I was wondering whether anyone else had an issue with an ADA program compiled under gnatmake version 4.8.3 hanging on any type of exception? Is there something wrong with my ADA code? Is there something wrong with my install? I'm running the code on cygwin, currently.
Thanks.

A: Looks fine and works fine (i.e. raises exception and exits :-) in Debian 8, gcc4.9.1.
brian@Gannet:~/Ada/Play$ gnatmake divide_by_zero.adb
gcc-4.9 -c divide_by_zero.adb
divide_by_zero.adb:6:19: warning: division by zero
divide_by_zero.adb:6:19: warning: "Constraint_Error" will be raised at run time
gnatbind -x divide_by_zero.ali
gnatlink divide_by_zero.ali
brian@Gannet:~/Ada/Play$ ./divide_by_zero

raised CONSTRAINT_ERROR : divide_by_zero.adb:6 divide by zero
brian@Gannet:~/Ada/Play$

So I believe the Cygwin installation is broken.
It may be worth having the Gnat-2014 Libre edition for testing, though I'm presuming the FSF compiler is your preference because of license conditions.
Alternatively there are at least 2 ways of getting a working FSF Gnat compiler targetting Windows.
I have successfully built Windows commandline applications on Debian simply by installing the gnat-mingw-w64-x86-64 and running e.g.  x86_64-w64-mingw32-gnatmake divide_by_zero.adb (oddly enough it builds a 32-bin Windows exe, but the package runs on a 64-bit host and the executable runs fine if I reboot to Windows).
I've also heard good things about the TDM build of the FSF Gnat/GCC mingw compiler available here There are choices available according to whether you need to build for 32 or 64 bit Windows executables. I think you need to download both the "Ada support" package (scroll down!) and the base compiler.
If you really need cygwin, you may have to continue digging, or report this failure to the cygwin community and (politely!) push for an answer. If you do so, please update the question here.


text:
Q: NGINX redirect HTTPS to HTTPS How can I redirect https from one domain to https of another?
Case description:
I own three domains that is directed to the same ip/website in the NS server:

*

*example1.com

*example2.com

*example3.com

I paid only for one SSL licence that initially was issued for the first domain, so when I bought the second domain, I redirected all traffic to https://example1.com
Lately, I wanted to redirect all calls to a new domain: https://example3.com. I reissued the old SSL licence for the new domain and installed it successfully. The last part is redirecting all traffic to the new domain.
Now, all traffic from http is redirect well, but https (https://example1.com and https://example2.com) is not directed at all, and results in working "Not secure" page.
When I try to listen to 443 SSL and redirect if from 1&2 name servers to the third one and run service nginx restart, I get:
Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.

When I run systemctl status nginx.service, I get:
nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sun 2020-05-24 17:53:24 UTC; 4min 5s ago
  Process: 14068 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 13952 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 14073 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)
 Main PID: 13957 (code=exited, status=0/SUCCESS)

My guess I'm doing something wrong and redirecting 443 SSL twice is not allowed.
Code
This is my conf that is working without redirecting https example1.com and example2.com:
On /etc/nginx/nginx.conf I have include /etc/nginx/sites-enabled/*;.
On /etc/nginx/sites-enabled/example3.com.conf I wrote this:
server {
    listen 80;
    server_name example3.com wwww.example3.com example1.com www.example1.com example2.com www.example2.com;
    rewrite ^/(.*) https://example3.com/$1 permanent;
}

server {
    listen 443 ssl;
    server_name example3.com;
    ssl_certificate /etc/ssl/certs/ssl-bundle.crt;
    ssl_certificate_key /etc/ssl/websitessl/example3.com.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    root /var/www/html;
    index index.php index.html index.htm index.nginx-debian.html;
}

This is maybe duplication of this:
HTTPS to HTTPS redirect Nginx
But I failed to make it work.

A: Thank's to @RichardSmith, I learned that in order to redirect HTTPS to HTTPS without "Page not secure" warning, you should put the ssl_ statements out of the server blocks so all the domains will be included.
ssl_certificate /etc/ssl/certs/ssl-bundle.crt;
ssl_certificate_key /etc/ssl/websitessl/example3.com.key;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

server {
        listen  80 default_server;
        listen  443 ssl default_server;
        return  301 https://example3.com$request_uri;
}

server {
    listen 443 ssl;
    server_name example3.com;

    root /var/www/html;
    index index.php index.html index.htm index.nginx-debian.html;
}


text:
Q: Traversing javascript promises tree I am new to javascript promises and tried to solve the subsequent problem:
There is a tree with nodes that have a structure like this
node: {id, children:node[]}

one node is received by calling
getNode(id)

where getNode returns a javascript promise
so I get one node object by
getNode(id).then(function(node) {
   id = node.id;
   children = node.children;

})
Now I want to get the whole tree in one object like
treeObject = getTree(rootNodeId)

so that in the end contents of treeObjects should be for example
 {1,children:
         [{2,children
              [{5,null},{6,null},{7,null]},
           {3,children[{8,null},{9,null]}...

???
thanks for any answers!

A: async function getTree ( id ){
  const node = await getNode(id);
  node.children = await Promise.all( node.children.map(getTree));
  return node;
}

or without async await:
 function getTree ( id ){
  return getNode(id).then(function(node){
   return Promise.all( node.children.map(getTree)).then(function(children){
      node.children = children;
      return node;
   });
 });
}

assuming that children is a list of ids


text:
Q: UIScrollView contentSize Issue Within my view I create a scrollview with a width of 320 and a height of 70.
Responding to the user touching a button, I expand the scrollview, so it is 380(h) x 320(w) in size.
The code for this is shown below:
CGRect scrollviewFrame = CGRectMake(0, 30, 320, 380);
[scrollView setFrame:scrollviewFrame];
[self layoutScrollImages:YES];
CGSize srect =  CGSizeMake([scrollView bounds].size.width, (kNumImages * kScrollObjHeight));
[scrollView setContentSize:srect];

As I debug this project, I can see that srect is 320 (w) x 8000 (h) in size; however my issue is the scrollable area (where the user can actually touch to scroll the scrollview) remains the same as when it was it's original size.
I'm obviously missing something, does anyone know what it is?
Edit: I have created a sample project to illustrate the issue I am having, it is available here: http://dl.dropbox.com/u/9930498/ScrollViewTest.zip

A: I think , you have issue with your below line of code.
CGSize srect =  CGSizeMake([scrollView bounds].size.width, (kNumImages * kScrollObjHeight));
   [scrollView setContentSize:srect];

debug your program and see the content of srect , Also let us know the value of below two constant
kNumImages,kScrollObjHeight .

A: You need to change the contentSize of the scrollview as well as the frame.
Maybe this will help aswell: UIScrollView Class Reference
Do this when setting the new size
scrollView.scrollEnabled = YES;
scrollView.showsHorizontalScrollIndicator = YES;
scrollView.showsVerticalScrollIndicator = YES;
[scrollView setFrame:CGRectMake(0, 30, 320, 380)];
CGSize srect =  CGSizeMake([scrollView bounds].size.width, (kNumImages * kScrollObjHeight));
[scrollView setContentSize:srect];
[self layoutScrollImages:YES];


text:
Q: Zip File getting corrupted when i save it to isolated storage I have downloaded a zip file from blob storage and save it to isolated storage of windows phone like this :- FileStream fs is downloaded from blob.
public static void SaveToIsolatedStorage(FileStream fs, string fileName)
        {
            var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            using (var streamWriter =
                            new StreamWriter(new IsolatedStorageFileStream(fileName,
                                FileMode.Create,
                                FileAccess.ReadWrite,
                                isolatedStorage)))
            {
                streamWriter.Write(fs);
            }
        }

But when checked this zip file using IsoStoreSpy it is showing corrupted. I have checked it by reading from isolated storage and tried to unzip it but not working. I am sure that it is corrupted because when i replace this file using IsoStoreSpy with some other zip and then tried to unzip it then it is working.
Edit:-
Code for downloading from Blob
private async Task DownloadFileFromBlobStorage()
    {
        var filename = "AppId_2.zip";
        var blobContainer = GetBlobClient.GetContainerReference("testwpclientiapcontainer");
        var blob = blobContainer.GetBlockBlobReference(filename);

        using (var filestream = new FileStream(filename, FileMode.Create))
        {
            await blob.DownloadToStreamAsync(filestream);

            SaveToIsolatedStorage(filestream, filename);
        }
    }

So anybody know how can i save the zip file to isolated storage without getting it corrupted ?

A: You're using a StreamWriter. That's for text. You shouldn't be using it to copy a zip file at all. Never use any TextWriter for binary data.
Next you're using StreamWriter.Write(object), which is basically going to call ToString on the FileStream. That's not going to work either.
You should just create an IsolatedStorageStream, and then call fs.CopyTo(output).
public static void SaveToIsolatedStorage(Stream input, string fileName)
{
    using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        // Simpler than calling the IsolatedStorageFileStream constructor...
        using (var output = storage.CreateFile(fileName))
        {
            input.CopyTo(output);
        }
    }
}

In your edit you've shown code which saves to a FileStream first, and then copies the stream from the current position. As you've noted in comments, you needed to rewind it first.
Personally I wouldn't use a FileStream at all here - why do you want to save it as a normal file and an isolated file? Just use a MemoryStream:
using (var stream = new MemoryStream())
{
    await blob.DownloadToStreamAsync(filestream);
    stream.Position = 0;
    SaveToIsolatedStorage(stream, filename);
}

(Note that your SaveToIsolatedStorage method is still synchronous... you may wish to consider an asynchronous version.)


text:
Q: How to load large amount of data from MySQL and save as text file? I'm fetching large amount of data from MySql Database using LIMIT and OFFSET like:
var offset = 0
for (s <- a to partition) {

  val query = "(select * from destination LIMIT 100000 OFFSET " + offset + ") as src"
  data = data.union(spark.read.jdbc(url, query, connectionProperties).rdd.map(_.mkString(","))).persist(StorageLevel.DISK_ONLY)
  offset += 100000
}
val dest = data.collect.toArray
val s = spark.sparkContext.parallelize(dest, 1).persist(StorageLevel.DISK_ONLY).saveAsTextFile("/home/hduser/Desktop/testing")

For small amount of data its working fine whereas for large amount of data it throws error like java.lang.OutOfMemoryError: Java heap space so if i can persist val dest = data.collect.toArray it will work as expected, sorry for such a naive question i'm new to spark.
Partition method:
val query = "(select * from destination) as dest"
val options = Map(
"url" -> "jdbc:mysql://192.168.175.35:3306/sample?useSSL=false",
"dbtable" -> query,
"user" -> "root",
"password" -> "root")

val destination = spark.read.options(options).jdbc(options("url"), options("dbtable"), "0", 1, 5, 4, new java.util.Properties()).rdd.map(_.mkString(","))
.persist(StorageLevel.DISK_ONLY).saveAsTextFile("/home/hduser/Desktop/testing")

Thank you

A:
I'm fetching large amount of data

That's why you use Spark, isn't it? :)
 for (s <- a to partition)
 val dest = data.collect.toArray
 spark.sparkContext.parallelize(dest, 1)

NOTE : Don't do that. I'd even call it a Spark anti-pattern where you load a
  dataset on executors (from MySQL using JDBC) only to transfer this
  "large amount of data" to the driver that in turn will transfer it
  back to the executors to save it to disk.

It's as if you wanted to get rid of Spark doing these network round trips.
spark.read.jdbc supports partitioning your dataset at load time out of the box using partitionColumn, lowerBound, upperBound options (see JDBC To Other Databases) or (undocumented) predicates option.

partitionColumn, lowerBound, upperBound describe how to partition the table when reading in parallel from multiple workers. partitionColumn must be a numeric column from the table in question. Notice that lowerBound and upperBound are just used to decide the partition stride, not for filtering the rows in table. So all rows in the table will be partitioned and returned. This option applies only to reading.

Let Spark do its job(s).


text:
Q: "Security restrictions" when linking to external stylesheet from SVG (when embedded as an image) According to this answer "for security reasons images must be standalone files". That is, when including a SVG file using an img tag it cannot reference any external stylesheets.
I think I've run into the same issue when trying to include SVGs as background images using CSS. The SVGs link to other SVG files and display fine when viewing them in Firefox directly, but fail to show the linked content when included as a CSS background image.
What are these 'security reasons' and where can I find out more information about them?

A: Consider a hypothetical forum that allows SVG images as avatars. If external resources were allowed a trickster/malicious user could upload an SVG file that contains
 <image xlink:href="http://evilhacker.com/myimage.png">
and (assuming they control evilhacker.com), they could do any & all of the following:

*

*receive a ping at their own domain whenever anyone views their
profile (& log the ip address of the person viewing it)

*potentially serve different-looking avatar to different people based
their IP address, request-headers, etc.

*potentially change the appearance of their avatar at-will (i.e. wait
for forum-admins to approve it thumbs-up, and then change it to be
NSFW)

See this Mozilla bug and the SVG integration specification for more details.


text:
Q: Running a powershell script at startup I am writing a script to remove a computer from the domain, rename it, then add it back. It works fine when I set the trigger to AtLogOn but when I switch to AtStartUp I run into some issues.
I get this error when it restarts to run the first scheduled task:
0x8007051F: There are currently no logon servers available to service the logon request.
I suspect the script tries to run with no network connection set up so I tested using the RandomDelay parameter, and it worked like its suppose to.
I cant rely on a random delay so I am looking for an alternative. Is there a way to test the network status before the script begins or a way to delay the script a specific amount of time? I am using Register-ScheduledJob provided by Powershell 3.0
Thanks in advance

A: You can probably use Test-Connection cmdlet to ping a domain controller.  Loop until a  positive response is received.

A: Start-Sleep with a if Test-connection = $true against DC


text:
Q: Split a string and capture all instances in python regex Newbie here, I have been trying to learn regex for some time but sometimes I feel I can't  understand how regex is handling strings. Because in planning phase I seem to work it out, but in implementation it doesn't work as I expect it.
Here is my little problem: I have strings that contains one or more names (team names). The problem is that if the string contains more than one, there is no separator. All names are joint directly.
Some examples :
------------String -----------------Contains----------Names to be extracted

*

*'RangersIslandersDevils' --> 3 names ->>> [Rangers, Islanders, Devils]

*'49ersRaiders' -------------> 2 names ->>> [49ers, Raiders]

*'Avalanche'----------------> 1 name  ->>> [Avalanche]

*'Red Wings'---------------> 1 name  ->>> [Red Wings]

I want to capture each name in each string and use them in a loop later on. But I can't seem to implement the pattern I imagine for it.
The pattern implementation in my head for the strings are like this:

*

*Start scanning the text which is expected to start with a capital
letter or number

*If you see a literal 's' followed by a capital letter (like ...s[A-Z]..) capture the text until "s" (including s)

*Repeat step two until you no more see (....s[A-Z]..) pattern. And capture the rest of the string as the last name.

*Optionally, Write all names in a list

Well I tried in vain some code in which the step two captures only one instance and step 3 normally gives another.
re.findall('([A-Z0-9].*s)*([A-Z].*)+', 'RangersIslandersMolsDevil')

That returns only two names:

[('RangersIslandersMols', 'Devil')]

whereas I want four:

[Rangers, Islanders, Mols, Devil]

A: ([A-Z0-9].*s)* will capture as many of any character as it can, so that's causing 'RangersIslandersMols' to get stuck together as one match.
It sounds like the boundary between team names is defined as a lowercase letter (not necessarily an 's', as in 'Avalanche') followed immediately by an uppercase letter or number, so our pattern should look for:

*

*uppercase letters or numbers, followed by

*lowercase letters

Because a team name can have multiple words, we'll also look for a space followed by the same pattern as above, for any possible number of words.
Try this pattern:
>>> pattern = r'[A-Z0-9]+[a-z]+(?: [A-Z0-9]+[a-z]+)*'
>>> findall(pattern, "RangersIslandersDevils49ersWashginton Football TeamAvalancheWarriors")
['Rangers', 'Islanders', 'Devils', '49ers', 'Washginton Football Team', 'Avalanche', 'Warriors']


text:
Q: git clone error. Read from socket failed: Connection reset by peer fatal: Could not read from remote repository While try to clone project from Mooveb getting below error.

$ git clone moov@git.moovweb.com:skoteeswaran/ving-test.git

Cloning into 'ving-test'...
Read from socket failed: Connection reset by peer fatal: Could not
  read from remote repository.
Please make sure you have the correct access rights and the repository
  exists.

A: You at least need to check that ssh moov@git.moovweb.com (and if not, check the output of ssh -Tvvv moov@git.moovweb.com)
The issue could be:

*

*client-side (port 22 blocked) or

*server-side

*

*(name or repo name incorrectly written, or with wrong case)

*error on the sshd (daemon) side


text:
Q: How do you create a 12hour time in JavaScript I would like to have a timer where it does something after 12 hours. I would like to begin at 6am and end at 6pm. The time only needs to be for 12 hours. I would like to know how I can adjust the time. What I would like to do is convert my current 12-hour clock into 24 hours.
I'm looking for working examples
The code example is in this CodePen link
Timer Link
    (function () {
      const second = 1000,
            minute = second * 60,
            hour = minute * 60,
            day = hour * 24;

      let birthday = "Nov 25, 2020 00:00:00",
          countDown = new Date(birthday).getTime(),
          x = setInterval(function() {

            let now = new Date().getTime(),
                distance = countDown - now;

            document.getElementById("days").innerText = Math.floor(distance / (day)),
              document.getElementById("hours").innerText = Math.floor((distance % (day)) / (hour)),
              document.getElementById("minutes").innerText = Math.floor((distance % (hour)) / (minute)),
              document.getElementById("seconds").innerText = Math.floor((distance % (minute)) / second);

            //do something later when date is reached
            if (distance < 0) {
              let headline = document.getElementById("headline"),
                  countdown = document.getElementById("countdown"),
                  content = document.getElementById("content");

              headline.innerText = "It's my birthday!";
              countdown.style.display = "none";
              content.style.display = "block";

              clearInterval(x);
            }
            //seconds
          }, 0)
      }());

A: This should work, it will show the time until 8:00 PM when its 8:00 AM. Here's the pen I made to test it Time Until.

var doIt = false;
var now = new Date();
var seconds;
var date1;
var eight = new Date();
eight.setHours(20, 0, 0);
var date2;
var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)
    var hours   = Math.floor(sec_num / 3600)
    var minutes = Math.floor(sec_num / 60) % 60
    var seconds = sec_num % 60

    return [hours,minutes,seconds]
        .map(v => v < 10 ? "0" + v : v)
        .filter((v,i) => v !== "00" || i > 0)
        .join(":")
}
function diff_seconds(dt2, dt1)
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  return Math.abs(Math.round(diff));

 }
window.setInterval(function(){
    date2 = new Date();
    if(date2.getHours() >= 8) {
        doIt = true;
    }
}, 1);
window.setInterval(function(){
    date2 = new Date();
    if(date2.getHours() >= 20){
        doIt = false;
    }
}, 1);
window.setInterval(function(){
  if(doIt === true){
    seconds = diff_seconds(new Date(), eight);
    document.querySelector("p").textContent = "It is from 8AM to 8PM";
    document.querySelector("#hours").textContent = toHHMMSS(seconds);
  }
}, 1000)

It is not 8 AM yet

Hope it works!

A: I would use Luxon.js:
npm install luxon

Then, it's an easy...
const {DateTime, Duration} = require('luxon');

function countdown(zeroDate) {
  const zero = DateTime.fromISO(zeroDate);
  const timer = setInterval(function() {
    const delta = zero
                 .diff(DateTime.local())
                 .shiftTo('days', 'hours', 'minutes', 'seconds', 'milliseconds');
    const {days: d, hours: h, minutes: m, seconds: s} = delta;

    if ( delta.valueOf() < 1 ) {
      console.log("Happy Birthday!");
      clearInterval(timer);
    } else {
      console.log(`${d}d ${h}h ${m}m ${s}s Remaining`);
    }

  }, 1000 );
}

If invoked with
const {DateTime, Duration} = require('luxon');

const start = DateTime.local().plus({seconds: 15}).toISO();
countdown(start);