text:
Q: Cylindrical coordinates in PDE I'm trying to write out the 3D incompressible Navier-Stokes equations in cylindrical coordinates but got stuck. The Navier-Stokes equations: $$u_t - \nu\Delta u + u\cdot \nabla u + \nabla p=0$$ $$\nabla \cdot u =0 $$
Here both $u$ denotes the velocity vector field and $p$ is the pressure.
We consider the cylindrical coordiantes: $x=r\cos \theta; y=r\sin \theta; z=z$. I know then $$\Delta=\frac{1}{r}\frac{\partial}{\partial_{r}}(r\frac{\partial}{\partial_{r}}) + \frac{1}{r^2}\frac{\partial^2}{\partial \theta^2} + \frac{\partial^2}{\partial z^2} $$. So the velocity components are $(u_{r}, u_{\theta},u_{z})$.
My question is: why is the following $r$ momentum equation true?
$$\frac{\partial u_r}{\partial t} + u\cdot \nabla u_{r}-\frac{1}{r}u_{\theta}^2+p_{r}=\nu(\Delta u_{r}-\frac{u_{r}}{r^2}-\frac{2}{r^2}\frac{\partial u_{\theta}}{\partial \theta})$$
I have no idea where the term $-\frac{1}{r}u_{\theta}^2$ comes from. And for the term on the right hand side, what are the two terms besides the laplacian operator?

A: Your confusion seems to stem from thinking $\mathbf{e}_r,\mathbf{e}_\theta$ are constants.  They are not, and so when differentiating you need to take account of their change too.
Remember the operator $\nabla$ is
$$
\nabla=\mathbf{e}_r\frac{\partial}{\partial r}+\mathbf{e}_\theta\frac{1}{r}\frac{\partial}{\partial\theta}+\mathbf{e}_z\frac{\partial}{\partial z}
$$
and the vector laplacian is defined as
$$
\nabla^2 \mathbf{A}=\nabla(\nabla\cdot\mathbf{A})-\nabla\times(\nabla\times\mathbf{A}).
$$
In cylindrical coordinates, we have
\begin{align*}
(\mathbf{u}\cdot\nabla)\mathbf{u}
&=\left(u_r\frac{\partial}{\partial r}+u_\theta\frac{1}{r}\frac{\partial}{\partial\theta}+u_z\frac{\partial}{\partial z}\right)(u_r\,\mathbf{e}_r+u_\theta\,\mathbf{e}_\theta+u_z\,\mathbf{e}_z)\\
\end{align*}
and note that $\frac{\partial}{\partial\theta}\mathbf{e}_\theta=-\mathbf{e}_r$, giving the extra term $-\frac1ru_\theta^2$ that you see in the LHS.
Similarly, when you expand the vector laplacian, you get
$$
(\nabla^2\mathbf{u})\cdot\mathbf{e}_r =
\nabla^2 u_r -\frac2{r^2}\frac{\partial u_\theta}{\partial\theta}-\frac{u_r}{r^2}.
$$


text:
Q: Generating a waveform of raw audio using ffmpeg not working right (not showing clippings) I generated a waveform of the raw audio with ffmpeg and it looks as perfectly normal audio on the picture. But when I imported it in Audacity, I can see and hear that the audio is clipping.
I tried simple command:
ffmpeg -f s16le -ar 16000 -ac 1 -i audio.raw -lavfi showwavespic audio.png

With this result: waveform image 1
And also tried this solution https://stackoverflow.com/a/32276471/12253501
Looks much prettier, but still can't see that audio actually clipped: waveform image 2.
For the second one I made sure to delete "compand=gain=-6" to get the actual audio level.
And here's what I see in Audacity: screenshot from Audacity
The audio I'm importing is raw data (16-bit signed PCM, Little-endian, 16000Hz Sample Rate). I also tried converting it to WAV first, but got the same results with ffmpeg and Audacity.
I'm wondering what I'm doing wrong and how to I get to see clipping on ffmpeg waveform output?
Here's the link for the audio file: raw and wav

A: Your audio is definitely clipping.  Try setting scale=log so you can see this better.
ffmpeg -i audio.wav -lavfi showwavespic=scale=log audio.png

Also keep in mind that some of this clipping may have occurred before this version of the file.  If this is clipping on the input stage of the recorder, but the recorded output was down a few dB, then you can hear clipping but not necessarily see it in the raw levels.

A: I couldn't achieve the results I wanted with just the ffmpeg, and I end up using audiowaveform, which gave me result similar to Audacity. Not sure if it's RMS or Peak, but works for me. Unfortunately, audiowaveform can't work with raw audio:
ffmpeg -f s16le -ar 16000 -ac 1 -i audio.raw audio.wav
audiowaveform -i audio.wav -o audio.png -e 105

Other downside of audiowaveform is that by default it only generates waveform for the first 15 seconds. Needs to calculate the length of the audio and give it as a parameter (-e seconds).
Here's the result:

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to callback a lua function from a c function I have a C function (A) test_callback accepting a pointer to a function(B) as the parameter and A will "callback" B.
//typedef int(*data_callback_t)(int i);
int test_callback(data_callback_t f)
{
    f(3);
}

int datacallback(int a )
{
    printf("called back %d\n",a);
    return 0;
}

//example
test_callback(datacallback); // print : called back 3

Now, I want to wrap test_callback so that they can be called from lua, suppose the name is lua_test_callback ;and also the input parameter to it would be a lua function. How should I achieve this goal?
function lua_datacallback (a )
    print "hey , this is callback in lua" ..a
end

lua_test_callback(lua_datacallback)  //expect to get "hey this is callback in lua 3 "

EDIT:
This link provide a way to store the callback function for later use .
//save function for later use
callback_function = luaL_ref(L,LUA_REGISTRYINDEX);

//retrive function and call it
lua_rawgeti(L,LUA_REGISTRYINDEX,callback_function);
//push the parameters and call it
lua_pushnumber(L, 5); // push first argument to the function
lua_pcall(L, 1, 0, 0); // call a function with one argument and no return values

A: I'm not sure I understand your question, if you are asking what would lua_test_callback look in C, it should be something like this
int lua_test_callback(lua_State* lua)
{
    if (lua_gettop(lua) == 1 && // make sure exactly one argument is passed
       lua_isfunction(lua, -1)) // and that argument (which is on top of the stack) is a function
    {
        lua_pushnumber(lua, 3); // push first argument to the function
        lua_pcall(lua, 1, 0, 0); // call a function with one argument and no return values
    }
    return 0; // no values are returned from this function
}

You cannot just wrap test_callback, you need entirely different implementation to call Lua functions.
(edit: changed lua_call to lua_pcall as suggested by Nick. I still omitted any error handling for brevity)

A: The convenient way of doing calls to different Lua functions with different signatures:
A. Make a class that will maintain Lua state safely and will provide easy interface. Do not write calls to Lua functions from scratch (with a lot of push/pop work and asserts) again and again - just use this class interface. This is safe, fast and convenient approach.
B. Define push and pop methods to push/pop arguments on/from Lua stack:

template<typename T> void push(T argument);
template<typename T> void get(const int index, T& return_value);

template<> void State::push(bool arg)
{
  lua_pushboolean (lua_state, arg ? 1 : 0);
}

template<> void State::push(float arg)
{
  lua_pushnumber (lua_state, arg);
}

template<> void State::push(int arg)
{
  lua_pushnumber (lua_state, arg);
}

// ...
template<> void State::get(const int index, bool& ret)
{
      if (!lua_isboolean(lua_state, index)) { ... }
      ret = lua_toboolean(lua_state, index) != 0;
}

C. Define functions to call Lua functions:

// Call function that takes 1 argument and returns nothing
template <typename A1>
void call(const char * funcName, A1 arg1)
{
  lua_getfield (lua_state, LUA_GLOBALSINDEX, funcName);       // push global function f on stack
  push (arg1);                                            // push first argument on stack
  assert_call(    lua_pcall(lua_state, 1, 0, this->err_h) );      // call function taking 1 argument and getting no return value
}

// call function that takes 2 argument and returns 1 value
template <typename R1, typename A1, typename A2>
void callr1(const char * funcName, R1& res, A1 arg1, A2 arg2)
{
  lua_getfield (lua_state, LUA_GLOBALSINDEX, funcName);       // push global function f on stack
  push (arg1);                                            // push first argument on stack
  push (arg2);
  assert_call(    lua_pcall(lua_state, 2, 1, this->err_h) );      // call function taking 2 arguments and getting 1 return value
  get  (-1, res);
  lua_pop(lua_state, 1);
}

D. Set error handler (lua_pcall will call this Lua function if error)

void setErrorHandler(const char * funcName)
{
  lua_getfield (lua_state, LUA_GLOBALSINDEX, funcName);
  this->err_h = lua_gettop(lua_state);
}


text:
Q: How to determine the ojdbc driver version of my weblogic server I am using weblogic 12.1.3 and could see that both ojdbc6 and 7 jars are available in path
C:\Oracle\Middleware\oracle_common\modules\oracle.jdbc_12.1.0\

I am trying to understand the ojdbc version  that my weblogic server is used to connect to database. I tried the below command, but both worked out for me.
java -jar ojdbc6.jar -getversion
Oracle 12.1.0.2.0 JDBC 4.0 compiled with JDK6 on Tue_Apr_22_08:54:06_PDT_2014
#Default Connection Properties Resource
#Tue Aug 15 14:25:00 CDT 2017

java -jar ojdbc7.jar -getversion
Oracle 12.1.0.2.0 JDBC 4.1 compiled with JDK7 on Tue_Apr_22_08:56:40_PDT_2014
#Default Connection Properties Resource
#Tue Aug 15 14:25:20 CDT 2017

Is there a way to find the same from weblogic console? if yes, please advise that as well.

A: The default driver for Oracle 12.1.3 is ojdbc7.jar.
See JDBC Drivers Installed with WebLogic Server


text:
Q: How can I represent a vector equation of a line segment in C++? I am working with computer graphics.
I would like to represent a line with two end points, and, then I would like my Line2d class to have a method that returns a Vector2d object.
Suppose, I have the following classes:
struct Point2d
{
    int x;
    int y;
};

Then, I can easily represent a line segment using two points:
class LineSegment2d
{
private:
    Point2d start;
    Point2d end;
public:
    ...
    ...
};

According to the definition, a vector is composed of a magnitude and a direction.
class Vector2d
{
private:
    Point2d p;
public:
    double Magnitude(void);
    Point Component(void);
    Vector2d Normal();
    Vector2d & Add(Vector & rhs);
    Vector2d & Subtract(Vector & rhs);
    Vector2d & Multiply(int scalar);
    int DotProduct(Vector2d rhs);
    Vector2d & CrossProduct(Vector2d rhs);
};

One object of Point2d is sufficient to represent a vector. For example, magnitude of a vector = sqrt(p.x*p.x + p.y*p.y);. And, p.x and p.y collectively represent the direction.

On the other hand, we know that the vector equation of a line passing through (x0,y0,z0) is, r =r0 + tv
Where,
r is the vector for the subject line.
r0  is a position vector that points to the direction of the point (x0, y0, z0). Since, r0  is a position vector, obviously, the origin of r0  would be (0,0,0).
t is any real numbered value, where, −∞<t<∞ –.
v is a vector which is parallel to our subject straight line.
Vector equation of a line segment between the points P(1, 3, 2) and Q(-4, 3, 0):
According to the above formula, the vector equation of the line PQ could be either
r =<1,3,2> + tv

or,
r =<-4,3,0> + tv

The vector that connects the two points P and Q is,
PQ  = <(-4-1), (3-3), (0-2)>
    = <-5, 0, -2>

And, this vector is parallel to our subject line for sure.
So, we can write,
r   =<1, 3, 2> + t <-5, 0, -2>
    =<1, 3, 2>+<-5t, 0, -2t>
    = <(1-5t), (3+0), (2-2t)>
    =<1-5t, 3, 2-2t>

According to the vector equation of a line segment, I think, my Vector class should look like the following:
class LineVector2d
{
private:
    Vector2d v;
    double t;
public:
    ..........
};

Is this the correct representation?
If that so, how can I calculate/set/find the value of t?

A: There are many forms of line representation.
If you mean line (not segment), then, probably, you'll find convenient to use class/structure, containing BasePoint and UnitDirectionVector.
For line segments, choose between (Point pt0, Point pt1) form, and, (Point pt, Vector v = pt1 - pt0) form.
The second one is more suitable for parametric approach like,
X = P0.X + t * D.X etc.

A: If you want to convert a line segment to a vector, you have to be aware that there is no "universal semantic" for the conversion, it is up to you to define what the conversion means. That said, I assume you want a vector with the same (Euclidean) norm as the length of the line segment and pointing in the same direction, i.e. something like this:
class LineSegment2d
{
   ....
   Vector2d getVector() const {
      return Vector2d(end) - Vector2d(start);
   }
};

In other words, offset the line segment to the origin point of the coordinate system. The end point can then be converted to a vector.
EDIT: After understanding a bit more about why you want this, you might be looking for another representation
class LineSegment2d
{
   ....
   Vector2d getVector() const {
      return Vector2d(end);
   }
};

This will get you one vector for each line segment: the end point. If your polygons consist of connected line segments, this will give you all the vertices in the polygon.

A: Use the representation of line segments you have in the question.
I'll write LS(a,b) for the line segment with start point a, and, end point b.
Now given two such segments LS(a,b), and, LS(c,d) that intersect (in your context one from the clipping polygon and one from the polygon being clipped; I am presuming you know how to determine this).
What you seem to want answered is if this intersection has LS(c,d) going to the inside of the polygon while crossing the edge LS(a,b).
For this, it is sufficient to determine the angle between the directions of the line segments. This is the same as the angle between the vectors v = b-a and w = d-c.
Also, you don't even need the angle, all you need is to see if the angle is positive or negative; so look at the vector w-v. If LS(c,d) crosses LS(a,b) to the inside, this vector will be in the lower half plane. If LS(c,d) crosses LS(a,b) to the outside, this vector will be in the upper half plane.
Determining upper verses lower half plane means looking at the second coordinate of end-start.
Apologies for the wall of text, but mathjax doesn't seem active on this site.  Also no code, but I believe that (if I didn't make any mistakes) all the operations I mentioned are easy to translate into code.

A: If you want to be very mathematical, maybe this can help: https://en.wikipedia.org/wiki/Homogeneous_coordinates
In 2d that means a position is (x,y,1) and a direction (dx,dy,0). The reason for this is projection, which is rare in 2d but common in 3d.
So to try to answer: Just use 4 component vectors all the time. Positions have a w=1, directions a w=0.
Just try it with a line based of two points A and B, both have w=1. The vector from A to B is B-A, which ends up with w=0.
Also what you use in your code does matter very little unless you end up optimizing a special case. Just go for the smallest data structure. Start and end should be fine.
Maybe think about indexed: A flat array of all vertices and every line is just two indices into the vertex array.

A: I think there's some confusion because of the following

According to the definition, a vector is composed of a magnitude and a direction.

There is more than one way of representing a vector. I think in your question you mean that a vector can be represented by a magnitude (scalar) and a unit vector indicating a direction. A vector can just be an ordered triplet (for three dimensions) that indicate the magnitude (sqrt(x^2 + y^2 + z^2)) and the direction from the origin.
I think the answer to your question is, you don't need to calculate t. Correct me if I'm mistaken, but I think you're interpreting t as the magnitude? You can calculate that from v with sqrt(x^2 + y^2 + z^2), but v can hold both a magnitude and direction as an ordered triplet by itself.
Edit:
template <typename T>
struct Point2d
{
    T x;
    T y;

    Point2d operator + (const Point2d<T>& rhs) const
    {
        return Point2d<T>{x + rhs.x, y + rhs.y};
    }
    Point2d operator - (const Point2d<T>& rhs) const
    {
        return Point2d<T>{x - rhs.x, y - rhs.y};
    }
    // ...

    Point2d operator * (const T value) const
    {
        return Point2d<T>{x*value, y*value};
    }
    Point2d operator / (const T value) const
    {
        return Point2d<T>{x/value, y/value};
    }
    // ...
};

template <typename T>
class Vector2d
{
private:
    Point2d<T> p;
public:
    Vector2d(const Point2d<T>& point) : p{point} {}

    /*double Magnitude();
    Point2d<T> Component();
    Vector2d Normal();
    int DotProduct(Vector2d rhs);
    Vector2d& CrossProduct(Vector2d rhs);*/

    Vector2d operator + (const Vector2d<T>& rhs) const
    {
        return p + rhs.p;
    }
    Vector2d operator - (const Vector2d<T>& rhs) const
    {
        return p - rhs.p;
    }
    // ...

    Vector2d operator * (const T value) const
    {
        return p*value;
    }
    Vector2d operator / (const T value) const
    {
        return p/value;
    }
    // ...
};

template <typename T>
class LineVector2d
{
private:
    Point2d<T>  p;
    Vector2d<T> v;

public:
    LineVector2d() = default;
    LineVector2d(const Point2d<T>& point, const Vector2d<T>& direction) : p{point}, v{direction} {}

    /// Returns the point on the line for the time/value `t`
    Point2d<T> valueAt(T t)
    {
        return p + v*t;
    }
};

A: Your representation of class LineSegment2d is fine. But the representation of class Vector2d is incorrect. This is because you are considering only those vectors that pass through the origin. A vector on a 2d plane can be represented with 3 components in the same way it done in 3d space. The 3 components of a vector are namely: Direction, Magnitude and A point through which it passes. If we define x, y and z axes for a 3d space then, for a point in the x-y plane z component is equal to 0. Also, direction in 3d space is defined in the form of direction cosines(ie. the cosine of the angle between the vector and an axis). Hence cosine of angle between vector and z-axis is equal to zero(because the angle = 90 degrees) for a vector in x-y plane.


text:
Q: How to stream an in-memory xml document as an attachment on an asp.net mvc site I thought MVC was supposed to make all this easier but I'm trying various ways and getting issues.
If I try the accepted answer for this question (changing the content type accordingly)... How to create file and return it via FileResult in ASP.NET MVC?
...I get into trouble because my encoding in the xml file is UTF-16.
The error I get is:
Switch from current encoding to specified encoding not supported.
This suggests that somewhere I need to tell MVC that I want UTF-16. Alternatively I want a different method that uses binary and not text.

A: This is what I've settled for:
public FileStreamResult DownloadXML()
{
    string name = "file.xml";
    XmlDocument doc = getMyXML();
    System.Text.Encoding enc = System.Text.Encoding.Unicode;
    MemoryStream str = new MemoryStream(enc.GetBytes(doc.OuterXml));

    return File(str, "text/xml", name);
}

I don't think this is perfect and I could probably just use a FileContentResult and not bother with the memory stream. Also, I don't think IE likes the unicode. It complains that "A name was started with an invalid character" despite the xml being fine and happily opening in firefox.
However it seems to do the job.

A:     public FileStreamResult DownloadXML()
    {
        string name = "file.xml";
        XmlDocument doc = getMyXML();
        var str = new MemoryStream();
        doc.Save(str);
        str.Flush();
        str.Position = 0;

        return File(str, "text/xml", name);
    }

Note that calling Flush and setting Position are mandatory things to do.
Saving to stream works better than initializing through OuterXml: 1) less frictions, 2) resulting XML is formatted instead of being one-line string.


text:
Q: Converting an integer to datetime and comparing the date in c# I am having an issue in parsing two integers to datetime in C#. I have two integers as follows:
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;

var scheduledDate = "25/08/2018";

What I want is to convert day, month and the current year to format dd/MM/yyyy and compare this date to scheduledDate which is in the format of dd/MM/yyyy. Can someone please help me with this ?

A: Rather than converting DateTime object to String you should always convert String to DateTime object and then compare it.
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;

var scheduledDate = "25/08/2018";
var dtScheduledDate = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var dtCurrentDate = new DateTime(currentYear, month, day);

if (dtScheduledDate < dtCurrentDate)
{
    // ...
}

A: var yourDateTime = new DateTime(currentYear, month, day);
var yourDateString = yourDateTime.ToString("dd/MM/yyyy");
// compare

A: If you want to compare only date then you can use Date Property of DateTime
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;

var dateToCompare = new DateTime(currentYear, month, day);

var scheduledDt = "25/08/2018";
var scheduledDate = DateTime.ParseExact(scheduledDt, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

if(dateToCompare.Date == scheduledDate.Date)
{
    //Your logic
}

POC: .Net Fiddler

A: Try the following, you could use DateTime.ToString() method to convert it into the format you need.
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;

var date = new DateTime(DateTime.Now.Year, month, day);
var formattedDate = date.ToString("dd/MM/yyyy");

var scheduledDate = "25/08/2018";

// Compare formattedDate and scheduledDate

OR
You could consider converting the scheduledDate string to date time and compare the date time objects, if that's more appropriate:
var scheduledDate = "25/08/2018";
var parsedDate = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

var date = new DateTime(DateTime.Now.Year, month, day);

// compare date & parsed date
bool areEqual = date.Equals(parsedDate);

A: If I understand your question, just keep the proceeding zero,
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var targetDate = $"{day}/{month.ToString().PadLeft(2,'0')}/{currentYear}";
var scheduledDate = "25/08/2018";
var difference = DateTime.Compare(DateTime.Parse(targetDate),
DateTime.Parse(scheduledDate));

A: In case you just want to convert it to a string, this should be the easiest way:
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;

// {day:D2} is equivalent to day.ToString("D2") which pads integers to a length of two
var createdDate = $"{day:D2}/{month:D2}/{currentYear}";

var scheduledDate = "25/08/2018";

EDIT
Picking up on a few things people here said, parsing both to a DateTime might be more suitable for the comparing part:
DateTime createdDateTime = new DateTime(currentYear, month, day);

DateTime scheduledDateTime = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

// Compare if it's the same day
if (createdDateTime.Date == scheduledDateTime.Date)
{
    // do stuff
}

// Get the difference in Days
int dayDifference = (createdDateTime - scheduledDateTime).Days;

Alternatively .TotalDays instead of .Days returns a double

A: int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;

var scheduledDate = "25/08/2018";

// parse string into DateTime structure
var ci = new CultureInfo("en-UK");
var dtScheduledDate = DateTime.Parse(scheduledDate, ci);

var dtOther = new DateTime(currentYear, month, day);

if(dtOther > dtScheduledDate)
{
  ...
}

A: In this case if your variable scheduleDate is a string you can convert the other variables (day,month and currentYear) into a string in the format you want:
var dt = day + "/" + month  + "/" + currentYear;

So to compare you do this:
if(dt.Equals(scheduleDate))
 //Do some
else
 //other thing

A: static void Main(string[] args)
{

    int transactionDate = 20201010;
    int? transactionTime = 210000;

    var agreementDate = DateTime.Today;
    var previousDate = agreementDate.AddDays(-1);

    var agreementHour = 22;
    var agreementMinute = 0;
    var agreementSecond = 0;

    var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
    var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

    DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

    Console.WriteLine("Selected Date : " + selectedDate.ToString());
    Console.WriteLine("Start Date : " + startDate.ToString());
    Console.WriteLine("End Date : " + endDate.ToString());

    if (selectedDate > startDate && selectedDate <= endDate)
        Console.WriteLine("Between two dates..");
    else if (selectedDate <= startDate)
        Console.WriteLine("Less than or equal to the start date!");
    else if (selectedDate > endDate)
        Console.WriteLine("Greater than end date!");
    else
        Console.WriteLine("Out of date ranges!");
}

Output:
Selected Date : 10.10.2020 21:00:00
Start Date : 8.10.2020 22:00:00
End Date : 9.10.2020 22:00:00
Greater than end date!


text:
Q: How to show all tables with column header as "Text" in mysql I am trying to show all tables in mysql I have used the following command.
 show tables;`

I don't want to display db name in the column header.How to display with "Text" as column header in mysql

A: You can use information_schema for this.
SELECT
table_name from information_schema.tables where
table_schema = 'extdirectnode';

A: You could use a query against the information_schema database, like this:
SELECT t.table_name AS `Text`
  FROM information_schema.tables t
 WHERE t.table_schema = 'extdirectnode'
 ORDER BY t.table_name


text:
Q: 2nd order ODE using Runge-Kutta method in C I want to model the motion of a particle using a set of 2nd order equations
the the equation is
d2x/dt2 = 1 + dy/dt + dz/dt
d2y/dt2 = 1 + dx/dt + dz/dt
d2z/dt2 = 1 + dx/dt + dy/dt

vector V is (dx/dt dy/dt dz/dt),  X is (x y z),
V = [0 0 0], X = [0 0 0] initially
I implemented this into C code for one of the ODEs below
CODE;
double X_function(double a[], double t, double at[],double b[],double c[]) {
//double yt, zt;
at[0] = a[0];
at[1] = 1 + b[0] + c[0];
double F = at[1];
return F;
}

i need help understanding how to use R-K in such a case

A: You have an equation
x''=F(x,x')

that you rewrite as an first order system
x' = v
v' = F(x,v)

Implement this coupled 6-dimensional system as one function
void derivs(double u[], double t, double du[]) {
    int j,k;
    for(k=0; k<3; k++) {
        du[k] = u[3+k];
        du[3+k] = 1;
        for(j=0;j<3; j++)
            if(j!=k) du[3+k] += u[j]
    }
}

then you can implement the Runge-Kutta method in a general form for a first-order system.


text:
Q: How to make c# unit test as a standalone console program? (without external runner or console) I want:

*

*Make standalone unit-test console program.
Direct run in console. Without external test runner.

*Testing entrance is under control.

To demonstrate what I mean, for an example in C++ gtest:

*

*Fully embedded.

*Testing entrance is RUN_ALL_TESTS().

*Options is configurable by argv.

::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();

A: With NUnit:
return new NUnitLite.AutoRun().Execute(args);

https://docs.nunit.org/articles/nunit/running-tests/NUnitLite-Runner.html
Trivial but difficult to google.
I need "built-in" exact match to reach that document page.


text:
Q: how to redirect to root folder after logout? i am in this address in my project
localhost/v1.2/login_pane/login_pane-personnelselect/profile/profile.php

and i want to redirect to this page [localhost/v1.2/login_pane/loginmain.html
and the page always redirect me to localhost/v1.2/login_pane/login_pane-personnelselect/login_pane/index.html
i have this php code in my logout.php but it doestnt work
<?php
    session_start();
    if(session_destroy())
    {
    header("Location: ../../loginmain.html");
    }
    ?>

how will i able to make it?

A: Try Like this
<?php
session_start();
if(session_destroy())
{
header("Location: ../../loginmain.html");
}
?>

A: try this
<?php
session_start();
session_unset();
header("Location: ../../loginmain.html");
?>

A: Please have try with following code:
session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not     have one use only this as follow **session_unset();**
header("Location: ../../loginmain.html");


text:
Q: LINQ To SQL in Compact Framework Im on to design my Data Access for a new solution i create. That solution though contains Compact Framework Device Application and libraries besides Desktop. All .NET 3.5. Desktop will handle all Data Access basically. I need the Data Objects to have in CF too, Desktop will communicate with SQL and then with Mobile and give the appropriate data...
I love LINQ, and more i love LINQ 2 SQL. There is a lot of hype out there and i don't buy internal Microsoft politics about recommending EF. For now EF is too heavy and too complex for someone to choose it besides it still evolving and EF 4 will have major changes when it comes in a few months. But i cant wait for months to create a project as every developer in here, i want something now! After that said i want to use LINQ 2 SQL, my problem is that i cant just copy the generated dbml and use the generated classes. I don't need the DataContext cause i don't intend to use CRUD or any operations on a database with the Mobile App. i Just want the Objects. Anyone ever came in a situation like this? The whole point is not to write all classes representing the tables by hand. Cause i need them for further LINQ to Objects manipulation.
Basically an ORM supporting CF would do the job! But i don't know any incompatibilities i would meet.

A: I've been able to modify SubSonic 3.0, the db4o/Mainsoft port of System.Linq.Expressions from the Mono project after adding the missing Queryable sources, and Matt Warren's IQToolkit on Codeplex to provide a L2S equivalent on the CF.
This is about what it takes, though, since Linq expression trees are not supported on .Net CF 3.5.
I was able to use the DbEntityProvider/DbEntitySession and AttributeMapping/XMLMapping imported to Subsonic from IQToolkit to provide better entity and table-to-class mapping support.

A: L2S works great with the compact framework. You can't use the drag-and-drop designer, though. You'll need to run SQLMetal.exe yourself to generate the classes for you.
SQLMetal.exe: http://msdn.microsoft.com/en-us/library/bb386987.aspx
Example with Northwind compact: http://blogs.msdn.com/sqlservercompact/archive/2007/08/21/linq-with-sql-server-compact-a-ka-dlinq-over-sql-ce.aspx
Another example, with lots of pictures: http://pietschsoft.com/post/2009/01/Using-LINQ-to-SQL-with-SQL-Server-Compact-Edition.aspx

A: You could use DevExpress persistent objects (XPO) on compact framework. I have used it before but found it to be somewhat slow for my purpose (data collection application).
The reason that you cannot find much of this on the compact framework is that speed is usually so important for device apps, that data access code is usually done manually.
I don't know if you can create objects from an already existing database with XPO.

A: This is one good option generating from dbml file plain POCO classes working with LINQ 2 SQL. Not tested yet but seems promised.
http://www.codeplex.com/ULinqGen

A: Have you checked out Kea - Linq for Sql Compact & Compact Framework?
http://kea.codeplex.com/


text:
Q: Query does not return records as expected Bellow query give  records as expected
@Query("From Transaction tr where tr.account.bankCustomer.customer.rokaId=?1 and tr.account.accountType=?2 order by createdDate desc")
List<Transaction> findTransactioForCorporate(String customerRokaId,AccountType accountType);

Bellow one give me record as expected.
@Query("From Transaction tr where tr.account.customerInvitation.owner.rokaId=?1 and tr.status !=?2 order by createdDate desc")
List<Transaction> findTransactioForCorporate(String ownerRokaId,Status status);

But bellow one only return records which satisfy my second query. ((tr.account.customerInvitation.owner.rokaId=?3 and tr.status !=?4))
@Query("From Transaction tr where (tr.account.bankCustomer.customer.rokaId=?1 and tr.account.accountType=?2) Or (tr.account.customerInvitation.owner.rokaId=?3 and tr.status !=?4) order by createdDate desc")
List<Transaction> findTransactioForCorporate(String customerRokaId,AccountType accountType,String ownerRokaId,Status status);

What I'm doing wrong here.
I'm using spring data jpa 1.7,1  , Kindly help me

A: You have problem with null values in joined (OneToOne mapping) fields probably users from the first query does not have customerInvitiation and this reduces your results to records from second query eg
select a from AppUser a where a.username is not null or a.role.name = :name

if I have 3 user and only one is connected with role and two have not been yet connected query will will return only one user but if I will remove or a.role.name = :name part which a or statement this query will return 3 users. For more info you can go here.


text:
Q: mirror bits of a 32 bit word How would you do that in C? (Example: 10110001 becomes 10001101 if we had to mirror 8 bits). Are there any instructions on certain processors that would simplify this task?

A: Per Rich Schroeppel in this MIT memo (if you can read past the assembler), the following will reverse the bits in an 8bit byte providing that you have 64bit arithmetic available:
byte = (byte * 0x0202020202ULL & 0x010884422010ULL) % 1023;

Which sort of fans the bits out (the multiply), selects them (the and) and then shrinks them back down (the modulus).
Is it actually an 8bit quantity that you have?

A: Nearly a duplicate of Most Efficient Algorithm for Bit Reversal ( from MSB->LSB to LSB->MSB) in C (which has a lot of answers, including one AVX2 answer for reversing every 8-bit char in an array).

X86
On x86 with SSSE3 (Core2 and later, Bulldozer and later), pshufb (_mm_shuffle_epi8) can be used as a nibble LUT to do 16 lookups in parallel.  You only need 8 lookups for the 8 nibbles in a single 32-bit integer, but the real problem is splitting the input bytes into separate nibbles (with their upper half zeroed).  It's basically the same problem as for pshufb-based popcount.
avx2 register bits reverse shows how to do this for a packed vector of 32-bit elements.  The same code ported to 128-bit vectors would compile just fine with AVX.
It's still good for a single 32-bit int because x86 has very efficient round-trip between integer and vector regs: int bitrev = _mm_cvtsi128_si32 ( rbit32( _mm_cvtsi32_si128(input) ) );.  That only costs 2 extra movd instructions to get an integer from an integer register into XMM and back.  (Round trip latency = 3 cycles on an Intel CPU like Haswell.)

ARM:
rbit has single-cycle latency, and does a whole 32-bit integer in one instruction.

A: The naive / slow / simple way is to extract the low bit of the input and shift it into another variable that accumulates a return value.
#include <stdint.h>

uint32_t mirror_u32(uint32_t input) {
    uint32_t returnval = 0;
    for (int i = 0; i < 32; ++i) {
        int bit = input & 0x01;
        returnval <<= 1;
        returnval += bit;    // Shift the isolated bit into returnval
        input >>= 1;
    }
    return returnval;
}

For other types, the number of bits of storage is sizeof(input) * CHAR_BIT, but that includes potential padding bits that aren't part of the value.  The fixed-width types are a good idea here.
The += instead of |= makes gcc compile it more efficiently for x86 (using x86's shift-and-add instruction, LEA).  Of course, there are much faster ways to bit-reverse; see the other answers.  This loop is good for small code size (no large masks), but otherwise pretty much no advantage.
Compilers unfortunately don't recognize this loop as a bit-reverse and optimize it to ARM rbit or whatever.  (See it on the Godbolt compiler explorer)

A: Fastest approach is almost sure to be a lookup table:
out[0]=lut[in[3]];
out[1]=lut[in[2]];
out[2]=lut[in[1]];
out[3]=lut[in[0]];

Or if you can afford 128k of table data (by afford, I mean cpu cache utilization, not main memory or virtual memory utilization), use 16-bit units:
out[0]=lut[in[1]];
out[1]=lut[in[0]];

A: If you are interested in a more embedded approach, when I worked with an armv7a system, I found the RBIT command.
So within a C function using GNU extended asm I could use:
uint32_t bit_reverse32(uint32_t inp32)
{
    uint32_t out = 0;
    asm("RBIT %0, %1" : "=r" (out) : "r" (inp32));
    return out;
}

There are compilers which expose intrinsic C wrappers like this. (armcc __rbit)  and gcc also has some intrinsic via ACLE but with gcc-arm-linux-gnueabihf I could not find __rbit C so I came up with the upper code.
I didn't look, but I suppose on other platforms you could create similar solutions.

A: It's actually called "bit reversal", and is commonly done in FFT scrambling.  The O(log N) way is (for up to 32 bits):
uint32_t reverse(uint32_t x, int bits)
{
    x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1); // Swap _<>_
    x = ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2); // Swap __<>__
    x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4); // Swap ____<>____
    x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8); // Swap ...
    x = ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16); // Swap ...
    return x >> (32 - bits);
}

Maybe this small "visualization" helps:
An example of the first 3 assignment, with a uint8_t example:
b7 b6 b5 b4  b3 b2 b1 b0
-> <- -> <-  -> <- -> <-
----> <----  ----> <----
---------->  <----------

Well, if we're doing ASCII art, here's mine:
7 6 5 4 3 2 1 0
 X   X   X   X
6 7 4 5 2 3 0 1
 \ X /   \ X /
  X X     X X
 / X \   / X \
4 5 6 7 0 1 2 3
 \ \ \ X / / /
  \ \ X X / /
   \ X X X /
    X X X X
   / X X X \
  / / X X \ \
 / / / X \ \ \
0 1 2 3 4 5 6 7

It kind of looks like FFT butterflies. Which is why it pops up with FFTs.

A: I've also just figured out a minimal solution for mirroring 4 bits (a nibble) in only 16 bits temporary space.
mirr = ( (orig * 0x222) & 0x1284 ) % 63

A: I think I would make a lookup table of bitpatterns 0-255. Read each byte and with the lookup table reverse that byte and afterwards arrange the resulting bytes appropriately.

A: quint64 mirror(quint64 a,quint8 l=64) {
    quint64 b=0;
    for(quint8 i=0;i<l;i++) {
        b|=(a>>(l-i-1))&((quint64)1<<i);
    }
return b;
}

This function mirroring less then 64 bits. For instance it can mirroring 12 bits.
quint64 and quint8 are defined in Qt. But it possible redefine it in anyway.

A: If you have been staring at Mike DeSimone's great answer (like me), here is a "visualization" on the first 3 assignment, with a uint8_t example:
b7 b6 b5 b4  b3 b2 b1 b0
-> <- -> <-  <- -> <- ->
----> <----  ----> <----
---------->  <----------

So first, bitwise swap, then "two-bit-group" swap and so on.

A: For sure most people won't consider my approach neither as elegant nor efficient: it's aimed at being portable and somehow "straightforward".
#include <limits.h> // CHAR_BIT

unsigned bit_reverse( unsigned s ) {
  unsigned d;
  int i;
  for( i=CHAR_BIT*sizeof( unsigned ),d=0; i; s>>=1,i-- ) {
    d <<= 1;
    d |= s&1;
  }
  return d;
}

This function pulls the least significant bit from the source bistring s and pushes it as the most significant bit in the destination bitstring d.
You can replace unsigned data type with whatever suits your case, from unsigned char (CHAR_BIT bits, usually 8) to unsigned long long (128 bits in modern 64-bit CPUs).
Of course, there can be CPU-specific instructions (or instruction sets) that could be used instead of my plain C code.
But than that wouldn't be "C language" but rather assembly instruction(s) in a C wrapper.

A: int mirror (int input)
{// return bit mirror of 8 digit number
  int tmp2;
  int out=0;
  for (int i=0; i<8; i++)
    {
      out = out << 1;
      tmp2 = input & 0x01;
      out = out | tmp2;
      input = input >> 1;
    }
   return out;
}


text:
Q: Laravel chunk and delete I have a large number of items (1M+) that i want to delete from a database, i fork a background job to take care of that, so that the user won't have to wait for it to finish to carry on whatever he/she was doing, the problem is, the app becomes unresponsive while the items are being deleted, so i thought that i would process the items chunk by chunk and sleep for a couple of seconds then carry on.
Here is the code that handles the delete:
// laravel job class
// ...
public function handle()
{
    $posts_archive = PostArchive::find(1); // just for the purpose of testing ;)
    Post::where('arch_id', $posts_archive->id)->chunk(1000, function ($posts) {
        //go through the collection and delete every post.
        foreach($posts as $post) {
            $post->delete();
        }
        // throttle
        sleep(2);
    });
}

Expected result: the posts are chunked and each chunk is processed, then idle for 2 seconds, repeat that until all the items are deleted.
Actual result: a random number of items is deleted once, then the process ends. no errors no indicators, no clue ?
is there a better way to implement this?

A: The reason your actual outcome is different to the expected outcome is to do with how Laravel chunks your dataset.
Laravel paginates through your dataset 1-page at a time, and passes the Collection of Post models to your callback.
Since you're deleting the records in the set, Laravel effectively skips a page of data on each iteration, therefore you end up missing roughly half the data that was in the original query.
Take the following scenario – there are 24 records that you wish to delete in chunks of 10:
Expected

+-------------+--------------------+---------------------------+
|  Iteration  |   Eloquent query   | Rows returned to callback |
+-------------+--------------------+---------------------------+
| Iteration 1 | OFFSET 0 LIMIT 10  |                        10 |
| Iteration 2 | OFFSET 10 LIMIT 10 |                        10 |
| Iteration 3 | OFFSET 20 LIMIT 10 |                         4 |
+-------------+--------------------+---------------------------+

Actual

+-------------+--------------------+----------------------------+
|  Iteration  |   Eloquent query   | Rows returned to callback  |
+-------------+--------------------+----------------------------+
| Iteration 1 | OFFSET 0 LIMIT 10  |                         10 | (« but these are deleted)
| Iteration 2 | OFFSET 10 LIMIT 10 |                          4 |
| Iteration 3 | NONE               |                       NONE |
+-------------+--------------------+----------------------------+

After the 1st iteration, there were only 14 records left, so when Laravel fetched page 2, it only found 4 records.
The result, is that 14 records out of 24 were deleted, and this feels a bit random but makes sense in terms of how Laravel processes the data.
Another solution to the problem would be to use a cursor to process your query, this will step through your DB result-set 1 record at a time, which is better use of memory.
E.g.

// laravel job class
// ...
public function handle()
{
    $posts_archive = PostArchive::find(1); // just for the purpose of testing ;)
    $query = Post::where('arch_id', $posts_archive->id);

    foreach ($query->cursor() as $post) {
        $post->delete();
    }
}

NB: The other solutions here are better if you only want to delete the records in the DB. If you have any other processing that needs to occur, then using a cursor would be a better option.

A: As Kelvin Jones points out, the reason the random number of items is being deleted is that you're deleting records as you page through them.
chunk simply uses offset & limit to "paginate" through your table. But if you delete 100 records from page 1 (IDs 1-100), then go to page 2, you're actually now skipping IDs 101-200 and jumping to 201-300.
chunkById is a way around this
Post::where('arch_id', $posts_archive->id)->chunkById(1000, function ($posts) {
    //go through the collection and delete every post.
    foreach($posts as $post) {
        $post->delete();
    }
});

Literally just replace the method name. Now, instead of using offset & limit to paginate, it will look at the maximum primary key (100) from the first page, then the next page will query where ID > 100. So page 2 is now correctly giving you IDs 101-200 instead of 201-300.

A: There is nothing Laravel specific about the way you'd handle this.  It sounds like your database server needs review or optimization if a delete query in a job is freezing the rest of the UI.
Retrieving each model and running a delete query individually definitely isn't a good way to optimize this as you'd be executing millions of queries.  You could use a while loop with a delete limit if you wish to try to limit the load per second in your application instead of optimizing your database server to handle this query:
do {
    $deleted = Post::where('arch_id', $posts_archive->id)->limit(1000)->delete();
    sleep(2);
} while ($deleted > 0);

A: If i understand correctly, the issue is that deleting a large amount of entries takes too much ressources.
doing it one post at a time will take too long too.
try getting the min and the max of post.id then chunk on those like
for($i = $minId; $i <= $maxId-1000; $i+1000) {
    Post::where('arch_id', $posts_archive->id)->whereBetween('id', [$i, $i+1000])->delete();
    sleep(2);
}

customize the chunk and the sleep period as it suites your server ressources.


text:
Q: For loop in a Script Shell My script is:
for i in $(seq $nb_lignes) a list of machines
do
ssh root@$machine -x "java ....."
sleep 10
done

--> i execute this script from machine C
i have two machines A and B ($nb_lignes=2)
ssh root@$machineA -x "java ....." : create a node with Pastry overlay
wait 10 secondes
ssh root@$machineB -x "java .....":create another node join the first (that's way i     have use sleep 10 secondes)

i run the script from machine C:
i'd like that it display : node 1 is created , wait 10 seconds and display node 2 is created
My problem: it display node 1 is created only
i tape ctrl+c it diplay node 2 is created
PS: the two process java are still runing in machine A and B
Thank you

A: From the way I'm reading this, armani is correct; since your java program does not exit, the second iteration of the loop doesn't get run until you "break" the first one.  I would guess that the Java program is ignoring a break signal sent to it by ssh.
Rather than backgrounding each SSH with a &, you're probably better off using the tools provided to you by ssh itself.  From the ssh man page:
 -f      Requests ssh to go to background just before command execution.
         This is useful if ssh is going to ask for passwords or
         passphrases, but the user wants it in the background.  This
         implies -n.  The recommended way to start X11 programs at a
         remote site is with something like ssh -f host xterm.

So ... your script would look something like this:
for host in machineA machineB; do
    ssh -x -f root@${host} "java ....."
    sleep 10
done

A: Try the "&" character after the "ssh" command.  That spawns the process separately [background] and continues on with the script.
Otherwise, your script is stuck running ssh.
EDIT: For clarity, this would be your script:
for i in $(seq $nb_lignes) a list of machines
do
ssh root@$machine -x "java ....." &
sleep 10
done


text:
Q: How to reproduce google login form effect i need a bit of help.
I'm trying to reproduce the google chrome user login page and i'm stucked (really stucked i don't even know where to start) with the input field of that form.
i tried inspecting chrome page but is quite difficult to understand how to reproduce the effect it has
let me explain my self with a little of code.
so i have my form with my inputs field (like shown under) when i click one of the field i want that the place holder come up like chrome do.
i really have no idea how to reproduce that kind of effect...
before click:
not selected
after click:
result
<input type="text" name="user-name" placeholder="Username"></input>
<input type="password" name="password" placeholder="Password"></input>

input{
border:solid 1px #222;
}
input:focus{
border:solid 2px #ddb760;
}

A: with css transform and :placeholder-shown pseudo class. Trick is, you have to add a placeholder(space as value) attribute to the inputs
 - placeholder=" ".

.g-input {
  position: relative;
  margin-bottom: 10px;
  box-sizing: border-box;
  display: inline-block;
}
.g-input label {
  background: white;
  padding: 3px;
  font-size: 12px;
  transition: transform 150ms cubic-bezier(0.4, 0, 0.2, 1), opacity 150ms cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: bottom left;
  color: #ddd;
  font-family: arial;
  position: absolute;
  top: 7px;
  left: 7px;
  z-index: 1;
  cursor: text;
}

.g-input input, .g-input textarea {
  border: 1px solid #ddd;
  display: block;
  padding: 10px;
  border-radius: 3px;
  width: 100%;
  box-sizing: border-box;
}

.g-input.fill {
  display: block;
  width: 100%;
}

.g-input input:focus, .g-input textarea:focus {
  outline: 0;
  border-color: #1873e8;
}

.g-input input:focus+label, .g-input input:not(:placeholder-shown)+label,
.g-input textarea:focus+label, .g-input textarea:not(:placeholder-shown)+label{
  transform: translateX(-3px) translateY(-15px);
  font-size: 10px;
  color: #1a73e8;
}

  <input type="text" id="user-name" name="user-name" placeholder=" ">
  Username

  <input type="password" id="password" name="password" placeholder=" ">
  Password

  <input type="text" id="user-name2" name="user-name2" placeholder=" ">
  Username

  <input type="password" id="password2" name="password2" placeholder=" ">
  Password

  <textarea id="ta" name="ta" placeholder=" "></textarea>
  Textarea

A: Google manage to make it look like placeholder, but it is just a div with text that is moving hover and on top of the input.
This is pretty much how to do it.

var text = document.getElementById("text");
var label = document.getElementById("label-text");

text.addEventListener("focusout", onfocusout);

function onfocusout(e) {
 if (text.value.length > 0) text.classList.add('not-empty');
 else text.classList.remove('not-empty');
}

// allow focus of the input even on click of div
label.onclick = function(e) {
 text.focus();
}
.input-group {
  position: relative;
}

#text {
  padding: 10px;

  border: 1px solid black;
  outline: none;
}

#label-text {
  padding: 0 5px;

  position: absolute;
  top: 10px;
  left: 5px;

  background-color: #fff;
  color: #999;

  transition: .2s;
}

#text:focus {
  border-color: blue;
}

#text:focus + #label-text {
  color: blue;
}

#text:focus + #label-text, #text.not-empty + #label-text {
  top: -10px;
  left: 5px;
}

  <input id="text" type="text" onfocusout="" />

Username

A: Perhaps something like this could help:
HTML:
<input type="text" name="user-name" placeholder="Username" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Username'">
<input type="password" name="password" placeholder="Password" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Password'">

CSS:
input {
  border:solid 1px #ddb760;
}

input:focus {
  border:solid 1px blue;
}

Fiddle:
https://jsfiddle.net/x9khyv71/


text:
Q: wrapped captcha control in a p tag, how to shift it to the right? wrapped captcha control in a p tag, how to shift it to the right about 50 px?
Edit
I am using reCaptcha using the .net control.  My input elements are to the right of the page by about 50 px.
My repactha is rendering left aligned (all the way to the left, so the alignment is off when compared to my other input fields).

A: #foo { margin-left: 50px }

general question, general answer :)

A: Did you try setting the style to a 50 pixel padding?
<p style="padding-left: 50px;"> ... </p>

If that doesn't work, you can always isert a 50 pixel image before the control.

A: Your question is really vague. I suppose the captcha is implemented using an image. In that case you could use CSS.
#captcha {
    position:relative;
    left:50px; /* moves the element 50px to the right */
}


text:
Q: Is this algorithm technically O(1) time? O(1) means "constant time", so is this max algorithm technically O(1) time?
int max (int x, int y)
{
    for (int k = 0; k < 100000000000000000000000000; ++k); // useless for-loop
    return (x > y ? x : y);
}

A: Yes it is constant time.
I understand your concern: constant time doesn't necessarily mean that it is fast, as your contrived example demonstrates (even though User 104 is right about the compiler not generating any code for the loop).  But a heck of a lot more often than not, big O notation tells us all we need to know.  And it is relatively easy to compute.
Bottom line: Big O notation is all about asymptotics.  If the Big O notation does not seem to agree with your intuition, then check your analysis again or check your intuition.  Repeat at least three times.  And if it still fails, then discuss it with your professor.  And only then if your professor says so, you should do a deeper analysis than big O (which will be difficult).


text:
Q: Show that a bijective function $f: V \to V^{'}$ is an isomorphism from graph $G$ to graph $G^{\ '}$ I have to show the following:

*

*For the case that someone uses other definitions:

*

*$V$ is the set of the vertices of $G$

*$E$ is the set of $2$-element subsets of $V$ defined as $E \subseteq {V \choose 2} = \{\{x,y \}: x,y \in V, x \neq y  \}$, i.e. the set of edges of $G$

*$N(v) = \{w \in V: \{v,w \} \in E \}$ is the neighborhood of $v$
Let $G = (V, E)$  and $G^{\ '} = (V^{'}, E^{'})$ be graphs. Show that a bijective function $f: V \to V^{'}$ is an isomorphism from $G$ to $G^{\ '}$, if for all $v \in V$ the following holds: $N(f(v)) = f(N(v))$.
I know that $f$ is an isomorphism, if for all $v,w \in V, v \neq w$ holds: $\{ v,w\} \in E \Leftarrow \Rightarrow \{ f(v), f(w)\} \in E^{'}$, so an edge  $\{ v,w\}$ in $E$ is also an edge after aplying the function on $v$ and $w$.
From the definition of the neighborhood I know

*

*$N(f(v)) = \{f(w) \in V^{'}: \{f(v), f(w) \} \in E^{'} \}$. Here I get all $f(w)$ which make an edge with $f(v)$ in $E^{'}$.

*$f(N(v)) = f(\{w \in V: \{v,w \} \in E \ \})$. This are all $w$ which make an edge with $v$ in $E{'}$ BEFORE aplying the function.

Here I'm basically stuck to make a senseful statement/argument/reasoning how the equality for the neighborhoods implies the isomorphism.

A: If $\{v,w\}$ is an edge, then $w\in N(v)$, then $f(w)\in f(N(v))=N(f(v))$, then $\{f(v),f(w)\}$ is an edge.
Conversely, if $\{f(v),f(w)\}$ is an edge, then $f(w)\in N(f(v))=f(N(v))$, then $f(w)=f(x)$ for some $x\in N(v)$. But as $f$ is objective, this means $x+v$, I i.e., $w\in N(v)$ and $\{v,w\}$ is an edge.


text:
Q: How does TF-IDF produce features for machine-learning ? What is different from a bag of words? I was hoping to get a brief explanation of how TF-IDF produces features that can be used for machine learning. What are the differences between bag of words and TF-IDF? I understand how TF-IDF works; but not how features are made with it and how these are used in classification/regression.
I am using scikit-learn; what does the following code actually do theoretically and in practice? I have commented it with my understanding and some questions, any help would be really appreciated :
  traindata = list(np.array(p.read_table('data/train.tsv'))[:,2]) #taking in data for TF-IDF, I get this
  testdata = list(np.array(p.read_table('data/test.tsv'))[:,2]) #taking in data for TF-IDF, I get this
  y = np.array(p.read_table('data/train.tsv'))[:,-1] #labels for our data

  tfv = TfidfVectorizer(min_df=3,  max_features=None, strip_accents='unicode',
        analyzer='word',token_pattern=r'\w{1,}',ngram_range=(1, 2), use_idf=1,smooth_idf=1,sublinear_tf=1) #making tf-idf object with params to dictate how it should behave

  rd = lm.LogisticRegression(penalty='l2', dual=True, tol=0.0001,
                             C=1, fit_intercept=True, intercept_scaling=1.0,
                             class_weight=None, random_state=None)

  X_all = traindata + testdata #adding data together
  lentrain = len(traindata) #what is this?
  tfv.fit(X_all) #is this where features are created? Are all words used as features? What happens here ?
  X_all = tfv.transform(X_all)#transforms our numpy array of text into a TF-IDF
  X = X_all[:lentrain]
  X_test = X_all[lentrain:]
  rd.fit(X,y) #train LR on newly made feature set with a feature for each word?

A: I guess idf is what make you confused here, since bag of words is the tf of word in the document, so why idf ? idf is a way to estimate how important the word is, usually, document frequency (df) is a good way to estimate how important a word in classfication, since when a word appear in less document (nba would always appear in documents belong to sports) show a better descrimination, so idf is in positive correlation to word's importance.

A: Tf-idf is the most common vector representation for documents. It takes into account the frequencies of the words in a text and also in the whole document corpus.
Obviously, this method is not scientifically backed, this means that it pragmatically works well in a bunch of contexts, like document similarity using cosine distance or other types of metrics, but was not derived from a mathematical proof.


text:
Q: air molecules in space Just wondering about escaped stuff in space like air and water molecules. Where would those molecules ultimately end up going?
Considering that there is other gravitational forces in space like planets , suns and black holes.
Is it possible that loose air molecules in space would all collect at the strongest gravitational source?

A: The more interesting question is what will happen to Earth. Loss of water by UV ionization of water and subduction of $H_2O$ by tectonic action will result in loss of water. On the other hand water and other elements in the aesthenosphere are replenished by volcanoes. There are general losses by atmospheres of planets. However, largely the biggest sequestration of molecules is by tectonic activity, and these are returned by some rate with volcanism.
Once they enter outer space these molecules may end up as interstellar gas. In time a supernova shock wave might gather some of them into the accretion of new stars and planets.

A: Different gases have different molecular masses and different planets have different thermal environments/ other forces that impart kinetic energy to the atmospheric gases.
So what gases get thrown off into spaces and what gases remain depends on their mass and available energies in the planet's atmosphere; primarily thermal energy. The molecules, like a rocket ship must reach escape velocity to leave the planet's surface. This wiki article Atmospheric Escape provides greater detail on the subject, and an excellent chart that compares escape velocity vs temperature, planet size and what gases are vulnerable to loss.


text:
Q: How to duplicate file input value? Is there any way to duplicate the file input value? in this case, if i have including a file in fileA input, the value of fileB is following fileA values, is there anybody know how to do this?
<input type="file" name="fileA" />
<input type="file" name="fileB" style="display:none;" />

A: You're not allowed to set the value of a file input element due to security issues.


text:
Q: Excel/VBA DB2 Timeout statement I'm connecting to a DB2 database through Excel VBA with the code below.  However, I've tried researching on connectionstrings.com as well as other websites the proper syntax for turning off the timeout so that I do not receive the "User Cancelled Operation" if the query takes a certain amount of time.  Right now, I'm using "Timeout=0", but I still get the error if my query contains more than 3,000 people.  Does anybody know the proper syntax to turn off the timeout?
With cn
.ConnectionString = "Driver={IBM DB2 ODBC DRIVER};"
 & "DBALIAS=" & Range(db_alias_range) & ";UID=" & username & ";PWD=" & Range(password_range) & ";Timeout=0;"
.Open
End With

A: I checked the IBM documentation for DB2 LUW version. It doesn't contain the keyword Timeout. You might want to use ReceiveTimeout. Check also all the other timeout options.
http://publib.boulder.ibm.com/infocenter/db2luw/v9/topic/com.ibm.db2.udb.apdv.cli.doc/doc/r0007964.htm


text:
Q: How to create a Jenkins job and/or user from a dockerfile? I am trying to set up a customised Jenkins 2 server from a dockerfile.
I use the official image and I want to be able to add things that I need like custom jobs and an admin user.
This is my dockerfile so far:
FROM openjdk:8-jdk

RUN apt-get update && apt-get install -y git curl && rm -rf /var/lib/apt/lists/*

ENV JENKINS_HOME /var/jenkins_home
ENV JENKINS_SLAVE_AGENT_PORT 50000

ARG user=jenkins
ARG group=jenkins
ARG uid=1000
ARG gid=1000

# Jenkins is run with user `jenkins`, uid = 1000
# If you bind mount a volume from the host or a data container,
# ensure you use the same uid
RUN groupadd -g ${gid} ${group} \
    && useradd -d "$JENKINS_HOME" -u ${uid} -g ${gid} -m -s /bin/bash ${user}

# Jenkins home directory is a volume, so configuration and build history
# can be persisted and survive image upgrades
VOLUME /var/jenkins_home

# `/usr/share/jenkins/ref/` contains all reference configuration we want
# to set on a fresh new installation. Use it to bundle additional plugins
# or config file with your custom jenkins Docker image.
RUN mkdir -p /usr/share/jenkins/ref/init.groovy.d

ENV TINI_VERSION 0.9.0
ENV TINI_SHA fa23d1e20732501c3bb8eeeca423c89ac80ed452

# Use tini as subreaper in Docker container to adopt zombie processes
RUN curl -fsSL https://github.com/krallin/tini/releases/download/v${TINI_VERSION}/tini-static -o /bin/tini && chmod +x /bin/tini \
  && echo "$TINI_SHA  /bin/tini" | sha1sum -c -

COPY init.groovy /usr/share/jenkins/ref/init.groovy.d/tcp-slave-agent-port.groovy

# jenkins version being bundled in this docker image
ARG JENKINS_VERSION
ENV JENKINS_VERSION ${JENKINS_VERSION:-2.19.2}

# jenkins.war checksum, download will be validated using it
ARG JENKINS_SHA=32b8bd1a86d6d4a91889bd38fb665db4090db081

# Can be used to customize where jenkins.war get downloaded from
ARG JENKINS_URL=https://repo.jenkins-ci.org/public/org/jenkins-ci/main/jenkins-war/${JENKINS_VERSION}/jenkins-war-${JENKINS_VERSION}.war

# could use ADD but this one does not check Last-Modified header neither does it allow to control checksum
# see https://github.com/docker/docker/issues/8331
RUN curl -fsSL ${JENKINS_URL} -o /usr/share/jenkins/jenkins.war \
  && echo "${JENKINS_SHA}  /usr/share/jenkins/jenkins.war" | sha1sum -c -

ENV JENKINS_UC https://updates.jenkins.io
RUN chown -R ${user} "$JENKINS_HOME" /usr/share/jenkins/ref

# for main web interface:
EXPOSE 8080

# will be used by attached slave agents:
EXPOSE 50000

ENV COPY_REFERENCE_FILE_LOG $JENKINS_HOME/copy_reference_file.log

USER ${user}

COPY jenkins-support /usr/local/bin/jenkins-support
COPY jenkins.sh /usr/local/bin/jenkins.sh
ENTRYPOINT ["/bin/tini", "--", "/usr/local/bin/jenkins.sh"]

# from a derived Dockerfile, can use `RUN plugins.sh active.txt` to setup /usr/share/jenkins/ref/plugins from a support bundle
COPY plugins.txt /usr/share/jenkins/plugins.txt
COPY plugins.sh /usr/local/bin/plugins.sh
COPY install-plugins.sh /usr/local/bin/install-plugins.sh

# Add the command line tools
COPY jenkins-cli.jar "$JENKINS_HOME"

# Create jobs
ARG job_name_1="my_super_job"
#ARG job_name_2="my_ultra_job"
# create the jobs folder recursively
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/workspace/
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/builds
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/builds/lastFailedBuild
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/builds/lastStableBuild
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/builds/lastSuccessfulBuild
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/builds/lastUnstableBuild
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/builds/lastUnsuccessfulBuild
RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_1}/builds/legacyIds
#RUN mkdir -p "$JENKINS_HOME"/jobs/${job_name_2}

## add the custom configs to the container
COPY ${job_name_1}_config.xml "$JENKINS_HOME"/jobs/${job_name_1}/config.xml
USER root
#RUN chmod 600 "$JENKINS_HOME"/jobs/${job_name_1}/config.xml
RUN java -jar /var/jenkins_home/jenkins-cli.jar -s http://localhost:8080 create-job my_super_job < /var/jenkins_home/jobs/my_super_job/config.xml
#COPY ${job_name_2}_config.xml "$JENKINS_HOME"/jobs/${job_name_2}/config.xml

# --Install plugins--
# Notice: Deprecated method which however works with a 'plugins.txt' file
#USER root
#RUN chmod 600 /usr/share/jenkins/plugins.txt
#RUN chmod 600 /usr/local/bin/install-plugins.sh
#RUN /usr/local/bin/plugins.sh /usr/share/jenkins/plugins.txt

# Notice: Recommended method with open case on Github [https://github.com/jenkinsci/docker/issues/348]
# Notice: Select whichever plugins you want
#RUN /usr/local/bin/install-plugins.sh \
#dashboard-view:2.9.10 \
#pipeline-stage-view:2.2 \
#parameterized-trigger:2.32 \
#bitbucket:1.1.5 \
#git:3.0.0 \
#github:1.22.4
# --Install plugins--

I have tried to create a job on build time by first launching a container, creating the job manually, saving the config.xml file, and then copying it in the image from the Dockerfile. Moreover, I am trying to replicate the files/folder structure when a job is being created.
But it is not working. The job is not appearing in Jenkins.
I also tried to use the jenkins-cli.jar, but as I understood , there must be a live Jenkins server to connect to and execute anything which is not the case at build time.
Finally, I suppose creating an admin user in build time must be way more complicated that creating a job...
So, does anyone have any experience on this?


text:
Q: React Js y Node Js - Solucionar error No 'Access-Control-Allow-Origin' Intento realizar una petición post desde React js con Axios y para ello utilizo Node Js como backend. Como tal el error es el siguiente:

Access to XMLHttpRequest at 'https://cotizador-ecuapanama-backend.herokuapp.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

He intentado varias de las soluciones que existen en problemas similares, pero ninguna funciona.
El código de Node Js es el siguiente.
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.get('/', (req, res) => {
    res.json('CORS Enabled 1')
})

app.post('/', (req, res) => {
    nodemailer.createTestAccount((err, account) => {
        const {name, lastName, email, company, phoneNumber, country, region, docUrl} = req.body;

        const htmlEmail = `

Cotizaciones Ecuapanama

Asunto: Cotización repuestos

Nombre: ${name}

Apellido: ${lastName}

Email: ${email}

Compañía: ${company}

Número telefónico: ${phoneNumber}

País: ${country}

Provincia/Estado: ${region}

Lista de productos

Enlace de descarga: ${docUrl}

        `
        let transporter = nodemailer.createTransport({
            host: "smtp.gmail.com",
            port: 465,
            auth: {
                user: "ecpancotizaciones@gmail.com",
                pass: '****************'
            }
        });
        let mailOptions = {
            from: email,
            to: "ecpancotizaciones@gmail.com",
            replayTo: email,
            subject: 'Cotizaciones Ecuapanama',
            html: htmlEmail
        }
        transporter.sendMail(mailOptions, (err, info) => {
            if (err) {
                return console.log(err)
            }
        });
    });
});

const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
    console.log(`Server on port ${PORT}`);
});

Código de React Js
const handleSubmit = async (e) => {
    e.preventDefault()

    let docUrl = await createDoc(products, items, stringId(8))

    if (name !== '' && lastName !== '' && email !== '' && phoneNumber !== '') {
        if (products.length > 0 || items.length > 0) {
            axios.post('https://cotizador-ecuapanama-backend.herokuapp.com/', {
                name,
                lastName,
                email,
                company,
                phoneNumber,
                country,
                region,
                docUrl
            });
            setName('');
            setLastName('');
            setEmail('');
            setCompany('');
            setPhoneNumber('');
            setAlert('Cotización enviada correctamente', true)
        } else (
            setAlert('No se han seleccionado productos', true)
        )
    } else {
        setAlert('Por favor, complete los campos', true)
    }
}


text:
Q: extjs: How to reduce space between multiple checkbox I am using checkboxgroup in my extjs file, but the spacing between 2 checkbox is too high. I need to reduce it. Please suggest changes.

A: Its Solved,
I just added columns: [50, 100],


text:
Q: how to solve error between axios and vuejs? I am working with net core and vuejs,
I followed the example of several pages until I got
here
I followed these steps but when I click on the button in the console the "response.data" brings me all the code from my system (typical call error I guess)
</template>

        Seleccione una imagen. <input id="file" type="file" accept=".jpg, .png" ref="file" v-
         on:change="handleFileUpload()" />

        <button class="btn btn-dark btn-block btn-xs m-b-5" @click="cargarImagen()"></button>

</template>

Config...
 export default {
name: 'cargarImagenes',
data() {
  return {
    file: null
  }
},
methods: {
  handleFileUpload() {
    this.file = this.$refs.file.files[0];
    console.log("la imagencita cargada", this.file);
  },
  cargarImagen() {
    let data = new FormData();
    data.append('file', this.file);
    this.$http.post("/Paciente/Imagen", data)
      .then(response => {
        this.imagenes = response.data;
        console.log("imagenCargada", response.data)
      })

and the error....(at least one of them)...
error in the response.data


text:
Q: Alamofire 4: Detecting No Network Connection I am able to find out if there's no network connection with Alamofire 3 since it enters the guard line if there's no WiFi.
Alamofire.request(.GET, url)
    .responseJSON { response in
        guard let object = response.result.value else {
            // no response <<<<<<<<<<<<<<<<<<<<<<<<<<
            return
        }
        let json = JSON(object)
        ...
        ...
}

, where url is a string.  The following code is for Alamofire 4. Even when the application detects no network connection, it doesn't enter the guard line.
Alamofire.request(url).responseJSON { response in
    guard let object = response.result.value else {
        // It doesn't enter here.
        return
    }
    let json = JSON(object)
    ...
    ...
}

I could use the SystemConfiguration framework to write a simple WiFi connection detection function.  But how could I let Alamofire 4 detects it?  I've read a few topics after running a search with [swift] [alamofire], by the way.
Thanks.

A: Alamofire have reachability which can detect network condition, still, in your case, just simply check for response.result.error instead of checking for the result value, if there's no connection or any other error then it wont be nil


text:
Q: How Tensorflow handles categorical features with multiple inputs within one column? For example, I have a data in the following csv format:
csv
col0  col1  col2  col3
1     A     E|A|C 3
0     B     D|F   2
2     C     |     2

Each column seperated by comma represent one feature. Normally, a feature is one-hot(e.g. col0, col1, col3), but in this case, the feature for col2 has multiple inputs(seperated by |).
I'm sure tensorflow can handle one-hot feature with sparse tensor, but I'm not sure whether it could handle features with multiple inputs like col2?
How should it be represented in Tensorflow's sparse tensor?
I am using the code below (but i don't know input method of col2)
col0 = tf.feature_column.numeric_column('ID')
col1 = tf.feature_column.categorical_column_with_hash_bucket('Title', hash_bucket_size=1000)
col3 = tf.feature_column.numeric_column('Score')

columns = [col0, col1, col3]

tf.estimator.DNNClassifier(
        model_dir=None,
        feature_columns=columns,
        hidden_units=[10, 10],
        n_classes=4
    )

Thanks for your help.

A: OK Looks like writing custom feature column worked for me with the same task.
I took HashedCategoricalColumn as a base, and cleaned up to work with strings only. Should add checks for type though.
class _SparseArrayCategoricalColumn(
    _CategoricalColumn,
    collections.namedtuple('_SparseArrayCategoricalColumn',
                           ['key', 'num_buckets', 'category_delimiter'])):

  @property
  def name(self):
    return self.key

  @property
  def _parse_example_spec(self):
    return {self.key: parsing_ops.VarLenFeature(dtypes.string)}

  def _transform_feature(self, inputs):
    input_tensor = inputs.get(self.key)
    flat_input = array_ops.reshape(input_tensor, (-1,))
    input_tensor = tf.string_split(flat_input, self.category_delimiter)

    if not isinstance(input_tensor, sparse_tensor_lib.SparseTensor):
      raise ValueError('SparseColumn input must be a SparseTensor.')

    sparse_values = input_tensor.values
    # tf.summary.text(self.key, flat_input)
    sparse_id_values = string_ops.string_to_hash_bucket_fast(
        sparse_values, self.num_buckets, name='lookup')

    return sparse_tensor_lib.SparseTensor(
        input_tensor.indices, sparse_id_values, input_tensor.dense_shape)

  @property
  def _variable_shape(self):
    if not hasattr(self, '_shape'):
        self._shape = tensor_shape.vector(self.num_buckets)
    return self._shape

  @property
  def _num_buckets(self):
    """Returns number of buckets in this sparse feature."""
    return self.num_buckets

  def _get_sparse_tensors(self, inputs, weight_collections=None,
                          trainable=None):
    return _CategoricalColumn.IdWeightPair(inputs.get(self), None)

def categorical_column_with_array_input(key,
                                        num_buckets, category_delimiter="|"):
  if (num_buckets is None) or (num_buckets < 1):
    raise ValueError('Invalid num_buckets {}.'.format(num_buckets))

  return _SparseArrayCategoricalColumn(key, num_buckets, category_delimiter)

Then it may be wrapped by embedding/indicator column.
Seems it is what you need.
It was first step for me. I need to handle column with values like "str:float|str:float...".


text:
Q: Conflict with definition of "face" I am given this definition of face from Convexity: An analytic viewpoint:
Definition: A face of a convex set $P$ is a set $F\subsetneq \overline{P}$ such that for every $x,y\in\overline{P}$ and for every $t\in(0,1)$, $tx+(1-t)y\in F \Rightarrow x,y\in F$.
But, I'm a little upset by this definition. We should hope that $F$ would be convex in every case. But, there's an easy counterexample. Take $F$ to be the extreme points of a triangle. Note that this is a valid face, as none of the points in $F$ are ever written as interior points. So the face property of this set is true by vacuity. Am I missing something here? Can we fix this by simply augmenting the definition to insist that $F$ is convex?


text:
Q: why can I login MacBook with different usernames of the same user I have only one user on my MacBookPro.
When I check the Users & Groups panel, I can see the username of this only user is "xxxyyy", then I also check the home directory of this only user in Terminal and it shows "/Users/xxx".
As a result, I can login my MacBook with the name "xxxyyy" or the name "xxx" as well.
It puzzles me a lot, Could anybody please give an explanation to this ~

A: When I entered my user name, it has, as standard, the long name and a short name based on the long name - that you can edit to be different if you want.
You can check in the system preferences : users and groups...


text:
Q: how to make my primary key in MySQL database Works for lower and higher case? I wanna make database which has table contains username and password.
and I want to make username primary key , to prevent duplication.
when I tried to make that , For Example :
1-Admin
2-admin
3-AdMiN
4-ADMIN
5-ADMin
etc ..
all these usernames aren't considered as duplicated.
how can I make these cases are considered as duplication ?
Thanks in advance

A: You can use a case sensitive coallation like utf8_general_cs on the table. Also your user name should not be the primary key. The PK should jsut be an auto_increment integer. If you want to make the username unique just make it a UNIQUE KEY.

A: The opposite as you want: Altering Mysql Table column to be case sensitive
The person which have post the question says the column is case insensitive by default in MySql.
Another post here say the same.

A: The table column in mySql is case sensitive by default and not the other way.


text:
Q: Struts 1 to Spring Migration - Strategy I have a legacy banking application coded in Struts 1 + JSP
Now requirement is to migrate the backend (for now MVC) to Springboot (MVC).
Later UI (JSP) will be migrated to angular.
Caveats
1.) Backend is not stateless
2.) Lot of data stored in session object
Approach

*

*Have 2 application running in parallel (Struts and Spring), and share the session object between the two, Storing session in Database, in memory (Redis) etc. This means lot of code changes, as currently session is manipulated across layers of JSP, action, service for every update/fetch

*Build complete Spring application and then make it live, which is again not feasible and we can't have user waiting.

*Marry Struts 1 and Spring in same app and later Divorce them, and removing struts components progressively.
Question
Is it feasible to have Struts 1 and Spring together in same web application.
Can 2 different servlets (ActionServlet & DispatcherServlet exists together), possible if i have 2 different context paths for spring & struts
Currently focus is to migrate MVC layer, service layer will not be an issue.
Also if i need to keep backend design of API to support REST in future, possible if i can design in such way.
Current
JSP -> Struts 1 MVC -> Service Layer -> DB
What we can built
JSP -> Struts 1 MVC <-> JSON Object parser <-> Spring REST MVC -> Service Layer -> DB
Future
Just remove JSP -> Struts MVC
Angular (or any other framework) -> Spring REST MVC -> Service Layer -> DB

A: My friend, it is so good to read your question! I lived the same hell you are about to enter using the very same stack...
Approach 3
Honestly I would never try it. The reason would be simple, we wouldn't want the risk of having old project and new project mixing with each other. Libraries from the legacy are very likely to conflict with libraries from the new project (same libraries, different versions) and you would then need to either refactor old code to allow use of the new version, or change libraries completely.
When migrating, you will want to keep your work on the legacy code to a minimal, to none if possible.
Approach 2
The perfect one, but as you said, it won't pay the bills. If you have the cash to work on it, then great, go for it, otherwise, you are for...
Approach 1
Strangulation, that's what worked for me. Start with a working shared login and then move to small functionalities. Think of a tree, you start by removing some small branches, them you move to nodes, until you are able to cut everything. As you remove the small functionalities, they should be made available on the new product (obviously you can't disrupt service otherwise you would go with approach 2).
More specifically, my suggestion is:
Back-end
1) Get the login working. In my case, legacy was all about session, but we didn't want that on the new product. So we implemented a method on the legacy code during login, which would call Oauth from the new product and store in the database the login information, just as you mentioned. The reason for this is on the front-end part of my reply.
2) Define how your legacy and back-end will live together and the resources to have both of them working (ram and CPU to be more precise).
2.1) If by any chance, your legacy runs on tomcat with custom libraries, you might have problems running your new product in a different context. If that happens, my suggestions, go for Docker (just get a close look on memory usage and make sure to limit them on your container(s)).
3) Start very small, replace functionalities related to creating new stuff which hold little to no logic (small crud, such as users, etc) then move to things that have mid-sized logic or that are really ugly on the legacy product and are used on day-to-day basis by your end-users.
4) All of the rest (by the time I left the company, we were not in this phase yet, so I can't provide much info on that).
5) Don't treat this project as a migration only. Get everyone on the page that this a new product. Old code should not be copied and pasted, it should be understood and improved using best practices.
5.1) Unit and integration tests as soon as possible, if your legacy have them, GREAT, compare results to make sure your refactoring didn't break anything or changed the expected outputs. THIS IS ESSENTIAL.
Front-end
1) Once you have the "unified" login working, you will be able to load the pages from the new product as if they were part of the legacy (you could even add a frame on the jsp of the legacy that will load your angular page, we did it and it works like a charm).
1.1) Not cute from a UI/UX perspective to have old and new pages, but it will add value to end-user and provide you with feedback from them once you release the pieces to production. Since your legacy now have access to the token (or whatever auth method you are using, that will be feasible).
2) Define the styles from the beginning. Don't get the job of UI/UX to later (like my team did). The sooner you figure out things such as colors, design, icons, etc, the less time you will waste on meetings that should discuss the release and its impact but are wasted discussing "this is not the color I wanted" or similar. Honestly, get UX defined before UI and make that crystal clear.
3) Design it as if you were designing a micro-services front-end. You might take a lot of time to get to that point, but if and when you do, the migration from the new architecture to micro-services will be much less traumatic.
Culture
I don't know the culture of your workplace, but mine was far from perfect, old people with old thinking into their comfort zones.
Get to change the workplace culture to adapt to what we currently have on the marketplace, old people sometimes tend to resist change, specially when they are technical and do not update on what's new out there. It will make much easier to replace people when they leave the company (because people do move on).
I heard they are still trying to run Scrum (as I mentioned I am no longer there), so there was a huge headache for developers defining What and How the migration of functionalities will take place.
Those are my two cents, hope they help you in some way, and I wish you the best of luck.

A: Since option 2 is not considerable because of business feasibility  let's talk about the other two.
Approach 1
If you push your session state as far back as appropriate datastore ( Redis/Memcache) and use a transparent mechanism to get the
session data and update any changes made by app server then you would not need to change any code interacting with session.
Any call to get session object from any piece of code in your application is delegated to container and it is container which
provides you with the object ( usually a mapping of sessionid and object is maintained). For container such as Tomcat I am aware of
session manager which can be replaced by just putting the jar in the container and pointing the config to the backend store. I have used
memcache based session manager successfully in production for a high traffic internet application.
Check this for Redis (https://github.com/pivotalsoftware/session-managers) and Redisson Tomcat manager (https://github.com/redisson/redisson/tree/master/redisson-tomcat), Memcache (https://github.com/magro/memcached-session-manager)
Using this will tranparently fetch/store session in respective datastore without changing any session related code in your application.
So the request with session id in cookie can land up on any of the tomcats ( hosting struts or Spring MVC app) and get the session
fetched from the backend store, made changes upon and tranparently stored back.
Approach 3
Is technically possible ( they are after all different servlets with different configuration responding to different url patterns)
but opens a lots of problems areas in terms of
dependency jars conflicts. But if you freeze the library versions of both the framework during the migration and somehow don't get any
conflict with a certain versions of your mix then it can be worth trying as eventually the struts library and it's dependencies will go away.
As for the Angular part - you can still still have the user info in the session and rest of the stateful interaction will need to be designed
in a series of stateless ( stateless on the middle tier as eventually you will need some state  - just that it will be pushed to the database) interactions.


text:
Q: Admob Unity Android Integration Problems I am in the process of releasing a game on the Play Store.
I had previously set up AdMob banner and interstitial ads using test ids. These worked perfectly. No problems. The app was then uploaded, with test ids being replaced with the correct add unit ids that I created in AdMob.
The ads did not show up, and the game would crash. The situation then gets weirder: after narrowing down the issue to AdMob, I reverted all add unit ids to their respective test ids. The odd behaviour is still there, even though functionally, the game is identical to what it was before attempting to release it.
One other thing to note is that prior to release, the app was not being signed under publishing settings. I also changed that back to what it was before. I'm not sure if it has something to do with signing the app... Previously compiled versions from before attempting to release still work fine.
Has anyone dealt with such an oddity, and is there a remedy?

A: So eventually I came right with all of this. I'm not sure what exactly happened to cause this. Could have been me accidentally deleting a file or folder. Could have been something got corrupted. Regardless, the solution was simple. Delete everything to do with admob from the unity project. Re-install. All is peachy.


text:
Q: How do I know which are the WSO2 critical security updates? When I launch WSO2 API Manager, I get the following notice:
There are 177 updates available for the product 'wso2am-3.2.0'.[WARNING] There
are 13 critical security updates for the product 'wso2am-3.2.0'. WSO2 strongly
recommends to apply these updates in production as soon as possible.

WSO2 doesn't bundle security updates, so I head to the GitHub issues. The problem is that if I go to the security tag, I don't see anything relevant to the 3.2.0 release: https://github.com/wso2/product-apim/issues?q=label%3Asecurity+is%3Aclosed
There is one "critical for 3.2.0": https://github.com/wso2/product-apim/issues?q=label%3ASeverity%2FCritical+label%3AAffected%2F3.2.0
There are two more using this deprecated tag: https://github.com/wso2/product-apim/issues?q=label%3ASeverity%2FCritical+label%3A3.2.0
So, it seems like what you have to do is look at the 4.0 milestones and cherry-pick those fixes and backport them.
Is there a tag I am missing? Is someone bundling these?
Thanks!

A: You can find the security advisors in here https://docs.wso2.com/display/Security/2020+Advisories


text:
Q: CSS - text-overflow not working with percentage based div In my div, it's defined the width in percentage based. But the text-overflow not working as i expect.
how to manage this?

div {
    width:50% /* instead giving 500px works!*/
    white-space: nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: You are missing a ; after your width property and hence your other property is ignored.. So even your width won't be applied nor white-space because the previous statement is not terminated with the ;
div {
    width:50%;
    white-space: nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    margin: auto;
}

Demo

A: Main problem is that your semicolon (;) is missing after the width property. Because of that it ignore first two properties. End semicolon is missing, both properties are recognize as one property.
div {
     width:50%; /* instead giving 500px works!*/
    white-space: nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

A: Only problem is semi-colon, ellipsis will work for percentage too.
Your code will be fine, once you add semi-colon


text:
Q: MySQL table design / architecture, table is too big I have a MySQL DB that contains a lot of text, I'm fetching data from a website and inserting it into a table.
I'm using a SSD HD (100GB) for the DB and I'm out of space, I think that something in the table structure made it too big, I can't predict the size of all the columns so I'm using varchar\text\medium text for most of the fields. when I insert all the data to the DB I monitor the errors and when I see that a certain field is too small for the data I'm trying to insert I'm increasing the size of the field (e.g. from varchar(1000) to varchar(2000)).
until now I have about 1.8M~ rows, I think that I'm doing something wrong.
here is the structure of my table -
CREATE TABLE `PT` (
  `patID` int(11) NOT NULL,
  `Title` varchar(450) DEFAULT NULL,
  `IssueDate` date DEFAULT NULL,
  `NoFullText` tinyint(1) DEFAULT NULL,
  `Abstract` text,
  `ForeignReferences` varchar(15000) DEFAULT NULL,
  `CurrentUSClass` varchar(2200) DEFAULT NULL,
  `OtherReferences` mediumtext,
  `ForeignPrio` varchar(900) DEFAULT NULL,
  `CurrentIntlClass` varchar(3000) DEFAULT NULL,
  `AppNum` varchar(45) DEFAULT NULL,
  `AppDate` date DEFAULT NULL,
  `Assignee` varchar(300) DEFAULT NULL,
  `Inventors` varchar(1500) DEFAULT NULL,
  `RelatedUSAppData` text,
  `PrimaryExaminer` varchar(100) DEFAULT NULL,
  `AssistantExaminer` varchar(100) DEFAULT NULL,
  `AttorneyOrAgent` varchar(300) DEFAULT NULL,
  `ReferencedBy` text,
  `AssigneeName` varchar(150) DEFAULT NULL,
  `AssigneeState` varchar(80) DEFAULT NULL,
  `AssigneeCity` varchar(150) DEFAULT NULL,
  `InventorsName` varchar(800) DEFAULT NULL,
  `InventorsState` varchar(300) DEFAULT NULL,
  `InventorsCity` varchar(800) DEFAULT NULL,
  `Claims` mediumtext,
  `Description` mediumtext,
  `InsertionTime` datetime NOT NULL,
  `LastUpdatedOn` datetime NOT NULL,
  PRIMARY KEY (`patID`),
  UNIQUE KEY `patID_UNIQUE` (`patID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

what should I do? I have about 20% of the data (which means I'm going to need 350GB~ space) what is the performance impact here? should I divide the table into several tables over several HDs? I'm going to use sphinx to index and query the data in the end.

A: All of the non-TEXT column values are stored in one 8KB record (undivided unit of space on your HDD). TEXT column values are stored as pointers to external blocks of data.
These kinds of structures (very text oriented) are better handled by NOSQL (Not Only SQL) databases like MongoDB.
But I suspect that there are a lot of things you could do regarding how to handle & structure your data in order to avoid saving huge chunks of text.
The process of structuring a database to avoid repetitious information and to allow for easy updates (update in one place - visible everywhere) is called normalization.
If the data you're storing in those big VARCHARs (ex.: Inventors length 1500) is structured as multiple elements of data (ex.: names of inventors separated by a coma) then you can restructure your DB table by creating an inventors table and referencing to it.


text:
Q: Change opacity of an element and rotate it via jquery animation I need to rotate my $('.closebtn') element and at the same time change its opacity.
css:
.closebtn{
    position: absolute;
    right: 15px;
    top: 5px;
    font-size: 35px;
    text-align: center;
    cursor: pointer;
    border-spacing: 0px;
    opacity: 0;}

I'm trying to use jquery animation:
$('.closebtn').animate(
                {  borderSpacing: 90 }, {
                step: function(now,fx) {
                  $(this).css('-webkit-transform','rotate('+now+'deg)');
                  $(this).css('-moz-transform','rotate('+now+'deg)');
                  $(this).css('transform','rotate('+now+'deg)');
                },
                duration: 200,
            });

Any ideas on how can I change opacity inside my animation event handler?

A: You could do it using CSS3 only too. This example is using CSS3 only on button one and jQuery on button 2.

$(document).ready(function(){
  var $elem = $('.closebtn2');
  $({ deg: 0 }).animate({ deg: 359 }, {
    duration: 5000,
    step: function (now) {
      var opacity = (1 * now / 359);
       $elem.css({
         transform: 'rotate(' + now + 'deg)',
         opacity: opacity
       });
    }
  });
});
.closebtn{
    font-size: 35px;
    text-align: center;
    cursor: pointer;
    border-spacing: 0px;
    opacity: 1;
}

.animate {
  -webkit-animation: animation-name 4s 1s; /* Safari 4+ */
  -moz-animation:    animation-name 4s 1s; /* Fx 5+ */
  -o-animation:      animation-name 4s 1s; /* Opera 12+ */
  animation:         animation-name 4s 1s;
}

@-webkit-keyframes animation-name {
  0%   { opacity: 0; transform: rotate(0deg); }
  100% { opacity: 1; transform: rotate(360deg); }
}
@-moz-keyframes animation-name {
  0%   { opacity: 0; transform: rotate(0deg); }
  100% { opacity: 1; transform: rotate(360deg); }
}
@-o-keyframes animation-name {
  0%   { opacity: 0; transform: rotate(0deg); }
  100% { opacity: 1; transform: rotate(360deg); }
}
@keyframes animation-name {
  0%   { opacity: 0; transform: rotate(0deg); }
  100% { opacity: 1; transform: rotate(360deg); }
}

<button class="closebtn animate">Test</button>

<button class="closebtn closebtn2">Test</button>


text:
Q: How to add not null constraint to existing column in MySQL I have table name called "Person" with following column names
P_Id(int),
LastName(varchar),
FirstName (varchar).

I forgot to give NOT NULL Constraint to P_Id.
Now I tried with following query to add NOT NULL Constraint to existing column called P_Id,
1. ALTER TABLE  Person MODIFY  (P_Id NOT  NULL);
2. ALTER TABLE Person ADD CONSTRAINT NOT  NULL NOT NULL (P_Id);

I am getting syntax error....

A: Just use an ALTER TABLE... MODIFY... query and add NOT NULL into your existing column definition. For example:
ALTER TABLE Person MODIFY P_Id INT(11) NOT NULL;

A word of caution: you need to specify the full column definition again when using a MODIFY query. If your column has, for example, a DEFAULT value, or a column comment, you need to specify it in the MODIFY statement along with the data type and the NOT NULL, or it will be lost. The safest practice to guard against such mishaps is to copy the column definition from the output of a SHOW CREATE TABLE YourTable query, modify it to include the NOT NULL constraint, and paste it into your ALTER TABLE... MODIFY... query.

A: Try this, you will know the difference between change and modify,
ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]

*

*You can change name and datatype of the particular column using CHANGE.

*You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

A: Would like to add:
After update, such as
ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get
ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)


text:
Q: How to update pandas dataframe columns based on another dataframe faster? I am using the below code to update a dataframe based on another one. However, it is dramatically slow. I am looking for a solution.
for inx, row in df1.iterrows():
    dfTmp = df2.loc[df2['KANR'].astype(str) == row['KANR']]
    if dfTmp.empty:
        continue

    if dfTmp.loc[dfTmp['STATUS'] == "F5"].empty is False:
        timestamp = "%s %s" % (dfTmp.loc[dfTmp['STATUS'].astype(str) == "F5"].iloc[0, ]["Date"],
                               dfTmp.loc[dfTmp['STATUS'].astype(str) == "F5"].iloc[0, ]["Time"])
        df1.set_value(inx, 'F5', timestamp)

A: You can use merge, which is optimized for speed and will be much faster for this kind of match task, something like this, assuming you don't have duplicated date time for each KANR:
df2['F5'] = df2['Date'].astype(str) + " " + df2['Time'].astype(str)
to_join = df2.loc[df2['STATUS'].astype(str) == 'F5', ['F5', 'KANR']].groupby('KANR').head(1)
df1.merge(to_join, how='left', on = 'KANR')