text:
Q: fetch_add with acq_rel memory order Consider an
std::atomic<int> x(0);

Let's suppose I have a function doing the following:
int x_old = x.fetch_add(1,std::memory_order_acq_rel);

Based on the description for acquire release memory ordering:

memory_order_relaxed  Relaxed operation: there are no synchronization or ordering constraints, only atomicity is required of this operation (see Relaxed ordering below)
memory_order_consume A load operation with this memory order performs a consume operation on the affected memory location: no reads or writes in the current thread dependent on the value currently loaded can be reordered before this load. Writes to data-dependent variables in other threads that release the same atomic variable are visible in the current thread. On most platforms, this affects compiler optimizations only (see Release-Consume ordering below)
memory_order_acquire A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread (see Release-Acquire ordering below)
memory_order_release A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable (see Release-Acquire ordering below) and writes that carry a dependency into the atomic variable become visible in other threads that consume the same atomic (see Release-Consume ordering below).
memory_order_acq_rel A read-modify-write operation with this memory order is both an acquire operation and a release operation. No memory reads or writes in the current thread can be reordered before or after this store. All writes in other threads that release the same atomic variable are visible before the modification and the modification is visible in other threads that acquire the same atomic variable.
memory_order_seq_cst Any operation with this memory order is both an acquire operation and a release operation, plus a single total order exists in which all threads observe all modifications in the same order (see Sequentially-consistent ordering below)

Is it possible for 2 distinct threads to receive the same x_old value of 0? Or are they guaranteed to execute in a manner that x_old is 0 for only one of them, and is 1 for the other.
If it is true that x_old could be 0 for both of them, does changing the memory ordering to std::memory_order_seq_cst guarantee uniqueness of x_old?

A:
Is it possible for 2 distinct threads to receive the same x_old value of 0?

It is not possible because the operation is atomic. It either happens in full, or not happen at all.
Ordering is concerned with preceding/following loads/stores and since you do not have any, ordering is irrelevant here. In other words, x.fetch_add(1, std::memory_order_relaxed); has the same effect here.
On current x86 is it the same lock xadd instruction regardless of memory_order, lock prefix provides both atomicity and ordering. For memory_order_relaxed the ordering part of lock is unnecessary.

A: Any operation that is performed on memory is done inside the processor. Even if it is an atomic operation, the processor will read, modify and write back the new value. If the operation fails (depending on implementation it may not be able to fail, but rather block), it repeats itself. If it succeeds, for the operation to be correct, the new value must be the immediately previous value, modified as requested and then stored. The value modified is returned to the user. There is no reason for the processor to read again from memory and return the value from a random time. If the value returned was not the immediately previous, the resulting operation would be incorrect.
You can test it using something like this:
long repeats = 1000000000;
long x = 0;
long sum = 0;
void *test_func(void*arg){
    long local_sum = 0;
    for (int i = 0; i < repeats; ++i) {
        local_sum += atomic_fetch_add_explicit(&x, 1, memory_order_relaxed);
    }
    atomic_fetch_add(&sum, local_sum);
    return NULL;
}

If the result is the same as a sequential execution, then all works fine.
    long correct_res = 0;
    for (int i = 0; i < repeats * no_threads; ++i) {
        correct_res = correct_res + i;
    }

And for the complete code:
#include <stdio.h>
#include <pthread.h>
#include <stdatomic.h>

long repeats = 1000000000;
long x = 0;
long sum = 0;
void *test_func(void*arg){
    long local_sum = 0;
    for (int i = 0; i < repeats; ++i) {
        local_sum += atomic_fetch_add_explicit(&x, 1, memory_order_relaxed);
    }
    atomic_fetch_add(&sum, local_sum);
    return NULL;
}

int main() {
    long correct_res = 0;
    for (int i = 0; i < repeats * 2; ++i) {
        correct_res = correct_res + i;
    }
    pthread_t pthread[2];
    pthread_create(&pthread[0], NULL, test_func, NULL);
    pthread_create(&pthread[1], NULL, test_func, NULL);

    pthread_join(pthread[0], NULL);
    pthread_join(pthread[1], NULL);
    printf("correct res : %ld\n res : %ld\n", correct_res, sum);
    if(correct_res == sum)
        printf("Success.\n");
    else
        printf("Failure.\n");
    return 0;
}


text:
Q: jQuery serialize serializes the URL wrong I have a form which I submit and I use .serialize to help me gather all data from the form. Now, I've checked in firebug what is sent in POST and I can see a nice formated string like example
index.php?data=sth&data2=sth

but the problem is with this & in the PHP - the PHP outputs it like this:
index.php?data=sth& a m p ;data2=sth

See this amp? Well it is written without spaces and it's and encoded (as I found out in google) version of &. So, what should I do to input this url correctly in the database and then fetch it a nd show it on the site without this & amp; ?
edit: if it's possible I would like a string with that & to be put in that format to DB. (so, with & sign).
edit#2:
how I send data:
 var formData = $("#myForm :input[value]").serialize();
 $.ajax({
     type: 'POST',
     cache:false,
     url: '_ajax/updateGameInfo.php',
     async: false,
     dataType: 'text',
     data: allData,
     success: function(jsonObj) {
         if (jsonObj){
             $msg = 'Data sucessfully updated! Reloading page...';
             alert($msg);
         }
         else{
             $msg = 'Error with the update!';
             alert($msg);
         }
     }
 });

And here is my updateGameInfo.php:
$gameRepos = new GameRepository();

$game = $gameRepos->updateGame();
echo json_encode( $game );

And if you also like, here is my updateGame function from GameRepository:
public function updateGame()
{
    $cleanPost = array_map( array('GameRepository', 'cleanPostData'), $_POST);
    $attributes = array_keys($cleanPost);
    $values = array_values($cleanPost);

    $table = $this->resolveTableName( $cleanPost["selectedTypeId"] );
    $id = $cleanPost["selectedGameId"];

    if ($this->openConnection())
    {
        $pairs = "";
        foreach ($cleanPost as $attribute => $value){
            if ($attribute != "selectedGameId" && $attribute != "selectedTypeId"){

            if ($attribute == "url")
                $value = str_replace("amp;", "", $value);

                $pairs .= $attribute . "='" . $value . "',";
            }
        }

        $pairs = rtrim($pairs, ','); //remove last comma

        $query = "UPDATE $table SET $pairs WHERE id=$id;";

        $result = pg_query($query);
        if (!$result){
            mysql_error());
            return false;
        }
        else
            return true;
    }
    else
        return false;
}

A: If you are passing in the URL as a POST variable, then PHP is going to automatically encode any special characters.  So, assuming the POST variable name is url, you would want to do this in your php script before everything else:
$_POST['page_url'] = htmlspecialchars_decode($_POST['page_url']);

The issue isn't with jquery, it's with php.  You'll run into similar issues when passing json strings.

A: Did you check the charset in the html header of the page?
Try to change it!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multithreading in Java-Android My problem is that I have an Activity and into there I want to take the result of the
read_list method. However the read_list method takes a lot of time to complete,
therefore I want to create a new Thread, and this to run this method and then
return it to the main activity. I know that I can do smt similar with the
AsyncTask, however now I want to do it with this way.
  public class Read<T> implements Runnable(){

    Thread t;
    read(){
         t = new Thread(this);
         t.start();
    }

    public void run(){

       read_list();
    }

    public ArrayList<T> read_list(){

       ..........
       return ArrayList<T>
    }

 }

The main Activity:
 public Name extends Activity{

    .
    .
    .

    Read<Data> read = new Read<Data>();
    read.read_list();

 }

Question: With the aforementioned code, will I activate a new thread to execute the
read_list method? Or the method will be executed on the main Thread?

A:
Question: With the aforementioned code, will I activate a new thread to execute the read_list method? Or the method will be executed on the main Thread?

Only Thread.start starts a new thread and calls the object's run method in that new thread. So no, read.read_list() will not execute in different thread.
BUT:
read(){
     t = new Thread(this);
     t.start();
}

I assume that is supposed to be Read, it is the constructor. It too calls start and run calls read_list and discards the result.
So as is, read_list will be called twice, possibly concurrently.
Finally, I think you will have a hard time implementing read_list, creating and filling up objects of arbitrary types

A: new thread won't be executed, however calling read.read() should start a new thread
btw. I would prefer using anonymous class, imho it is easier to read:
public Name<T> extends Activity{
  .
  .
  .
  private List<T> stuff;

  Runnable read = new Runnable(){
    public void run(){
      ...
      stuff = new ArrayList<T>(..);
    }
  };
  read.start();
}


text:
Q: Check if image has been loaded Hello i have this code:
BitmapImage image = new BitmapImage(new Uri(contact.PreviewPhoto, UriKind.Relative));
a.photo.Source = image;

contact.PreviewPhoto="https://files.test.lv/public/photos/h66/38B83D35-15B5-4872-8CE5-F3E50001E921.jpg";

How can i determine if image has been loaded?
Because sometimes internet connection can get lost, or the link is blank, how to replace it in that case?

A: I don't know for check image has loade . But here is the sample for the image has exist or not
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("YourImageUrl");
request.Method = "HEAD";

try
{
    request.GetResponse();
    return true;
}
catch
{
   return false;
}

A: Yes, thanks to Fabrice, the correct answer will be:
   BitmapImage image = new BitmapImage(new Uri(contact.PreviewPhoto));
                            image.ImageFailed += (s, e) =>
                            {
                                image = new BitmapImage(new Uri("/no-picture.png", UriKind.Relative));
                                a.photo.Source = image;
                            };

A: It seems you're more looking for NOT loaded instead of loaded...
You can listen to BitmapImage's events like DecodeFailed or DownloadFailed: (msdn.microsoft.com/library/system.windows.media.imaging.bitmapimage_events.aspx).
If a.photo is of type Image, then you can also listen to the events ImageFailed and ImageOpened (msdn.microsoft.com/library/windowsphone/develop/system.windows.controls.image_events(v=vs.105).aspx)


text:
Q: Duplicate columns from MySql db to c#, why? id pojam opis id pojam opis(duplicate columns)
I am just testing connection from db to c#, and instead of columns id pojam opis I am actually getting id pojam opis id pojam opis in datagridview in c#. Here is part of code which I use to connect database to c#:
public partial class Form1 : Form
{
    BindingSource bindingSource1 = new BindingSource();
    MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=test;user=root;password=;");

    public Form1()
    {
        this.Load += new System.EventHandler(Form1_Load);
        InitializeComponent();
    }

    public void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.DataSource = bindingSource1;
        ubaciPodatke();
    }
    public void ubaciPodatke()
    {
        try
        {
            MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM csharp", conn);
            DataTable table = new DataTable();
            da.Fill(table);
            bindingSource1.DataSource = table;    dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Is it my mistake, or It has to do something with phpmyadmin: Version information: 4.7.0-rc1. I was thinking it can happen because this version isnt stable yet?
edit: what do You think if I delete this form.resx file
user added rows, would this solve the problem?

A: Solution: I had to comment some lines link1 in form.designer.cs and problem disappeared as shown in this photo link2. I am still curious why this happened as I remember only dragging dgv from toolbox and not adding manually column names.

A: Few things:
There is no need to do the data binding in the Load event. You can just do it in the constructor after the InitializeComponent() call. This is irrelevant to your issue.
I don't know what ubaciPodatke means since I don't speak that language, but hopefully it is equivalent of InitializeGrid(). In that case you should put
dataGridView.DataSource = null;
dataGridView.Rows.Clear();
dataGridView.Columns.Clear();

as the first line after try. I do such "clean initialize" since I sometimes design the Grid in designer, for "documentation & visualization" purposes, but do the actual grid from the code. Also, it keeps the InitializeGrid() reusable, to be called from other places.
Also, related to the question in the comments,

Am I reading data from dgv wrong?

You should read the data from the bound DataTable and not directly from the  DataGridView when binding.


text:
Q: Traslation of a bar on a plane - Contrasting results I have a bar which can translate on a plane (gravity along y), at estremity A there are two forces and a moment, G is the center of mass, here I applied the gravity force:

The dynamic equations are:
$$ F_x = m \, a_x $$
$$ F_y -m \, g = m \, a_x $$
The problem is the rotational equation; the angular acceleration is null because the bar can only translate. If I write the equation with respect to the point A, I get:
$$ M=0 $$
instead if I choose G:
$$ M-b \, F_x=0 $$
Why?
Thank you for your time.

A:
the angular acceleration is null because the bar can only translate.
  If the bar can only translate, if teams that there is some external factor that prevents it from rotating. Thus, any moment will be 0, because the bar is held firmly on its axis.

It does not matter if you choose the point A or G in order to calculate the moment, as it will still be 0, because the bar is not allowed to rotate.
If the bar COULD rotate, then you should not take point A as your reference points, as that is the point to which you are applying the torques, and torques are $$\tau = Fdcos(\theta)$$but in this case, you are applying a force on that very point, so d would be 0, and so is your torque. It is like trying to open a door by pushing on its pivots rather than its handle. You have to always look for the simplest possible point, which in this case seems to be the center of the bar, G.


text:
Q: getEventTime() in S3EventNotification.S3EventNotificationRecord vs LastModified for S3 object Sry I am new to AWS and I am confused with event trigger.
Is it possible that the LastModified of a object is not equal to getEventTime() considering it has subscribers which triggers when a new object is inserted.
If yes then why should it be the case since event-notification should be triggered only when the object is inserted so getEventTime() being equal to lastModified should make more sense?
Note: by getEvenTime() mean
S3EventNotification.S3EventNotificationRecord notification;
notification.getEventTime()


text:
Q: add ordinal ranking to word frequency in bash Similar to this question How to create a frequency list of every word in a file?
I want to create a frequency table for words with a different output. Instead of having just the word and its frequency I would like to have the ranking of the word. So that the most frequent word is number 1, 2nd less frequent is 2 and so on. Words with the same frequency should have the same ranking.
I tried to understand the awk syntax or the other suggestions but I did not manage.
Example of input text file:
ora
remo
ora
ora
hello
tr
tr
tr
remo
rand
rand
rand
hello

Output should look like:
tr 1
rand 1
ora 1
remo 2
hello 2

A: Based on your expected output:
sort file|uniq -c|sort -r|awk '$1!=L{L=$1;c=++a}{print $2, c}'

Result:
tr 1
rand 1
ora 1
remo 2
hello 2

Explanation
First step: sort the file as uniq expects.
$ sort file
hello
hello
ora
ora
ora
rand
rand
rand
remo
remo
tr
tr
tr

From uniq man page:

Repeated lines in the input will not be detected if they are not
adjacent, so it may be necessary to sort the files first.

Next: Let's count it:
$ sort file|uniq -c
   2 hello
   3 ora
   3 rand
   2 remo
   3 tr

-c Precede each output line with the count of the number of times the line occurred in the input, followed by a single space.

Third step, sort again the file in reverse order:
$ sort file|uniq -c|sort -r
   3 tr
   3 rand
   3 ora
   2 remo
   2 hello

Finally the awk part:
awk '$1!=L{L=$1;c=++a}{print$2, c}'
The idea is simple:
$1!=L: Increment the rank c=++a only when the first field (the one that refers to the count) changues.
Also we're going to use L to store $1 last/previous value
{print $2, c}:  [Applies for all the records] print the current word (second field) followed by it's ranking.

A: Kludgy solution (datamash, mktemp, nl, etc.) until something cleaner comes to mind:
x=`mktemp`
datamash  -g 1 -s count 1 < file |
datamash -s -g 2 reverse |
tac | tee $x | cut -f1 | uniq | nl |
while read a b ; do
    sed -n "/^$b/{s/^$b\W*\(.*\)/\1\t$a/p}" $x ;
done ; rm $x

Output:
tr      1
rand    1
ora     1
remo    2
hello   2

A: Using GNU awk, results are same, but order differs a bit
One-liner:
awk 'BEGIN{PROCINFO["sorted_in"]="@val_num_desc"}{a[$1]++}END{for(i in a){ if(a[i]!=p){r++; p=a[i]}print i,r}}' infile

Explanation:
awk '
     BEGIN{
             PROCINFO["sorted_in"]="@val_num_desc"
          }
          {
             a[$1]++
          }
       END{
           for(i in a)
           {
              if(a[i]!=p)
              {
                r++;
                p=a[i]
              }
              print i,r
           }
          }
  ' infile

Ref :
https://www.gnu.org/software/gawk/manual/html_node/Controlling-Scanning.html
https://www.gnu.org/software/gawk/manual/html_node/Controlling-Array-Traversal.html

*

*PROCINFO["sorted_in"] - In order to control the order in which gawk traverses an array during a for loop.

*"@val_num_desc" - values, treated as numbers, are ordered from high to low.

*a[$1]++ a is array, $1 being array index, and array a holds count of occurrence, array key.

*if(a[i]!=p){r++; p=a[i]} since array values are sorted in descending order, whenever there  is change in array value, increment r++, p=a[i] variable holds previous value, used for comparison.
Input:
$ cat infile
ora
remo
ora
ora
hello
tr
tr
tr
remo
rand
rand
rand
hello

Output:
$ awk 'BEGIN{PROCINFO["sorted_in"]="@val_num_desc"}{a[$1]++}END{for(i in a){ if(a[i]!=p){r++; p=a[i]}print i,r}}' infile
rand 1
tr 1
ora 1
hello 2
remo 2


text:
Q: iPhone 11 Pro - repeatedly being asked to enter passcode to continue using iCloud? I recently changed the passcode on  my iPhone 11 Pro.  About a day after, I started receiving messages saying:
"Confirm iPhone Passcode - Confirm your iPhone passcode to keep using iCloud.  You recently changed this passcode you use to unlock this iPhone.  This passcode also protects access to data stored in iCloud."
Is this legit?  I've changed passcodes several times in the past and never encountered this. Wouldn't Apple program it so that when you change passcodes, it does so for all services? I searched for this issue on a few sites but haven't found an answer.


text:
Q: Reading a Text File From a .jar File I have a rookie question.
I'm currently writing a program that takes in alot of data from a text file using the File and Scanner class as shown below:
   File data = new File("champdata.txt");
   Scanner read = new Scanner(data);
   read.useDelimiter("%");

The Scanner then retrieves data from the text file correctly while in the IDE, but when I run the program as a .jar file, the file cannot be retrieved.
I've read a little about adding a text file to the .jar file itself, and using the InputStream and BufferedReader classes to read the file, but I have never used these classes, nor do I understand what they do differently/how to use them in place of the File and Scanner classes.
Can anyone help me out?

A: It will be necessary to retrieve the file by URL, since it is an embedded resource.  See the embedded resource Wiki for more details.
Update

So if I placed the text file in a folder "Resource" in the src folder, the URL I'd use is "resources/champdata.txt"

No.  If it is in a Resource path in the Jar, the String needs to be:
..getResource("/Resource/champdata.txt");

If it is in the resources path:
..getResource("/resources/champdata.txt");

The string needs to be the exact letters, (plurality &) case.

A: The Scanner class has a constructor Scanner(InputStream); so you can still use this class to read the data like you did before.
All you have to do is to read the file from the Jar, you can do this like so:
InputStream is = getClass().getResourceAsStream("champdata.txt");
Scanner read = new Scanner(is);
read.useDelimiter("%");

Where the file named champdata.txt is located at the root of your jar file (which is just a zip file, you can use any unzipper to verify where the file is being located).
Now if you want to have the same functionality while developing in your IDE, place the file in your source directory, so that when the project is being built, it is placed in your classes folder. This way, the file can be loaded as described above using getResourceAsStream()


text:
Q: O que significa o arroba (@) em variáveis no Ruby? O que significa arroba (@) na frente de variáveis no Ruby?
Por exemplo
@s = gets.to_i

A: Significa que o scopo dessa variável, ou seja o limite que ela pode ser acessada é de dentro de uma classe. Ela é uma váriavel de instância.
Esse seu código é só uma linha fica difícil explicar só com essa linha.
Mas segue o exemplo abaixo
class Pessoa
   def initialize(nome, sobrenome)
     contador_de_letras_do_nome = nome.size
     @nome = nome
     @sobrenome = sobrenome
   end

   def nome_completo
     @nome + @sobrenome
   end
end

No exemplo acima a classe pessoa pode acessar dentro dela as váriaveis
@nome e @sobrenome. Eleas inclusive são usadas dentro no método nome_compleo.
Porém a variável contador_de_letras_do_nome não pode ser acessada dentro do método nome_compleo se por acaso eu precisasse. Pois essa várial não tem o @, ou seja, o escopo dela é de método.
Você pode ver mais nesse post.
ruby várial escopo


text:
Q: How to extract exif data from shape using vba Excel 2010? The project I'm working on imports images from a blob in a MySQL database. Sometimes these images are rotated 90 degrees and the user needs to manually rotate them to the correct orientation.
So my question is, is anyone aware of a function that extract exif data from a shape in Excel using vba? I'm trying to avoid any third party applications to do this.

A: I eventually turned something up in the bowels of social.msdn.microsoft.com.
Here is the solution. Microsoft Shell Controls and Automation reference required. Credit to OssieMac on social.msdn.microsoft.com. Link to page of post
Pointing it at a shape doesn't seem to work (gives me an error), but I save my mysql blob to a temp file on the pc anyway so this works out for me anyway.
Sub ListMetadata()

Dim fileFolder As String
Dim fileName As String
Dim objShell As Shell32.Shell
Dim objFolder As Shell32.Folder
Dim objItem As Shell32.FolderItem
Dim i As Long

'Edit following line to your path. (Note NO back slash on end.)
fileFolder = ThisWorkbook.Path & "\Picture Test"

'Can insert path like following if you prefer.
'fileFolder = "C:\Users\OssieMac\Documents\Excel\Test Macros\Picture Test"

'Edit following line to your file name
fileName = "DSC00093.JPG"

Set objShell = New Shell
Set objFolder = objShell.Namespace(fileFolder)
Set objItem = objFolder.ParseName(fileName)

With objFolder
  For i = 1 To 1000
    Sheets("Sheet1").Cells(i, "A") = .GetDetailsOf(objItem.Name, i)
    Sheets("Sheet1").Cells(i, "B") = .GetDetailsOf(objItem, i)
  Next i
End With

Set objItem = Nothing
Set objFolder = Nothing
Set objShell = Nothing

End Sub


text:
Q: Google OAuth - Is using "anonymous" as key and secret insecure? I have been experimenting with some scripts in the Google Spreadsheets environment, and have been trying to take a document, convert it to a PDF, and then e-mail it. In the process, I've stumbled across a few snippets of code that used the following lines:
/* This snippet taken from : https://gist.github.com/anonymous/4169590 - I would include my version of this code here, but since I have not posted on Stack Exchange much yet, I am limited as to what I can include in my post. */
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");

My question is, is using the anonymous key and secret phrase a potential security risk for those running my script?
In other words, could someone who has the same key and phrase access the data I have authorized for the anonymous account with the "anonymous" secret?
I've spent some time looking around for this in other posts, and haven't seen anyone else ask this question. It very well could be that this is a silly question.

A: That only identifies the application (your script) as I understand it that's for unregistered apps so should be fine.


text:
Q: AssertJ no such method error when building locally I'm having an issue during local build of a multi-module project.
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.118
sec <<< FAILURE! - in org.end2end.ClientEnd2EndIT
org.end2end.ClientEnd2EndIT  Time elapsed: 0.118 sec  <<< ERROR!
java.lang.NoSuchMethodError:
org.assertj.core.util.Throwables.
              appendStackTraceInCurrentThreadToThrowable

Exactily when executing this instruction in setupClass method of the test:
frame = GuiActionRunner.execute(() -> GUI.createGui(false));

Where GuiActionRunner.execute() is a method of AssertJ dependency. In the same project I'm building the Client before the End2End module and this instruction is executed even in client's integration tests but in that case the NoSuchMethodError does not take place. I would specify that if I build under a macOS system or on Travis-ci (both linux and mac builds) this problem does not appears. This seems to be just a local problem (I'm using linux Mint 18.2). Can anyone help?

A: Solved. The problem was an hidden headless exception thrown while creating the jframe, and this was due to the fact that I was calling:
SpringApplicationBuilder builder = new
SpringApplicationBuilder(ServerApplication.class);
builder.run(new String[] { "--server.port=9999" });

I solved by adding:
SpringApplicationBuilder builder = new SpringApplicationBuilder(ServerApplication.class);
    builder.headless(false); //this line
    builder.run(new String[] { "--server.port=9999" });


text:
Q: maven install fail I follow the guide of how to use PlayN with Maven, but when i perform the command:

    maven install

it fails.
The error log is the following:

    [INFO]
    [INFO] --- maven-android-plugin:3.0.0-alpha-2:dex (default-dex) @ playn-showcase-android ---
    [INFO] /usr/lib/jvm/java-6-openjdk/jre/bin/java [-Xmx1024m, -jar, /opt/android-sdk/platform-tools/lib/dx.jar, --dex, --output=/home/hox/Projects/playn/playn/sample/showcase/android/target/classes.dex, /home/hox/Projects/playn/playn/sample/showcase/android/target/android-classes]
    [INFO]
    [INFO] --- maven-jar-plugin:2.3.2:jar (default-jar) @ playn-showcase-android ---
    [INFO] Building jar: /home/hox/Projects/playn/playn/sample/showcase/android/target/playn-showcase-android-1.0-SNAPSHOT.jar
    [INFO]
    [INFO] --- maven-android-plugin:3.0.0-alpha-2:apk (default-apk) @ playn-showcase-android ---
    [INFO] /opt/android-sdk/platform-tools/aapt [package, -f, -M, /home/hox/Projects/playn/playn/sample/showcase/android/AndroidManifest.xml, -S, /home/hox/Projects/playn/playn/sample/showcase/android/res, --auto-add-overlay, -I, /opt/android-sdk/platforms/android-11/android.jar, -F, /home/hox/Projects/playn/playn/sample/showcase/android/target/playn-showcase-android-1.0-SNAPSHOT.ap_]
    [ERROR] Cannot create the APKBuilder object
    java.lang.NullPointerException
        at com.jayway.maven.plugins.android.phase09package.ApkBuilder.(ApkBuilder.java:195)
        at com.jayway.maven.plugins.android.phase09package.ApkMojo.doAPKWithAPKBuilder(ApkMojo.java:334)
        at com.jayway.maven.plugins.android.phase09package.ApkMojo.createApkFile(ApkMojo.java:249)
        at com.jayway.maven.plugins.android.phase09package.ApkMojo.execute(ApkMojo.java:207)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
    [INFO] ------------------------------------------------------------------------
    [INFO] Reactor Summary:
    [INFO]
    [INFO] PlayN Project ..................................... SUCCESS [0.125s]
    [INFO] PlayN Project Archetype ........................... SUCCESS [0.650s]
    [INFO] PlayN Core ........................................ SUCCESS [1.962s]
    [INFO] PlayN JBox2D ...................................... SUCCESS [2.125s]
    [INFO] PlayN WebGL ....................................... SUCCESS [0.914s]
    [INFO] PlayN Java ........................................ SUCCESS [1.740s]
    [INFO] PlayN HTML ........................................ SUCCESS [1.419s]
    [INFO] PlayN Flash ....................................... SUCCESS [1.414s]
    [INFO] PlayN Android ..................................... SUCCESS [1.552s]
    [INFO] PlayN Server ...................................... SUCCESS [0.524s]
    [INFO] PlayN Demos Project ............................... SUCCESS [0.002s]
    [INFO] PlayN Hello Metaproject ........................... SUCCESS [0.003s]
    [INFO] PlayN Hello Core .................................. SUCCESS [0.574s]
    [INFO] PlayN Hello HTML .................................. SUCCESS [18.829s]
    [INFO] PlayN Hello Flash ................................. SUCCESS [22.045s]
    [INFO] PlayN Hello Android ............................... SUCCESS [14.519s]
    [INFO] PlayN Showcase Metaproject ........................ SUCCESS [0.003s]
    [INFO] PlayN Showcase Core ............................... SUCCESS [1.567s]
    [INFO] PlayN Showcase HTML ............................... SUCCESS [21.663s]
    [INFO] PlayN Showcase Flash .............................. SUCCESS [35.783s]
    [INFO] PlayN Showcase Android ............................ FAILURE [11.533s]
    [INFO] PlayN Cute Metaproject ............................ SKIPPED
    [INFO] PlayN Cute Core ................................... SKIPPED
    [INFO] PlayN Cute HTML ................................... SKIPPED
    [INFO] PlayN Cute Flash .................................. SKIPPED
    [INFO] PlayN Cute Android ................................ SKIPPED
    [INFO] PlayN Payments .................................... SKIPPED
    [INFO] PlayN Payments Core ............................... SKIPPED
    [INFO] PlayN Payments Demo Metaproject ................... SKIPPED
    [INFO] PlayN Payments Demo Core .......................... SKIPPED
    [INFO] PlayN payments HTML ............................... SKIPPED
    [INFO] PlayN payments Server ............................. SKIPPED
    [INFO] PlayN Payments Demo HTML .......................... SKIPPED
    [INFO] PlayN Tests Metaproject ........................... SKIPPED
    [INFO] PlayN Benchmark Metaproject ....................... SKIPPED
    [INFO] PlayN Benchmarks Core ............................. SKIPPED
    [INFO] PlayN Benchmark HTML .............................. SKIPPED
    [INFO] PlayN Manual Tests Metaproject .................... SKIPPED
    [INFO] PlayN Manual Tests Core ........................... SKIPPED
    [INFO] PlayN Manual Tests HTML ........................... SKIPPED
    [INFO] PlayN Manual Tests Flash .......................... SKIPPED
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 2:20.302s
    [INFO] Finished at: Tue Oct 25 15:44:44 CEST 2011
    [INFO] Final Memory: 122M/318M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal com.jayway.maven.plugins.android.generation2:maven-android-plugin:3.0.0-alpha-2:apk (default-apk) on project playn-showcase-android: Cannot create the APKBuilder object: NullPointerException -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
    [ERROR]
    [ERROR] After correcting the problems, you can resume the build with the command
    [ERROR]   mvn  -rf :playn-showcase-android

I found the same error here, but no solution.

A: Are you using the recently released r14 of the Android SDK? It seems like it has some issues with the version of the Maven Android plugin playn uses. Try replacing the plugins section in samples/showcase/android/pom.xml with the following:
<plugins>
  <plugin>
    <groupId>com.jayway.maven.plugins.android.generation2</groupId>
    <artifactId>android-maven-plugin</artifactId>
    <version>3.0.0</version>
    <configuration>
      <androidManifestFile>${project.basedir}/AndroidManifest.xml</androidManifestFile>
      <assetsDirectory>${project.basedir}/assets</assetsDirectory>
      <resourceDirectory>${project.basedir}/res</resourceDirectory>
      <sdk>
        <platform>11</platform>
      </sdk>
      <undeployBeforeDeploy>true</undeployBeforeDeploy>
      <jvmArguments>
        <jvmArgument>-Xmx1024m</jvmArgument>
      </jvmArguments>
      <dex>
        <jvmArguments>
          <jvmArgument>-Xmx1024m</jvmArgument>
        </jvmArguments>
      </dex>
    </configuration>
    <extensions>true</extensions>
  </plugin>
</plugins>

Then cd into samples/showcase and run mvn clean then mvn install.
If that works, I'll look at upgrading all the samples to use the latest android maven plugin later today.


text:
Q: Testcafe - Unable to upload files with input type="url" which is a react custom made file upload component I am trying to upload a file but getting error "The specified selector does not match a file input element", I know testcafe requires input type="file" for uploading files, But as we are reusing our custom component for file uploads where we are giving input type="url" It's not working with testcafe.
Here is the java script/HTML code
<input name="images" accept="image/*" type="url" class="form-control col-11 false" value="">

And I am trying to access the css selector like this
const click_add_image=Selector('input[name="images"]')
const add_image=Selector('input[name="images"],input[inputtype="url"]')

test
    ('add images', async t=>{
        await t
            .click(click_add_image)
            .wait(2000)
           .setFilesToUpload(add_image,[
           './_uploads_/Share_Knowledge.png'
            ])

I am getting error  The specified selector does not match a file input element


text:
Q: I need help. I am running Ubuntu 16.04 and have no idea how to fix this So I've had trouble installing some drivers and updates and this is where the internet has led me, but I can't find a solution to these problems.
When I put insudo dpkg --configure -a
This is the output:
dpkg: dependency problems prevent configuration of cups:
 cups depends on cups-common (>= 2.1.3-4ubuntu0.1); however:
  Version of cups-common on system is 2.1.3-4.

dpkg: error processing package cups (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cups-bsd:
 cups-bsd depends on cups-common (>= 2.1.3-4ubuntu0.1); however:
  Version of cups-common on system is 2.1.3-4.

dpkg: error processing package cups-bsd (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cups-client:
 cups-client depends on cups-common (>= 2.1.3-4ubuntu0.1); however:
  Version of cups-common on system is 2.1.3-4.

dpkg: error processing package cups-client (--configure):
 dependency problems - leaving unconfigured
dpkg: error processing package libcups2:amd64 (--configure):
 package libcups2:amd64 2.1.3-4ubuntu0.1 cannot be configured because libcups2:i386 is at a different version (2.1.3-4)
dpkg: error processing package libcups2:i386 (--configure):
 package libcups2:i386 2.1.3-4 cannot be configured because libcups2:amd64 is at a different version (2.1.3-4ubuntu0.1)
dpkg: dependency problems prevent configuration of cups-filters:
 cups-filters depends on libcups2 (>= 1.7.0); however:
  Package libcups2:amd64 is not configured yet.

dpkg: error processing package cups-filters (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cups-browsed:
 cups-browsed depends on libcups2 (>= 2.0.2); however:
  Package libcups2:amd64 is not configured yet.

dpkg: error processing package cups-browsed (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libcupsmime1:amd64:
 libcupsmime1:amd64 depends on libcups2 (= 2.1.3-4ubuntu0.1); however:
  Package libcups2:amd64 is not configured yet.

dpkg: error processing package libcupsmime1:amd64 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cups-daemon:
 cups-daemon depends on libcups2 (= 2.1.3-4ubuntu0.1); however:
  Package libcups2:amd64 is not configured yet.
 cups-daemon depends on libcupsmime1 (>= 1.5.0); however:
  Package libcupsmime1:amd64 is not configured yet.

dpkg: error processing package cups-daemon (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cups-core-drivers:
 cups-core-drivers depends on libcups2 (= 2.1.3-4ubuntu0.1); however:
  Package libcups2:amd64 is not configured yet.
 cups-core-drivers depends on cups-daemon (>= 2.1.3-4ubuntu0.1); however:
  Package cups-daemon is not configured yet.

dpkg: error processing package cups-core-drivers (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libcupsppdc1:amd64:
 libcupsppdc1:amd64 depends on libcups2 (= 2.1.3-4ubuntu0.1); however:
  Package libcups2:amd64 is not configured yet.

dpkg: error processing package libcupsppdc1:amd64 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libcupsimage2:amd64:
 libcupsimage2:amd64 depends on libcups2 (= 2.1.3-4ubuntu0.1); however:
  Package libcups2:amd64 is not configured yet.

dpkg: error processing package libcupsimage2:amd64 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cups-filters-core-drivers:
 cups-filters-core-drivers depends on libcups2 (>= 1.7.0); however:
  Package libcups2:amd64 is not configured yet.
 cups-filters-core-drivers depends on libcupsimage2 (>= 1.4.0); however:
  Package libcupsimage2:amd64 is not configured yet.

dpkg: error processing package cups-filters-core-drivers (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of libcupscgi1:amd64:
 libcupscgi1:amd64 depends on libcups2 (= 2.1.3-4ubuntu0.1); however:
  Package libcups2:amd64 is not configured yet.

dpkg: error processing package libcupscgi1:amd64 (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 cups
 cups-bsd
 cups-client
 libcups2:amd64
 libcups2:i386
 cups-filters
 cups-browsed
 libcupsmime1:amd64
 cups-daemon
 cups-core-drivers
 libcupsppdc1:amd64
 libcupsimage2:amd64
 cups-filters-core-drivers
 libcupscgi1:amd64


text:
Q: Rational function and morphisms of quasiprojective varieties Let be $k$ an algebraically closed field and let be $X$ a projective nonsingular curve.
Notations
We call $X_h : = X\setminus V(h)$ for any homogeneous polynomial $h$.
A function $f:X\longrightarrow k$ is called regular at $p\in X$ if there exist two homogenous polynomials $F,G$ of the same degree such that $p\in X_G$ and, for every $q\in X_G$ we have $f(q)=F(q)/G(q)$.
Let be $U_f$ the set of the points of $X$ in which $f$ is regular as in the above definition. It's straightforward that $U_f$ is open in $X$.

*

*If $U_f$ is dense, we call $f$ rational;

*if $U_f=X$ we call $f$ regular.

A map $\phi: X\subseteq \mathbb{P}^m \dashrightarrow Y\subseteq \mathbb{P}^n$ defined in an open set $V_{\phi}$ between quasi-projective varieties is called $rational$ if for every $p\in V_{\phi}$ there exist homogenous polynomials $F_0,\ldots ,F_n$ such that $p\in X_{F_0}\cup\ldots\cup X_{F_n}$ and for every $q\in X_{F_0}\cup\ldots\cup X_{F_n}$ we have $\phi(q)=[F_0(q):\ldots :F_n(q)]$.
The facts
I want to prove that each rational function $f\in k(X)$ induces a morphism (i.e. a regular mapping) $\phi : X\longrightarrow \mathbb{P}^1_k$.
We can put $\phi (p)=[1:f(p)]$ if $p\in U_f:=\{q\in X\mid f \text{ regular at }p\}$ and $\phi(p)=[0:1]$ if $p\notin U_f$. In fact, I cannot prove properly that $\phi$ is regular. I want to show that for every $p\in X$ there are two homogeneous polynomials $F,G$ of the same degree such that $p\in X_G\cup X_F$ and for every $q\in X_F\cup X_G$ we have $\phi(q)=[G(q):F(q)]$.
Let be $p\in U_f$; then by rationality of $f$ we have two homogeneous polynomials $F,G$ of the same degree such that $p\in X_G$ and, for every $q\in X_G$ we have $f(q)=F(q)/G(q)$. In this situation I can prove that
$$\phi(q)=[G(q):F(q)]$$ for every $q\in  X_G$ but how can I prove this when $q\in X_F\setminus X_G$??

Edit
I've been told that $X_F\cap U_f\subseteq X_G $ (*) so in this case $X_F\setminus X_G$ does not contain points in which $f$ is regular, thus for every $q\in X_F\setminus X_G$ we have
$$\phi(q)=[0:1]=[G(q):F(q)]$$
Another problem comes from the points $p\in X\setminus U_f$? I know that $X\setminus U_f = X\cap V(h_1,\ldots ,h_s)$ for some polynomials, but only this. I started thinking about choosing $h=\mathrm{gcd}(h_1,\ldots,h_s)$ so if $p\in X\setminus U_f$ we have $p\in V(h)$. If we put $p=[a_0:\ldots :a_n]$ in homogeneous coordinates, there is a $j$ such that $a_j\neq 0$. So put $l=X_j^{\mathrm{deg}\,h}$. With these choiches, we have $p\in X_l\subseteq X_l\cup X_h$ and we must prove that for every $q\in X_l\cup X_h$ there  holds $\phi(q)=[h(q):l(q)]$.
This is somewhat annoying, because

*

*if $q\in X_l\setminus X_h$ then $q\in X\setminus X_h = V(h)\cap X\subseteq V(h_1,\ldots,,h_s)\cap X = X\setminus U_f$. So $$\phi (q) = [0:1]=[h(q):l(q)]$$ and we have done;

*

*if $q\in X_h$ I've no idea of what could happen. Seems rather logical that $V(h)=V(h_1,\ldots,h_s)$ but this would bring to the unpleasant idea that $$q\in X_h=X\setminus (X\cap V(h))=X\setminus (X\cap V(h_1,\ldots,h_s))=X\setminus(X\setminus U_f)=U_f$$ . This is unpleasant because $\phi(q)\neq [0:1]$ and I see no way to make $\phi(q)=[h(q):l(q)]$.

2nd. Edit
I managed to prove the part (*), that is for every quasi-projective variety $X$ and for every rational function $f\in k(X)$ with a local expression $F/G$, we have $U_f\cap (X_F\setminus X_G)=\varnothing $ where $U_f$ is the regular locus of $f$. This is really simple: if $p\in U_f\cap (X_F\setminus X_G)$ the fact that $G(p)=0$ but $p$ is regular point means that we must find another local expression, that is two homogenous polynomials $M,N$ of the same degree such that $N(p)\neq 0$ and $f=M/N$ over $X_N$; by hypothesis we have also $G(p)=0$ and $F(p)\neq 0$. But two local expression must satisfy $MG=FN$ and  evaluating at $p$ we get $0\neq F(p)=M(p)G(p)/N(p)=0$ which is contradictory.
So the only thing to prove is the quoted part above.

A: The point is to prove that $\phi : X\longrightarrow \mathbf{P}^1_k$ as defined above is regular at every point of $X$, even in these which $f$ is not regular at.
The argument must use the fact that $X$ is non-singular, as there are curves such that the extension $\phi$ is not defined. In particular, one must proceed as Hoot suggested in one of the comments.
Let $p\in X\setminus U_f$; we know that there is a regular function $u$ such that $u(p)=0$ and such that $m_p =(u)$, where $m_p$ is the maximal ideal of $\mathscr O _{X,p}$. Then, as $f\in k(X)=\mathrm{Quot}(\mathscr O _{X,p}$ but $f\notin O _{X,p}$, writing $f=\alpha /\beta$ for $\alpha,\beta \in \mathscr{O}_{X,p}$ leads to $\beta \in m_p$. So there is $\beta _1 \in \mathscr O _{X,p}$ such that $\beta = \beta _1 \cdot u$.
If $\beta _1 \notin m_p$, it's great because $\alpha /\beta_1$ is regular and nonzero at $p$ and $f=(\alpha /\beta _1)u^{-1}$ so
$$\phi(p)=[0:1] = [u(p):\alpha (p)/\beta(p)]$$
Else, if $\beta _1\in m_p$ we can repeat the argument and find $\beta_2\in \mathscr O _{X,p}$ such that $f=(\alpha /\beta _2)u^{-1}$. If we could repeat in this way for infinitely many times, we could buid a sequence $\{\beta _j\}_{j\geq 1}$ such that $\beta_j\mid \beta _{j-1}$, and this can't be possibile is the sequence is not finite, being $\mathscr{O}_{X,p}$ an UFD.
So in every case we can write $f=\rho\cdot u^{-\nu}$ where $\rho$ is regular and nonzero at $p$ and $u$ is regular and vanishes at $p$, for some natural $\nu$. Clearly this proves that
$$\phi(p)=[0:1]=[u^{\nu}(p):\rho(p)]$$
defines a regular function for $p\notin U_f$.


text:
Q: Lightest weight MTA to forward all mail to script I need to forward *@domain.com to a script.
I know the EXIM way and the PROCMAIL way.
Is there a lighter way? Any experiences? Which one is the fastest if I JUST WANT it to delivery emails to script? (no pop accounts, nothing else)
(I knew qmail but I don't want to install "big" software that eats too many resources on the server).

A: What you are asking is really about MTAs (Mail Transfer Agents) rather than MDAs (Mail Delivery Agents). Your question includes comments about both (Procmail is an MDA, exim is an MTA).
In your case you are going to dispose of any MDA by just "delivering" to your script. In exim an alias like username: |/path/to/script is enough to get that part done with no fancy internal routing or MDA needed.
As for the MTA, Exim is actually pretty light weight. It doesn't provide pop accounts or anything else, it just handles the chat with other mail servers to accept messages, then passes them off to somebody (Usually an MDA or other mail servers).
Don't make life more complicated for yourself down the road by trying to make a non-standard setup, short circuit normal protections like the validation that MTA's run on incoming mail, etc. Just wire the right parts together. Using a pipe-alias in exim as above is a dead simple way to route mail to a script and still behave properly as an MTA.

A: Do you really want the script to just run, regardless of what is passed to it? Or do you want proper SMTP handling?
The lightest way might be to use something like Python's Twisted library listening for SMTP or a node.js SMTP server script, and have it fire of a script on each message required. That way you get full multi-threading, without much of anything else in the way.
I would say though that Exim and the others like it will be more than fast enough for 99% of uses.

A: If you can spare port 25 on a unique IP what about using netcat to listen on port 25 ? That's truly zero load and install. A wrapper script to restart it after a reboot/fail should be easy too.

A: If you just want to recieve E-Mails you can use a "server" like http://code.google.com/p/subethasmtp/ .
You can have a 1 file java program using this library that will accept all emails and execute some code for it. The problem with it is you will need to have java present on the machine.


text:
Q: Cross dataframe columns "contains List" with dictionary I am trying to create dataframe . from a combination of dataframe with a cross dictionary  as below
enter image description here
dataframe contains multiple columns "N numbers of columns x,y,z,a,b,c ......etc more than 100 columns "
df = pd.DataFrame({'ID':['EF407412','KM043272']
               , 'x': ['[2788, 3140, 4836]','[539, 906, 1494, 1932, 2029,7001]']
               , 'y': ['[1408, 1572, 2277]','[]']
               # dataframe contains multiple columns "N numbers of columns x,y,z,a,b,c ......etc more than 100 columns "
               })

dictionary name is scale, and its items (keys to values) are Customizable and transformation rules from input dataframe to output dataframe were mentioned in the below comments
scale = ("500-10000", {

# Key= Scales and value = Weights, both Customizable

    500: 7000,   #  key is 500 and value is compared with List as  List items >= 7000
2500: 3000,  #  key is 2500 and value is compared with List as  List 7000 > items >= 3000
5000: 1000,  #  key is 5000 and value is compared with List as  List 3000 > items >= 1000
7500: 400,   #  key is 7500 and value is compared with List as  List 1000 > items >= 400
10000:250    #  key is 10000 and value is compared with List as  List 400 > items >= 250
             #  any others List items < 250 will be neglected
             #  any others List items < 250 will be neglected })

important p.s >>> If the input list items contain redundant data, it will be treated in the output as separate values. for example x column contain List [4836, 4836, 4836] output inside column of x_2500 will be [4836, 4836, 4836]

A: Using your df and scale objects...
def make_new_columns(series: pd.Series) -> pd.DataFrame:
    """Given column, make new columns using `scale`."""
    # convert str representation of list to literal list
    series = series.apply(ast.literal_eval)

    scale_dict = scale[1]

    frames = []
    for k, v in scale_dict.items():
        k_frame = pd.DataFrame({f"{series.name}_{k}": series.apply(lambda x: [i for i in x if i >= v])})
        frames.append(k_frame)

    frame = pd.concat(frames, axis="columns")

    cols = frame.columns[frame.columns.str.startswith(f"{series.name}_")]

    for col0, col1 in zip(cols, cols[1:]):
        frame[f"{col1}_"] = frame[[col0, col1]].applymap(set).apply(lambda x: x[col1].difference(x[col0]), axis=1)

    # the first `x_...` col is `x_500` and will not change -- remove others
    frame = frame.drop(columns=cols[1:])

    frame.columns = frame.columns.str.strip("_")

    frame[cols] = frame[cols].applymap(lambda x: [0] if not len(x) else list(x))

    return frame

# apply `make_new_columns` to x, y, z, a, b, c, ...
cols_to_apply = df.loc[:, "x":].columns

to_join = []
for col in cols_to_apply:
    new = make_new_columns(df[col])
    to_join.append(new)

df = df[["ID"]].join(to_join)

df

A: Try:
from ast import literal_eval

df["x"] = df["x"].apply(literal_eval)
df["y"] = df["y"].apply(literal_eval)

x = df.set_index("ID").stack().to_frame().explode(0).dropna()

x["name"] = pd.cut(
    x[0],
    list(scale[1].values())[::-1] + [float("inf")],
    right=False,
    labels=list(scale[1])[::-1],
)
x["tmp"] = x.index.get_level_values(1)

x = x.pivot_table(
    index=pd.Grouper(level=0),
    columns=["tmp", "name"],
    values=0,
    aggfunc=list,
)

idx = pd.MultiIndex.from_product(
    [set(x.columns.get_level_values(0)), scale[1].keys()]
)

x = x.reindex(idx, axis=1)
x.columns = [f"{a}_{b}" for a, b in x.columns]
x = x.apply(lambda s: s.fillna({i: [0] for i in x.index}))

print(
    x[
        sorted(x.columns, key=lambda x: (x.split("_")[0], int(x.split("_")[1])))
    ].reset_index()
)

Prints:
         ID   x_500        x_2500              x_5000      x_7500 x_10000 y_500 y_2500              y_5000 y_7500 y_10000
0  EF407412     [0]  [3140, 4836]              [2788]         [0]     [0]   [0]    [0]  [1408, 1572, 2277]    [0]     [0]
1  KM043272  [7001]           [0]  [1494, 1932, 2029]  [539, 906]     [0]   [0]    [0]                 [0]    [0]     [0]


text:
Q: STL Set inside Map , weird seg fault and Valgrind analysis I have a weird segmentation fault in my code which use following data structure :
map< uint64_t, set<uint64_t> > _key_to_block;

Valgrind complain of _key_to_block.erase(it) with this message:
Address 0x6106118 is 56 bytes inside a block of size 88 free'd

for erasing an element from map like this:
map< uint64_t, set<uint64_t> >::iterator it     = _key_to_block.find(key);
(it->second).clear();
_key_to_block.erase(it);

Moreover, Valgrind also complains of (it->second).insert(k); with this massage:
Invalid read of size 8

for inserting an element in the STL set like this:
map< uint64_t, set<uint64_t> >::iterator it = _key_to_block.find(key);
(it->second).insert(value);

However, it does not complains of this line :
setit = it->second.find(value);

Any idea ?

A: I don't see any checks against end() so I'm going to take a guess that your find calls didn't actually find the key and returned the end iterator. Once you start dereferencing that, all bets on behavior are off. You should either use operator[] to always create the element or check the results of your find against end.


text:
Q: Adding GDELT to BigQuery I've been trying to add GDELT events data to BigQuery with no success so far..
I use the link below in my attmpets; clicking view dataset >> create table >> add arbitrary table name >> create table and then I get this error:
You are missing permissions and may need to talk to your administrator. Original error message: Failed to create table: Access Denied: Dataset gdelt-bq:gdeltv2: Permission bigquery.tables.create denied on dataset gdelt-bq:gdeltv2 (or it may not exist).
I tried changing my roles to admin and data editor but I still get the same error above.
Anyone who can help?
https://console.cloud.google.com/marketplace/details/the-gdelt-project/gdelt-2-events?filter=solution-type:dataset&id=a41570ce-2ee5-444c-80d8-1dd6ee6602ad&walkthrough_tutorial_id=java_gae_quickstart
_gae_quickstart

A: GDELT is a public dataset where it can't be edited or you can't create a table without the administrator's permissions. Even if you tried changing your roles to Admin and Data Editor, the changes you made are within your project only. The ones who handle GDELT dataset are the ones who will grant you the permissions, but I don't think it is possible since GDELT is for public use.
I highly recommend the procedure written in the comment above for you to be able to view and explore GDELT database.


text:
Q: How to use wkhtmltopdf 0.12.3 in alpine linux typing:
pdfkit.from_string("hello world", "output.pdf"),

then get the following:

IOError: wkhtmltopdf exited with non-zero code -6. error:
  QXcbConnection: Could not connect to display


text:
Q: Is GLX_ARB_multisample supported by OSX I'm trying to use glfw3 with OpenGL 3.3 (core profile) on OSX with full screen anti-alisiang via glfwWindowHint(GLFW_SAMPLES,4). My extension loader glad tells me that GLX_ARB_multisample is not supported, which is required for GLFW_SAMPLES to work.
My question is very basic: Am I doing something wrong or is multi-sampling currently not supported by glfw on OSX?

A: No, GLX_ARB_multisample is not supported by OSX's native GL API.

My extension loader glad tells me that GLX_ARB_multisample is not supported, which is required for GLFW_SAMPLES to work.

You are totally wrong here. GLX_ARB_multisample is an GLX extension, which is relevant for the X11 Window System, not for OSX's  Cocoa/NSOpenGL APIs. OSX does support multisampling, and it is controlled via the NSOpenGLPFASamples attribute, and GLFW is using it.
If you even try to load GLX extensions on that platform, you are doing something wrong (and this is not glad's fault).


text:
Q: re expressing the Cauchy Riemann Equations $$
\begin{split}
\frac{\partial f}{\partial z}
 &= \frac{\partial f}{\partial x}
    \frac{\partial x}{\partial z}
  + \frac{\partial f}{\partial y}
    \frac{\partial y}{\partial z}\\
 &= \frac12 \left(\frac{\partial f}{\partial x}
                -i \frac{\partial f}{\partial y}
 \right)
\end{split}
$$
I saw the Cauchy-Riemann on wolfram alpha and am confused as to how the second equality comes about, any insight would be great!
http://mathworld.wolfram.com/Cauchy-RiemannEquations.html

A: To deduce the second equality it is sufficient to note that, since $z=x+iy$ (and $\bar{z}=x-iy$), then
$$
x=\frac{1}{2}(z+\bar z)\quad y=-\frac{i}{2}(z-\bar z)
$$
so
$$
\frac{\partial x}{\partial z}=\frac{1}{2}\quad\frac{\partial y}{\partial z}=-\frac{i}{2}
$$


text:
Q: Pandas not importing when run in visual studio code command line? I'm running a simple .py file that only contains
import pandas as pd

in the visual studio code terminal on my desktop and I get this error ModuleNotFoundError: No module named 'pandas', but when I run
import pandas as pd

in a cell in a .ipynb file in visual studio in the same directory it runs fine. What might be the problem here?
UPDATE: In fact, simply running
python3 test.py

in the terminal runs the code perfectly. So I seem to be not understanding something about how to use the visual studio code terminal


text:
Q: discord.py entering none instead of there @username Here is what i have right now!

@client.command()
async def punch(ctx, *, response):
      response = response.replace("(", "")
      response = response.replace(")", "")

      member = discord.utils.get(client.get_all_members(), id=response)

      embed = discord.Embed(title=f":house_with_garden: Punched: {member} :punch:", color=discord.Colour.green())
      await ctx.send(embed=embed)

And this is what happens: I want it to be Sauq#(then my tag)

A: You can use MemberConverter
@client.command()
async def punch(ctx, member: discord.Member): # By typehinting the member arg, `MemberConverter` will automatically convert it to a `discord.Member` instance
    embed = discord.Embed(title=f":house_with_garden: Punched {member} :punch:", color=discord.Colour.green()) # If you want to mention the member: `member.mention`
    await ctx.send(embed=embed)


text:
Q: Capacitance of a single straight wire What is the capacitance of a single straight wire?
calculating the electric field using Gauss's law, I get a constant divided by the distance from the wire (r). Integrating 1/r gives me ln(r). evaluating r at the radius of the wire and infinity gives me infinity. On the one hand, I am thinking that I am using the field from an infinitely long straight wire, maybe an infinitely long wire has infinite capacitance. But what is confusing is that using q = CV (charge = capacitance times voltage) , I get cL = Cck*ln(r) where c is charge per unit length and k is the rest of the constants. There I am plugging in L, which means I am not technically using an infinitely long wire.

A: Using Gauss's law, you should have found that the field strength (radial) at distance $r$ from the central axis of a long straight wire of length $\ell$ and radius $r_1$ carrying charge $Q$ is of magnitude
$$E= \frac{Q}{4 \pi \epsilon_0 \ell r}$$
So the pd between the surface of the wire (of radius $r_1$) and a surrounding co-axial conducting surface of radius $r_2$ is
$$V=\int_{r_1} ^{r_2} \frac{Q}{4 \pi \epsilon_0 \ell r}dr=\frac{Q}{4 \pi \epsilon_0 \ell} \ln \frac{r_2}{r_1}$$
The capacitance is therefore
$$C=\frac QV=\frac{4 \pi \epsilon_0 \ell}{\ln \frac{r_2}{r_1}}$$
So, not surprisingly, the capacitance is proportional to the length of the wire.
More interestingly, the capacitance goes to zero as we make the surrounding conducting surface larger and larger ($r_2>>r_1$). In other words, an isolated conducting wire would have zero capacitance. In practice there will be objects at various distances from the wire, and the charged wire will induce charges on these objects, so the system's capacitance, though hard to calculate, will not actually be zero (when it can be defined at all).
Hope this helps.


text:
Q: How to find logical 'or' operator (||) from a sequence using Regex Python I want to find and replace the logical "or" operator (||) from my sequence. How can I do it?
Following is the code, I'm trying
import re
sequence = "if(ab||2) + H) then a*10"
expr = re.sub(r"||","_or_",sequence)
print (expr)

Expected answer should be
if(ab_or_2) + H) then a*10

A: You need to use escape sequence '\' here since '|' is a special character.
Python docs:

'|'
A|B, where A and B can be arbitrary REs, creates a regular
  expression that will match either A or B. An arbitrary number of REs
  can be separated by the '|' in this way. This can be used inside
  groups (see below) as well. As the target string is scanned, REs
  separated by '|' are tried from left to right.

So you need to do :
expr = re.sub(r"\|\|","_or_",sequence)

Or, using re.escape() : thanks to @Steven for pointing this out
expr = re.sub(re.escape("||"),"_or_",sequence)

And you will get :
IN : sequence = "if(ab||2) + H) then a*10"
OUT : 'if(ab_or_2) + H) then a*10'

Edit :
If you are not required to just use regex, you can directly use replace for the string. ie,
sequence.replace('||','_or_')

Here you won't have to worry about the special character.


text:
Q: Proving the limit $\lim _{n\to \infty }\left(\frac{1}{\sqrt{n^2+1}}+\frac{1}{\sqrt{n^2+2}}+...+\frac{1}{\sqrt{n^2+n}}\right)=1$ I think I tried everything I know when trying to prove this limit
$$\lim _{n\to \infty }\left(\frac{1}{\sqrt{n^2+1}}+\frac{1}{\sqrt{n^2+2}}+...+\frac{1}{\sqrt{n^2+n}}\right)=1$$
but I think that either there is some rule that I don't know or I am simply missing the creativity needed to solve it.. Help would be very appreciated.

A: Very informally,
$$\lim _{n\to \infty }\frac1n\left(\frac{1}{\sqrt{1+\frac1{n^2}}}+\frac{1}{\sqrt{1+\frac2{n^2}}}+\cdots\frac{1}{\sqrt{1+\frac n{n^2}}}\right)=\lim _{n\to \infty }\int_0^1\frac{dx}{\sqrt{1+\frac xn}}.$$

A: You might consider the following "creative"...
It's easy to see that $a_n:=-2\sqrt{n} +\sum_{k=1}^n \frac1{\sqrt{k}}$ is decreasing, and since $$2\sqrt{n}-2=\int_1^n\frac{dx}{\sqrt{x}}\le\sum_{k=1}^n \frac1{\sqrt{k}}$$ we find $a_n$ converges. It thus suffices to note your expression can be written as $$\sum_{k=1}^{n^2+n} \frac1{\sqrt{k}} -\sum_{k=1}^{n^2} \frac1{\sqrt{k}}=2\sqrt{n^2+n}-2n+o(1)=2n\left(\sqrt{1+1/n}-1\right)+o(1)\to1.$$

A: Hint: squeeze that thing
$$\frac n{\sqrt{n^2+n}}\le\frac1{\sqrt{n^2+1}}+\frac{1}{\sqrt{n^2+2}}+...+\frac{1}{\sqrt{n^2+n}}\le\frac n{\sqrt{n^2+1}}$$


text:
Q: Is there an implemented example of an almost reversible heat engine? I'm reading Feynman's discussion of Reversible engines (Vol I 44.3) in The Feynman Lectures on Physics.  His discussion is very abstract, and leaves a lot of practical questions unanswered.  Rather than attempting to ask several questions which come to mind, it seems reasonable to consider a real mechanism which comes "as close as possible" to an ideal heat engine.
Has anybody created such a device?  That is, one which requires very little additional energy in order to get the machine to return to its initial state after "doing work one the Universe" by transferring the work from the Universe back to the engine?

A: The Rankine cycle is a very important model of steam turbine operation in which the isothermal compression segment is via steam to liquid phase change and also while heat is absorbed there is an isothermal expansion segment during which liquid to steam phase change takes place. There are two near adiabatic compression/expansion segments of the cycle and to the extent these are reversible are also isentropic. This is not quite a Carnot cycle but most of the "action" is like that, see details in https://en.wikipedia.org/wiki/Rankine_cycle .

A: In the low power limit real Stirling engines approach ideal efficiency.
The actual cycle of these machines is not ideal over finite temperature differences, but they can run over very small temperature differences (albeit at low power) minimizing their deviation from ideal behavior.
There is also an idealized cycle, but it is not terribly representative of real machines.
You can buy low power demo version for a few hundred dollars that are designed to run on the temperature difference between a hot or cold beverage and the ambient temperature of the room (they reverse direction when you move them from your coffee to your ice tea!).

A: Well known examples of (almost) reversible heat engines are the Stirling engines developed by Philips NV, The Netherlands, since the 1950. These Stirling engines use the Stirling cycle which has the same efficiency as the Carnot cycle. As motors (generators) they work with different external heat supplies (combustion, solar, etc.). With the reverse cycle and mechanical work input they work as compact and small heat pumps that are used for cooling and liquid air production. Thus the Stirling engines are prime examples of commercially implemented heat engines that use a reversible thermodynamic process in both directions.


text:
Q: Notifications being blocked I don't know is this is the place to ask or even if this is a VC issue.
I am using firebase cloud messaging.
The page works fine and the messaging works as expected
However, when I debug the page in VCODE using F5 or SHIFT F5 the notifications are blocked
Has anyone got any recommendations where I can start looking
So far I have reinstalled both CHROME and VSCODE with no success
Thanks

A: OK, so I found the issue.
It was the configuration of the launch.json file
I had to include "port":443, in it
I have no idea how it changed


text:
Q: Is there an equivalent to webmock for testing client side code Is there an equivalent to webmock or vcr for client side code? ... Or is it possible to use webmock with client side code already?

A: You can use sinon's FakeXMLHttpRequest, or nock.

A: A rewriting web proxy for testing interactions between your browser and external sites. Works with ruby + rspec

A: Nowadays, try Mockttp.
It can mock requests for both Node & browser, it uses real requests thereby giving you far more accurate results than Nock et al, and it can either mock as a fake server (reconfiguring your target URLs) or an intercepting proxy (making requests to the real URLs, and intercepting some/all of them).
It's also got good support for running tests in parallel, which global-mocking libraries can't do, and lots of other nice modern features.


text:
Q: UIViewContentModeScale mode of the cell image change silently after the cell is touched(highlighted) EDIT:
I get the issue fixed by create a customize cell.(However, still have another questions.) But why the default cell does not work is still a mystery...
Cory 's answer did not fix the issue but clipsToBounds is really a point and I appreciated his continuous help. So I give him the bounty but not accept his answer as the answer. The answer still in the wind....
================================
I set the UIViewContentModeScale mode of the cell image to AspectFill (left image) and the image was correctly displayed(Fill the image view but keep the aspect). However, after touch and hold on the cell, image's will change: the imageView's frame and contentViewMode are changed. (see the first cell of the left image below )
This is really wired and I can believe such as basic thing could goes wrong so there must be some stuff I was missing out.
Environment: Xcode 4.3 iOS5.1 simulator & device.

UPdate:
I set the UIViewContentMode using the inspector of the storyboard.
And by the way ,I used SDWebImage/UIImageView+WebCache.h.
UPdate2:
I set explicitly the content mode in the code but issue still there.
[cell.imageView setContentMode:UIViewContentModeScaleAspectFill];
update4:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumCell"];

    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"AlbumCell"];

    }
    //[cell.imageView setContentMode:UIViewContentModeScaleAspectFill];
    //[cell.imageView setClipsToBounds:YES];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    Album *album = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [album.title description];
    cell.detailTextLabel.text = [self.userVisiableDateFormatter stringFromDate:album.releaseDate];

    //[cell.imageView setContentMode:UIViewContentModeScaleAspectFill];
    [cell.imageView setImageWithURL:[NSURL URLWithString:album.coverThumbnailUrl]
                placeholderImage:[self placeHolderImage]];

}

A: I was able to find a couple of different things that might be the problem.
First it try setting the clipsToBounds property:
img1.contentMode = UIViewContentModeScaleAspectFill;
img1.clipsToBounds = YES;

The second is:
The reason you don't see a difference between those modes is that the UITableViewCell automatically sizes its image view to fit the aspect ratio of the image. The content modes only come into play when the view's aspect ratio is different from the image's.
Either override layoutSubviews in your custom UITableViewCell class or create an image view yourself (don't use the one that the table view cell provides).
EDIT 1:
After looking at your code the problem may lie in how your handling your cell configuration. Pointers maybe getting released when they shouldn't. Try these 2 options:
Option 1:
Keep your current method of passing off configuration to a new method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumCell"];

    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"AlbumCell"];

    }

    return [self configureCell:cell atIndexPath:indexPath];
}

- (UITableViewCell*)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* returnCell = cell;

    Album *album = [self.fetchedResultsController objectAtIndexPath:indexPath];
    returnCell.textLabel.text = [album.title description];
    returnCell.detailTextLabel.text = [self.userVisiableDateFormatter stringFromDate:album.releaseDate];

    [returnCell.imageView setContentMode:UIViewContentModeScaleAspectFill];
    [returnCell.imageView setClipsToBounds:YES];

    [returnCell.imageView setImageWithURL:[NSURL URLWithString:album.coverThumbnailUrl]
                placeholderImage:[self placeHolderImage]];

    return returnCell;
}

Option 2: (my recommendation)
Configure the cell in the delegate method. It's ok to do this here and it's not bad practice. This is delegate method is there to configure the cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumCell"];

    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"AlbumCell"];

    }

    Album *album = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [album.title description];
    cell.detailTextLabel.text = [self.userVisiableDateFormatter stringFromDate:album.releaseDate];

    [cell.imageView setContentMode:UIViewContentModeScaleAspectFill];
    [cell.imageView setClipsToBounds:YES];

    [cell.imageView setImageWithURL:[NSURL URLWithString:album.coverThumbnailUrl]
                placeholderImage:[self placeHolderImage]];

    return cell;
}

A: set the same image for highlighted state also .

A: it could be the case that you need to set your auto-resizing (or struts & springs, if you have learned that terminology).
in an app in which i have a custom cell with an image on the left similar to yours, i have my autoresizing set up as in the following picture:

note that i have it set up so that the size remains constant within the cell frame, and that the top, bottom and left size are commanded to hug those edges with that much gap on each side.
aside from that, i believe you are right that aspectFill is the choice for that setting.  clipToBounds really shouldn't matter; it will only be necessary if that view were a subview of another view in which it was supposed to appear where it's size was larger than the view it is a subview of.

A: I encountered a similar issue for a subclassed UITableViewCell with a subclassed UIImageView property. Changing the name of this property from 'imageView' to something else fixed the problem for me.


text:
Q: Magento 2: Image Field Checkbox Not Working I'm new to Magento, i have a image field, when i upload image and edit it, like next time i want to remove the uploaded image, i checked the checkbox and hit the save button, but image do not delete, I WANT TO DELETE IMAGE WHEN CHECKBOX CHECKED.
Here is my image field:
        $fieldset->addField(
            'filename',
            'image',
            [
                'label' => __('File'),
                'title' => __('File'),
                'name' => 'filename',
                'required' => true,
                'disabled' => $isElementDisabled,
            ]
        );

\app\code\EC\Customimport\Controller\Adminhtml\Index\Save.php
<?php
namespace EC\Customimport\Controller\Adminhtml\Index;

use Magento\Backend\App\Action;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;

class Save extends \Magento\Backend\App\Action
{

    /**
     * @param Action\Context $context
     */
    protected $_fileUploaderFactory;

    public function __construct(
        Action\Context $context,
        // \Magento\Framework\File\UploaderFactory $uploaderFactory,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
        StoreManagerInterface $storeManager,
        \Magento\Framework\Filesystem $filesystem
        )
    {
        $this->_fileUploaderFactory = $fileUploaderFactory;
        $this->_storeManager = $storeManager;
        $this->_filesystem = $filesystem;
        parent::__construct($context);
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        $pathurl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'customimport/';
        $mediaDir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
        $mediapath = $this->_mediaBaseDirectory = rtrim($mediaDir, '/');

        if(!empty($_FILES['filename']['name'])){
            $uploader = $this->_fileUploaderFactory->create(['fileId' => 'filename']);
            $uploader->setAllowedExtensions(['jpg','jpeg','gif','png','csv','xlsx']);
            $uploader->setAllowRenameFiles(true);
            $path = $mediapath . '/customimport/';
            $result = $uploader->save($path);
        }
        $currenttime = date('Y-m-d H:i:s');

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {
            $model = $this->_objectManager->create('EC\Customimport\Model\Customimport');

            $id = $this->getRequest()->getParam('customimport_id');
            if ($id) {
                $model->load($id);
            }

            // =============UPDATED CODE=============
            if(!empty($_FILES['filename']['name'])){
              $model->setData('filename', $_FILES['filename']['name']);
            }
            elseif(isset($data['filename']['delete'])){
                $model->setData('filename', null);
            }

            $model->setData('title', $data['title']);
            $model->setData('status', $data['status']);
            $model->setData('created_time', $currenttime);
            $model->setData('update_time', $currenttime);

            try {
                $model->save();
                $this->messageManager->addSuccess(__('Item detail has been saved.'));
                $this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['customimport_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\RuntimeException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the entry.'));
            }

            $this->_getSession()->setFormData($data);
            return $resultRedirect->setPath('*/*/edit', ['customimport_id' => $this->getRequest()->getParam('customimport_id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }
}

A: Add This Condition in save.php file :-

Add This Code After if ($data) {

            if(!empty($_FILES['filename']['name'])){
              $model->setData('filename', $_FILES['filename']['name']);
            }
            elseif(isset($data['filename']['delete'])){
                $model->setData('filename', null);
            }


text:
Q: Computing basis from projector Given an idempotent matrix $P$, is there any way to "extract" a basis of the subspace that $P$ projects onto?

A: The subspace that $P$ projects onto is its image, so it suffices to get a basis for the image (column space) of $P$.
The traditional method is as follows: row-reduce, and note which columns become "pivot columns" (columns containing a row's leading $1$).  The columns of $P$ that become pivot columns form a basis of the image of $P$.


text:
Q: Metodo me retorna como valor nulo Quando crio meu código abaixo, ele me retorna essa mensagem de erro, dizendo que meu método é indefinido para nil (undefined method 'errors' for nil:NilClass)
Código:

  <% @task.errors.full_messages.each do |message| %>

<%= message %>

  <%end%>

<%=form_for @task do |f|%>
    <%=f.label :description, 'Descrição'%>
    <%=f.text_field :description%>
    <%=f.label :status, 'Status'%>
    <%=f.check_box :status%>
    <%=f.submit 'Criar'%>
<%end%>

A: No controller, você deve ter uma action apontando para essa view. Lá na action, @task precisa ser instanciado. Veja:
def new
  @task = Task.new
end


text:
Q: SQL query for airline database What will the SQL query be to find the details of the earliest flight based on departure from each airport??
Columns
flight_id, flight_no, departure, arrival, airport_name

A: You can use ROW_NUMBER() to assign a number to each row, per airport, based on the departure time.
For example, you can do:
select *
from (
  select
    flight_id, flight_no, departure, arrival, airport_name,
    row_number() over(partition by airport_name order by departure) as rn
  from t
) x
where rn = 1

A: If you only want the earliest flights then this should help:
select * from t where departure = (select min(departure) from t)

Because the departure could be the same for more than one flight this could result in more than one result row.
To get the earliest flights (same departure at each airport) you could use:
select t1.* from t t1
   JOIN (select airport_name, min(departure) as departure
           FROM t t2 GROUP BY airport_name, departure) x
   ON t1.airport_name = x.airport_name
      AND t1.departure = x.departure

You can still get more than one flight for each airport as there is no further condition which one should be shown if they have the same departure.


text:
Q: Trouble Parsing HTML I currently have a large HTML file filled with directories that I have to parse and extract the names, addresses, zip-codes, phone numbers, alternative phone numbers, and etc, where I will then put the contents inside an array. Some of these directory listings (like the snippet shown below) are less challenging and straightforward to parse.
Aletheia House

201 Finley Avenue West

Birmingham, AL 35204

(205) 324-6502x22

Intake: (205) 324-6502

Sample Array Output
["Aletheia House", "201 Finley Avenue West",
 "Birmingham, AL 35204", "(205) 324-6502x22", "Intake: (205) 324-6502"]

However, with scenarios like the snippet below, I am currently facing issues figuring out a way to go about parsing a scenario using BeautifulSoup, Python and RegEx.
Alcohol and Drug Abuse

Treatment Centers Inc/Pearson Hall

2701 Jefferson Avenue SW

Birmingham, AL 35211

(205) 923-6552x12

Intakes: (205) 923-6552x10 (205) 923-

6552x13

Sample Array Output:
["Alcohol and Drug Abuse Treatment Centers Inc/Pearson Hall",
 "2701 Jefferson Avenue SW", "Birmingham, AL 35211", "(205) 923-6552x12",
 "Intakes: (205) 923-6552x10 (205) 923-6552x13"]

Thank you!


text:
Q: Spring API gateway exception handling I am using Spring 2.7 (webflux) along with Spring API Gateway.
I am not able to catch the exception thrown in interal service throwing an error (403 - Invalid URI)
How to configure Exception handling at Spring API gateway level?
@Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {

        Builder routeBuilder =  builder.routes();
        serviceDiscoveryMetaDataRepository.findAllActiveServiceMetaData().forEach( serviceMetatData -> {
            routeBuilder
                .route(serviceMetatData.getServiceName(),
                        r -> r.path(serviceMetatData.getContextRoot() + "/**")
                        //.and()
                            .filters( f -> {
                                GatewayFilterSpec c = null;
                                try {
                                    c = f.filter(customAddRequestHeaderGatewayFilterFactory.apply());
                                    //c.filter(customHeaderGatewayFilterFactory2.apply());
                                } catch(Exception ex ) {
                                    System.out.println(ex);
                                }
                                return c;
                            })
                            .uri(serviceMetatData.getUri()))
                .build();
        });
        return routeBuilder.build();


text:
Q: How can i get all image urls from my nasa api and add them into an image slider This is my component of imageslider with button next and previous
I need som help how i can get individual img_src values and add them into another array and them use them in my image slider.
I welcome every solution corresponding to my aproach
const ImageSlider = () => {
  const dispatch = useDispatch();
  const ImageList = useSelector((state) => state.ImageList);

  const { loading, error, Images } = ImageList;

  useEffect(() => {
    dispatch(ListImages());
  }, [dispatch]);

  var items = [Images.photos];

  console.log(Images);

  const classes = useStyles();

  function Item(props) {
    return (
      <Paper>
        {props.item.map(data => (

        ))}

        {({ onClick, className, style, next, prev }) => {
          return (
            <Button onClick={onClick} className={classes.button} style={style}>
              {next && "Next"}
              {prev && "Previous"}
            </Button>
          );
        }}
      </Paper>
    );
  }
 return (
    <>
      {loading ? (
        <Loader />
      ) : error ? (

{error}

      ) : (
        <Carousel>
          {items.map((item, i) => (
            <Item key={i} item={item} />
          ))}
        </Carousel>
      )}
    </>
  );
};

export default ImageSlider;
```

A: First of all you should move the Item component out of the ImageSlider. It is being redefined every render. You can use localState to keep track of the index.
const useImageIndexer = (maxIndex) => {
    const [index, setIndex] = useState(0);
    const nextImage = () => {
        setIndex((current) => Math.min(maxIndex, current + 1));
    };
    const prevImage = () => {
        setIndex((current) => Math.max(0, current - 1));
    };
    return [index, nextImage, prevImage];
}

Then to use inside the slider
const ImageSlider = () => {
      const dispatch = useDispatch();
      const ImageList = useSelector((state) => state.ImageList);
      const photos = ImageList.Images.photos;
      const [index, nextImage, prevImage] = useImageIndexer(photos.length);
      const currentPhoto = photos[index];

     // Further down in the code

     if(loading) {
         return (<Loader />);
     }
     if (error) {
         return (
Oh no!
);
     }

     return (

       <button onClick={prevImage}>Previous</button>
       <button onClick={nextImage}>Next</button>

);

It seemed like you were wrapping photos which sounds like an array inside another array, that doesn't look right.
  var items = [Images.photos];


text:
Q: GitHub Pages cannot load pages I use vite to bundle my project, deploy it to GitHub, and would like to use GitHub Pages to load it. For deployment, I use GitHub Actions to deploy my project. But when the page is opened, it is blank and shows this error on the network tab and the error message on the console:

failed to load resource the server responded with a status of 404

I understand the reason for this issue, but can not find a proper solution. Could someone suggest any?

I search online to try to find a solution, like editing vite.config.ts, adding base, or changing the absolute path and relative path for my main.tsx. But the deployed GitHub Pages still be blank. I expect that the project can show on my GitHub Pages.


text:
Q: What does "indexers" mean in this context? Does the sentence in bold mean "This meant that retail customers had to pay for everything to keep institutions/companies from buying Yahoo's stocks"?
One reason the stock rose so quickly after its addition to the index was announced, Silverblatt says, is that it was owned primarily by retail customers rather than institutions. This meant indexers had to pay whatever it took to pry the shares away from Mom and Pop.
Source: https://www.washingtonpost.com/business/economy/what-the-yahoo-sale-tells-us-about-stock-market-bubbles/2017/02/21/ff28abd8-f854-11e6-9845-576c69081518_story.html?utm_term=.13e43f31bc22

A: "indexers" as used here refers to managers of stock market funds that follow the Standard & Poor's 500-stock index (S&P 500). Those funds try to keep the same mix of stocks as is represented in the S&P 500.
When Yahoo joined the S&P 500 those funds had to buy Yahoo shares to keep their mix of stocks in accordance to the new S&P 500 mix. A lack of shares for sale required the funds to pay high prices to small investors ("Mom and Pop"). This is different to you version, because the funds were the buyers paying high prices to the small investors, rather than the retail customers paying high prices to keep their shares.


text:
Q: Convert u'\xe0' to '\u00E0' in Python 2.x? In Python 2.x, how can I convert an unicode string (ex, u'\xe0') to a string (here I need it to be '\u00E0')?
To make it clearer. I do like to have '\u00E0', a string with length of 6. That is, ¥u is treated as 2 chars instead of one escaped char.

A: \u doesn't exist as a string escape sequence in Python 2.
You might mean a JSON-encoded string:
>>> s = u'\xe0'
>>> import json
>>> json.dumps(s)
'"\\u00e0"'

or a UTF-16 (big-endian)-encoded string:
>>> s.encode("utf-16-be")
'\x00\xe0'

but your original request is not fulfillable.
As an aside, note that u'\u00e0' is identical to u'\xe0', but '\u00e0' doesn't exist:
>>> u'\u00e0'
u'\xe0'


text:
Q: Can I use yt-dlp to extract only one video info from a playlist? Here's my code using Python (simplified version):
import yt_dlp

YDL_OPTIONS = {
    'format': 'bestaudio*',
    'noplaylist': True,
}

with yt_dlp.YoutubeDL(YDL_OPTIONS) as ydl:
    info = ydl.extract_info(url, download=False)

The problem comes up when the url directs to a playlist
(e.g. https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)
Here's the output:
[youtube:tab] PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb: Downloading webpage
[youtube:tab] PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb: Downloading API JSON with unavailable videos
[download] Downloading playlist: C++
[youtube:tab] playlist C++: Downloading 100 videos
[download] Downloading video 1 of 100
[youtube] 18c3MTX0PK0: Downloading webpage
[youtube] 18c3MTX0PK0: Downloading android player API JSON
[download] Downloading video 2 of 100
[youtube] 1OsGXuNA5cc: Downloading webpage
[youtube] 1OsGXuNA5cc: Downloading android player API JSON
[download] Downloading video 3 of 100
[youtube] 1E_kBSka_ec: Downloading webpage
[youtube] 1E_kBSka_ec: Downloading android player API JSON
...

As you can see, the 'noplaylist' option didn't work in this case.
Is there an option or function making ydl only extract one video info, for instance the first one, in the entire playlist?

A:
noplaylist: Download single video instead of a playlist if in doubt.

Source: github.com/yt-dlp/yt-dlp
What you shared with us isn't a playlist of a single video so, according to me, there isn't any doubt here.
You can request yt_dlp to treat only the first video of the playlist by adding 'playlist_items': '1' to YDL_OPTIONS. Then the info concerning the video are in info['entries'][0].


text:
Q: Why does Instagram API return two different user_id values for the same user? Nutshell: PHP implementation gets correct user_id, React.js implementation gets incorrect user_id. Why!?
I implemented the Instagram Basic Display API OAuth flow in PHP and in Javascript under React.
The flow under PHP works fine - I get a code, I POST it using curl to /oauth/access_token, I receive a client_id and an access_token, all fine, subsequent Graph API requests work just fine.
Then I moved to rebuild it in Javascript. Here, when I get a code, and I POST it using fetch to /oauth/access_token, with the same client_id and client_secret, and the same authenticating user, essentially the same request, just a different redirect URL (obviously), I receive a token and a different user_id, one that does not work (it gets a 400 error from Graph API).
Oddly enough, the bad user_id is consistently smaller by 1 than the one that I get with PHP: the good one ends with 93, the bad one ends with 92. If I do the unspeakable and just manually increase the wrong user_id I received, I obtain a valid user_id for which the token works!
So why is Instagram sending me a wrong user_id, and how can I help it?

A: I finally found the cause, moments ago, after writing the question and earlier wasting 5 hours on analyzing whatever I could think of.
The user_id is sent as a number larger than Number.MAX_SAFE_INTEGER, and thus JSON.parse fails to parse it correctly. Instagram should be encoding the user_id field as a string. This API endpoint thus needs to be parsed manually. I "fixed" mine by filtering the results as such:
text = text.replace(/"user_id":\s*(\d+)/,'"user_id":"$1"'). Still, encoding such large numbers as "numbers" in JSON is a horrible practice and Instagram should fix their API instead.


text:
Q: Is there a way to customise keyboard shortcuts for a Java executable? Is there a way to customise keyboard shortcuts for a Java executable? I cannot add it in System Preferences > Keyboard > Shortcuts > App Shortcuts as it's an executable and does not end in .app.
It's part of the JRE (Java SE Runtime Environment) bundle in Contents/Home/bin/java.


text:
Q: Conditional span display in table I'm displaying in a table, several columns with different values. I would like only to show the "spans" in the cells if the value is not empty. I can achieve this with something like this:

            {claim.state && (
              State: {claim.state})}
            {claim.comment && (
              Comment: {claim.comment})}

            {claim.something && (
              Something: {claim.something})}
            {claim.another && (
              Another: {claim.another})}

          (...)

I'm wondering if there is a more efficient/cleaner way to do it, so I wouldn't have to repeat {claim.x && ( per span, as there are several columns with several spans + values.

A: You can make separate component:
let SpanRender = ({ data, propName, text }) =>
  data[propName] && (

      {text}
      {data[propName]}

  );

Usage:
  <SpanRender data={{ name: 'David' }} propName="name" text="Name is" />


text:
Q: self cache website for offline html5 I have built a html5 gallery which does work offine but what I need help with is getting the app to detect if the user is online and if so will update the mainifest when the user opens up the app.

A: Firstly, you need to make sure that the manifest file isn't listed in the manifest file as this will prevent it from being re-fetched even if the user is online.
Once you have done this, if you set cache-mode to prefer-online it will re-fetch the pages when a connection is available. If you only want to update the manifiest, you don't need to do this step, most user agents will re-fetch the manifest when a connection is available as long as it is not included in its own listing.
You can also force it using the JavaScript API:
window.applicationCache.update()

You can see this example and lots more details of the JavaScript API here.


text:
Q: Outlook web add-in for iOS not persisting 3rd party cookies - works in Safari I am developing an app for our company; because of legacy reasons when the user logs in we use a
third party JSESSIONID cookie.
Issue
What I am seeing is that the cookie when sent to the client is not saved, and therefore not sent on subsequent requests to the server.  As such, the server does not think the user is logged in.
Normally I would attribute this to the blocking of 3rd party cookies feature of WebKit/View, but I have turned this off in the Safari settings.
As an FYI we have an Ionic/Cordova project that is based on the same code and it works fine in iOS.

*

*If I use the Add-in on MacOS (Native Outlook and Outlook Web) it works fine.

*Works fine in Chrome/Firefox as well.

*Works in Android on Outlook for Android app

Our server sets all the correct CORS headers as well.
Since the add-in is just a webapp, I can launch it directly in Safari on iOS, and login there; this also works.
I am aware that Apple regressed WebKit in version 12 (CORS related), but they fixed it in the latest version of iOS 13/MacOS.  However, Outlook for iOS (WebView) does not appear to be saving cookies.  I can see that looking at the requests coming to the server, they are missing the SessionID which was sent to the client.
I can also see it from the requests when I run through a proxy (Charles) that the Cookie header is not set.
It is also almost impossible to debug the WebView in Outlook for iOS (the webview does not show up in the Safari Developer menu on my Mac).  I am easily able to debug other WebViews such as the mobile project mentioned above.
Question
Is the Webview configured to prevent 3rd party cookies explicitly? if yes, can it be turned off somehow? I have turned off the 3rd party tracking in Safari, but that does not appear to help.
I have been reluctant to use the DialogJS API since the login flow is working on my Mac; and this would considerable change our UX for login.  Also, I have not seen any examples of using this API for a mobile project.  Can it be used with a mobile project, and if so what would it look like?
All the examples relate to the desktop only.