text:
Q: Why this actionEvent on a Java Swing menu item does not work? I have created a basic JFrame using NetBeans form designer. I have reduced it to just a couple of menu items.
I intend to do something when user clicks on "Open", my understanding is that I have to add an "actionPerformed" through a listener, which can be done using NetBeans Designer.

    private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
        System.out.println("ACTION PERFORMED");
    }

But when I click on "Open" nothing happens I can not see the output message.
This is my main routine:
package test.dbviewer;

import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class SealionDBViewer {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {

        UIManager.setLookAndFeel ("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
        JFrame databaseViewer = new DatabaseViewer();
        databaseViewer.setVisible(true);
    }

}

This is the reproducible code that NetBeans generate:
package test.dbviewer;

public class DatabaseViewer extends javax.swing.JFrame {

    /**
     * Creates new form DatabaseViewer
     */
    public DatabaseViewer() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu3 = new javax.swing.JMenu();
        jMenu4 = new javax.swing.JMenu();

        jMenuItem1.setText("jMenuItem1");

        jMenuItem2.setText("jMenuItem2");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jMenu3.setText("Open");
        jMenu3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu3ActionPerformed(evt);
            }
        });
        jMenuBar2.add(jMenu3);

        jMenu4.setText("Exit");
        jMenuBar2.add(jMenu4);

        setJMenuBar(jMenuBar2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 267, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
        System.out.println("ACTION PERFORMED");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DatabaseViewer().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JSplitPane jSplitPane1;
    // End of variables declaration
}


text: Q: varios usuarios un login buenas tengo una duda estoy trabajando en sql server y quisiera saber si en un mismo login puede haber varios usuarios? ya que cuando lo intento me sale:' El inicio de sesión ya tiene una cuenta con otro nombre de usuario.'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting of time and/or date I am trying to figure out how to verify the sorting of time and/or a date using java and selenium. Here is my situation... So if I receive an email today, my Inbox displays the time the message was received. However if I received an email yesterday, the Inbox would display yesterday's date. I am trying to verify that in descending order, the emails with a time would appear first, followed by emails with dates.
Here is my code which works if there is only dates. Can someone please help me with figuring out how to verify the time as well?
  protected void validateDateDescendingOrder(String className) {
    // create a list
    List<WebElement> messageElements = driver.findElements(By.cssSelector("div.scrollable-panel div." + className));
    List<String> messageList = new ArrayList<String>();
    for (WebElement element : messageElements) {
      messageList.add(element.getText());
    }

    // create a new list and sort
    List<String> sortedmessageList = new ArrayList<String>();
    sortedmessageList.addAll(messageList);
    Collections.sort(sortedmessageList, new Comparator<String>() {
      DateFormat f = new SimpleDateFormat("MM/dd/yy");

      @Override
      public int compare(String o1, String o2) {
        try {
          return f.parse(o2).compareTo(f.parse(o1));
        } catch (ParseException e) {
          throw new IllegalArgumentException(e);
        }
      }
    });

    // compare the original list order with the sorted list to make sure they match
    assertEquals(sortedmessageList, messageList);
  }

A: hope this will help to you using java 8
List<String> date = Arrays.asList("2015-11-09", "2015-11-11", "2015-11-08", "2015-11-08");
List<LocalDate> convetedSortedDate = date.stream().map(LocalDate::parse).sorted().collect(Collectors.toList());

//or
 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy '@'hh:mm a");
    Collections.sort(datestring, (s1, s2) -> LocalDateTime.parse(s1, formatter).
            compareTo(LocalDateTime.parse(s2, formatter)));

A: *

*Change DateFormat f = new SimpleDateFormat("MM/dd/yy"); format to also include Time

*If an exception is thrown in the Parse section, do concatenation between Date.Now and the Time; then do the Parse again. (Maybe the date in this case is 0/0/0 or something and you need to identify if this the case)

*Do the sort

A: All you are missing is the parser. There is a very useful library - Apache-lang - that has many interesting helper methods.
In my case, I have am also comparing dates, but the date strings have several different formats. Using the above library, I can do something like this:
import org.apache.commons.lang3.time.DateUtils;

private Date magicParseDate(final String date) {
try {
    return DateUtils.parseDate(date, "yyyyMMdd-S", "yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy HH:mm:ss z");
} catch (ParseException ignore) {
    // empty values
    return new Date(0);
}
}

Then in your compare function just call magicParseDate().


text:
Q: Full Outer Join on Access I need to perform a FULL OUTER JOIN in Access, so I found a thread on Stack Overflow that gave me the following model:
SELECT *
    FROM AA
        LEFT JOIN BB ON AA.C_ID = BB.C_ID AND AA.Currency = BB.Currency
UNION
SELECT *
    FROM AA
        RIGHT JOIN BB ON AA.C_ID = BB.C_ID AND AA.Curency = BB.Currency

So at first it seems to work (around 95% of the results match) but when I check the total sum of a column, it has slightly changed (In my case I have 800K rows, therefore the change is quite important).
Also, some of the IDs in each table are NULL, and each row with an ID NULL needs to be on a different row after the full outer join .
I think that some rows, do you know what's wrong ?
Thanks in advance

A: I would recommend creating a list of all ids/currency combinations and then using  left joins:
SELECT AA.*, BB.*
FROM ((SELECT AA.C_ID, AA.Currency FROM AA
       UNION  -- on purpose to remove duplicates
       SELECT BB.C_ID, BB.Currency FROM BB
      ) as IDS LEFT JOIN
      AA
      ON AA.C_ID = IDS.C_ID AND
         AA.Currency = IDS.Currency
     ) LEFT JOIN
     BB
     ON AA.C_ID = BB.C_ID AND
        AA.Currency = BB.Currency;

NULL values pose an issue for the full joins.  As with the definition of FULL JOIN in SQL, NULL values do not match.  You can extend the logic to also compare NULL values:
SELECT AA.*, BB.*
FROM ((SELECT AA.C_ID, AA.Currency FROM AA
       UNION  -- on purpose to remove duplicates
       SELECT BB.C_ID, BB.Currency FROM BB
      ) as IDS LEFT JOIN
      AA
      ON (AA.C_ID = IDS.C_ID OR AA.C_ID IS NULL AND IDS.C_ID IS NULL) AND
         (AA.Currency = IDS.Currency OR AA.CURRENCY IS NULL AND IDS.CURRENCY IS NULL)
     ) LEFT JOIN
     BB
      ON (BB.C_ID = IDS.C_ID OR BB.C_ID IS NULL AND IDS.C_ID IS NULL) AND
         (BB.Currency = IDS.Currency OR BB.CURRENCY IS NULL AND IDS.CURRENCY IS NULL);


text:
Q: How does LaTeX tell me that it wants to be run a second time? Sometimes, when I use the longtable package I get a message in the output:
Package longtable Warning: Table widths have changed. Rerun LaTeX.

I read that it can be as often as three times that XeLaTeX must be run until the message disappears. So currently my deploy script re-runs XeLaTeX until the output no longer contains the string Rerun LaTeX.
So, is this the official way (used by all packages) to detect that a re-run is necessary or is there another way like a specific return value? I can already rule out the existence of the .aux file as an indicator, because that file is never deleted.

A: There is no general mechanism in the LaTeX2e kernel for reporting 'rerun LaTeX' or similar to the user. As such, it is down to each package author to decide how to pass on this information. For example, the kernel will issue a message of the form
LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.

if there are new \label commands in the document, a model followed by the etaremune package which also uses the LaTeX warning mechanism:
LaTeX Warning: Etaremune labels have changed.
               Rerun to get them right.

However, other packages use 'info' messages, write directly to the log, etc.
The logreq package is perhaps the closes there is to a general mechanism to request rerunning. It was written by Philipp Lehman principally to pass information to the user from biblatex to request LaTeX/BibTeX/Biber runs, but is designed to be both general and to provide parsable information in the log for automated systems. Before Philipp 'vanished' from the LaTeX world, he and I had discussed briefly implementing a similar idea for LaTeX3 (expl3), and this remains on my 'to do' list. As with most things, a strong need to sort it out is most likely to get me to do it!


text:
Q: Authenticating model upload to VertexAI job from Cloud Scheduler I am trying to run a custom training job on VertexAI. The goal is to train a model, save the model to cloud storage and then upload it to VertexAI as a VertexAI Model object. When I run the job from local workstation, it runs, but when I run the job from Cloud Scheduler  it fails. Details below.
Python Code for the job:
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
import os
import pickle
from google.cloud import storage
from google.cloud import aiplatform

print("FITTING THE MODEL")

# define dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=3)
# define the model
model = RandomForestClassifier(n_estimators=100, n_jobs=-1)
# fit the model
model.fit(X, y)

print("SAVING THE MODEL TO CLOUD STORAGE")
if 'AIP_MODEL_DIR' not in os.environ:
    raise KeyError(
        'The `AIP_MODEL_DIR` environment variable has not been' +
        'set. See https://cloud.google.com/ai-platform-unified/docs/tutorials/image-recognition-custom/training'
    )

artifact_filename = 'model' + '.pkl'
# Save model artifact to local filesystem (doesn't persist)
local_path = artifact_filename
with open(local_path, 'wb') as model_file:
    pickle.dump(model, model_file)

# Upload model artifact to Cloud Storage
model_directory = os.environ['AIP_MODEL_DIR']
storage_path = os.path.join(model_directory, artifact_filename)
blob = storage.blob.Blob.from_string(storage_path, client=storage.Client())
blob.upload_from_filename(local_path)

print ("UPLOADING MODEL TO VertexAI")

# Upload the model to vertex ai
project="..."
location="..."
display_name="custom_mdoel"
artifact_uri=model_directory
serving_container_image_uri="us-docker.pkg.dev/vertex-ai/training/tf-cpu.2-4:latest"
description="test model"
sync=True

aiplatform.init(project=project, location=location)
model = aiplatform.Model.upload(
    display_name=display_name,
    artifact_uri=artifact_uri,
    serving_container_image_uri=serving_container_image_uri,
    description=description,
    sync=sync,
)
model.wait()

print("DONE")

Running from Local Workstation:
I set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to the location of the Compute Engine default service account keys I have downloaded on my local workstation. I also set the AIP_MODEL_DIR environment variable to point to a cloud storage bucket. After I run the script, I can see the model.pkl file being created in the cloud storage bucket and the Model object  being created in VertexAI.
Triggering the training job from Cloud Scheduler:
This is what I ultimately want to achieve - to run the custom training job periodically from Cloud Scheduler. I have converted the python script above into a docker image and uploaded to google artifact registry. The job specification for the Cloud Scheduler is below, I can provide additional details if required. The service account email in the oauth_token is the same whose keys I  use to set the GOOGLE_APPLICATION_CREDENTIALS environment variable. When I run this, (either from local workstation or directly in a VertexAI notebook), I can see that the Cloud Scheduler job gets created which keeps triggering the custom job. The custom job is able to train the model and save it to the cloud storage. However, it is not able to upload it to VertexAI and I get the error meessages, status = StatusCode.PERMISSION_DENIED and {..."grpc_message":"Request had insufficient authentication scopes.","grpc_status":7}. Cannot figure out  what the authentication issue is because in both cases I am using the same service account.
job = {
  "name": f'projects/{project_id}/locations/{location}/jobs/test_job',
  "description": "Test scheduler job",
  "http_target": {
    "uri": f'https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/customJobs',
    "http_method": "POST",
    "headers": {
      "User-Agent": "Google-Cloud-Scheduler",
      "Content-Type": "application/json; charset=utf-8"
    },
    "body": "..." // the custom training job body,
    "oauth_token": {
      "service_account_email": "...",
      "scope": "https://www.googleapis.com/auth/cloud-platform"
    }
  },
  "schedule": "* * * * *",
  "time_zone": "Africa/Abidjan"
}


text:
Q: logs from entity framework generation I'm using EF to communicate with my database.
I made a function import mapping so I can call a Stored Procedure. By on run time I get a error saying "Method not found" referring the method that was created to invoke the SP.
I'm assuming that is an error during the generation on run time.
The question is: Is there any way to see what's going on during the execution time generation so I can find the problem?


text:
Q: C: Convert special ASCII characters ÄÖÜ I'm reading out text from a website with Curl. All the rawdata is being returned character by character with
return memEof(mp) ? EOF : (int)(*(unsigned char *)(mp->readptr++));

My problem is, that all the special characters such as ÄÖÜäöüß etc are all wrong and look very cryptic. I'm currently correcting them manually by adjusting their values using this table:
http://www.barcoderesource.com/barcodeasciicharacters.shtml
I was wondering now, if there is a more elegant way to do this and how others approach these kinds of issues.

A: I guess you have to use an external library like iconv to create a wchar_t string which contains the data. This depends on the used character encoding.

A: This is an encoding issue. If you read data byte by byte, you can handle correctly and easily just single byte encodings (like ISO-8859 "family" and many more), provided you have a way to convert them correctly in a target encoding, if you need. But with encodings like UTF-8 you are less lucky, since to get the right code you need to read 1 byte, or maybe 2, or maybe three... If you stream them into a string, and print the string altogether, and the output device intended encoding is the same of the input encoding, you get the right char shown anyway.
If it does not happen, and you are not printing each byte as if it were a symbol for sure, then the output device intended encoding does not match the one the string is written with.
If the output, once you print the string "altogether" looks ok, then the problem is that you are interpreting each byte as a single character, while it is not (you have a multibyte encoding for char like the special one you mentioned; likely it is UTF-8 but it could be not too).
If you get equal results in both cases (when you print each byte one by one and when you output a string that keeps the whole byte sequence), then the output device intended encoding is a single byte encoding like the input encoding, but they do not match.
Further details would need to know how you collect the bytes you read in order to print them and say that they looks cryptic.
An example.
const char *string = "\xc3\xa8\xc3\xb2\xc3\xa0";
int i;
for(i = 0; string[i] != 0; i++)
{
   printf("%c\n", string[i]);
   // using \n is important; if you "sequence" the chars and the output enc is
   // utf-8, you obtain the right output
}
printf("%s", string);

You obtain different results if the output device encoding is UTF-8; if it is a single byte encoding, you obtain the same output (newlines apart), but it is "wrong" with respect to what I've written, i.e. èòà.
The "same" text is, in Latin1, "\xe8\xf2\xe0". Latin1 is a single byte encoding, so the above speech applies. If printed on a terminal understanding utf-8, you can obtain something like �� ...
So, encodings matter, device/format output encoding matters too, and you must be aware of both in order to handle and show properly the text. (About format, an example could be html, where you can specify the encoding of the content... you must be coherent, and you'll see everything fine)


text:
Q: Trying to make a light bulb using HTML & CSS & JS

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3 Circle</title>

    <button class="circle circle1">Circle1</button>
    <button class="circle circle2">Circle2</button>
    <button class="circle circle3">Circle3</button>

I am trying to make 3 light bulbs represented by circles using HTML & CSS.
So if I turn one light bulb on using the button, the other ones should turn off using the addeventlistener. I can't find ways to make the light bulb turn yellow. Is there anything I am doing wrong? I looked for typos but I can't find any.

A: A few small things need to changed here.

*

*The event type to be passed to the addEventListener is 'click' rather than 'onClick'.

*The variable allCircle returns a list of dom nodes and not a single dom node. So it is essentially a []. Hence properties and methods that are available on a dom node are not accessible on the variable. What you can rather do is write a loop to access each element of the array and then modify their classes one by one
Might also suggest you to put debugger inside your code to see what is happening line by line. This article by Google should help you on using the Chrome dev tools.
This is my first answer on Stack Overflow.

let cir1 = document.querySelector('.circle1')
let cir2 = document.querySelector('.circle2')
let cir3 = document.querySelector('.circle3')

cir1.addEventListener('click', onButton1Click);
cir2.addEventListener('click', onButton2Click);
cir3.addEventListener('click', onButton3Click);

function removeActive() {
  cir1.classList.remove('active');
  cir2.classList.remove('active');
  cir3.classList.remove('active');
}

function onButton1Click() {
  removeActive();
  cir1.classList.add('active');
}

function onButton2Click() {
  removeActive();
  cir2.classList.add('active');
}

function onButton3Click() {
  removeActive();
  cir3.classList.add('active');
}
body {
  background: black;
}

.container {
  display: flex;
  align-items: flex-start;
}

.circle {
  width: 100px;
  height: 100px;
  max-height: 100px;
  -webkit-border-radius: 250px;
  -moz-border-radius: 250px;
  border-radius: 250px;
  background: white;
}

.active {
  background: yellow !important;
  color: red;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3 Circle</title>

    <button class="circle circle1">Circle1</button>
    <button class="circle circle2">Circle2</button>
    <button class="circle circle3">Circle3</button>

A: There seem to be two issues here.

*

*When adding an event listener for a click event, it must be called with click that is to be passed as the first parameter to the listener, but you've added onClick

*querySelectorAll returns a HTMLCollection. So classList will not be a valid property on it. You might want to loop through the elements from allCircles to remove the class.

I've modified the listener and corrected the classist related fix for the first button here https://jsfiddle.net/gr33nw1zard/y7f5wnda/

A: should be click event, not 'onClick'.
cir1.addEventListener('click', onButton1Click);

A: Created one common function for all 3 buttons. onClick event is not available in plain javascript, it's the click that is the correct keyword here. Also, you have to iterate over allCircle's object or use getElementsByClass. This will work for you!

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3 Circle</title>

    <button class="circle circle1">Circle1</button>
    <button class="circle circle2">Circle2</button>
    <button class="circle circle3">Circle3</button>

A: The onClick should be edited to click


text:
Q: Getting inherited property methods to work when wrapped inside method in child class I am trying to get property/setter methods described in the parent class to work when inherited into a child class. I am able to get it to work when I directly assign the call from the parent class as shown below. In my case though, I need to wrap the same call inside a method so that I can make some calculations before I call the parent class. I could get it to work by using fget method and passing an object to it, but I would like the former method to work.
I looked up the issue on StackOverflow and found some methods mentioned that involved using super(), which I tried, but it did not work.
Any help getting this inherited property method to work inside a child class is appreciated!
class A(object):
    """ Base Class """
    def __init__(self, n):
        self.n = n
    @staticmethod
    def slices():
        def get_slices(self):
            return self.n
        def set_slices(self, n):
            self.n = n
        return property(get_slices, set_slices)

class B(A):
    def __init__(self, n):
        self.n = n
    his_slices = A.slices() # <--- works well
    def her_slices(self): # <--- does not work
        return A.slices()

if __name__ == "__main__":
    b = B(100)
    # This works
    print("%d slices" % b.his_slices)
    # 100 slices

    # This fails
    print("%d slices" % b.her_slices)
    # TypeError: %d format: a number is required, not method

    # Can be made to work like this, but I want above to work
    ss = b.her_slices()
    print("%d slices" % ss.fget(b))
    # 100 slices

A: I think you're looking for something more like this.
class A(object):
    """ Base Class """
    def __init__(self, n):
        self.n = n
        self.slices
    def get_slices(self):
        return self.n
    def set_slices(self, n):
        self.n = n
    slices = property(get_slices, set_slices)

class B(A):
    def __init__(self, n):
        self.n = n
    his_slices = A.slices # <--- works well
    def her_slices(self): # <--- does not work
        return self.slices

if __name__ == "__main__":
    b = B(100)
    # This works
    print("%d slices" % b.his_slices)
    # 100 slices

    # This fails
    print("%d slices" % b.her_slices())
    # TypeError: %d format: a number is required, not method

I'm not exactly sure what you're trying to do though.

A: Treat this like any other inheritance. If you need to modify the behavior of a regular function within the child class, you would just redefine the function and either completely change its contents, or extend it with super and further modify it.
In case of setters/getters, you'd do the same thing ... redefine/extend them.
In your case things are a little different because, as one of the commenters points out, slices is actually a staticmethod that returns a property, and not a property attribute itself. So you really don't have an existing named property that you can inherit and extend.
Looking at what you're trying to do in __main__, what you really want to do is create a new property called his_slices in your child class and invoke A.slices appropriately within the getter and setter. Like so
class A(object):
    """ Base Class """
    def __init__(self, n):
        self.n = n

    @staticmethod
    def slices():
        def get_slices(self):
            print("Get", self.n)
            return self.n

        def set_slices(self, n):
            print("Set", n)
            self.n = n

        return property(get_slices, set_slices)

class B(A):
    def __init__(self, n):
        self.n = n

    @property
    def his_slices(self):
        return A.slices().fget(self)

    @his_slices.setter
    def his_slices(self, v):
        value = self.n + v
        print("modified n in setter", value)
        A.slices().fset(self, value)

if __name__ == "__main__":
    b = B(100)

    # setter
    b.his_slices = 101
    # getter
    print("%d slices" % b.his_slices)

If slices were truly a property in the base class, this is how you would inherit and modify the getter and setter. It is also described here
class A(object):
    """ Base Class """
    def __init__(self, n):
        self.n = n

    def get_slices(self):
        print("Get A", self.n)
        return self.n

    def set_slices(self, n):
        print("Set A", n)
        self.n = n

    slices = property(get_slices, set_slices)

class B(A):
    @property
    def slices(self):
        print("Get B", self.n)
        return A.slices.fget(self)

    @slices.setter
    def slices(self, v):
        value = self.n + v
        print(".. Modifing value before Set", value)
        A.slices.fset(self, value)

if __name__ == "__main__":
    a = A(10)
    b = B(10)

    a.slices = 9
    b.slices = 11
    print("%d a-slices" % a.slices)
    print("%d b-slices" % b.slices)

Output from the above code:
Set A 9
Modifing value before Set 21
Set A 21
Get A 9
9 a-slices
Get B 21
Get A 21
21 b-slices

... and when in doubt, it's always useful to get back to basics and listen to what Raymond Hettinger has to say about properties


text:
Q: fulltext search results showing where most repeated words I inserted in my web browser and it works great, but it shows me messy results, I would like to show me at the top where over the word or words in the search is repeated.
I looked online tutorials but I can not do it and always come messy, do not understand why.
Right now I have it like this:
$sql="SELECT art,tit,tem,cred,info,que,ano,url
FROM contenido
WHERE MATCH (art,tit,tem,cred,info)
AGAINST ('" .$busqueda. "' IN BOOLEAN MODE)
ORDER BY id DESC";

There is not much information on the Internet about refine or optimize searches for Mysql FULLTEXT. See if experts come through here and so we all learn.
How could refine your search? Thank you.

A: I think the issue is that you're sorting by the id.
The fulltext sorts by the match score it calculates, showing stronger matches first.  When you apply  ORDER BY id DESC, you loose this sort-by-match ordering.
You can see the actual score in your result set if you want by:
SELECT art,tit,tem,cred,info,que,ano,url,
      MATCH (art,tit,tem,cred,info)
      AGAINST ('your term' IN BOOLEAN MODE) AS score
FROM contenido
WHERE MATCH (art,tit,tem,cred,info)
  AGAINST ('your term' IN BOOLEAN MODE)
   ORDER BY id DESC

BTW: Use prepared statements for the 'your term' portion.
If your search string has spaces but each term matter, you need to treat them as separate pieces. So if it's important to have BOTH "Mercedes" AND "Benz":

*

*Don't: AGAINST ('Mercedes Benz' IN BOOLEAN MODE) <--- This means either Mercedes or Benz

*Do: AGAINST ('+Mercedes +Benz' IN BOOLEAN MODE)
If you want to have anything that must have the first term, but optionally the second term (ranking higher when both found) do:
 AGAINST ('+Mercedes Benz' IN BOOLEAN MODE)

Here's a long list of combinations: https://dev.mysql.com/doc/refman/5.6/en/fulltext-boolean.html
AND dont forget, get rid of the ORDER BY id DESC.  I think you're final query should look something like this for "Mercedes Benz"
SELECT art,tit,tem,cred,info,que,ano,url
    FROM contenido
 WHERE MATCH (art,tit,tem,cred,info)
  AGAINST ('+Mercedes Benz' IN BOOLEAN MODE);

Yep, freetext in MySQL has a lot of quirks, but play around, you'll get the hang of it.


text:
Q: WindowDecorActionBar error in latest Android Studio I have just installed the latest Android Studio 1.4.1 on OS X (10.10.5). When I create a blank activity, I receive an error caused by the source code generated by Android Studio on its own.
The error can be seen in the attached screenshot:

May be there is a conflict between the AppCompatActivity and other stuff.
This is the Activity generated by AS:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ScanActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
    }
}

with the following XML for the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="it.informagica.mywings.ScanActivity">

</RelativeLayout>

The compilation settings are the following ones:

And the dependencies are these:

I think I have installed all the SDK Platforms and SDK tools I need. However, I have this error and I have no clue on how to solve it.
Any help?

A: in style.xml change
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

A: I had this exception for the android studio version 1.5.
All i did is to change in style.xml
Just change the Style Parent into parent="Theme.AppCompat.Light.NoActionBar"
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

I haven't find any other better options, if you any one of you have better options to resolve the issue please let us know.


text:
Q: rm: cannot remove : No such file or directory
but the file clearly exists and I can open the contents in it, just the 'link' field is 0 when trying ls -Al, so I couldn't delete it,
I am using  Ubuntu app from the Windows 10 store
Any help is much appreciated.
Thanks

A: The Windows Subsystem for Linux Version 1 does not have its own kernel so it's still dependent on Windows for memory usage, disk usage, ... whereas having an Ubuntu running on a native Linux kernel, there is no issue with deleting open files!  if you sudo rm --force somefile
the file will be deleted! :-)
Ubuntu running under WSL V1 still uses the Windows kernel with a translation layer in-between Ubuntu and Windows so you need to close all the applications / users that access the file as otherwise you get errors that actually don't mean anything like:

rm: cannot remove : No such file or directory

(which solved your issue)  0:-)
In Ubuntu running under WSL V2, it depends:

*

*If running an application on a Linux file system like EXT4: no issues

*If running applications in the Windows File system (aka NTFS): Windows errors still apply
Relevant XKCD:

A: I closed all the editors accessing the directory and deleted it from windows and it worked...


text:
Q: Is there a way to distinguish the commit from home and company? I want to distinguish the commit that I made from the company and from home.
I've already tried to change user.name and user.email in the local repository at home but the content of commit didn't change anything.
I still can't see the difference between the commit from home or company.

A: I wouldn't advice you to use different values for user.email and user.name because they are properties to represent/identified the person who's contributing to the project, and in both cases, it is you, the fact that you're working from different locations is irrelevant.
A possible solution to achieve use purpose is to use git notes
git notes add  -m "From: Home"
git notes add  -m "From: Office"

As per msandord comment this will work just with new commits, already pushed ones would need to be rebased

A: Yes it is very complex and you will find yourself downloading the appstore repeatedly while trying to get it fixed and being ha ked and publicly humiliated all while doing so.


text:
Q: Huffman storing code in bits I have build the huffman tree. But I have no idea to store the code to bits due to I don't know how
to handle the variable length.
I want to create a table that store the huffman code in bits for print the encoded result.
I cannot use the STL containter like bitset.
I have try like that
   void traverse( string code = "")const
   {
        if( frequency == 0 ) return;
        if ( left ) {
             left->traverse( code + '0' );
             right->traverse( code + '1' );
        }
        else {//leaf node
             huffmanTable[ch] = code;
        }
   }

Can you give me some algorithm to handle it?
I want to store the '0' use 1 bit and "1" use 1 bit.
Thx in advance.

A: You'll need a buffer, a variable to track the size of the buffer in bytes, and a variable to track the number of valid bits in the buffer.
To store a bit:

*

*Check if adding a bit will increase the number of bytes stored. If not, skip to step 4.

*Is there room in the buffer to store an additional byte? If so, skip to step 4.

*Reallocate a storage buffer a few bytes larger. Copy the existing data. Increase the variable holding the size of the buffer.

*Compute the byte position and bit position at which the next bit will be stored. Set or clear that bit as appropriate.

*Increment the variable holding the number of bits stored.

A: You can use a fixed size structure to store the table and just bits to store encoded input:
struct TableEntry {
  uint8_t size;
  uint8_t code;
};

TableEntry huffmanTable[256];

void traverse(uint8_t size; uint8_t code) const {
        if( frequency == 0 ) return;
        if ( left ) {
             left->traverse(size+1, code << 1 );
             right->traverse(size+1, (code << 1) | 1 );
        }
        else {//leaf node
             huffmanTable[ch].code = code;
             huffmanTable[ch].size = size;
        }
}

For encoding, you can use the algorithm posted by David.

A: Basically I'd use one of two different approaches here, based on the maximum key length/depth of the tree:

*

*If you've got a fixed length and it's shorter than your available integer data types (like long int), you can use the approach shown by perreal.

*If you don't know the maximum depth and think you might be running out of space, I'd use std::vector<bool> as the code value. This is a special implementation of the vector using a single bit per value (essentially David's approach).


text:
Q: Creating a UITableView with Firebase I'm trying to create a UITableView of the data shown in this screenshot. What I want to have is a list of all the "Walks" name's and ignore the other data for now. So for example the list would be Apple Run, Walk, etc.
The code I have so far is this:
 self.walksArray = [[NSMutableArray alloc] init];

 NSString *userID = [[NSUserDefaults standardUserDefaults] stringForKey:@"User_ID"];

 Firebase* listRef = [[Firebase alloc] initWithUrl:[NSString stringWithFormat:@"https://myFirebase.firebaseio.com/users/%@/walks/", userID]];

 [listRef observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
    //
    [self.walksArray addObject:snapshot.value];
    NSLog(@"Snapshot: %@", snapshot.value);

    // Reload the table view so the new walk will show up.
    [self.walksListTableView reloadData];
 }];

What this gives me is
{
"Apple Run" =     (
            {
        latitude = "37.335072";
        longitude = "-122.032604";
        time = "00:19:40";
    },
            {
        latitude = "37.335072";
        longitude = "-122.032604";
        time = "00:19:43";
    },
            {
        latitude = "37.335072";
        longitude = "-122.032604";
        time = "00:19:47";
    },
            {
        latitude = "37.335072";
        longitude = "-122.032604";
        time = "00:19:49";
    }
);
Walk =     (
            {
        latitude = "37.334922";
        longitude = "-122.033042";
        time = "00:40:50";
    },
...

What I can't figure out is how to 'strip' the rest of the data and just show the name of the walk.


text:
Q: Why is my reveal modal not working? I want to make a reveal modal, but its not working. I don't know why. This is my code:
Add Policy

Awesome. I have it.

Your couch.  It is mine.

Im a cool paragraph that lives inside of an even cooler modal. Wins

  ×

I'm pretty sure my browser loaded the js as it does not show any error in the debugger. I copy paste from foundation docs, but I don't know why this is not working.

A: Initialise foundation..
Have this at the end of your body


text:
Q: linking libdl is needed for dlopen(); function or not? i'm currently building camerahal library for android M for my device, i dont know what the situation is with "dlopen function in android" question is that  i included dlfcn.h(needed for dlopen functions) into camerahal.cpp where i used dlopen functions but i didnt link against libdl somehow i didnt face any compile error but probably i have to link against libdl because docs are saying that ı must link against libdl with the following define LOCAL_LDLIBS := -ldl source
but in the following example, developer didnt link against libdl although he is using dlopen function
library
so do ı have to define on Android.mk to link against libdl or just defining dlfcn.h is enough?

A:
docs are saying that ı must link against libdl
  developer didnt link against libdl although he is using dlopen

You should always prefer documented approach to "it seems to work in this random example" approach.
The former is likely to continue to work. The latter is likely to stop working on next release (or the one after that).


text:
Q: Angular ui grid - specific class for unselectable row I use angular ui-grid to display my data.
I enabled the option to select row in gridOptions:
enableRowSelection: true,
But for specific rows I disable the selection by this code:
$scope.mygrid.isRowSelectable = function (row) {
    if (row.entity.id == 2) {
        return false;
    } else {
        return true;
    }
};

This is work, I cant select row with id =2,
But I want to add class for this row to notify that it is unselectable.
Any idea?

A: To Highlight the actual row:
You can write your own rowTemplate and assign the class to the row based on the entity id something like this,
 var rowTemplate =  '
' +
                 '

' +
                 '
';
  $scope.gridOptions = {
    rowTemplate:rowTemplate,
    enableSorting: true,
    columnDefs: [
      { field: 'name'},
      { field: 'company'}
    ]
  };

Instead of the row.entity.company=\'Enersol\' you can change it to row.entity.id and assign the class name.
In this example the the 'red' gives background color of yellow and foreground color of red.
Take a look at this plnkr. http://plnkr.co/edit/vaqBY235Lfz7WLvy0FCc?p=preview
To modify the actual row header icons:
You can override the template for the selection row header buttons and add custom class css. Inject templateCache in your controller and override the template like this.
$templateCache.put('ui-grid/selectionRowHeaderButtons',
    "

"
  );

The template uses a method in your controller scope to identify whether the row is selectable.
Sample plnkr here http://plnkr.co/edit/vaqBY235Lfz7WLvy0FCc?p=preview

A: In the columnDefs you can add a cellClass.
function applyClass(grid, row, col, rowRenderIndex, colRenderIndex) {
    if (row.entity.IsMapped) {
        return 'disabledRow';
    }
}

$scope.yourGrid = {
    columnDefs: [
        { cellClass: applyClass }
    ]
};


text:
Q: Cannot access List<> within a List<> Generics rookie struggling to access a list inside a class which is contained in a list. Basically I am trying to list the occupations of people that the user entered (I am sure there is an easier way of doing this, but this code was made to practise generics).
Class Code
namespace GenericPersonClass
{
class GenericPerson<T>
{
    static public List<T> Occupations = new List<T>();
    string name, famName;
    int age;

    public GenericPerson(string nameS,string famNameS,int ageI, T Note)
    {
        name = nameS;
        famName = famNameS;
        age = ageI;
        Occupations.Add(Note);
    }

    public override string  ToString()
        {

            return "The name is " + name + " " + famName + " and they are " + age;
        }
  }
}

Main Code
namespace GenericPersonClass
{
class Program
{
    static void Main(string[] args)
    {
        string token=null;
        string nameS, lastNameS,occS;
        int age;
        List<GenericPerson<string>> Workers = new List<GenericPerson<string>>();

        while (token != "no" || token != "No")
        {
            Console.WriteLine("Please enter the first name of the person to input");
            nameS = Console.ReadLine();
            Console.WriteLine("Please enter the last name of the person " + nameS);
            lastNameS = Console.ReadLine();
            Console.WriteLine("How old is " + nameS + " " + lastNameS);
            age = int.Parse(Console.ReadLine());
            Console.WriteLine("What is the occupation of " + nameS + " " + lastNameS);
            occS = Console.ReadLine();
            Console.WriteLine("Enter more data?...Yes/No");
            Workers.Add(new GenericPerson<string>(nameS, lastNameS, age, occS));
            token = Console.ReadLine();
        }

        Console.WriteLine("You provide the following employment...\n");
        for (int i = 0; i < Workers.Count; ++i)
        {
            Console.WriteLine("{0} \n", Workers[0].Occupations[i]);
//This line above is shown as wrong by VS2010, and intellisense does not see Occupations...
        }

    }
}
}

Thanks for any help,
Leo

A: So, you're trying to access a static List from an instance variable.  That's the problem there.  You can access this directly by using the class not the instance.
Something like:
GenericPerson<string>.Occupations[i]

It doesn't have anything to do with the List - it's all about the static part.


text:
Q: Erro ao Inicializar Classe de Modelo. Erro (2693) Estou com o seguinte erro no meu código:
**'AlunoModel' only refers to a type, but is being used as a value here.ts(2693)**

Preciso criar um objeto para fazer um put em minha API, para isso criei um Model do meu objeto da API chamado AlunoModel e tentei iniciar ele da seguinte forma:
aluno: AlunoModel = new AlunoModel();
Preciso corrigir esse erro para prosseguir com a aplicação, esse erro é devido a alguma configuração do tsconfig ou existe uma outra forma de fazer esse código?
alunos.component.ts
import { Component, OnInit } from '@angular/core';
import { AlunosService } from 'src/app/services/alunos.service';
import { AlunoModel } from '../../interfaces/aluno-model';
@Component({
  selector: 'app-alunos',
  templateUrl: './alunos.component.html',
  styleUrls: ['./alunos.component.css']
})
export class AlunosComponent implements OnInit {

  aluno: AlunoModel = new AlunoModel();
  alunos: Array<any> = new Array();

  constructor(private alunosService: AlunosService) {
    this.listarAlunos();
  }

  ngOnInit(): void {
  }

  cadastrar(){
    console.log(this.alunos);
  }

  listarAlunos(){
    this.alunosService.listarAlunos()
    .subscribe( alunos => {
      this.alunos = alunos;
    },
      () => {alert('Falha ao Listar Alunos!');})
  }
}

alunos.component.html

Alunos Cadastrados:

        ID:
        NOME:
        IDADE:

        {{aluno.id}}
        {{aluno.nome}}
        {{aluno.idade}}

Cadastro de Alunos:

  <form>
      Nome: <input type="text" name="nome" [(ngModel)]="aluno.nome">
      Idade: <input type="text" name="idade" [(ngModel)]="aluno.idade">

      <button type="button" (click)="cadastrar()">Cadastrar</button>
  </form>

A: Bom, após muitos testes...
O que estava acontecendo era que no model AlunoModel o export estava sendo feito como:
export interface AlunoModel
Mudei o export e o fiz como:
export class AlunoModel
O erro sumiu logo após a mudança...


text:
Q: Follow-up: continuous linear operator and measurability Consider

*

*a probability space $(\Omega, \mathcal{F}, \mathbb{P})$

*separable Hilbert spaces $H$ and $V$

*an $H$-valued random variable $X$ defined on $(\Omega, \mathcal{F}, \mathbb{P})$

*A random variable $L : \Omega \rightarrow \mathcal{L}(H,V)$, where $\mathcal{L}(H,V)$ is the space of linear continuous (bounded) operators from $H$ to $V$ with the operator norm.

Is the mapping
$$
Y : \Omega \rightarrow V, \quad Y (\omega) := L(\omega)(X(\omega))
$$
a random variable, i.e., $\mathcal{F}-\mathcal{B}(V)$-measurable. If necessary one can assume that $L$ takes finitely many values in $\mathcal{L}(H,V)$.

One can further introduce
$$
\hat{L} : \Omega \times H \rightarrow V, \quad (\omega, h ) \mapsto \hat{L}(\omega, h) := L(\omega)h.
$$
and rewrite
$$
L(\omega)(X(\omega)) = \hat{L}(\omega, X(\omega)) \quad \forall \omega \in \Omega.
$$
The mapping
$$
\Omega \rightarrow \Omega \times H \quad \omega \mapsto (\omega, X(\omega))
$$
is $\mathcal{F}-\mathcal{F}\otimes\mathcal{B}(H)$-measurable, since $\omega \mapsto \omega$ is $\mathcal{F}-\mathcal{F}$-measurable and $\omega \mapsto X(\omega)$ is $\mathcal{F}-\mathcal{B}(H)$-measurable.
Is it possible to show that $\hat{L}$ is $\mathcal{F}\otimes\mathcal{B}(H)-\mathcal{B}(V)$-measurable. If so, then the composition $\omega \mapsto \hat{L}(\omega, X(\omega))$ will have the desired measurability.

Some further thoughts:
For every fixed $\omega \in \Omega$ the mapping $h \mapsto \hat{L}(\omega, h)$ is continuous by assumption. If one can show that for every fixed $h \in H$ the mapping $\omega \mapsto \hat{L}(\omega, h)$ is $\mathcal{F}$-measurable, then $\hat{L}$ would be jointly measurable as a Carathéodory function.

A: I think this is also false.  Let $H=V=\mathbb{R}$, $Y: \Omega \rightarrow \mathbb{R}$ be any function on $\Omega$ that is not $\mathcal F$-measurable, $X=1$ be a constant random variable, and $L(\omega)(h) = hY(\omega)$.  $L(\omega)$ is a continuous linear operator from $\mathbb{R}$ to $\mathbb{R}$, but $L(\omega)(X(\omega)) = Y(\omega)$ is not $\mathcal F$-measurable.


text:
Q: How obtain smooth subpixel animation when animating Width of a TCircle? When I animate the Position of a TCircle, the animation is smooth and appears to happen in subpixel increments/decrements. However, when I animate the Width (or/and Height) of a TCircle, the animation progresses in pixel-increments, making it look a lot less smooth.
This is particularly striking when performing a slow animation where the Positions (X and Y), Width, and Height are simultaneously animated, creating a scaling effect. The left and upper part of the circle animate smoothly outward, while the right and bottom parts are jerky.
Can't figure out why this is happening. All suggestions much appreciated.
(btw, this doesn't happen when Scale.X and Scale.Y are animated. Smooth. But I don't want the stroke thickness to scale, hence the use of Width and Height)
(using XE2)
Some TForm code to demonstrate:
object Form6: TForm6
  Left = 0
  Top = 0
  Caption = 'Form6'
  ClientHeight = 821
  ClientWidth = 1108
  Visible = False
  StyleLookup = 'backgroundstyle'
  object cirPulse: TCircle
    Position.Point = '(352,192)'
    Width = 200.000000000000000000
    Height = 200.000000000000000000
    Fill.Kind = bkNone
    StrokeThickness = 10.000000000000000000
    object FloatAnimation1: TFloatAnimation
      Enabled = True
      Duration = 50.000000000000000000
      StartFromCurrent = True
      StopValue = 400.000000000000000000
      PropertyName = 'Width'
    end
    object FloatAnimation2: TFloatAnimation
      Enabled = True
      Duration = 50.000000000000000000
      StartFromCurrent = True
      StopValue = 400.000000000000000000
      PropertyName = 'Height'
    end
    object FloatAnimation3: TFloatAnimation
      Enabled = True
      Duration = 50.000000000000000000
      StartFromCurrent = True
      StopValue = 252.000000000000000000
      PropertyName = 'Position.X'
    end
    object FloatAnimation4: TFloatAnimation
      Enabled = True
      Duration = 50.000000000000000000
      StartFromCurrent = True
      StopValue = 92.000000000000000000
      PropertyName = 'Position.Y'
    end
  end
end

A: I seem to have solved this issue, as far as I can tell until now, by changing following line in the FMX.Types unit, in
function FitRect(var R: TRectF; BoundsRect: TRectF): Single;

Change
if ratio < 1 then
begin
  R := RectF(0, 0, RectWidth(R), RectHeight(R));
end
else
begin
  R := RectF(0, 0, round(RectWidth(R) / ratio), round(RectHeight(R) / ratio));
end;

into
if ratio < 1 then
begin
  R := RectF(0, 0, RectWidth(R), RectHeight(R));
end
else
begin
  R := RectF(0, 0, RectWidth(R) / ratio, RectHeight(R) / ratio);
end;

Hence, getting rid of the Round.
Haven't tested enough to discover side-effects yet.


text:
Q: undefined index while trying to echo a variable $_SESSION, php jquery ajax,  edit i am not getting the error undefined index 'time' any longer. Now i am not getting any errors, but when i try echoing $timezone; nothing happens.
what am i missing here that is causing the undefined index 'time'? i do have jquery in the page.
index.php
<?php
session_start();
$timezone=$_SESSION['time'];

?>

script, using jquery to get the time and then setting it as a $_SESSION['time'] variable.
<script>
$(document).ready(function() {
    if("<?php echo $timezone; ?>".length==0){
        var visitortime = new Date();
        var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
        $.ajax({
            type: "GET",
            url: "<?php echo $_SERVER['DOCUMENT_ROOT'].'/social_learning/php/timezone.php';?>",
            data: 'time='+ visitortimezone,
            success: function(){
                location.reload();
            }
        });
    }
});
</script>

timezone.php
 <?php
  session_start();
  $_SESSION['time'] = $_GET['time'];
 ?>

A: just change $timezone=$_SESSION['time']; to
$timezone=isset($_SESSION['time'])?$_SESSION['time']:"";


text:
Q: Delay in getting the value in salesforce classic I need to update the commission field based on some calculations. I am using the future method to update the commission field. Commission field is getting updated immediately in lightening as expected. However, in salesforce classic, I need to refresh the page manually then only it reflects me the updated commission value.
Can someone please help me to provide the solution?

A: This is normal behavior.
From the documentation:
"A future method runs in the background, asynchronously."
So.. your @Future method runs only when the server resources are free (after your trigger update ends).
I wonder if in lightning experience there's a refresh mechanism (like "rerender" or "$A.get('e.force:refreshView').fire()") that occurs when the operation finishes and this can explain why in Lightning you see the results without the need to update the page.


text:
Q: Matrix exponential using Jordan form I'm trying to calculate the matrix exponential $e^{At}$ for $$A=\frac{1}{2}\begin{bmatrix}-1&1&-1\\2&-2&0\\1&-1&-1\end{bmatrix}$$
I found the eigenvalues $\lambda_1=\lambda_2=-1, \lambda_3=0$ which give the eigenvectors $$v_{\lambda_{1,2}}=\begin{bmatrix}0\\1\\1\end{bmatrix},v_{\lambda_3}=\begin{bmatrix}1\\1\\0\end{bmatrix}$$
I now would like to find the matrices $S$ and $J$ so that $$A=SJS^{-1}$$
Constructing these matrices requires another column vector. I now try to find the generalized eigenvector for eigenvalue $-1$ as follows. $$(A-(-1)I)\mathbf{v}=\begin{bmatrix}1/2&1/2&-1/2\\1&0&0\\1/2&-1/2&1/2\end{bmatrix}\mathbf{v}=\begin{bmatrix}0\\1\\1\end{bmatrix}$$
But this has no solution, so I am stuck.

A: Wolfram alpha gives
\begin{eqnarray}
J&=& \begin{bmatrix}
-1&1&0\\
0&-1&0\\
0&0&0
\end{bmatrix},\ \mbox{and}\\
S &=& \begin{bmatrix}
0&1&1\\
1&-1&1\\
1&0&0
\end{bmatrix}\ .
\end{eqnarray}
Since
$$
J^n = \left(-1\right)^n\begin{bmatrix}
1&-n&0\\
0&1&0\\
0&0&0
\end{bmatrix},
$$
then
$$
e^{tJ} = \sum_{n=0}^\infty\frac{t^n J^n}{n!}=\begin{bmatrix}
\sum_{n=0}^\infty \frac{(-t)^n}{n!}&-\sum_{n=0}^\infty n\frac{(-t)^n}{n!}&0\\
0&\sum_{n=0}^\infty \frac{(-t)^n}{n!}&0\\
0&0&0
\end{bmatrix}\\
=\ \begin{bmatrix}
e^{-t}&te^{-t}&0\\
0&e^{-t}&0\\
0&0&0
\end{bmatrix}\ .
$$
So
\begin{eqnarray}
e^{tA} &=& S\, e^{tJ} S^{-1}\\
&=&\frac{1}{2} \begin{bmatrix}
e^{-t}&-e^{-t}&e^{-t}\\
(t-1)\,e^{-t}&(1-t)\,e^{-t}&(1+t)\,e^{-t}\\
te^{-t}&-te^{-t}&(2+t)\,e^{-t}
\end{bmatrix}\ .
\end{eqnarray}


text:
Q: Custom item inside style I would like to know if is it possible to add custom items inside of a style.
For example:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="color5">@color/myColor</item>
</style>


text:
Q: In Toad for Oracle using SQL Query how do I change data output to representative characters I made a query and my output has columA. In column A the potential data is Dog or Cat,
if the Output is:

*

*Dog then I want it to be shown as B

*Cat I want it to be shown as T.

How can I do this in Toad for Oracle using a SQL Query?

A: select decode(columnA,'dog','B','cat','T','not a dog or cat')
from dual

A: DECODE is universally used in the Oracle world, but I'd use the CASE statement, because it is much more readable:
SELECT CASE myinput
       WHEN 'Dog' THEN 'B'
       WHEN 'Cat' THEN 'T'
                  ELSE '?'
       END myoutput
  FROM ...

A: select decode(columnA,'Dog', 'B','Cat', 'T', 'None') from dual;

Here is how the DECODE function works
DECODE([If ColumnA is] 'Dog' [then] 'B' [elsif] 'Cat' [then] 'T' ..... [else] 'None')


text:
Q: C++: How to install OpenCV with the compiler MinGW 9.2.0 on Windows 10 I am a few days ago trying to install opencv using Dev-Cpp and Windows 10, i add the directories of the .h, .lib and .dll files to the Dev-Cpp, but when i compile the code always give me the same error.
In compiler options i add the next directories:
-C++ Headers--
C:\Users\admin\Downloads\opencv\build\include
-Libraries-
C:\Users\admin\Downloads\opencv\build\x64\vc15\lib
-Binary files-
C:\Users\admin\Downloads\opencv\build\x64\vc15\bin
-Code-
#include <iostream>
#include <opencv2/imgcodecs.hpp>

int main(){
    cv::Mat img;
    img = cv::imread("Goten.jpg");
    return 0;
}

-Errors-
c:\mingw\mingw32\bin\ld.exe C:\Users\admin\AppData\Local\Temp\cciHfDkS.o:main.cpp:(.text+0x62): undefined reference to `cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)'
c:\mingw\mingw32\bin\ld.exe C:\Users\admin\AppData\Local\Temp\cciHfDkS.o:main.cpp:(.text$_ZN2cv3MatD1Ev[__ZN2cv3MatD1Ev]+0x2d): undefined reference to `cv::fastFree(void*)'
c:\mingw\mingw32\bin\ld.exe C:\Users\admin\AppData\Local\Temp\cciHfDkS.o:main.cpp:(.text$_ZN2cv3Mat7releaseEv[__ZN2cv3Mat7releaseEv]+0x40): undefined reference to `cv::Mat::deallocate()'
c:\mingw\mingw32\bin\ld.exe C:\Users\admin\AppData\Local\Temp\cciHfDkS.o:main.cpp:(.text$_ZN2cv3MataSEOS0_[__ZN2cv3MataSEOS0_]+0xb4): undefined reference to `cv::fastFree(void*)'
C:\Users\admin\Desktop\Programacion\collect2.exe    [Error] ld returned 1 exit status

I have installed MinGW 9.2.0, i tried compile it with the standards C++11, C++14 and C++17
What can i do to fix this error? - Sorry for my english

A: Those are linker errors: it means the compiler can't find the binary code for those functions.
In other words, you might have forgotten to specify a few OpenCV libraries. If I'm not mistaken, imread() resides in opencv_imgcodecs.

A: Does vcpkg on Windows require VisualStudio, or does it also work with MinGW?  (Doing a very quick Google search seems to show it might work.)  Cause ever since I discovered vcpkg, I must admit that I'd never go back to installing and building things the old way.
Now, to get almost anything on windows, I'd clone the vcpkg repo, run the bootstrap script, and then run vcpkg.exe install opencv.

A: Consider using a good source code editor (perhaps GNU emacs) and compile on the command line (e.g. by using a build automation tool such as GNU make or ninja) in a terminal emulator.
Then MinGW is actually some command with g++ or g++.exe
Then you just can download the source code of OpenCV and compile it in some terminal emulator. Or even better, get the source code from github. The compilation of OpenCV from source code could last a dozen of minutes or an hour of computer time/
BTW, if you really are interested in programming OpenCV, I recommend installing a Linux distribution (e.g. Debian). Most GNU/Linux systems have a genuine and recent GCC, not just an emulation of GCC called MinGW.


text:
Q: PHP invoking another script but through http (isolating them) Let's see if I make myself clear. I have an old set of scripts that run well on PHP4 and better don't thouch em. I have to integrate a new functionality implemented on PHP5, I need just to invoke a script on the new app from the old one.
To not have to touch the old stuff I think to somehow "kin of remotely" invoke the new one, need only to pass the $_REQUEST[] data. I can not include it as that would require migrating to another PHP version (and some name clashing). I don't need any output from the new one.
What would be the cleaner way to "call" that script passing parameters, fopen("http://theserver.com/thescript.php"....) and then passing all the necessary headers to pass the parameters? or there's somethign more direct?
Thanks!

A: If you need to pass POST data, you can use cURL; otherwise, you can just do file_get_contents('http://example.com/yourscript.php?param1=x&param2=y&param3=...'); and the HTTP wrapper will do the request for you (simplest way).

A: You're going to give yourself nightmares with this.
But if you really need to do it, you're not going to be able to rely on fopen. I would recommend using cURL, as Piskvor suggests.
But please, make sure you're validating and escaping any data you're pushing across correctly, or you're in for a world of hurt - the fact that you're making a cURL request to the other part of the system means that in theory, anyone else can do exactly the same thing.
This is most definitely not a long term solution, I would advise you rewrite the old parts as a priority.

A: After considering what you suggested on previous answers and considering safety I thought something: If both scripts are on the same server the "called" one should be on the same IP than the caller so if ips differ the invoked should not run. Is that a good idea?


text:
Q: What is the best way to save data of a C++ Program ? Binary vs JSON serialization We are implementing a CAD program (in C++, Qt) where we have interdependant classes :
The smallest brick is the Pattern, it is just a distribution of points. Then we have Layouts which contain Patterns at a given height (z = constant). And finally Stacks, which are a stacking of Layout.
All these entities have a unique id and can also have a list of masks which are applied to it.
Knowing that each of the classes are linked (std::vector of pointers everywhere) by a tree structure, what would be the best way to save a project countaining several stacks ? The objective of saving would be to later load again the project and modify it.
We already looked into Boost and Qt Serialization but it seems to me that binary Serialization may be way too much for what we want to do (as it needs time to be integrated). On the other hand we tought about an XML/JSON serialization, having something which would look like this :
<Layout>
 <id> 12</id>
 <z> 0</z>
 <patterns>
  <pattern id> pattern0</pattern id>
  <pattern id> pattern1</pattern id>
 </patterns>
</Layout>

Are they some other ways ? What would be the best one and why ? We lack of objectivity on this point.

A: I've had great success using SQLite databases as a file format for graphics applications.  Its both very reliable, and being a standard format, its contents are easily viewed/converted by external programs.

A: First thing I would check is if using an existing CAD format would not be sufficient. That would not only prevent you from reinventing the wheel, but also improve the interoperability with other CAD programs. Moreover, adapting the terms of such a format like "Layers" and "Entities", instead of using terms like "layouts" and "patterns" (which have typically different meanings in other CAD systems), you might be able to reduce communication issues.
If you really feel you need to create your own file format, make sure you can keep the format backwards compatible with each new version of your CAD system, otherwise you will run sooner or later into problems.  This is much simpler when your format provides a lot of metadata. In my experience, formats like XML or JSON make it easier to fulfill this requirement than proprietary binary formats. The decision between these two is surely pretty opinonated. XML is still more wideley used and supported by a lot more third party tools. It will allow you easier integration of other existing XML based standards. On the other hand, it has the drawback that the files tend to become very big, much bigger than a typical JSON file carrying the same information. This is a tradeoff you need to consider for your use case.

A: JSON is simple and portable. External tools won't have any problems reading or writing it. You won't have any problems yourself reading and writing the data on any architecture, which is very nice. It is also very easy to be compatible with older and newer version, often just by ignoring items that you don't understand.
JSON is a bit verbose if you store a lot of dictionaries with long keys. For example if you store 1000 longitude/latitude pairs you could store it like
[
  { "longitude": 10.29340, "latitude": 35.34989 },
  { "longitude": 10.29340, "latitude": 35.34989 },
  ... repeat 998 more times
]

If you have so much data that this is negatively affecting you, you can as well store the data more compact as
{ "latitudes": [10.29340, 10.29340, .. 998 more values],
  "longitudes": [35.34989, 35.34989, ... 998 more values]
}

Another nice thing is that you can store data in a more compact or more readable format. (Compact by removing line separators, spaces).
JSON can store arrays, dictionaries (key-value pairs), any Unicode strings, numbers, booleans and null values. It cannot store dates but there is a standard for storing dates as strings in JSON.
If you are worried about version compatibility, I'd recommend adding one key/value pair specifiying the number of the spec used for writing the data, and one key/value pair specifying the number of the lowest spec that can process the data by ignoring information that it doesn't know about.

A: Ignoring the specific CAD issue, but taking into account that this use case could potentially generate rather large files, I would recommend looking into protobuf. It's a rather compact binary format with easy versioning for your future needs:

... language-neutral, platform-neutral, extensible mechanism for
  serializing structured data – think XML, but smaller, faster, and
  simpler. You define how you want your data to be structured once, then
  you can use special generated source code to easily write and read
  your structured data to and from a variety of data streams and using a
  variety of languages.

Disclaimer: We use it for message serialization, not for file storage.
Caveat: One limitation I know for protobuf is that a single message max approx. size is 64MB. So a file format such as yours should normally be designed as a stream of multiple protobuf messages instead of one "huge" message per file.

A: XML and to a lesser extent JSON is probably the best options out there if you want a human readable format.
However, human readable also means human editable, which in turn means having people make changes that are invalid and then having to provide support to allow these humans to figure out their mistakes.
Both XML and JSON do not solve the format extensions that will occur over time, allowing newer programs to work on older versions and vice versa.
I would also consider Google protocol buffers as a good choice for a binary format option. It has good support in C, generates smaller data files than JSON and will allow the reading of different data format versions.
It will allow your team to focus on the data structure, and to manage format changes comfortably.


text:
Q: GitHub Actions Runner Container on Google Cloud Run that can build docker image I have built a docker image that when run, it registers itself as a GitHub Runner. This runner will, amongst other things, be used to build and push images to GitHub Container Registry. I don't want to deploy the containers to GKE or Compute, as I don't want the overhead of managing those resources. I would prefer to deploy the containers to Google Cloud Run. I've scoured the docs for help but I can't seem to find the answers to the following question:

*

*Can I run 'docker in docker' when the container is deployed to GCP Cloud Run?

*How do I specify the volume mount required when deploying the container to Google Cloud Run, i.e. the usual mapping with docker run would be:
-v /var/run/docker.sock:/var/run/docker.sock

A: *

*I never tested but it's possible that the current Cloud Run sandbox prevent this king of use. And I don't really know the use case for this!

*You can't mount volume in Cloud Run, it's stateless. You only have a in-memory file system in the /tmp directory (and it's in memory, size correctly your Cloud Run instance memory to take this into account). You can connect your instance to 3rd party product, such as Google Cloud Storage or databases, but no volume mountable on Cloud Run (for now)

If you have these requirement you can maybe have a look to autopilot and deploy directly your container on fully managed K8S.


text:
Q: Java file transfer - Incomplete files So I have been working with sockets a bit in the past few days, and tried to make a basic program to transfer files. The files do transfer, but they are incomplete. Like, when I try to send a 500kB file, the receiver only gets a 480kB one. I searched for quite a while but I just cant find the error. I found on some similar errors that the streams werent closed, but mine is, and it still doesnt send properly.
Sender:
//Main
//...
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
//...

public void sendFile(File file)
{
    try {
        buffer = new byte[(int) file.length()];
        DataInputStream filestream = new DataInputStream(new FileInputStream(file));
        filestream.readFully(buffer);

        DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());

        send("FILE_"+file.length()+"_\t"+file.getName());

        outStream.write(buffer);
        outStream.flush();

        filestream.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void send(String data) {
    out.println(data);
}

Receiver:
DataInputStream inStream = new DataInputStream(client.getInputStream());

File file = new File("temp"+"\\"+expectedFile);
file.createNewFile();

BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file, false));

buffer = new byte[1024];

while (size > 0 && (receivedBytes = inStream.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
{
    fileOut.write(buffer, 0, receivedBytes);
    fileOut.flush();
    size -= receivedBytes;
}

fileOut.close();

Thanks for any kind of help :)

A: You drop the first read of data on the floor in this line:
int receivedBytes = inStream.read(buffer, 0, buffer.length);

Not really sure what that line of code is for (old debugging?).  You basically just need to remove it.
UPDATE:
You seem to indicate that you are sending additional metadata at the beginning of the stream.  My guess is that you are using some sort of BufferedInputStream/Reader when reading the initial metadata, and that is swallowing part of the subsequent file data.
You can somewhat solve this problem by wrapping the DataInputStream around the BufferedInputStream you are using to read the metadata.  You have to be careful, however, that whatever you are using to read the metadata doesn't read more data than it should.  It's actually trickier to do this than you might think.  You might want to look at using the DataInput/Output streams exclusively (use writeUTF/readUTF to handle the file name and writeLong/readLong to handle the file size).

A: receiving end in general should look something like this...
socket = serverSocket.accept();
socket is = socket.getInputStream();

FileOutputStream fos = new FileOutputStream("fileName");
BufferedOutputStream bos = new BufferedOutputStream(fos);

int count;
while ((count = is.read(bytes)) > 0) {
        bos.write(bytes, 0, count);
    }


text:
Q: iOS App distribution for enterprise( Distributing app to a client organisation) I'm part of an enterprise and we have enrolled apple enterprise license .
I'm looking for iOS enterprise distribution.  I wanted to distribute my app to my client organisation. How can I do it ?
What developer program my client organisation has to enrol .
If the client organisation is having a Apple enterprise account , can I map the app into their bundle ID and sharing the ipa files with a download link .
Will it allow the client employees can download and use the app!
Help me out

A: Applivery allows to distribute apps creating an enterprise app store, and you can use the MDM solution to distribute apps from apple app store or directly from Applivery without upload an .ipa to Apple. it is a quite good feature. They have a free trial and you can test the app distribution and app management (feature of MDM solution): https://www.applivery.com/enterprise-app-store/


text:
Q: Make a backward compatible project in Visual studio 2017? At school we are using Visual Studio 2015 but at home I have Visual studio 2017. When I start project at home there is a lot of error happening when I get back to school.
Our homeworks are made so they can both be made in the two versions. So is there any way I could se a parameter so my projects made with 2017 version of visual could be fully compatible with the 2015 version?
Thanks in advance.

A: You can set VS 2017 to use the compiler from VS 2015 pretty easily. Bring up the project settings page and choose "Visual Studio 2015 (v140)" for the "Platform Toolset":

So even though you're using the VS 2017 IDE, you're still using the VS 2015 compiler, so if you write any code that won't work with VS 2015, you'll find out about it immediately.

A: The easiest thing to do would be to have your C++ source code in a separate folder from your project files.   That is you have two different solutions:
c:\projects\YourProject\Src (Your source code goes here)
c:\projects\YourProjects\VS2015 (Create a Visual Studio 2015 in this directory and add files from ..\Src here)
c:\projects\YourProjects\VS2017 (reate a Visual Studio 2015 in this directory and add files from ..\Src here)
This comes with the slight annoyance that you'd have to maintain two sets of project files. But I'm guessing for homework, you just need a handful of source files and not a lot (if any) project customizations beyond just adding source files to it.


text:
Q: How to check Customer login or not when we click on customer navigation tab magento2? In Magento 1 if we create custom customer navigation link in that when we load page that time we check that customer is login or not if not than we redirect that page to login page using this code in controller
public function preDispatch()
{
    parent::preDispatch();

    if (!Mage::getSingleton('customer/session')->authenticate($this)) {
        $this->setFlag('', 'no-dispatch', true);
    }
}

In Magento 2 How can i check this if customer is not login than redirect to login page???

A: In Your Controller
namespace Company\Module\Controller\Index;
use Magento\Framework\App\RequestInterface; //use this
class .....{
     public function __construct(
        .....
        \Magento\Customer\Model\Session $customerSession,
        .....
     ){
         ....
         $this->customerSession = $customerSession;
         ....

     }
     public function dispatch(RequestInterface $request)
     {
          if (!$this->customerSession->authenticate()) {
              $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
          }
          return parent::dispatch($request);
     }
         ....

}

In Magento 2 We can do that using this code

A: Following code you can check customer login or not anywhere
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}

From controller
$this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}

I hope this will help you.


text:
Q: Can you tell TeXShop to compile a certain way without using a shebang? I have a custom class that has a bibliography option.  If I am not using that option, I would prefer to compile with pdflatex; if I am using that option, however, I would like to use pdflatexmk.  This is because pdflatexmk takes considerably longer to compile, which I do not want unless I need it.
The problem is, I do believe the shebang needs to be at the top of the file, as this:
\newif\ifbib\bibfalse
\DeclareOption{bib}{\bibtrue}

\ifbib
    % !TEX TS-program = pdflatexmk
\else
    % !TEX TS-program = pdflatex
\fi

does not work.  How might I be able to achieve what I want?

A: Use the directive for pdflatexmk in the file. Use Cmd-T to typeset with pdflatexmk and Shift-Cmd-L (which overrides the directive and uses the Typeset Menu's LaTeX command) to use pdflatex.

A: There's no way to do this in the way you are trying. The magic comment lines are parsed by the editor; they have no connection to any of the TeX code in the document.  It's not clear why you need to do what you're doing anyway.  latexmk is usually smart enough not to do multiple runs when they're not needed. What I do when I'm drafting a document is simply use the non-latexmk version until I near the end and then change to using latexmk. This far less work than setting an option in the code; you simply take off or add the mk part to the magic command as needed.
If you really think you need to have more control over the build process, you could also use the arara TeXShop engine.


text:
Q: Select records if they contain all of the subquery results I am trying to create a select statement. I want to select records which contains all the records from subquery.
I have a subquery like:
SELECT P.pid
FROM Parts P
INNER JOIN Manifacturers M INNER JOIN M.mid ON P.pid
WHERE M.name = 'Mercedes'

I want to select suppliers if they sell all of these parts. I tried couple of things:
SELECT s.name
FROM Suppliers S
INNER JOIN Parts P1 ON S.pid = P1.pid
WHERE p1.pid IN ( SELECT P.pid
    FROM Parts P
    INNER JOIN Manifacturers M INNER JOIN M.mid ON P.pid
    WHERE M.name = 'Mercedes' )

This clearly failed. This returns suppliers if they have any of the parts. Actually I manage to get close by using INTERSECT:
SELECT P1.pid
FROM Suppliers S
INNER JOIN Parts P1 ON S.pid = P1.pid
INTERSECT
SELECT P.pid
FROM Parts P
INNER JOIN Manifacturers M INNER JOIN M.mid ON P.pid
WHERE M.name = 'Mercedes'

This returns the correct pids but this syntax doesn't allow me to return s.name. It won't let me add any field which doesn't exists in the second query.

A: You should try using conditional COUNT()
SELECT COUNT(CASE WHEN M.name = 'Mercedes' THEN 1 END) AS total_mercedes
FROM Parts P
INNER JOIN Manifacturers M INNER JOIN M.mid ON P.pid

Then your manufactures must have the same number of parts.
SELECT s.name,
       COUNT(CASE WHEN M.name = 'Mercedes' THEN 1 END) AS total_supplier
FROM Suppliers S
INNER JOIN Parts P1 ON S.pid = P1.pid
INNER JOIN Manifacturers M INNER JOIN M.mid ON P.pid
CROSS JOIN ( SELECT COUNT(CASE WHEN M.name = 'Mercedes' THEN 1 END) AS total_mercedes
             FROM Parts P
             INNER JOIN Manifacturers M INNER JOIN M.mid ON P.pid
           ) M
GROUP BY s.name
HAVING T.total_mercedes  = total_supplier

Another Option is with LEFT JOIN.
First you need every Pid from Mercedes and every supplier. Then check if have any NULL rows
SELECT S.name
FROM  ( SELECT P.Pid
        FROM Parts P
        INNER JOIN Manifacturers M INNER JOIN M.mid ON P.pid
        WHERE M.name = 'Mercedes'
      ) M
CROSS JOIN (SELECT DISTINCT S.name,
            FROM Suppliers S
           ) S
LEFT JOIN Suppliers Sales
      ON M.Pid = Sales.Pid
     AND S.name = Sales.Name
GROUP BY S.name
HAVING COUNT(CASE WHEN Sales.Pid IS NULL THEN 1 END) = 0


text:
Q: Finding elements by class name inside a loop, selenium I need to scrape in python a page that has some classes that are number like class1, class2, class3, ... classN and I would like to locate the text contained in all those classes.
I tried using find_element() function:

list = []
for i in range(N-1)
  list.append(driver.find_element(By.CLASS_NAME, "class" + str(i+1) ).text))

but unfortunately I get this error message:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".class1"}
  (Session info: chrome=107.0.5304.68)

Is there any other way I could succeed in this scraping?

EDIT
This is the page I would like to scrape and I would like to get the games won by both players per every set.
In the source code the classes are named "smh__part  smh__home smh__part--" + str(i+1) and respectively "away"

A: Class_name only accept single class name not multiple.
Instead use css selector. use python format() function
list = []
for i in range(N-1):
  list.append(driver.find_element(By.CSS_SELECTOR, "[class='smh__part  smh__home smh__part--{}']".format(i+1)).text)

OR CLASS_NAME with single class value
list = []
for i in range(N-1):
  list.append(driver.find_element(By.CLASS_NAME, "smh__part--" + str(i+1) ).text)


text:
Q: Reactjs + Python. Connecting frontend to backend and handling post requests Hi i am pretty much a beginner and so far i dont have much experience dealing with backend. So I need to build this reactjs + python(flask framework?) to-do list app. This project requires me to store the input written in the react into a database(i'm using MySQL). I pretty much have the frontend working fine however my issue right now is with the backend part of this project. I am able to connect python to the mysql database though.
This will be my issues:

*

*how do you connect the frontend part to the backend part

*how do you handle the post request from the form using python to be able to insert the data into the database

*I do not know what i need to do first

This is my reactjs code where the input form is used:
import React,{useState} from 'react'
import useKeypress from './onkeypresshook'

function Addnote(props) {

    const [notetext,setNotetext] = useState('')
    const wordsleft = 200

    const handlechange=(e)=>{
        setNotetext(e.target.value)
    }

    const handlesave=()=>{
        if(notetext.trim().length>0){
            props.handleaddnote(notetext)
            setNotetext("")
        }

    }

    useKeypress(handlesave,"Enter")

    return (
        <form method="POST" action='' target='_blank'>

                <input className="text-area new" placeholder='Type here to add text...' name="notepad" type="text" value={notetext} onChange={handlechange} maxLength ={wordsleft}/>

                    {wordsleft - notetext.length} remaining
                    <button type="submit"  value="submit" className='save-button' onClick={handlesave} >Save</button>

        </form>

    )
}

export default Addnote

this is my file tree:

thank you so much i hope the community can help and guide me

A: Great that you want start to learn to code!
I'll answer your question as good as possible and then I'll recommend an alternative to your approach.
What you could do
A simple way to solve your problem would be via REST API (- Google that term and whatever Python framework you're using).
If you expose a REST API endpoint with your Python app, you can send data to it from your React app using fetch.
In your react code, you can remove your handleSend and handleSave functions, and instead attach a onSubmit to your <form /> component like this:
function handleSubmit(event) {
  event.preventDefault();
  const formData = new FormData(event.currentTarget);
  const body = Object.fromEntries(formData);
  // Replace XXXX with the port your Python app is running on
  // and your-endpoint with your route URL.
  fetch('http:localhost:XXXX/your-endpoint', {
    method: 'POST',
    body
  });
}

// ... later in your form
<form onSubmit={handleSubmit} />

My recommended alternative
Instead of starting out with a multi language stack, learn a single language fullstack framework.
I'd recommend Remix. It uses only JavaScript / TypeScript. And it has a great tutorial here, that teaches you to read and write to a database!
Good luck on your programming journey!


text:
Q: How to make custom dictionary for Hunspell I have a question about building a custom dictionary for hunspell.
I'm using a general English dictionary and affix file right now. How can I add user-specified words to that dictionary for each of my users?

A: I'm trying to do the same but haven't found enough information to begin yet.
However, you may want to look at hunspell - format of Hunspell dictionaries and affix files
.
UPDATE
If you are working with .NET, you can download Hunspell .NET port. Using it is fairly easy too.
var bee = new Hunspell();
bee.Load("path_to_en_US.aff");
bee.Load("path_to_en_US.dic");
bee.Add("my_custom_word1");
bee.Add("my_custom_word2");
var suggestions = bee.Suggest("misspel_word");

A: The secret to getting hunspell to work (at least for me) was to figure out the locations it would search that were owned by me, and put the custom dictionaries there.  Also bear in mind that the dictionaries are in a specific format, so you need to obey those rules.
Running hunspell -D will show you the search path.  On MacOS, mine includes /Users/scott/Library/Spelling so I created that directory and put mine there.   Let's say you want to call your dictionary mydict and your input datafile of words is called dict.txt.  We'll use the path I just showed.
First, copy the default .aff file.  You will see it when you run hunspell -D as described above.   For me, it's in /Library/Spelling/en_US/.  So
cp /Library/Spelling/en_US.aff /Users/scott/Library/Spelling/mydict.aff
Then, every time you update your input list (dict.txt), do this:
DICT=/Users/scott/Library/Spelling/mydict.dic
cd ~/doc/dict
cat dict.txt | sort | uniq > dict.in
wc -l dict.in > $DICT
cat dict.in >> $DICT
rm dict.in
To run hunspell, just specify both dictionaries.  So for me, because I want a list of misspellings, I use
hunspell -l -d scott,en_US <filename>

A: create your own word-list and affix file for your language, if that doesn't exist. Well, for papiamentu - Curaçao's native language - such dictionary doesn't exist. But I had a hard time finding out how to create such files, so I am documenting it here: http://www.suares.com/index.php?page_id=25&news_id=233

A: I am implementing this type of feature as well.  Once you've created the Hunspell object with an associated dictionary you can add individual words to it.
Keep in mind though that these words will only be available for as long as the Hunspell object is alive.  Every time you access a new object you will have to add all the user defined words again.

A: Have a look at the documentation in openoffice
http://www.openoffice.org/lingucomponent/
specially this document
http://www.openoffice.org/lingucomponent/dictionary.html
It's a good starting point


text:
Q: unable to delete merge pull subscription Environment:
Merge pull subscription with anonymous subscribers, using web sync, publisher is 2008R2, subscribers are SQLEXPRESS 2008R2.
Issue:
I run sp_dropmergepullsubscription on subscriber and sp_dropmergesubscription on publisher, subscription is removed on subscriber, but why do I see an entry in sysmergesubscriptions on publisher, for that subscriber, with status 1 still?
I found a way here
which suggests to manually delete entries, but why do I have to manually delete stuff?
Is it required to run sp_dropmergesubscription on publisher after running sp_dropmergepullsubscription on subscriber? Just deleting on subscription on subscriber side is not enough?

A: Do not manually delete the entries in sysmergesubscriptions.  Manually deleting these entries can result in not being able to add new subscribers down the road.
To delete a pull subscription to a Merge publication at the subscriber on the subscription database execute sp_dropmergepullsubscription.  Then at the publisher on the publication database execute sp_dropmergesubscription.  This is covered in How to: Delete a Pull Subscription.
Executing sp_dropmergesubscription at the publisher will not remove the entry from sysmergesubscription but will set the status to 2, which indicates it has been deleted.
If the status is still 1 in sysmergesubscriptions then perhaps you executed sp_dropmergesubscription incorrectly.  Make sure to specify @publication, @subscriber, and @subscriber_db.  Also, specify a value of pull for @subscription_type.


text:
Q: Does the path separator actually needs to be escaped in filter query but not in the facet prefix in solrj? In my java application powered by solrj I need to add drill down function on the document paths which are tokenized at index time by the PathHierarchyTokenizer.
While researching why the expected results did not come up, I noticed that the path I wanted to search against needed to be properly java escaped in the fq parameter, ie "/" -> "/" ("\/" in java). So query.toQueryString() prints out fq=path_descendent_path%3A%5C%2Fhome%5C%2Fuser1%5C%2FTestDir.
So I am a bit confused because when escaping "/" the facet prefix does not work (facet count returns null) whereas without escaping "/" in the path, the correct counts are returned.
The full query that work is select?q=test&q.op=AND&start=0&rows=10&defType=edismax&qf=contents_txt&facet=true&facet.mincount=1&facet.field=path_descendent_path&facet.limit=-1&fq=path_descendent_path%3A%5C%2Fhome%5C%2Fuser1%5C%2FTestDir&f.path_descendent_path.facet.prefix=%2Fhome%2Fuser1%2FTestDir.
Consequently I wonder if this is usual to use escaped path for the fq parameter and unescaped path in facet prefix or if I missed something ?
Please note : according to lucene doc "/" is a special character in Lucene as "+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ /" also are. But I have never needed to escape "[ ]" for example in fq parameter dealing with date range.
Any help greatly appreciated

A: foo:/.../ is a regular expression pattern match. This works where a query is expected, such as the main query and the filter query (I'm not sure if it'd work in other arguments as it works on the token level iirc.)
The facet prefix is not a query - it's applied directly to match the front of the generated token.
Escaping in relation to date range - you would have to escape it if you expected it to be inside the literal part of the query. In a date range it's used as syntax.


text:
Q: How to receive a response package from GET request for OneNote API I'm getting a acknowledgement but no response message (details) i.e. list of notebooks from the OneNote API.  Below is my code.  I am able to receive the header and JSON details from a POST message but not the GET.  I have tried to convert the POST code in order to submit a GET request.
private async void getRequestClick(object sender, RoutedEventArgs e)
    {
     await GetRequests(true, "test");
    }
    async public Task<StandardResponse> GetRequests(bool debug, string sectionName)
    {
         Uri PagesEndPoint1 = new Uri("https://www.onenote.com/api/v1.0/notebooks");
        var client = new HttpClient();
        //// Note: API only supports JSON return type.
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //// This allows you to see what happens when an unauthenticated call is made.
        if (IsAuthenticated)
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authClient.Session.AccessToken);
        }
        HttpResponseMessage response;
        HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Get, PagesEndPoint1);
        response = await client.SendAsync(createMessage);
        tbResponse.Text = response.ToString();
        return await TranslateResponse(response);
    }

    private async static Task<StandardResponse> TranslateResponse(HttpResponseMessage response)
    {
        StandardResponse standardResponse;
        if (response.StatusCode == HttpStatusCode.Created)
        {
            dynamic responseObject = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
            standardResponse = new CreateSuccessResponse
            {
                StatusCode = response.StatusCode,
                OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
                OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
            };
        }
        else
        {
            standardResponse = new StandardErrorResponse
            {
                StatusCode = response.StatusCode,
                Message = await response.Content.ReadAsStringAsync()
            };
        }
        // Extract the correlation id.  Apps should log this if they want to collcet the data to diagnose failures with Microsoft support
        IEnumerable<string> correlationValues;
        if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues))
        {
            standardResponse.CorrelationId = correlationValues.FirstOrDefault();
        }
        return standardResponse;
    }

My POST messages are working OK.  I can create a new page etc.

A: I think you need to change the expected status code from HttpStatusCode.Created to HttpStatusCode.OK for Get requests, since they return a 200 and not a 201. Try doing that in your TranslateResponse method.