text:
Q: Convergence of fixed point iteration for polynomial equations
I'm looking for the solution $x$ of
$$x^n+nx-n=0.$$

Thoughts: From graphing it for several $n$ it seems there is always a solution in the interval $[\tfrac{1}{2},1)$. For $n=1$, the solution is the fraction $\tfrac{1}{2}$ and for higher $n$, the solution shifts to the right.
I then saw that the equation reads $$F_n(x)=x$$ with
$$F:[0,1]\to[0,1],\ \ \ \ \ \ F_n(x):=1-\frac{x^n}{n}.$$
I think I got all conditions together for making the iteration of $F_n$'s the general soluton for the equation. I computed $$x_5=F_5(F_5(F_5(F_5(F_5(F_5(F_5(F_5(x_S)))))))),$$
with starting value $x_S=\tfrac{1}{2}$ and it seems to be the solution of the equation for $n=5$.
Related wikipedia links: Fixed point theorem, Banach fixed-point theorem, Fixed point iteration;
I wonder:

Have I found the soluton and can one evaluate the iteration to a closed form?

Might be that it involves polylogs. edit: At least Wolfram Alpha claims to know $$n(x)=W\left(\frac{-\log(x)}{x-1}\right)/\log(x),$$ even if $n(x)$ isn't too interesting.

In my case, how is the relation between the function $x(n)$ and (I think) the fixed point combinator for the iteration?
Does it matter what I choose for $x_S$ here? Can one relate it's value and the number for necessary iteration for a good agreement with the real value?

(Also, are there any results on which polynomial equations this technique works? The property $F:[0,1]\to[0,1]$ seemed accidental to me.)

A: You can get a good approximation of the solution as $n \to \infty$ by supposing that $x$ can be written as an asymptotic series in powers of $1/n$, say
$$
x \sim 1 + \sum_{k=1}^{\infty} \frac{a_k}{n^k},
$$
then substituting this into the given equation and calculating the coefficients recursively.  For example we can calculate $a_1$ and $a_2$ by writing
$$
\begin{align*}
0 &\approx \left(1 + \frac{a_1}{n} + \frac{a_2}{n^2}\right)^n + n\left(1+\frac{a_1}{n} + \frac{a_2}{n^2}\right) - n \\
&= \left(1 + \frac{a_1}{n} + \frac{a_2}{n^2}\right)^n + a_1 + \frac{a_2}{n} \\
&= a_1 + e^{a_1} + \frac{2a_2 (1+e^{a_1}) - a_1^2 e^{a_1}}{2n} + O\left(\frac{1}{n^2}\right).
\end{align*}
$$
By sending $n \to \infty$ we get that $a_1 + e^{a_1} = 0$ and so
$$
a_1 = -W(1),
$$
where $W$ is the Lambert W function.
Then, setting the coefficient of $1/n$ to $0$ and substituting the above value of $a_1$ we find that
$$
a_2 = \frac{W(1)^3}{2(1+W(1))}.
$$
Thus we have
$$
x \approx 1 - W(1) n^{-1} + \frac{W(1)^3}{2(1+W(1))} n^{-2}.
$$
This approximation seems to be pretty good.  Below is a plot which compares the numerical roots with the asymptotic formula for $1 \leq n \leq 10$.

This series might actually converge for large enough $n$ but I don't see how to prove it.  If the implicit function theorem could be employed then you would be set.

A: Isn't this simply the result of the Banach fixed-point theorem?
In you case one must prove that there exists $q$ such that:
$$d(F_n(x),F_n(y))=\frac{|y^n-x^n|}{n} \le q |x-y|$$
Which is true for all $n>1, x>0$, with say, $q=0.9$, So that it doesn't matter what $x_S$ you choose.
Regarding a closed form - convergence of an iterative series says nothing about the existence of such a closed form solution.


text:
Q: TIdSSLIOHandlerSocketOpenSSL and TLS protocol I have a Windows desktop application developed in XE2 that pulls data from a remote server in JSON format. I use Indy 10 to manage this.
The application was working fine until I received an email from the server provider people:
"...the only protocol for securing the communication will be TLS 1.2. Older versions (TLS.1.0, TLS.1.1 or SSLv3) will no longer work."
They advise using TLS 1.2 or superior.
Since then I have the following runtime error

First chance exception at $7518845D. Exception class
  EIdOSSLUnderlyingCryptoError with message 'Error connecting with SSL.
  Error connecting with SSL. error:1408F10B:SSL
  routines:SSL3_GET_RECORD:wrong version number'.

I found out the error is triggered when I call FidHTTP.Post (FidHTTP is an instance of TidHTTP).
I have amended the method that creates the classes in the following way:
constructor TMyClass.Create;

begin
  FidHTTP := TidHTTP.Create(nil);
  FidHTTP.HTTPOptions := FidHTTP.HTTPOptions - [hoForceEncodeParams];
  FidHTTP.Intercept := TIdLogFile.Create(FidHTTP);

  TIdLogFile(FidHTTP.Intercept).Filename := 'c:\'+s+'.log';
  TIdLogFile(FidHTTP.Intercept).Active := true;
  {$IFDEF VER230}
  FIdSSL := TIdSSLIOHandlerSocketOpenSSL.Create;
  FIdSSL.SSLOptions.Method:=sslvTLSv1; // I have added this line
  {$ENDIF}
end;

but now I have another error:

First chance exception at $7518845D. Exception class EIdSocketError
  with message 'Socket Error # 10054 Connection reset by peer.'.

I have googled this but I have found information regarding FTP only, which is not my case.
What am I doing wrong? Is it because I have an old version of Indy without sslvTLSv1_2 option or?

A: sslvTLSv1 is for TLS v1.0 only.  To use TLS v1.2, you need to use sslvTLSv1_2 instead:
FIdSSL.SSLOptions.Method := sslvTLSv1_2;

Or:
FIdSSL.SSLOptions.SSLVersions := [sslvTLSv1_2];

If your version of Indy does not have sslvTLSv1_2 then you will have to upgrade.  The current version of Indy is v10.6.2.5494.
Also, make sure you are using at least OpenSSL v1.0.1, which is the version that first added support for TLS v1.2.  The latest version of OpenSSL that Indy 10 supports is v1.0.2.
Also, you need to remove the {$IFDEF VER230} from your code.  That is limiting your code to creating the TIdSSLIOHandlerSocketOpenSSL only when compiling for XE2 specifically.  By default, TIdSSLIOHandlerSocketOpenSSL enables TLS v1.0 only, so you will have to change the code to always create the TIdSSLIOHandlerSocketOpenSSL unconditionally in order to enable TLS v1.2 regardless of the compiler version used (at least until this ticket is implemented).

redpajama_set_name: RedPajamaStackExchange


text:
Q: D I - Method or Tabulator method collapses at $\sin^2(x)$ - why is that? I have  recently learned about the tabulator or D-I Method.
This method - as far as I got it right - is just a variation of integration by parts. It works out very well, even in cases where you get a repetition in one line. But for $\int \sin^2(x) \ dx$ it doesn't work out and ends in $0=0$.  I tried to do it several times, checked each step and it doesn't work out.
Why is that?
Edit:
Calculations (this is the same as when using the DI-Method):
$$\int sin²(x) \\= -sin(x)*cos(x) - \int cos(x)*cos(x) \\=-sin(x)*cos(x)+cos(x)*sin(x) + \int cos(x)*sin(x) $$ at this spot you can see that each part is canceling out each other.


text:
Q: foreach loop not finding var So basically the loop runs trough a text file which is in my project folder.
 And what I'm trying to do while printing them out to a web-page is finding one specific id which would be $id I've tried echoing out $id to see if is actually there and it is. So I'm not too sure why this isn't working. Keep in mind I am new to PHP so its probably something dumb :p
 <?php
    require 'steamauth/steamauth.php';
    require 'steamauth/userInfo.php';

    $id = $_SESSION['steamid'];
    $pid = $id;
    echo "pid = $pid \n" . "
";
    $lines = file('admins.txt');
    foreach ($lines as $line_num => $line) {
        echo "" . htmlspecialchars($line) . "
\n";
        if($line == $id){
          echo "found";
        }
    }
    ?>

A: First:-
session_start(); missing on the page code
Then
Based on manual:-http://php.net/manual/en/function.file.php
Use FILE_IGNORE_NEW_LINES like below:-
$lines = file('admins.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Now check:-
 if($line == $id){
    echo "found";
 }

Or
if(strpos($id,$line)!==false){
  echo "found";
}

A: Add a trim before comparring to the line content to $id
<?php
  require 'steamauth/steamauth.php';
  require 'steamauth/userInfo.php';

  $id = $_SESSION['steamid'];
  $pid = $id;
  echo "pid = $pid \n" . "
";
  $lines = file('admins.txt');
  foreach ($lines as $line_num => $line) {
        echo "" . htmlspecialchars($line) . "
\n";
        if(trim($line) == trim($id)){
           echo "found";
        }
  }
?>


text:
Q: Remove a timestamp from string So I have been trying to take off a timestamp from a string, a file name to be more specific.
I tried making a substring, but the size of the timestamp is variable.
For example, sometimes it's like this:
2016-05-05 03:45:00.907text.txt

and sometimes like this:
2016-05-05 03:45:00.83text.txt

Maybe regex is the answer?
The string to be processed will always have a timestamp plus a filename. The filename can start with numbers or letters.
I forgot to say it's for Java.

A: this sed will cleanup the timestamp
$ echo "2016-05-05 03:45:00.83text.txt" |
 sed -r 's/^[0-9]{4}(-[0-9]{2}){2} ([0-9]{2}:){2}[0-9]{2}\.[0-9]{2,3}//'

text.txt

will also work for the other case, however it will not know the difference if your file name is "7text.txt".

A: String input = "2016-05-05 03:45:00.907text.txt";
String regex = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d+";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

if(matcher.find()){
    String output  =  matcher.group();

    Date date = formatter.parse(output);
    long time = date.getTime();

    System.out.println(time);
}

You have to find the date with regex, then you convert the String in a proper Date and then you can get the timestamp.

A: This will remove leading timestamps:
filename = filename.replaceAll("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(\\.\\d+)?", "");

But you won't be able to distinguish the end of a "short" timestamp and the start of the other part when the other part start with a digit.
This also handles when the timestamp has whole seconds (and no fractional ending).


text:
Q: Jquery is it possible to refresh page if download start? i have an application which the user choose the checkbox,
press button download and download the data based on checked box,
the problem is if i am not checking any checkbox, it will show error message in div alert.
and when i check and click download, download run well, but the error message is still in the page.
how to detect if download start, automatically page refresh, or how to solve it more easily?
my download code :
  public function downloadFile($name)
  {
    $storagePath = "/opt/tmp/";

    // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)

    if (!is_file("$storagePath/$name")) {
        throw new \yii\web\NotFoundHttpException('The file does not exists.');
    }
    return Yii::$app->response->sendFile("$storagePath/$name", $name);
  }

how i can make detect download start and refresh it using jquery?

A: You need to Hide the Error message as soon as you click on Checkbox.
something Like that
$("#id").hide();
Here id is the Id of the error message div

A: You can detect download start when client click download link.
Before send request!
Something like this:
$('#download-link').on('click', function() {
    setTimeout(function() {
        document.location.reload();
    }, 500);
    return true;
});


text:
Q: with_pg_search_highlight with associated field Currently I am using trying to perform pg_search with with_pg_search_highlight on an associated table field and I am getting:
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "pg_search_17ebb3b05265b756196ca6"

I am using rubygem
pg_search -v 2.3.2
on my item model
item.rb
belongs_to :brand

include PgSearch::Model
pg_search_scope :associated_search,
  against: [[:name, 'A']],
  associated_against: {brand: [:code]},
  using: {
    tsearch: {
      prefix: true,
      dictionary: "english",
      negation: true,
      highlight: {
        StartSel: '',
        StopSel: '',
        MaxWords: 10,
        MinWords: 2,
        ShortWord: 4,
        HighlightAll: false,
        MaxFragments: 3,
        FragmentDelimiter: '
---
'
      }
    }
  }

items_controller.rb
Item.associated_search(params[:query]).with_pg_search_highlight

A: Dug a little bit through the issues in the gem and it's actually a 2 year old bug which hasn't been addressed yet.
https://github.com/Casecommons/pg_search/issues/350


text:
Q: Passing / forwarding events to a sub-object in Qt I'm working on a Qt application and I have a problem with getting mouse events where I want them.
Here's a high-level view of what I have (there are other things going on at each level that dictate the need for the views and scenes):
+----------------
| App Window       -- QMainWindow
| +--------------
| | View           -- QGraphicsView   --- Grabbing mouse events here for Mode 1
| | +------------
| | | Scene        -- QGraphicsScene
| | | +----------
| | | | Image      -- QGraphicsPixmap --- Want to grab mouse events here for Mode 2
| | | |

In Mode 1, I'm grabbing the event mousePressEvent at the View level.  In Mode 2, I'd like to grab the mouse events at the Image level.  Before I overloaded mousePressEvent in the View class I was able to get all events in Image.  Now that I'm capturing at View I can't get mouse events in Image.  Image is private within Scene and I don't want to expose it.
There is no inheritance here; each item is an object created by the object above it.
Reading through this question Qt -- pass events to multiple objects? makes it seem like I want to capture mouse events at the Image level and let them go back up; however, I would still need to create mousePressEvent in View and I'd be right back where I am.
Is there a way to turn on/off event handling during run-time and make sure they get to the lower levels?  Or is there a way to forward events to a sub-object?

A: Is there a way to turn on/off event handling during run-time and make sure they get to the lower levels? Or is there a way to forward events to a sub-object?
There are some possibilities :

*

*Use QGraphicsScene::sendEvent(...) to send event to items. As the scene() is accessible from any items by the method scene(). Maybe it's a solution for you.

*You can use the static method QCoreApplication::sendEvent (...) for doing the same job.

*Event filter can do the job, see Events and event filters chapter.

*You can use specific install event system of Graphicsview framework (QGraphicsItem::sceneEventFilter(...) and installSceneEventFilter(...)

At runtime, it's possible to turn off/on mouse event with the method QGraphicsItem::setAcceptedMouseButtons(...).
There are many other possibilities...
Hope it helps !


text:
Q: String indices must be integers I am getting the following error:

string indices must be integers, not str

How can I resolve this?  Here is the code:
    if args['params']['text'][:5] == '!temp':
        degreeChar = u'\u00b0'
        url = 'http://api.worldweatheronline.com/free/v1/weather.ashx?q=' + args['params']['text'][9:] + '&format=json&num_of_days=1&key=' + WeatherAPIkey
        json_obj = urllib.urlopen(url)
        data = json.load(json_obj)
        temp = int(data['data']['current_condition']['temp_C'])
        ws.send('5:::' + genMessage('chatMsg', channel, username, 'Temperature in ' + args['params']['text'][6:] + ': ' + temp + degreeChar + 'C'))

The error is on this line: temp = int(data['data']['current_condition']['temp_C'])
The API is here: img

A: data['data']['current_condition']  returns a list so you need use:
 `data['data']['current_condition'][0]['temp_C']`

to access the dict inside the list.


text:
Q: KnpSnappy and CKditor : how to allow bold tags to my pdf? I'm working in Symfony with Ckeditor to write some content, and I use KnpSnappy to convert them as a PDF file.
My issue is when I use tags like bold or italic to my text, I can't see it to my pdf.
There is an option to allows tag to KnpSnappy ?
Update : solved, It was because of the option striptags, I removed it and it fixed my issue :
<p>{{ annonce.contactAdresse|striptags|replace({' ':''})|raw }}</p>


text:
Q: Is the word "work" a noun or a verb in "Get something to work"? We are having some dispute over the sentence below.

I've tried everything under the sun to fix this lock, but I just can't get it to work.

All of us agree on the meaning of the sentence.
However, what we are arguing about is whether the word "work" in this sentence is a verb or a noun.
Is it a verb or a noun???

A: It's a verb.
If work were a noun, then to would be the directional preposition, as in "Dad leaves the house and travels to work," meaning that he goes to his place of work. Work in your sentence doesn't mean "place of work".
You can replace the all-purpose get with a verb like make: "I just can't make it work." In that sentence, work is definitely a verb.
You could qualify your existing sentence: "I just can't get it to work for me," which again shows that work cannot be a noun and must be a verb.
The to is not a preposition but the particle necessary with an infinitive verb.


text:
Q: Convert and Return generic value from database I want to return values from database.
I defined table where each columns has defined Type of data:
public enum TTableOffers
{
    [CStringValue("id")]
    [CType(typeof(Integer))]
    Id = 0,
    [CStringValue("project")]
    [CType(typeof(String))]
    ProjectId = 1,

}
So column "id" is type Integer, "project" is String etc.
Now I want to get value from specific column by this enum like this:
    public T Value<T>(Enum enumColumn) where T : class // <<< class!
    {
        object aResult = m_aSqlDataReader.GetValue(columnIndex); // Here the aResult is filled with correct value (object) from database (working fine)

        ...

        Type colType = CTypeAttribute.GetTypeValue(enumColumn); // Read the type from table - Integer or String (this is working fine)

        if (aResult == null)
            return default(T);
        else
        {
           if (Convert.IsDBNull(aResult))
              return default(T);
           else
              aResult = ChangeType(aResult, colType); // Change the type to desired one --- here is the crash!!!
        }

        return (T)aResult;
       // here I also tried: return aResult as T;
    }

As method ChangeType I use this one: Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32, mscorlib]].
Column with type String are working fine, but with Integer there is a problem.
As I cannot use Int32 (which is struct) so I defined my own class Integer like this:
public class Integer : IComparable, IFormattable, IConvertible, IComparable<Integer>, IEquatable<Integer>
{
    int value = 0;

    public Integer(int value)
    {
        this.value = value;
    }

    // (Integer)123
    public static implicit operator Integer(int value)
    {
        return new Integer(value);
    }

    // (int)myInteger
    public static implicit operator int(Integer integer)
    {
        if (integer == null)
            integer = new Integer(default(int));

        return integer.value;
    }

    public static int operator +(Integer one, Integer two)
    {
        return one.value + two.value;
    }

    public static Integer operator +(int one, Integer two)
    {
        return new Integer(one + two);
    }

    public static int operator -(Integer one, Integer two)
    {
        return one.value - two.value;
    }

    public static Integer operator -(int one, Integer two)
    {
        return new Integer(one - two);
    }

    public static bool operator >(Integer one, int two)
    {
        return (int)one > two;
    }

    public static bool operator <(Integer one, int two)
    {
        return (int)one < two;
    }

    public static bool operator >(int one, Integer two)
    {
        return one > (int)two;
    }

    public static bool operator <(int one, Integer two)
    {
        return one < (int)two;
    }

    public TypeCode GetTypeCode()
    {
        throw new NotImplementedException();
    }

    public bool ToBoolean(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public byte ToByte(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public char ToChar(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public DateTime ToDateTime(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public decimal ToDecimal(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public double ToDouble(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public short ToInt16(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public int ToInt32(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public long ToInt64(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public sbyte ToSByte(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public float ToSingle(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public string ToString(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public object ToType(Type conversionType, IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public ushort ToUInt16(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public uint ToUInt32(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public ulong ToUInt64(IFormatProvider provider)
    {
        throw new NotImplementedException();
    }

    public int CompareTo(object obj)
    {
        throw new NotImplementedException();
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        throw new NotImplementedException();
    }

    public int CompareTo(Integer other)
    {
        throw new NotImplementedException();
    }

    public bool Equals(Integer other)
    {
        throw new NotImplementedException();
    }
}

For String everything is working fine but for Integer I got "Invalid cast from 'System.Int32' to 'Code.Data.Integer'." exception.
I set breakpoints on EVERY line in class Integer and no one is hit. I assume I am missing something important in class Integer as it is never hit and no conversion is done.
What am I missing?

A: Your problem is that your value, in this case an int, does not implement the IConvertible interface. From the MSDN documentation:

ChangeType is a general-purpose conversion method that converts the
  object specified by value to conversionType. The value parameter can
  be an object of any type, and conversionType can also be a Type object
  that represents any base or custom type. For the conversion to
  succeed, value must implement the IConvertible interface, because the
  method simply wraps a call to an appropriate IConvertible method. The
  method requires that conversion of value to conversionType be
  supported.

Additionally, from the documentation on IConvertible:

If you implement the IConvertible interface, your implementation will
  be called automatically by the Convert.ChangeType method if the Object
  parameter is an instance of your implementing type and the Type
  parameter is a common language runtime type.

You are calling this in the reverse fashion: going from a CLR type (int) to your custom type, which is not going to work.

A: Why don't you make two Value method like this:
public Nullable<T> Value<T>(Enum enumColumn) where T : struct {...}

public string Value(Enum enumColumn) {...}

The first one will allow you to return null integers among others.
Much cleaner, no? :)


text:
Q: Split string in using bash not working in debian server I want to split ins_data string using " of " and get 2 numbers into 2 variables.
My code lokes like this.
#!/usr/bin/env bash

ins_data="3,998 of 5,903"
IFS=' of ' read -ra ins_data_arr <<< ${ins_data}
total_ins=${ins_data_arr[1]//,}
missed_ins=${ins_data_arr[0]//,}

echo $total_ins
echo $missed_ins

This code works fine in my mac os machine.
But it is not working in Debian server.

A: $ ins_data="3,998 of 5,903"

$ IFS=' of ' read -ra ins_data_arr <<< ${ins_data}
$ declare -p ins_data_arr
declare -a ins_data_arr='([0]="3,998" [1]="" [2]="5,903")'

$ IFS=' of ' read -ra ins_data_arr <<< "$ins_data"
$ declare -p ins_data_arr
declare -a ins_data_arr='([0]="3,998" [1]="" [2]="5,903")'

I found this behaviour quite confusing at first: where is that empty field coming from? I thought that any sequence of  IFS characters would delimit fields.
That is true for the default value of IFS.
This is a very subtle behaviour of IFS related to Word Splitting:

If IFS has a value other than the default, then sequences of the whitespace characters space, tab, and newline are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter.

Thus: sequences of zero or more whitespace and a single non-whitespace IFS character delimit fields.
The empty array element at index 1 is the empty string between the "o" and the "f".
This test reinforces that claim:
$ IFS=' of ' read -ra ins_data_arr <<< "3,998 off 5,903"
$ declare -p ins_data_arr
declare -a ins_data_arr='([0]="3,998" [1]="" [2]="" [3]="5,903")'

Now we have an empty field between "o" and "f", and an empty field between "f" and "f".
I assume this is new behaviour as of bash version 4 -- the default bash on OSX is version 3.something. The answer to the behaviour change will be somewhere in here: https://git.savannah.gnu.org/cgit/bash.git/tree/CHANGES?h=bash-4.4

Found it: https://git.savannah.gnu.org/cgit/bash.git/tree/CHANGES?h=bash-4.4#n3970

zz. The word splitting code now treats an IFS character that is not space,
     tab, or newline and any adjacent IFS white space as a single delimiter, as
     SUSv3/XPG6 require.

This documents "changes between this version, bash-3.1-alpha1,
and the previous version, bash-3.0-release." -- so your "it works" version of bash must be very old.

Having said all that, my recommended fix: don't use a custom IFS, just account for the fact that you'll read 3 words:
$ read -r missed of total <<<"$ins_data"
$ declare -p missed of total
declare -- missed="3,998"
declare -- of="of"
declare -- total="5,903"
$ echo "${missed//,/}"
3998
$ echo "${total//,/}"
5903


text:
Q: Identical calls to arc producing different sizes I'm trying to figure out why drawing a shape, then drawing over it in a new color (as though to highlight it), and then re-drawing the original (un-highlighting it) is leaving traces of the highlighted color.
I've reproduced the issue in this fiddle.  The wedge is drawn in a light-blue color.  There's a red button that'll draw over it in red, then another button that re-draws the original shape.  All parameters are identical (except for the color), but yet after clicking the button to reset the color, there's a faint trace of red over the wedge.
Before:

After:

Here's the relevant code:
drawWedge(250, 250, 200, 0, 18, "rgb(150, 254, 223)");

$("#red").click(function () {
    drawWedge(250, 250, 200, 0, 18, "rgb(255, 0, 0)");
});

$("#back").click(function () {
    drawWedge(250, 250, 200, 0, 18, "rgb(150, 254, 223)");
});

function d2r(degrees) {
    return degrees * (Math.PI / 180.0);
}

function drawWedge(centerX, centerY, r, start, end, color) {
    context.beginPath();
    context.moveTo(centerX, centerY);
    context.arc(centerX, centerY, r, d2r(start), d2r(end), false);
    context.closePath();
    context.fillStyle = color;
    context.fill();
}

A: This question was already answered, but I wanted to give a little more thorough explanation.

When you draw at a diagonal, your passing through "parts" of pixels (show in my example). So what does the browser do to the part of the pixel outside of the shape? It uses anti-aliasing (anti-aliasing is always on by default for browsers) to color the rest of the pixel (if you didnt have anti-aliasing the line would look jagged). If you notice, the faint trace of red is not a bright red because its getting blended due to anti-aliasing. And the reason you see it is because when you draw your shape on the canvas, the faint trace of red is not part of your shape, its part of the pixel on the outside of your shape.
Now as the answer mentioned, you can call clearRect to clear the canvas. However, you should read this SO question as it explains things in more detail (the selected answer is not as good as the second answer). Also, ever wonder why they call it a "canvas"? Think of an actual art canvas used by artists, once they paint on the canvas there is no way to take it off unless you get a new canvas or paint over it!

A: When drawing on canvas, it just keeps stacking things on top of each other until you clear it. The easiest way to clear it is ctx.clearRect(0,0,width,height)
I put that in your drawWedge function here:
http://jsfiddle.net/X7deh/1


text:
Q: Binding to same port using INADDR_ANY and a specific IP simultaneously A simple experiment in python (on Windows) shows that I am able to bind to the same port on both the wildcard address and a specific address simultaneously:
import socket
import select

MY_PORT = 13337

sany = socket.socket()
sany.bind(('', MY_PORT))
sany.listen(0)

sloc = socket.socket()
sloc.bind(('127.0.0.1', MY_PORT))
sloc.listen(0)

socks = [sany, sloc]
ready, _, _ = select.select(socks, [], [])
print socks.index(ready[0])

Conceptually, they overlap in what they're supposed to cover. Continuing the experiment by connecting to ('127.0.0.1', 13337) from a different prompt indicates that the more specific socket 'wins' (i.e. 1 is printed).
I'm seeing similar behavior in SOCK_DGRAM sockets.
My questions are as follows:

*

*Is this behavior somehow contractual (Winsock, Berkeley Sockets, etc.)?

*How should this behave for multicast sockets?

*How should this behave on *nix systems?

A: What you describe is possible on Windows Server 2003 and later, but only when the two bind() calls are made by the same user account:
Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE

Enhanced socket security was added with the release of Windows Server 2003. In previous Microsoft server operating system releases, the default socket security easily allowed processes to hijack ports from unsuspecting applications. In Windows Server 2003, sockets are not in a sharable state by default. Therefore, if an application wants to allow other processes to reuse a port on which a socket is already bound, it must specifically enable it. If that is the case, the first socket to call bind on the port must have SO_REUSEADDR set on the socket. The only exception to this case occurs when the second bind call is performed by the same user account that made the original call to bind. This exception exists solely to provide backward compatibility.
The table below describes the behavior that occurs in Windows Server 2003 and later operating systems when a second socket attempts to bind to an address previously bound to by a first socket using specific socket options.

...
The socket binding behavior changes when the socket bind calls are made under different user accounts. The table below specifies the behavior that occurs in Windows Server 2003 and later operating systems when a second socket attempts to bind to an address previously bound to by a first socket using specific socket options and a different user account.

In earlier Windows versions, the behavior was different:

The table below describes the behavior that occurs in Windows XP and earlier when a second socket attempts to bind to an address previously bound to by a first socket using specific socket options.

...
In the case where the first call to bind sets either SO_REUSEADDR or no socket options at all, the second bind call will "hijack" the port and the application will be unable to determine which of the two sockets received specific packets sent to the "shared" port.


text:
Q: Как превратить строку в формулу? Допустим, я прошу пользователя ввести любую формулу графика, для простоты пусть это будет
"y = x^n" где n — любая степень, которую может ввести пользователь

Строку можно получить так:
 String str = formulafield.getText();
 str.toLowerCase();
 String [] arr = str.split("y = ");
 String formula = arr[0];

можно заменить "^" на "pow(r,"
formula.replaceAll("^", "pow(r,");

Получится строка
 "xpow(r,n"

Затем находим символы.
int xIndex = formula.indexOf('x');
int commaIndex = formula.indexOf(',');

Затем заменяем 'r' на 'x'
formula.replase('r', 'x');
if(xIndex==0){
formula.replace('x','');
}

получим строку
 "pow(x,n"

Далее добавим к этой строке скобку и точку с запятой
 String fullformula = formula.concat(");");

Можно ли как-то получившуюся строку
 "pow(x,n);"

Превратить в
 Math.pow(x, n); ?

Подскажите алгоритм

A: Можно использовать exp4j https://www.objecthunter.net/exp4j/
String str = formulafield.getText();
str.toLowerCase();
String [] arr = str.split("y = ");
String formula = arr[0];
Expression e = new ExpressionBuilder(formula)
.variables("x")
.build()
.setVariable("x", 2.3);
double result = e.evaluate();

Это отработанная вещь вычисление выражений.


text:
Q: How to call event on the select only when condition meets in Vuejs I have a method that opens the modal.
I need to open modal only when select component option value is "I have a coupon"
 <Select
          placeholder="Want to get a discount"
          @click="openModal"
          v-model="coupon.source"
        >
      ...

How can I conditionally fire that openModal() method only when value is v-model is "From Groupon" selected otherwise don't call any method at all?

A: You can check the "From Groupon" condition in the on click function,openModal and decide what action need to be taken


text:
Q: How to define multiple emacs faces? I'm trying to define some emacs font faces to do some custom highlighting. This seems to work when I define them individually:
(defface my-r-face `((t (:foreground "red")))  "Red highlight")
(defvar m-r-face 'my-r-face "Red.")
(defface my-g-face `((t (:foreground "green")))  "Green highlight")
(defvar m-g-face 'my-g-face "Green.")
(defface my-b-face `((t (:foreground "#0088ff")))  "Blue highlight")
(defvar m-b-face 'my-b-face "Blue.")
....etc

However I have a few dozen of these and I want to define them all in one go from some kind of colour table:
(setq ctable '(("red" "r")
           ("orange" "o")
           ("yellow" "y")
           ("#88ff00" "gy")
           ("green" "g")
           ("#00ff88" "gc")
           ("cyan" "c")
           ("#0088ff" "bc")
           ("blue" "b")
           ("purple" "bm")
           ("magenta" "m")
           ("#ff0088" "rm")
           ("grey" "lg")
           ("white" "w") ))

My difficulty is with assembling the symbol names for each face, ie concatenating "my-" and "-face" onto either side of an entry from the table. I have discovered (intern) that can make a new symbol from a string, however this symbol is then not acceptable to (defface), as it seems what I am doing is equivalent to (defface 'my-r-face ..., and defface doesn't like the quoted symbol, and expects (defface my-r-face .. instead. My attempt is as follows:
(dolist (tpl ctable)
  (defvar (intern (concat "my-" (nth 1 tpl) "-face"))
    (quote (intern (concat "my-" (nth 1 tpl) "-face"))) "colour")
  (defface (intern (concat "my-" (nth 1 tpl) "-face"))
    `((t (:foreground ,(car tpl)))) "Highlight" :group 'fortran)
)

Running this results in
Lisp error: (wrong-type-argument symbolp (intern (concat "fegs-" (nth 1 tpl) "-face")))
  (defvar (intern (concat "fegs-" ... "-face")) (quote (intern ...)) "colour")

Can anyone shed some light on what I'm doing wrong, or if I'm barking up the wrong tree entirely and there is a better way of doing this?
Thanks.

A: You can avoid eval:
(defconst my-ctable '(...))

(defmacro my-init-cfaces ()
  `(progn
    ,@(mapcar (lambda (tpl)
               `(defface ,(intern (format "my-%s-face" (nth 1 tpl)))
                  '((t :foreground ,(car tpl)))
                  ,(format "Face for color %s." (car tpl))
                  :group 'fortran))
              my-ctable)))

(my-init-cfaces)

A: defvar is an special form, defface is a macro (so arguments are passed unevaluated).  Have you tried to use something in the line of
(eval `(defface ,(intern "foo") '((t (:foreground "red"))) "Highlight" :group 'fortran))

(eval `(defvar ,(intern "bar")))

A: The complete code that worked in the end is as follows:
(setq ctable '(("red" "r")
           ("orange" "o")
           ("yellow" "y")
           ("#88ff00" "gy")
           ("green" "g")
           ("#00ff88" "gc")
           ("cyan" "c")
           ("#0088ff" "bc")
           ("blue" "b")
           ("purple" "bm")
           ("magenta" "m")
           ("#ff0088" "rm")
           ("grey" "lg")
           ("white" "w") ))

(dolist (tpl ctable)
  (let ((fname (concat "fegs-" (nth 1 tpl) "-face")))
    (eval `(defface ,(intern fname) '((t (:foreground ,(car tpl)))) "Highlight" :group 'fortran))
    (eval `(defvar ,(intern fname) ',(intern fname)))
  )
)

My defvar line is slightly different as this allows the face to be picked up by the highlighting code elsewhere as  a global variable.


text:
Q: What's So Difficult About `uint64_t`? (Conversion Assembly From `float`) I am in a situation where I need to compute something like size_t s=(size_t)floorf(f);.  That is, the argument is a float, but it has an integer value (assume floorf(f) is small enough to be represented exactly).  While optimizing this, I discovered something interesting.
Here are some conversions from float to integers (GCC 5.2.0 -O3).  For clarity, the conversion given is the return value of a test function.
Here's int32_t x=(int32_t)f:
    cvttss2si   eax, xmm0
    ret

Here's uint32_t x=(uint32_t)f:
    cvttss2si   rax, xmm0
    ret

Here's int64_t x=(int64_t)f:
    cvttss2si   rax, xmm0
    ret

Last, here's uint64_t x=(uint64_t)f;:
    ucomiss xmm0, DWORD PTR .LC2[rip]
    jnb .L4
    cvttss2si   rax, xmm0
    ret
.L4:
    subss   xmm0, DWORD PTR .LC2[rip]
    movabs  rdx, -9223372036854775808
    cvttss2si   rax, xmm0
    xor rax, rdx
    ret

.LC2:
    .long   1593835520

This last one is much more complex than the others.  Moreover, Clang and MSVC behave similarly.  For your convenience, I've translated it into pseudo-C:
float lc2 = (float)(/* 2^63 - 1 */);
if (f<lc2) {
    return (uint64_t)f;
} else {
    f -= lc2;
    uint64_t temp = (uint64_t)f;
    temp ^= /* 2^63 */; //Toggle highest bit
    return temp;
}

This looks like it is trying to compute the first overflow mod 64 correctly.  That seems kindof bogus, since the documentation for cvttss2si tells me that if an overflow happens (at 2^32, not 2^64), "the indefinite integer value (80000000H) is returned".
My questions:

*

*What is this really doing, and why?

*Why wasn't something similar done for the other integer types?

*How can I change the conversion so as to produce similar code (only output lines 3 and 4) (again, assume that the value is exactly representable)?

A: Since cvttss2si does a signed conversion, it will consider the numbers in the interval [2^63, 2^64) to be out of range, when in fact they are in range for unsigned. Hence, this case is detected and mapped to the low half in the float, and a correction is applied after conversion.
As for the other cases, notice that the uint32_t conversion still uses a 64 bit destination which will work for the full range of the uint32_t and further truncation is implicit by using the low 32 bits of the result according to calling convention.
In terms of avoiding the extra code, it depends on whether your input may fall into the above mentioned range. If it can, there is no way around it. Otherwise, a double cast first to signed then to unsigned could work, ie. (uint64_t)(int64_t)f.


text:
Q: Automated tests using MessageBox with MessageBoxButtons.YesNoCancel I'm using the TestStack.White framework for a WinForms .Net 2.0 C# application's coded automated regression tests. I have no problem handling OK/Cancel message boxes (MessageBox.Show(...)) but I'm having trouble handling the Yes/No buttons when using MessageBoxButtons.YesNoCancel. Thing is, I do not know what the button names are.
These work in my test jigs:
    public ButtonTestJig OkButton
    {
        get { return new ButtonTestJig(Window, "okButton"); }
    }

    public ButtonTestJig CancelButton
    {
        get { return new ButtonTestJig(Window, "cancelButton"); }
    }

Does anybody know the equivalent "cancelButton" for the NO button and the equivalent "okButton" for the YES button? Or perhaps even better, how to find them. My googling failed me.
Thanks

A: You can use http://uiautomationverify.codeplex.com/releases/view/11366 or inspect.exe (which comes in the windows SDK to see what the automation Id's for those controls are.


text:
Q: What Geotransformation (NAD27 to WGS84) to use for Gulf of Mexico?
I'm working with datasets that are spread out across the northern part of the Gulf of Mexico, stored in NAD 27.  I've been told the polygons shown above were obtained from BOEMRE (formerly known as MMS).
I'm projecting it into Web Mercator (WGS 84), and would like to choose the most suitable geotransformation.  Arcmap presents a long list of choices, but I'm not sure which one would be the overall best fit.  Is there a map somewhere showing how the error varies for various geotransformations?
Better yet, is there an industry standard geotransformation for GoM whose parameters I could plug into a custom geotransformation?

A: Esri has a support page and a pdf file that lists the general geographic extents of the different transformations. Somewhere there's a page that contains pdf maps of the NAD transformations, but I haven't found that one yet. This document show projections and transformations by specific areas of interest, but doesn't list a transformation for the Gulf of Mexico

A: The documentation you are looking for is originally in NOAA Technical Memorandum NOS NGS-50: see p. 10 for the definitions of the NADCON regions in the Gulf/Caribbean region and pp. 28-30 for error estimates.
You can also download the original grid files from the NADCON pages and inspect them to check actual errors within any region covered by those grids.

A: For individual offshore oil leases, EPSG lists several possibilities that are NAD27/WGS84.
EPSG online registry
Almost all have comments that say replaced by 15851 (NAD 1927 To WGS 1984 (79)) which uses NADCON conus grid file). US Bureau of Land Management (BLM) states that NADCON (conus) should be used for NAD27/NAD83 conversions, but I can't turn up a reference for it.


text:
Q: ¿Cómo interceptar datos vacíos de un marco de datos? Tengo un marco de datos con valores que faltan (ni siquiera Nan, simplemente no hay nada). Quiero contar la información que falta.
    S02Q18b_01  S02Q18b_02  S02Q18b_05  S02Q18b_06  S02Q18b_07  S02Q18b_08  S02Q18b_09
0
1
2   -1      0           0
3   -1
4
... ... ... ... ... ... ... ...
4570    -1  -1  1       -1      1
4571    -1  1   1   0   -1  -1  1
4572    -1  1   0   1   -1  -1  1
4573    -1  -1  1   -1  -1  -1  1
4574    0   0   0   0   0   0

De hecho missing = np.where(df[filter_col].applymap(lambda x: x == '')), me envía de vuelta:
(array([], dtype=int64), array([], dtype=int64))

Actualización
con .isnull().sum(min_count=1)
Intenté tambien:
miss_values_count = df[filter_col].isnull().sum(min_count=1)
miss_values_count = miss_values_count[miss_values_count != 0]

print(f"Number of columns with missing values: {miss_values_count.shape[0]}")
if miss_values_count.shape[0]:
    print("Null value count per column: ")
    for name, miss_vals in miss_values_count.items():
        p = miss_vals > 1
        print(f"  - For column name '{name}' there are{'n' if p else ''} "
              f"{miss_vals} ({100*(miss_vals/df[filter_col].size)}) missing values{'s' if p else ''}.")

Pero me da Number of columns with missing values: 0
con fillna.(np.nan)
Intente la solucion de Rubiales Alberto pero no rellena las valores que faltan:

A: Prueba a hacer esto, siendo "dataframe" tus datos.
import numpy as np
import pandas as pd

dataframe.fillna(np.nan, inplace=True) #rellenamos todos los valores que faltan con NaN
dataframe.isna().sum() #Sumamos los NaN de cada columna

EDICIÓN 2
Vale viendo tu update, ya sé lo que ocurre, lo que pasa es que esas celdas son un string con espacios o sin nada. Para cambiarlo tienes que hacer lo siguiente:
#realizamos las operaciones para cambiar las celdas vacias o con espacios a nan
dataframe = dataframe.replace('\s+', np.nan, regex=True).replace('', np.nan)

#sumamos para saber los números de nan por columnas
dataframe.isna().sum()

Lo que hacemos en el primer replace es sustituir todos las celdas que tienen un espacio o más por, nan. Y con el segundo replace sustituimos todas las celdas que son strings vacios por nan.


text:
Q: Python, fastest way to iterate over regular expressions but stop on first match I have a function that returns True if a string matches at least one
regular expression in a list and False otherwise. The function is called
often enough that performance is an issue.
When running it through cProfile, the function is spending about 65% of
its time doing matches and 35% of its time iterating over the list.
I would think there would be a way to use map() or something but I can't
think of a way to have it stop iterating after it finds a match.
Is there a way to make the function faster while still having it return
upon finding the first match?
def matches_pattern(str, patterns):
    for pattern in patterns:
        if pattern.match(str):
            return True
    return False

A: The way to do this fastest is to combine all the regexes into one with "|" between them, then make one regex match call.  Also, you'll want to compile it once to be sure you're avoiding repeated regex compilation.
For example:
def matches_pattern(s, pats):
    pat = "|".join("(%s)" % p for p in pats)
    return bool(re.match(pat, s))

This is for pats as strings, not compiled patterns.  If you really only have compiled regexes, then:
def matches_pattern(s, pats):
    pat = "|".join("(%s)" % p.pattern for p in pats)
    return bool(re.match(pat, s))

A: The first thing that comes to mind is pushing the loop to the C side by using a generator expression:
def matches_pattern(s, patterns):
    return any(p.match(s) for p in patterns)

Probably you don't even need a separate function for that.
Another thing you should try out is to build a single, composite regex using the | alternation operator, so that the engine has a chance to optimize it for you. You can also create the regex dynamically from a list of string patterns, if this is necessary:
def matches_pattern(s, patterns):
    return re.match('|'.join('(?:%s)' % p for p in patterns), s)

Of course you need to have your regexes in string form for that to work. Just profile both of these and check which one is faster :)
You might also want to have a look at a general tip for debugging regular expressions in Python. This can also help to find opportunities to optimize.
UPDATE: I was curious and wrote a little benchmark:
import timeit

setup = """
import re
patterns = [".*abc", "123.*", "ab.*", "foo.*bar", "11010.*", "1[^o]*"]*10
strings = ["asdabc", "123awd2", "abasdae23", "fooasdabar", "111", "11010100101", "xxxx", "eeeeee", "dddddddddddddd", "ffffff"]*10
compiled_patterns = list(map(re.compile, patterns))

def matches_pattern(str, patterns):
    for pattern in patterns:
        if pattern.match(str):
            return True
    return False

def test0():
    for s in strings:
        matches_pattern(s, compiled_patterns)

def test1():
    for s in strings:
        any(p.match(s) for p in compiled_patterns)

def test2():
    for s in strings:
        re.match('|'.join('(?:%s)' % p for p in patterns), s)

def test3():
    r = re.compile('|'.join('(?:%s)' % p for p in patterns))
    for s in strings:
        r.match(s)
"""

import sys
print(timeit.timeit("test0()", setup=setup, number=1000))
print(timeit.timeit("test1()", setup=setup, number=1000))
print(timeit.timeit("test2()", setup=setup, number=1000))
print(timeit.timeit("test3()", setup=setup, number=1000))

The output on my machine:
1.4120500087738037
1.662621021270752
4.729579925537109
0.1489570140838623

So any doesn't seem to be faster than your original approach. Building up a regex dynamically also isn't really fast. But if you can manage to build up a regex upfront and use it several times, this might result in better performance. You can also adapt this benchmark to test some other options :)

A: Adding to the excellent answers above, make sure you compare the output of re.match with None:
>>> timeit('None is None')
0.03676295280456543
>>> timeit('bool(None)')
0.1125330924987793
>>> timeit('re.match("a","abc") is None', 'import re')
1.0200879573822021
>>> timeit('bool(re.match("a","abc"))', 'import re')
1.134294033050537

A: It's not exactly what the OP asked, but this worked well for me as an alternative to long iterative matching.
Here is some example data and code:
import random
import time
mylonglist = [ ''.join([ random.choice("ABCDE") for i in range(50)]) for j in range(3000) ]

# check uniqueness
print "uniqueness:"
print len(mylonglist) == len(set(mylonglist))

# subsample 1000
subsamp = [ mylonglist[x] for x in random.sample(xrange(3000),1000) ]
# join long string for matching
string = " ".join(subsamp)

# test function 1
def by_string_match(string, mylonglist):
    counter = 0
    t1 = time.time()
    for i in mylonglist:
        if i in string:
            counter += 1
    t2 = time.time()
    print "It took {} seconds to find {} items".format(t2-t1,counter)

# test function 2
def by_iterative_match(subsamp, mylonglist):
    counter = 0
    t1 = time.time()
    for i in mylonglist:
        if any([ i in s for s in subsamp ]):
            counter += 1
    t2 = time.time()
    print "It took {} seconds to find {} items".format(t2-t1,counter)

# test 1:
print "string match:"
by_string_match(string, mylonglist)
# test 2:
print "iterative match:"
by_iterative_match(subsamp, mylonglist)


text:
Q: ARKit – Session's configuration check How would I check for the currently running tracking configuration?
if sceneview.session.configuration == ARWorldTrakingConfiguration() {
    print("foo")
}

Doesn't do the job. I understand that I am comparing some types, so the statement is never true. But is there any way?

A: All ARSession configurations are subclasses of ARConfiguration so you can  check if your current configuration is of the appropriate type like below:
if sceneView.session.configuration is ARWorldTrackingConfiguration {
    print("configuration is of type ARWorldTrakingConfiguration")
}

A: You have to use your if-statement inside DispatchQueue.main.asyncAfter() to give an extra time (0.5 second) for your configuration to be initialised and run.
Here's a code:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let configuration = ARWorldTrackingConfiguration()
    sceneView.session.run(configuration)

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {

        if self.sceneView.session.configuration == ARWorldTrackingConfiguration() {
            print("Current configuration is a WorldTracking")
        } else {
            print("Current configuration isn't known")
        }
    }
}

P.S. Remember, it doesn't work on iOS Simulator and on Playground.


text:
Q: I am receiving an error when trying to build a docker image from a project in Gitlab CI I am new to Devops and I am trying to build a Docker image in a self-hosted gitlab instance. I have installed Gitlab from Docker image, I have installed gitlab-runner from Docker image and I can see the runner inside Gitlab and I have configured it for a certain project, I created a gitlab-ci.yml file and went to jobs to build the project to a Docker image. It says running for a few second after that it gives me this error:
ERROR: Failed to remove network for build
ERROR: Preparation failed: Got permission denied while trying to connect to the Docker
daemon socket at unix:///var/run/docker.sock: Get
http://%2Fvar%2Frun%2Fdocker.sock/v1.25/info: dial unix /var/run/docker.sock: connect:
permission denied (docker.go:858:0s)

I have tried a solution to give permision with this command:
sudo chmod 666 /var/run/docker.sock

Here is the gitlab-ci.yml file content:
# This file is a template, and might need editing before it works on
your project.
# Build a Docker image with CI/CD and push to the GitLab registry.
# Docker-in-Docker documentation:
https://docs.gitlab.com/ee/ci/docker/using_docker_build.html
#
# This template uses one generic job with conditional builds
# for the default branch and all other (MR) branches.
docker-build:
# Use the official docker image.
image: docker:latest
stage: build
services:
- docker:dind
before_script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD"
$CI_REGISTRY
# Default branch leaves tag empty (= latest tag)
# All other branches are tagged with the escaped branch name (commit
ref slug)
script:
- |
  if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
    tag=""
    echo "Running on default branch '$CI_DEFAULT_BRANCH': tag =
'latest'"
  else
    tag=":$CI_COMMIT_REF_SLUG"
    echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag"
  fi
- docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" .
- docker push "$CI_REGISTRY_IMAGE${tag}"
# Run this job in a branch where a Dockerfile exists
rules:
- if: $CI_COMMIT_BRANCH
  exists:
    - Dockerfile

And after that I retried to build the project but I get the same error.
Please help and thanks in advance


text:
Q: Git: trigger a "robot" commit when a master branch is merged I have master branch and other branches from my team members. master is sync with the product. I want to have another additional commit that upgrading version (change a file content say 'release.md') when an MR is merged into master from other branches, no matter what changes have been made.
This is for a gitlab v11.10.4, running on ubuntu 16.04 system.
At the beginning, I want to set a git hook (update hook) on gitlab server-side. In the script, I need to do: 1) check if target merge branch is master 2) if it does, check the commit's message is not like "upgrading version" 3) if not then add an additional commit before merge.
touch release.md
git commit -a -m "upgrade version"

I know that in an update hook I could get args which are "refname", "oldrev" and "newrev", theoretically I could parse info from this to finish step 1) and step 2). but I have no idea how to add additional commit to this branch.
It is easy to have it in local hook (git add . blahblah), but in that way every developer in my team gonna need to maintain a hook file in .git of any repo. Which is error prune. Any idea and suggestions?

A: An update hook cannot add new commits.1  The function of an update hook is to either accept or reject a name-change.2  To accept the name-change, exit zero.  To reject the name-change, exit nonzero.
What you should do for this case is verify that the user making a change to refs/heads/master is making a correct change.  If not, reject the change-request.  The user doing the git push must make the correct annotation.  You simply verify that the annotation exists and is correct.  If it does not, produce an error message: this error will be displayed to the user running git push, prefixed by the word remote:.
In other words, if you do:
echo "ERROR"
echo "ERROR: you must supply a commit with a correct message"
echo "ERROR: ... describe enough to tell the user what that is ..."
echo "ERROR"
exit 1

the user will see the ERROR messages prefixed by remote:, as in:
remote: ERROR
remote: ERROR: you must supply a commit with a correct message
remote: ...

1Technically, it is possible to do sneaky things in Git hooks.  However, branch name changes require locking.  The lock is already in place for the proposed update at this point, so the update hook can't add new commits to the proposed-update branch name, as that requires locking the lock that's already locked, which means waiting for the user that has the lock, which is yourself, to finish verifying the operation.  This is a classic deadlock.  You could in theory update some other branch, since you are then not waiting for yourself.  But it's a bad idea in general.
2The "change" is one of: create a reference (e.g., new branch), delete a reference (e.g., delete a branch), or update in place (e.g., add new commits to a branch, or remove commits from a branch due to a force-push operation).  You tell which kind of change by inspecting the old and new hash IDs, and using git rev-list if/as needed.

A: If you don't want to enforce that policy on the developer side, and still insists on adding that "upgrading version" metadata ("meta" as "it is not a "data", which is "source code"), then you might consider git notes.
git notes adds, removes, or reads notes attached to objects, without touching the objects themselves.
That means your update, or even post-receive hook can check:

*

*the new commit was done on master

*the new commit was a merge commit (two parent)

In that case, it can add a note to that commit, specifying it is an "upgrade version" kind. Without having to mess with the history of commits.


text:
Q: Set up Kerberos Authentication with Delegation on IIS 7 w/ Windows Server 2008 Situation:
I have a .NET asmx web service deployed on my web server. This service calls a service on another server (our SharePoint server, if that's relevant). I want to impersonate/delegate the call to the SharePoint service from my web service by using the credentials of the client.
Problem:
I'm getting a 401 response back from the SharePoint service when I call MY Web Service and it calls SharePoint.
Setup:

*

*My web server is running IIS 7. The app pool is running under "Network Service"

*On my Windows Server 2003 domain controller the web server has "Trusted for Delegation (Kerberos Only)" enabled.

*In ISS my app has Anonymous Authentication Disabled, Impersonation Enabled, and Windows Authentication Enabled with all three providers enabled (Negotiate:Kerberos, Negotiate, and NTLM)

*The SharePoint server is set up with Anonymous Enabled, Impersonation enabled and Windows Authentication Enabled with ONLY provider NTLM enabled.

I can see on the SharePoint logs that when I run locally in Visual Studio a username is getting passed through (and the service works correctly) but when I run it on the web server NO username is on the log file and I get a 401 error
What an I setting up wrong to make the Kerberos delegation work?
Ideas? Thanks!

A: Platform:
Using IIS7 this is what I did on BOTH servers. The first server and the second that we want the Kerberos authentication to "hop" to.
Step 1:
For the IIS site that has the services in it that you are calling (on each server) go into IIS manager, click on the site on the left under Connections and open up the "Authentication" section under IIS. Set "ASP.NET Impersonation" to Enabled and 'Windows Authentication" to Enabled. All other options under Authentication (Ananymous, Forms, etc.) should be be set to Disabled.
Under "Windows Authentication" right click and select "Providers". Set the only provider to be "Negotiate:Kerberos" (This forces Kerberos. If you want, after you get Kerberos working you can use both the "Negotiate" and "NTLM" providers and remove "Negotiate:Kerberos" so that clients unable to do Kerberos can connect. Note: I currently have mine set to "Negotiate" and "NTLM" and it seems to work)
Under "Windows Authentication" right click and select "Advanced Settings". Uncheck the "Enable Kernal-mode" box. (My Extended Protection option was set to off, didn't try anything else)
Step 2:
For each server you have to set up SPNs. The SPNs would be the following (either A OR B):
A:
If your app pool is running under an IDENTITIY that is a DOMAIN ACCOUNT add the following SPNs to THAT DOMAIN ACCOUNT on the domain controller
http/COMPUTER_NETBIOS_NAME
http/COMPUTER_NETBIOS_NAME.FULLY_QUALIFIED_DOMAIN_NAME
http://COMPUTER_NETBIOS_NAME.FULLY_QUALIFIED_DOMAIN_NAME

(if your not running on the default port, also add an additional 3 entries with the port name attached: http/COMPUTER_NETBIOS_NAME:PORT etc.)
B:
If your app pool is running under the IDENTITY "NetworkService" then add the same SPNs as above except replace "http" with "HOST" BUT ADD THEN TO COMPUTER_NETBIOS_NAME on your domain controller.
I'm still working to implement this in production, but this is what works for me in my Test environment. I'll keep this updated as I find out more.
Note:
This works if you are using the COMPUTER_NETBIOS_NAME directly in the url when you connect. If you are using a alias (www.mysite.mydomain.com) or the IP address directly this will not work. I believe, although I have not fully tested it, that you would have to folle the steps above but replace COMPUTER_NETBIOS_NAME with the alias or IP address when adding the SPNs. (or add it with both the netbios and the alias/ip, not really sure)
Also, if you get an error about a setting not being valid for integrated... after you turn on the "ASP.NET Impersonation" then you might need to add
<validation validateIntegratedModeConfiguration="false" />

to your web.config in the system.webServer section

A: Try this:
Move Negotiate to the top of the Providers' list. And, in the applicationHost.config file usually under C:\Windows\System32\inetsrv\config, add useKernelMode="true" useAppPoolCredentials="true" to the <windowsAuthentication> tag under the <location> tag for your application, like below:
<location path="YOUR_APPLICATION_PATH">
    <system.webServer>
        <security>
            <authentication>
                <anonymousAuthentication enabled="false" />
                <windowsAuthentication enabled="true" useKernelMode="true" useAppPoolCredentials="true">
                    <providers>
                        <clear />
                        <add value="Negotiate" />
                        <add value="NTLM" />
                    </providers>
                </windowsAuthentication>
            </authentication>
        </security>
    </system.webServer>
</location>

A: Delegation requires Kerberos.  You'll have to make the SharePoint server support authentication with Kerberos.


text:
Q: Asymmetry between definitions of curvature in 2-space and 3-space Edit
I am coming back to this question because although the answer I received cleared the matter a little bit I am still confused by the difference between the 2D and 3D case.
So in 2D case one can define abstractly the normal versor N(s) as the unique vector such that the ordered set $\{T(s), N(s)\}$ forms an orthonormal, positively oriented basis of $\mathbb{R}^2.$
Then one sees that since $\dot{T}(s)=\frac{d}{ds}T(s)$ is orthogonal to $T(s),$ one may take $N(s)$ to be equal to $\frac{\dot{T}(s)}{\|\dot{T}(s)\|}$ for all $s$ such that $\text{det}(T(s),\dot{T}(s))=1$ and equal to $- \frac{\dot{T}(s)}{\|\dot{T}(s)\|}$ for all $s$ such that the determinant is equal to $-1.$ This determines the sign of the curvature at each point $s.$
In 3D case instead, one starts with $T(s)$ and $N(s)=\frac{\dot{T}(s)}{\|\dot{T}(s)\|},$ which amounts to choosing by definition that the curvature must be positive. Then since $B= T \land N$ must be orthogonal to both $T$ and $N,$ those three vectors are linearly independent and thus form an orthonormal basis of $\mathbb{R}^3$.
Question

Is $B$ the unique vector such that $\{ T, N, B \}$ forms a positively oriented basis of $\mathbb{R}^3$?

How can I have an interpretation of the sign of the torsion in a way similar to the one I gave above for curvature?

A: You haven't been explicit in your definitions. In the plane, you can require that $T,N$ form a right-handed orthonormal basis, and then you find that $dT/ds$ is possibly a negative multiple of $N$ (what is going on here is convexity/concavity). However, in three dimensions, there is no way to define $N$ other than by saying it's the unit vector in the direction of $dT/ds$ (assuming that vector is non-zero, of course). The right-handed orthonormal basis comes in when you add in the binormal vector $B$. It then makes sense to ask if the curve is twisting toward $B$ (positive torsion, by most people's definition) or away from $B$ (negative torsion); here is the sign you were attaching to curvature in the case of a plane curve.


text:
Q: CFL grammer questions I'm preparing to my test and I have 2 question in past test with no answers.
Could you help me?

*

*Prove or disprove the following claim. The language $$L=\{a^n\mid n!=k^2, k\ge 0\}$$ is a CFL.

I now that is not true, but I'm struggling prove it. I'm always stuck on the pumping lemma by choosing the right word.
2.Given a Content Free Language $L$ and its grammar $G$. Write a CFG $G'$ for a new
language: $$\operatorname{AddLetter}(L)=\{uxv\mid x \in \Sigma,  u,v \in \Sigma^*, u,v\in L\}\,.$$
I tried to get a correct grammar, but I don't know what I need to do with the $L$ language - I have no clue of its alphabet.

A: That first question is more about number theory than about formal languages and automata: $n!$ is never a perfect square if $n\ge 2$, so $L=\{\varepsilon,a\}$, which is even a regular language.

Added: J.-E. Pin has pointed out that the original pure text version, which I'd not seen, is ambiguous, and that the OP may well have intended $L$ to be the set $a^n$ such that $n$ is not the perfect square of any non-negative integer. If that's the case, then of course the above answer is irrelevant, and it turns out that $L$ is not context-free.

One way to prove this is to apply Parikh's theorem, which implies that a language over a one-letter alphabet is context-free if and only if it is regular. It is easy to use the pumping lemma for regular languages to show that $L$ is not regular. (It is perhaps even easier to use the pumping lemma for regular languages to show that $\{a\}^*\setminus L=\left\{a^{k^2}:k\ge 0\right\}$ is not regular and then use the fact that regular languages are closed under complementation.)

For the second question I think that you may assume that $\Sigma$ is the alphabet for both languages; $\operatorname{AddLetter}(L)$ is simply the set of words over $\Sigma$ that can be decomposed as $uxv$, where $u$ and $v$ are in $L$, and $x$ is any single character in the alphabet $\Sigma$. If $S$ is the initial non-terminal of $G$, give $G'$ a new initial symbol $S'$; then for each $x\in\Sigma$ the grammar $G'$ will have a production $S'\to \_x\_$, where I'll leave it to you to fill in the two blanks.


text:
Q: Windows equivalent of Linux JQ tool command I have a linux jq command
 jq -r '."FOO-BAR"[] | .foo+ " " + .bar[]'

What would be equivalent of this in Windows shell syntax? I have tried this and I get a compile error
 jq -r "."FOO-BAR"[] | .foo+ " " + .bar[]"

A: The double-quotes in the original (i.e., the interior double-quotes) must be escaped, as discussed in the Windows section of the jq FAQ.
Thus your example would become:
jq -r ".\"FOO-BAR\"[] | .foo+ \" \" + .bar[]"


text:
Q: Перенос текста с разрывом слов Здравствуйте!
Есть проблема с переносом длинных слов внутри блока. Слишком длинные слова переносятся на следующую строку и тем самым ломают всю вёрстку.

Подскажите скрипт который бы осуществлял перенос с разрывом слов.

Было бы идеально если бы разрыв слов осуществлялся по правилам русского языка, но в тексте присутствуют и слова на латинице!
A: Javascript hyphenator
A: В 2017 году более актуально будет использовать Hyphenopoly.js. С этой библиотекой сначала проверяется поддержка расстановки переносов в самом браузере, и только потом подгружаются библиотеки если поддержки в браузере нет.
В большинстве современных браузеров уже есть поддержка расстановки переносов слов при условии правильного указания кода языка. За это отвечают правила CSS:
<style type="text/css">
    .hyphenate {
        hyphens: auto;
        -ms-hyphens: auto;
        -moz-hyphens: auto;
        -webkit-hyphens: auto;
    }
</style>

Язык указывается так:
<article lang="ru">


text:
Q: How to scrape content from a complex div class using Beautiful Soup I'm making some exercises to practice web scraping using Python and I would like to get the values of the first row ("Total Revenue") of the table of this Yahoo page (Bank of America at NYSE).
Looking at the page source, my idea is to find the first occurrence of
 and get the values but I'm not sure how to navigate inside the first div.
Below I present the HTML code where the first row is presented:

                <button aria-label="Total Revenue" class="P(0) M(0) Va(m) Bd(0) Fz(s) Mend(2px) tgglBtn">
                    <svg class="H(16px) Fill($primaryColor) Stk($primaryColor) tgglBtn:h_Fill($linkColor) tgglBtn:h_Stk($linkColor) Cur(p)" width="16" style="stroke-width:0;vertical-align:bottom" height="16" viewBox="0 0 48 48" data-icon="caret-right">
                        <path d="M33.447 24.102L20.72 11.375c-.78-.78-2.048-.78-2.828 0-.78.78-.78 2.047 0 2.828l9.9 9.9-9.9 9.9c-.78.78-.78 2.047 0 2.827.78.78 2.047.78 2.828 0l12.727-12.728z"></path>
                    </svg>
                </button>
                Total Revenue

90,742,000

89,113,000

85,528,000

91,244,000

91,247,000

In my code I'm using Selenium to process the page. Not sure if its the best way but with other libraries like urlopen I wasn't able to see the HTML content. I'm able to open the page, click the accept button, but after that I'm not sure how to navigate inside the first div. I'm actually getting an error like: "AttributeError: 'NoneType' object has no attribute 'get_text'"
import requests
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
url = "https://finance.yahoo.com/quote/BAC/financials?p=BAC"
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html, "html.parser")

# Click accept button
aceitar = driver.find_element(By.NAME, "agree")
aceitar.click()

# Find the div of the Revenue row

primeiraLinha = soup.find("div", {"class":""})
print(primeiraLinha.get_text())

BTW, I think Selenium make this process very slow.

A: Here is a Selenium solution to get the entire table in a pandas dataframe.
Imports required
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd

Start web driver
# Replace your CHROME DRIVER path here
chrome_path = r"C:\Users\hpoddar\Desktop\Tools\chromedriver_win32\chromedriver.exe"
s = Service(chrome_path)
driver = webdriver.Chrome(service=s)

Fetch the page
driver.get('https://finance.yahoo.com/quote/BAC/financials?p=BAC')

Wait for table to load
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//div[@class="D(tbhg)"]')))

Get the header row
headers_elem = driver.find_elements(By.XPATH, '//div[@class="D(tbhg)"]/div/div')
col_headers = [header.text for header in headers_elem]
df = pd.DataFrame(columns = col_headers)
df

Output:
Empty DataFrame
Columns: [Breakdown, TTM, 12/30/2021, 12/30/2020, 12/30/2019, 12/30/2018]
Index: []

Get the rows from the table
Here each row in the table is stored in rows
rows = driver.find_elements(By.XPATH, '//div[@class="D(tbrg)"]//div[@data-test="fin-row"]')
for row in rows:
    row_values = row.find_elements(By.XPATH, 'div/div')
    df.loc[len(df)] = [row_value.text for row_value in row_values]

Output:
Which gives us the expected output:

Breakdown
TTM
12/30/2021
12/30/2020
12/30/2019
12/30/2018

0
Total Revenue
90,742,000
89,113,000
85,528,000
91,244,000
91,247,000

1
Credit Losses Provision
560,000
4,594,000
-11,320,000
-3,590,000
-3,282,000

2
Non Interest Expense
59,763,000
59,731,000
55,213,000
54,900,000
53,381,000

3
Special Income Charges
-
-
-
-
0

4
Pretax Income
31,539,000
33,976,000
18,995,000
32,754,000
34,584,000

5
Tax Provision
3,521,000
1,998,000
1,101,000
5,324,000
6,437,000

6
Net Income Common Stockholders
26,565,000
30,557,000
16,473,000
25,998,000
26,696,000

7
Diluted NI Available to Com Stockholders
26,565,000
30,557,000
16,473,000
25,998,000
26,696,000

8
Basic EPS
-
3.60
1.88
2.77
2.64

9
Diluted EPS
-
3.57
1.87
2.75
2.61

10
Basic Average Shares
-
8,493,300
8,753,200
9,390,500
10,096,500

11
Diluted Average Shares
-
8,558,400
8,796,900
9,442,900
10,236,900

12
INTEREST_INCOME_AFTER_PROVISION_FOR_LOAN_LOSS
47,080,000
47,528,000
32,040,000
45,301,000
44,150,000

13
Net Income from Continuing & Discontinued Operation
28,018,000
31,978,000
17,894,000
27,430,000
28,147,000

14
Normalized Income
28,018,000
31,978,000
17,894,000
27,430,000
28,147,000

15
Total Money Market Investments
348,000
-90,000
903,000
4,843,000
3,176,000

16
Reconciled Depreciation
1,953,000
1,898,000
1,843,000
1,729,000
2,063,000

17
Net Income from Continuing Operation Net Minority Interest
28,018,000
31,978,000
17,894,000
27,430,000
28,147,000

18
Total Unusual Items Excluding Goodwill
-
-
-
-
0

19
Total Unusual Items
-
-
-
-
0

20
Tax Rate for Calcs
0
0
0
0
0

21
Tax Effect of Unusual Items
0
0
0
0
0

TL:DR
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd

chrome_path = r"C:\Users\hpoddar\Desktop\Tools\chromedriver_win32\chromedriver.exe"
s = Service(chrome_path)
driver = webdriver.Chrome(service=s)

driver.get('https://finance.yahoo.com/quote/BAC/financials?p=BAC')

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//div[@class="D(tbhg)"]')))

headers_elem = driver.find_elements(By.XPATH, '//div[@class="D(tbhg)"]/div/div')
col_headers = [header.text for header in headers_elem]
df = pd.DataFrame(columns = col_headers)

rows = driver.find_elements(By.XPATH, '//div[@class="D(tbrg)"]//div[@data-test="fin-row"]')
for row in rows:
    row_values = row.find_elements(By.XPATH, 'div/div')
    df.loc[len(df)] = [row_value.text for row_value in row_values]

The result is stored in df.


text:
Q: mongodb sum aggregation return float instead of integer I have a document which history embedded field is as below:
first_pn_data = {'_cls': 'InstallationEmbeddedHistory',
 'coverage': 0.8197712971965834,
 'date': datetime.datetime(2020, 9, 7, 0, 0),
 'estimated_installs': 39349022,
 'popularity_rank': 0,
 'rank': 1851}

second_pn_data = {'_cls': 'InstallationEmbeddedHistory',
 'coverage': 0.8197712971965834,
 'date': datetime.datetime(2020, 9, 7, 0, 0),
  'estimated_installs': 23412618,
 'popularity_rank': 0,}

The estimated_installs field is an integer.
when I run the following query:
query = [
    {
        "$match": {
            "package_name": {
                "$in": ["first_pn", "second_pn"]
            }
        }
    },
    {
        "$unwind": "$history"
    },
    {
        "$group": {
            "_id": "$history.date",
            "total": {
                "$sum": "$history.estimated_installs"
            }
        }
    }
]

the result for the above date is:
{'_id': datetime.datetime(2020, 9, 7, 0, 0), 'total': 62761640.54968266}

while I expect the total=62761640.
I don't know why the result is float and has a decimal.
Can someone help me with this?


text:
Q: Detecting button click of button added to javafx listview I am very new to Java so please be patient with me. I have successfully added buttons, labels and even a progress bar to a listview cell. I need to be able to detect when one of the buttons has been clicked. Adding controls to listview content I managed to get from a couple of posts here the code i am using is shown below
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class ListViewDemo extends Application {

  public static class lvCell extends VBox {

    Label labelName = new Label();
    Label labelPath = new Label();
    Label labelElapse = new Label();
    Button buttonPlayPause = new Button();
    Button buttonStop = new Button();
    ImageView ivStop = new ImageView();
    ImageView ivPlay = new ImageView();
    Pane buttonSpacer = new Pane();
    Pane progressBarSpacer = new Pane();

    HBox hbDetail = new HBox();
    HBox hbProgress = new HBox();

    ProgressBar pbProgress = new ProgressBar();

    File filePlay;
    File fileStop;

    double prefWidth = 10;
    double prefHeight = 10;

    lvCell(String labelText) {
      super();

      labelName.setText(labelText);
      labelName.setMaxWidth(Double.MAX_VALUE);
      labelPath.setMaxWidth(0);
      labelPath.setText("Path");

      pbProgress.setMaxWidth(Double.MAX_VALUE);

      HBox.setHgrow(labelName, Priority.ALWAYS);
      HBox.setHgrow(pbProgress, Priority.ALWAYS);

      HBox.setMargin(labelName, new Insets(5, 0, 0, 0));
      HBox.setMargin(pbProgress, new Insets(0, 0, 0, 0));

      labelPath.setVisible(false);

      buttonSpacer.setPrefSize(prefWidth, prefHeight);

      labelElapse.setPrefSize(50, prefHeight);
      labelElapse.setText("Time");;

      progressBarSpacer.setPrefSize(prefWidth * 6, prefHeight);

      filePlay = new File("src/image/play.png");
      fileStop = new File("src/image/stop.png");

      Image imagePlay = new Image(filePlay.toURI().toString());
      Image imageStop = new Image(fileStop.toURI().toString());

      ivPlay.setImage(imagePlay);
      ivStop.setImage(imageStop);

      ivPlay.setFitHeight(prefHeight);
      ivPlay.setFitWidth(prefWidth);
      ivStop.setFitHeight(prefHeight);
      ivStop.setFitWidth(prefWidth);

      buttonPlayPause.setGraphic(ivPlay);
      buttonStop.setGraphic(ivStop);

      buttonPlayPause.setMaxSize(prefWidth, prefHeight);
      buttonStop.setMaxSize(prefWidth, prefHeight);

      pbProgress.setMaxHeight(2);
      pbProgress.setPrefHeight(2);

      hbDetail.getChildren().addAll(buttonPlayPause, buttonStop, buttonSpacer, labelName, labelPath);
      hbProgress.getChildren().addAll(progressBarSpacer, pbProgress, labelElapse);
      this.getChildren().addAll(hbDetail, hbProgress);
    }

  }

  public Parent createContent() {
    BorderPane layout = new BorderPane();

    List < lvCell > list = new ArrayList < > ();
    for (int i = 0; i < 10; i++) {
      list.add(new lvCell("Item " + i));
    }

    ListView < lvCell > listView = new ListView < lvCell > ();
    ObservableList < lvCell > myObservableList = FXCollections.observableList(list);
    listView.setItems(myObservableList);

    layout.setCenter(listView);

    return layout;
  }

  @Override
  public void start(Stage stage) throws Exception {
    stage.setScene(new Scene(createContent()));
    stage.setWidth(300);
    stage.setHeight(200);
    stage.show();
  }

  public static void main(String args[]) {
    launch(args);
  }
}

The screen looks like this:

Any help will be greatly appreciated.
Thanks in advance, and wishing you a peaceful journey.
Yas

A: This is not a class well designed to put into a ListView. An object used as item in a ListView should contain data; the ListCell implementation produced by the cellFactory is responsible for determining the visual representation of the data in the ListView. This way you avoid the creation of nodes for every object reducing the memory footprint, which is exactly what ListView is designed for.
Simplified example
The data here contains just the progress and some text; it's displayed in a ProgressBar and the text of the cell; an additional button in the cell allows increasing the progress by 0.25 for each click and removing any items reaching a progress of 1.
Data class
public class Data {

    private final DoubleProperty progress = new SimpleDoubleProperty();

    private final String text;

    public Data(String text) {
        this.text = text;
    }

    public double getProgress() {
        return progress.get();
    }

    public void setProgress(double value) {
        progress.set(value);
    }

    public String getText() {
        return text;
    }

    public ObservableValue<? extends Number> progressProperty() {
        return progress;
    }

}

ListView code
ListView<Data> listView = new ListView<>(someData);
listView.setCellFactory(l -> new ListCell<Data>() {

    private final ProgressBar progressBar = new ProgressBar();
    private final Button button = new Button("increase");
    private final HBox content = new HBox(progressBar, button);

    {
        button.setOnAction(evt -> {
            Data item = getItem();
            int index = getIndex();
            double progress = item.getProgress() + 0.25;
            item.setProgress(progress);
            if (progress >= 1) {
                getListView().getItems().remove(index);
            }
        });
    }

    @Override
    protected void updateItem(Data item, boolean empty) {
        super.updateItem(item, empty);
        progressBar.progressProperty().unbind();

        if (item == null) {
            setGraphic(null);
            setText("");
        } else {
            setGraphic(content);
            setText(item.getText());
            progressBar.progressProperty().bind(item.progressProperty());
        }
    }

});


text:
Q: Buttons with TabControl not Working I've placed label1, richTextBox1, Button1, and Button2 in Form1;
Then I wrote the code below; all works fine, except Button1 and button2 are not working;
Any idea why?
Public Class Form1

Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged

    Select Case TabControl1.SelectedIndex
        Case 0 'first tab
            RichTextBox1.Clear() : RichTextBox1.AppendText("I'm on the first tab" & vbCrLf)
            '...
            With TabControl1.SelectedTab.Controls
                .Add(RichTextBox1)
                .Add(Label1)
                .Add(Button1)
            End With
        Case 1 'second tab
            RichTextBox1.Clear() : RichTextBox1.AppendText("Now; I'm on the Second tab" & vbCrLf)
            '...
            With TabControl1.SelectedTab.Controls
                .Add(RichTextBox1)
                .Add(Button2)
            End With
    End Select
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs)
    For s = 1 To 100
        RichTextBox1.AppendText(" Button1 - " & s & vbCrLf)
    Next
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs)
    For s = 1 To 100
        RichTextBox1.AppendText(" Button2 - " & s & vbCrLf)
    Next
End Sub

End Class

A: Your button click handlers seem to have lost their association with the buttons.  Either you copy-pasted the code in without hooking up the handlers or de-selected the handlers in the object's Events pane.  Just add the Handles clause back in like :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For s = 1 To 100
        RichTextBox1.AppendText(" Button1 - " & s & vbCrLf)
    Next
End Sub

See : Handles Clause (MSDN)
As an aside, you should also seriously consider turning ON Option Explicit and Option Strict in your project options.  These can be turned off for compatibility with legacy VB code but they encourage sloppy code that can lead to headaches and trouble.  Your handler would look like this with those options :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim s As Integer   ' Option explicit - must declare all variables!
    For s = 1 To 100
        RichTextBox1.AppendText(" Button1 - " & s.ToString() & vbCrLf)
        ' Option strict -> no implicit casting of types (ie : int to string ^^)
    Next
End Sub


text:
Q: RXTX and LRC transmission procedure So, I have a card locking system device which connects through RS-232 DB9 serial port.
This is my first time dealing with an external device using that. So I read the manual
an it says that the transmission procedure text format is defined as follows:
-The text must consist of up to 500 characters between STX and ETC
-LRC computed area ranges from the first character from STX to ETX
there is also a list of control characters (STX, ETX, ACK, NAK) with their hex codes.
I have no idea about this. Please enlighten me.
Oh and also, could I detect whether a device is connected or not to a specific port?
I've managed to connect to the comm port using this code below:
public class TwoWaySerialComm
{
    protected InputStream inputStream;
    protected OutputStream outputStream;

    public TwoWaySerialComm()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_7,SerialPort.STOPBITS_1,SerialPort.PARITY_ODD);

                inputStream = serialPort.getInputStream();
                outputStream = serialPort.getOutputStream();

                (new Thread(new SerialReader(inputStream))).start();
                (new Thread(new SerialWriter(outputStream))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /** */
    public static class SerialReader implements Runnable
    {
        InputStream in;

        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void run ()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            try
            {
                while ( ( len = this.in.read(buffer)) > -1 )
                {
                    System.out.print(new String(buffer,0,len));
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        }
    }

    /** */
    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        }
    }

    public static void main ( String[] args )
    {
        try
        {
            TwoWaySerialComm comm = new TwoWaySerialComm();
            comm.connect("COM3");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

And this is the code I've found which is used to get LRC from an array of bytes:
    public byte calculateLRC(byte[] data)
    {
        byte checksum = 0;
        for (int i = 0; i <= data.length - 1; i++) {
            checksum = (byte) ((checksum + data[i]) & 0xFF);
        }

      checksum = (byte) (((checksum ^ 0xFF) + 1) & 0xFF);
        return checksum;
    }

Now supposedly I have to send text "CES01" properly to the device, how do I do that?

A: STX :start character
ETX: end character
ACK : Acknowledgement

    char STX = 0x02;
char ETX = 0x03;
char EOT = 0x04;
char ENQ = 0x05;
char ACK = 0x06;

Also see the  link for LIS/RIS message format
http://www.hl7standards.com/
sending Acknowledgement
public void sendAcknowledgement()throws IOException{
         String ack= ASCIITable.ACK + "";
         outputStream.write(ack.getBytes());
    }

A: If you have absolutely no experience with serial comms I would start out by studying some existing, known to work implementation.  John Ellinwood's answer to this SO question contains the Java source to the XModem protocol, an old, simple modem file transfer protocol.  This will show you how to handle the communication itself (you always have to be prepared for timeouts and other error conditions) and the control characters.
A pecularity of Java you must not forget is the absence of unsigned types in Java, almost always these low level protocols become a bit more complicated to program if the only variable types you have at your disposal are signed.  But as the XModem code shows, it's perfectly doable.

A: OutputStream writes bytes so you have to convert your string to a byte array first:
outputStream.write("CES01".getBytes());


text:
Q: Can asyncpg be used as database client for mysql? Currently my company uses Mysql as server database
and I want to develop api with (FastAPI + sqlalchemy with asyncpg) stack
because I read a blog says "if you want to maximize performance of FastAPI, you should consider combination of fastapi and asyncpg"
but I guess asyncpg is database client for PostgreSQL which is not currently used in company Im working now.
document told me to create async engine with
engine = create_async_engine('postgresql+asyncpg://user:pass@server_addr/database', pool_size=20 ,echo=True, pool_pre_ping=True)

but can I use this code for connection with Mysq? Would it work?
If it doesn't, what kind of client should I use for async sqlalchemy?
(like engine = create_async_engine('mysql+aiomysql: ...'))


text:
Q: stack level too deep (SystemStackError) when recursing I want to make this simple calculation but it complains that the the stack isn't deep enough even for very small numbers for n such as 4. Other SO posts for similar topics recommend tail recursion but that isn't applicable here since you only add to an accumlated value when you reach the base case.
RubyVM::InstructionSequence.compile_option = {
:tailcall_optimization => true,
:trace_instruction => false
}

def recursively_count_paths(x , y, n)
 if x == n &&  y == n
  return 1
  puts " we got a path people"
 elif x == n
  puts "x is done"
  return recursively_count_paths(x, y + 1, n)
 elif y == n
  puts "y is done"
  return recursively_count_paths(x + 1, y, n)
 else
 return (recursively_count_paths(x + 1, y, n) +
recursively_count_paths(x, y + 1, n))
 end
end

recursively_count_paths(0, 0, 20)

am I not supposed to return in other cases?

A: Tail recursion  isn't relevant in this case. Since you call the method recursively several times, the compiler can't make that optimization. Most of those calls are unnecessary. I was able to rewrite your code to:
def recursively_count_paths(x, y, n)
  return 0 if x > n or y > n
  return 1 if x == n &&  y == n
  return recursively_count_paths(x+1, y, n) + recursively_count_paths(x, y+1, n)
end

The first line looks for paths that are out of bounds and doesn't count those. The second line is equivalent to your first if statement. It returns 1 if a path has been completed. The final line is the same as your final return statement and simply adds all the paths going north with all the paths going east. Since we call recursively_count_paths twice, tail-call optimization still won't help.
If you run it using n=20, you might notice it takes awhile. This is because this algorithm takes exponentially longer as the size of the grid increases. That's because you count the same subpaths over and over again. It's also Project Euler Problem 15, so I won't provide my solution here. I will give you a hint, however: save your work.


text:
Q: Casida equation, excited states and response theory I have several doubts about the characterization of excited states within the framework of TD-DFT (Time dependent Density Functional Theory) / Response Theory.
Just to give some context and fix notation, I will explain very quickly the general picture.
Context:
Basic Linear Response Theory (that is, 1st Order Response Theory) applied to the Kohn-Sham hamiltonian gives:
$$n_1(r,t)=\int \int  \chi(r,r^\prime,t-t^\prime)v_1(r^\prime,t^\prime) dt^\prime dr^\prime,$$
where $\chi$ is the Kohn-Sham density-density response function, computable from a Ground State DFT calculation and $v_1$ is the effective Kohn-Sham one-electron potential approximated to first order.
It is useful to define the so-called XC-Kernel $f_{xc}(r,r^\prime,t,t^\prime)= \dfrac{\delta v_{xc}[n](r,t)}{\delta n(r^\prime,t^\prime)}\vert_{n_0(r)},$ for which there are a lot of possible approximations. After going over to frequency space and after tons of algebra (details can be found for example in "Density Functional Theory: An Advanced Course" by Engel & Dreizler or in "Time-Dependent Density-functional theory" by Ullrich; both are excelent and quite pedagogical references for this material, in a beginner's opinion!) one reaches the so-called Casida equation which is an eigenvalue problem:
$$C\vec{Z}=\Omega^2 \vec{Z},$$
where $\Omega$ are the frequencies corresponding to the excitation energies and $C$ is a matrix which depends on the Ground-state KS states and on the XC Kernel. This Kernel, in principle, depends on the frequency $\Omega$ (at least if one whishes to go beyond the adiabatic approximation), and so this equation is not solvable by a single diagonalization, but rather a self-consistent approach is needed! The eigenvectors $\vec{Z}$ contain all the information needed to construct de excited-states densities to first order, $n_1(r,\Omega).$
Question 1:  This is not a TD-DFT approach, right?
I don't see any time progagation going on here, so I'm a bit confused because I thougth this was all part of TD-DFT, but it seems to me that one "just" has to perform a ground state DFT and afterwards solve Casida equation, so one does not need with the Time Dependent Schrödinger equation, right? Or am I wrong?. Okey, strictly speaking, one needs Runge-Gross and Van Leeuwen theorems to give a rigorous justification to all of this, but the time-dependent Schrödinger equation, time propagation and numerical integration schemes (such as Crank-Nicolson integrator) don't come into play in all of this at any point,.... right? Or am I misunderstanding something fundamental about the method?
Question 2:
Say we want to study the dynamics of nuclei in a excited state. So, what do we do? Imagine $\Omega_0$ is the lowest eigenvalue in the Casida problem above. From that we can get the excited state density corresponding to $\Omega_0,$ $n_1(r,\Omega_0).$ But how do we compute the forces? We cannot just plug this density in the Energy functional, that wouldn't make sense, since that functional is defined for ground state densities, right?  We could of course calculate the first-order correction to the effective Kohn-Sham potential to first order, but nothing else. How to compute the XC energy in the excited state? Or what about the kinetic energy; how to compute it from the density in a DFT-style if one doesn't have a representation of the excited state as a Slater determinant?
Question 3: Imagine on whished to go beyond linear responde theory, to N-th order response theory. The equations can be formally written, but then I have no idea as to what would be the strategy to compute the excitation energies or the excited-state densities. You wouldn't have that sort of eigenvalue problem. So, it is not only that the problem would become much harder. The thing is that even at the most basic conceptual level I wouldn't know how one would define excitation energies and related properties within a Higher-order Response Theory.
If all of this is of any interest, I will post later more questions and doubts related to these problems.

A: *

*You are right. There is no time anymore in Casida's equation, though one uses the time-dependent Schroedinger equation and the whole machinery of TD-DFT in its derivation. In practice you just do a ground state calculation with DFT and then use the orbitals and Kohn-Sham energies to set up Casida's equation.
The term TD-DFT is a bit confusing as people use it both for the linear response methods like Casida's equation and the explicit solution of the time-dependent Schroedinger equation through the time-dependent Kohn-Sham scheme. It would be nice to distinguish these rather different things by name, and some people refer to the former as LR-TD-DFT where LR stands for linear response. But that is unfortunately not standard and I'm afraid you'll have to live with the confusion.

*Let $E_0 = E[\rho_0]$ be the total energy you got from your ground state DFT calculation. If you call your excitation energy $\Omega_n$, then the energy of the excited state $E_1$ is just given by
$$ E_n = E_0 + \Omega_n \; .$$
The gradients in the excited state are then just
$$ \vec \nabla E_1 = \vec \nabla E_0 + \vec \nabla \Omega_n \; .$$
Here $\vec \nabla E_0$ is just the normal gradient from DFT. There are analytical expressions for the gradient of the excitation energy $\vec \nabla \Omega_n$, but they are rather nasty. Check this paper.

I don't know the answer to your 3rd question. Maybe someone else can jump in.