text:
Q: Rails 6: Can a model be aware of changes made to one of its has_many associations? I have a model Profile with many gallery_items.
class Profile < ApplicationRecord
  # ...

  has_many :gallery_items, dependent: :destroy
  accepts_nested_attributes_for :gallery_items, allow_destroy: true

I want to fire code in Profile any time a gallery item is changed. Is there a way to do this without amending the GalleryItem class?

A: You can use the after_touch hook on the Profile.  Just be sure to denote that the GalleryItem touches the Profile in its association.
class GalleryItem < ApplicationRecord
  belongs_to :profile, touch: true
end

class Profile < ApplicationRecord
  has_many :gallery_items
  after_touch :my_fancy_method

  private
    def my_fancy_method
      puts 'Doing some stuff after a GalleryItem was created/updated'
    end
end

A: Rails 6 has only 4 possible ActiveRecord Association Callbacks at the moment: before_add, after_add, before_remove and after_remove.
Source: Here
Unfortunately as the names themselves suggest, they are not aware of updates or changes to the associated objects, so if you to be aware of updates on gallery items small tweaks need to be done to the GalleryItem class as Jared suggested for example, or using an after_update.


text:
Q: Loading AWS Glue S3 Source Data I have a use case where AWS Glue is a good fit for data transformation.
However, the source file for this transformation job is retrieved via a HTTPs call which can take 45 mins to return.
What is the best approach to load this data to S3 and then sftp the glue output once completed?
This job needs to be both scheduled and run on demand.

A: I don't think there's a way of loading the data directly from Glue for HTTP/s now.
You can create a lambda or a EC2 instance with a service that extracts that source file and puts that file into an s3 bucket.
I would suggest you to do this:

*

*Create an empty S3 bucket

*Create a lambda or an EC2 instance with a service that extracts the source file and loads it into the previous S3 bucket

*Configure the previous bucket with notifications when a new file is PUT/uploaded into the bucket so it notifies an SNS topic.

*Create an AWS lambda subscribed to the previous SNS topic that triggers the Glue Job with your transformations.

*Create a Glue Job that loads the data from the S3 bucket you create, do the transformations and load it into S3.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to report a missing DTD files to the user? Given the code :
public class ModelHandler
{
//members
private DocumentBuilderFactory m_domFactory;
private DocumentBuilder m_builder;
private Document m_doc;
private XPathFactory m_factory;
private List<String> m_inputErrorLog;

public void openXmlFile(File file)
{

    this.m_inputErrorLog = new LinkedList<String>() ;

    try
    {
        m_builder = m_domFactory.newDocumentBuilder();
    }

    catch (ParserConfigurationException ex) { m_inputErrorLog.add(ex.getMessage());}

       try
       {
            m_doc = m_builder.parse(file);
       }
        catch (Exception ex)
       {
           m_inputErrorLog.add(ex.getMessage());
           m_domFactory.setValidating(false);
       }

        try
        {
            getNodesList("/"+m_doc.getDocumentElement().getNodeName());
        }
        catch (XPathExpressionException ex) {
        m_inputErrorLog.add(ex.getMessage());
    }
}

I want to present to the user that the DTD file is missing , while working with GUI .
How can I do that while trying to open the XML file ?
Thanks

A: Here is the solution , for anyone who would might need it some day :
import java.io.IOException;
// DOM
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
// SAX
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.XMLReader;

import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.InputSource;

public class XMLUtils {

  private XMLUtils() {}

  // validate using DOM (DTD as defined in the XML)
  public static boolean validateWithDTDUsingDOM(String xml)
    throws ParserConfigurationException, IOException
  {
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(true);
      factory.setNamespaceAware(true);

      DocumentBuilder builder = factory.newDocumentBuilder();

      builder.setErrorHandler(
          new ErrorHandler() {
            public void warning(SAXParseException e) throws SAXException {
              System.out.println("WARNING : " + e.getMessage()); // do nothing
            }

            public void error(SAXParseException e) throws SAXException {
              System.out.println("ERROR : " + e.getMessage());
              throw e;
            }

            public void fatalError(SAXParseException e) throws SAXException {
              System.out.println("FATAL : " + e.getMessage());
              throw e;
            }
          }
          );
      builder.parse(new InputSource(xml));
      return true;
    }
    catch (ParserConfigurationException pce) {
      throw pce;
    }
    catch (IOException io) {
      throw io;
    }
    catch (SAXException se){
      return false;
    }
  }

  // validate using SAX (DTD as defined in the XML)
  public static boolean validateWithDTDUsingSAX(String xml)
    throws ParserConfigurationException, IOException
  {
    try {

      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setValidating(true);
      factory.setNamespaceAware(true);

      SAXParser parser = factory.newSAXParser();

      XMLReader reader = parser.getXMLReader();
      reader.setErrorHandler(
          new ErrorHandler() {
            public void warning(SAXParseException e) throws SAXException {
              System.out.println("WARNING : " + e.getMessage()); // do nothing
            }

            public void error(SAXParseException e) throws SAXException {
              System.out.println("ERROR : " + e.getMessage());
              throw e;
            }

            public void fatalError(SAXParseException e) throws SAXException {
              System.out.println("FATAL : " + e.getMessage());
              throw e;
            }
          }
          );
      reader.parse(new InputSource( xml ));
      return true;
    }
    catch (ParserConfigurationException pce) {
      throw pce;
    }
    catch (IOException io) {
      throw io;
    }
    catch (SAXException se){
      return false;
    }
  }

  public static void main (String args[]) throws Exception{

    System.out.println(XMLUtils.validateWithDTDUsingDOM("c:/temp/howto.xml"));
    System.out.println(XMLUtils.validateWithDTDUsingSAX("c:/temp/howto.xml"));
    /*
      output :
               true
               true
    */
  }
}


text:
Q: Adding a timer to my code I have searched and tried to implement a timer on my own and cannot figure it out for the life of me. So what I want to do is every five seconds I want the random circle to change to a new random location. It seems so simple but I cant get it to work.
public class BounceThread implements Runnable {
  JFrame frame;
  int myX = 500 / 2;
  int myY = 500 / 2;;

  int X;
  int Y;

  Canvas canvas;
  BufferStrategy bufferStrategy;
  BufferStrategy bufferStrategy2;
  boolean running = true;
  Random rand = new Random();
  Random rand2 = new Random();

  int n = rand.nextInt(450) + 1;
  int n2 = rand.nextInt(450) + 1;

  public BounceThread() {
    frame = new JFrame("Basic Game");
    JPanel panel = (JPanel) frame.getContentPane();
    panel.setPreferredSize(new Dimension(500, 500));
    panel.setLayout(null);
    canvas = new Canvas();
    canvas.setBounds(0, 0, 500, 500);
    canvas.setIgnoreRepaint(true);
    panel.add(canvas);
    canvas.addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(KeyEvent evt) {
        moveIt(evt);
      }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setResizable(false);
    frame.setVisible(true);
    canvas.createBufferStrategy(2);
    bufferStrategy = canvas.getBufferStrategy();
    canvas.requestFocus();
  }

  public void run() {
    while (running = true) {
      Paint();
      if ((myX == n || myX == n) && (myY == n2 || myY == n2)) {

        n = rand.nextInt(450) + 1;
        n2 = rand.nextInt(450) + 1;
        n2 = 10 * (Math.round(n / 10));
        n = 10 * (Math.round(n / 10));
        Paint();

      }
    }
  }

  public static void main(String[] args) {
    BounceThread ex = new BounceThread();
    new Thread(ex).start();
  }

  public void Paint() {

    Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    g.clearRect(0, 0, 500, 500);
    Graphics2D e = (Graphics2D) bufferStrategy.getDrawGraphics();
    e.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    e.clearRect(0, 0, 500, 500);

    Paint(g, e);

    bufferStrategy.show();
  }

  protected void Paint(Graphics2D g, Graphics2D e) {
    n2 = 10 * (Math.round(n / 10));
    n = 10 * (Math.round(n / 10));
    g.fillOval(myX, myY, 30, 30);

    g.setColor(Color.red);

    e.fillOval(n, n2, 30, 30);

    e.setBackground(Color.white);
  }

  public void moveIt(KeyEvent evt) {
    switch (evt.getKeyCode()) {
    case KeyEvent.VK_DOWN:
      if (myY >= 450) {
        break;
      } else {
        myY += 10;
        break;
      }
    case KeyEvent.VK_UP:
      if (myY <= 30) {
        break;
      } else {
        myY -= 10;
        break;
      }
    case KeyEvent.VK_LEFT:
      if (myX <= 30) {
        break;
      } else {
        myX -= 10;
        break;
      }
    case KeyEvent.VK_RIGHT:
      if (myX >= 450) {
        break;
      } else {
        myX += 10;
        break;
      }
    }
  }
}

A: I would extend from a component (such as JComponent) and let JFC/Swing do as much of the lifting as possible. Please don't call canvas.setIgnoreRepaint(true); and remember to repaint(); after every move. Next, you need an ActionListener for the Timer events. Your switch logic could be expressed with break outside the if-else logic. Something like
public class BounceThread extends JComponent implements ActionListener {
    JFrame frame;
    int myX = 500 / 2;
    int myY = 500 / 2;;

    int X;
    int Y;

    Canvas canvas;
    BufferStrategy bufferStrategy;
    boolean running = true;
    Random rand = new Random();

    int n = rand.nextInt(450) + 1;
    int n2 = rand.nextInt(450) + 1;

    public BounceThread() {
        frame = new JFrame("Basic Game");
        JPanel panel = (JPanel) frame.getContentPane();
        panel.setPreferredSize(new Dimension(500, 500));
        panel.setLayout(null);
        canvas = new Canvas();
        canvas.setBounds(0, 0, 500, 500);
        // canvas.setIgnoreRepaint(true);
        panel.add(canvas);
        canvas.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                moveIt(evt);
                repaint();
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
        canvas.createBufferStrategy(2);
        bufferStrategy = canvas.getBufferStrategy();
        canvas.requestFocus();
    }

    public static void main(String[] args) {
        BounceThread ex = new BounceThread();
        int delay = 5000; // milliseconds
        new Timer(delay, ex).start();
    }

    @Override
    public void repaint() {
        Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        Graphics2D e = (Graphics2D) bufferStrategy.getDrawGraphics();
        e.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.clearRect(0, 0, 500, 500);
        e.clearRect(0, 0, 500, 500);
        Paint(g, e);
        bufferStrategy.show();
        super.repaint();
    }

    protected void Paint(Graphics2D g, Graphics2D e) {
        g.fillOval(myX, myY, 30, 30);
        g.setColor(Color.red);
        e.fillOval(n, n2, 30, 30);
        e.setBackground(Color.white);
    }

    public void moveIt(KeyEvent evt) {
        switch (evt.getKeyCode()) {
        case KeyEvent.VK_DOWN:
            if (myY < 450) {
                myY += 10;
            }
            break;
        case KeyEvent.VK_UP:
            if (myY > 30) {
                myY -= 10;
            }
            break;
        case KeyEvent.VK_LEFT:
            if (myX > 30) {
                myX -= 10;
            }
            break;
        case KeyEvent.VK_RIGHT:
            if (myX < 450) {
                myX += 10;
            }
            break;
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        n = rand.nextInt(450) + 1;
        n2 = rand.nextInt(450) + 1;
        repaint();
    }
}

A: Adding the following to the beginning of your run() method, on the first line before the while loop is probably doing what you're looking for:
    TimerTask task = new TimerTask() {@
        Override
        public void run() {
            n = rand.nextInt(450) + 1;
            n = 10 * (Math.round(n / 10));
        }
    };
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, 0, 5 * 1000);

Just to give you an idea though, I think the overall design (reuse of code etc.) would have to be improved.


text:
Q: Is this how I would expect a voltage regulator to work? I have a question just to check that I understand voltage regulators from a conceptual standpoint.
Say I have a power source, which delivers 8V. I need to step it down to 6V for a continuous load of 1A. Am I correct to assume that the overall circuit will only draw 1A from the power source, but 25% of that power will be dissipated as heat by the voltage regulator?

Now, I do plan on doing this, but with an L7806 voltage regulator (see page 11 for L7806 electrical characteristics), an 8V power source, and 2 motors which draw 1A each. The first problem I am seeing with this setup is that my power source is under the rated input voltage (8.6 - 19V, my source is 8V). Next, it is rated for a current draw of up to 1A (but I need to draw 2A).
So I am not sure what to do. From what I understand, if I use 2 voltage regulators to independently provide the power to each motor (each wired in parallel to the power source), then the max draw per regulator would be 1A. I still have the problem of my power source being under the voltage source though, but I may be able to fix that.
The other option I found is to use something from the RC world called a UBEC. For example, this one is rated to output 6V at a maximum of 3A, with better heat dissipation.
So what I am looking for from an answer is (1) a confirmation that I am understanding how voltage regulators work at a basic level (as well as any corrections or improvements to my misunderstanding), and (2) suggestions as to how I can achieve what I need. I would prefer to have an IC solution (like the 7806, but maybe something more appropriate for my case) because it is cheaper than the UBEC.

A:
Am I correct to assume that the overall circuit will only draw 1A from the power source, but 25% of that power will be dissipated as heat by the voltage regulator?

A linear voltage regulator works in the way described in the question. Switching regulators work differently, described further down.
The regulator draws current from the power supply, 1 Ampere in the example plus some marginal operating overhead of the regulator itself, and power dissipated by each load is calculated by P = I2 x R, or P = V x I, or P = V2 / R, whichever is more convenient to calculate. In this case, as current through elements in series is equal through each element and the combination, and the voltages are known:

*

*Pload = 6 * 1 = 6 Watts

*Preg = (8 - 6) * 1 = 2 Watts

The first problem I am seeing with this setup is that my power source is under the rated input voltage

A type of linear regulator known as a Low Drop Out (LDO) regulator is designed to work with lower voltage headroom. One of those should be used instead of the 7806, although in practice, most 7806 regulators will actually function even with 2 Volt headroom - Regulation quality may suffer, i.e. it may "drop out of regulation".

The other option I found is to use something from the RC world called a UBEC.

Standard UBECs are actually switching regulators or buck regulators. The way these work is, a high frequency oscillator "switches" the supply voltage on and off, this oscillating voltage is transformed up or down using either inductors, magnetic or piezoelectric transformers, or possibly in some other way, and then rectified and smoothed out to deliver the desired output voltage, in a method akin to using PWM to regulate "effective" current or voltage.
A switching regulator thus does not waste power proportionately to the voltage difference between input and output. Instead, this technology delivers anywhere from 80 to 93% efficiency, since the voltage that needs to be "reduced" is not being dropped across a resistive load at all.
In other words, a nearly constant 7 to 20% (design-dependent) of the final output power is the overhead that appears as heat and inaudible vibration at the switching regulator.

Yes, an UBEC can be used for the purpose described, or a "DC-DC buck regulator module" can be sourced from sites like eBay, often for much less than an UBEC, and possibly with better performance.
Heat generated at the regulator will be less than for a linear regulator, at the mentioned operating load.

A: A linear regulator, such as the 7806 or the LD1085 mentioned below, acts like a variable resistor between input and output. The control circuitry alters the effective resistance to "drop" excess voltage and this is dissipated as heat. In your case with Vin=8V and Vout = 6V and I load = 2A, your dissipation in the regulator
= I x V
= 2A x (8-6) V
= 4 Watts.
A heatsink will be needed.
As Anindo says, a UBEC is a switching regulator which "transforms" energy at one voltage level to energy at another voltage with relatively low losses. In this case with only 2V drop you will find the linear regulator simple and probably acceptable loss wise.

The variable voltage regulator ST LD1085 regulator in stock at Digikey for about $US1.65 in ones will meet your needs.
Pricing page
It allows up to 30V input, up to 3A output, drops only 1.3V minimum at 3A and can be configured to supply any voltage in the range 1.5V - 30V.
Use fig3 page 6, right hand diagram to set the output voltage to suit.


text:
Q: Fabric.js: clone loaded svg This might be very basic, but I am new to Fabric.js. I cannot clone a loaded svg like this:
var canvas = new fabric.Canvas('canvas');
fabric.loadSVGFromURL('/test/fabric/sphere.svg', function(objects, options) {
    var sphere1 = fabric.util.groupSVGElements(objects, options);
    sphere1.set({left: 100, top: 100 });
    canvas.add(sphere1).renderAll();
});
var sphere2=fabric.util.object.clone(canvas.sphere1);
sphere2.set({ left: 200, top: 150 });
canvas.add(sphere2).renderAll();

Also instanciating sphere2 like below did not work:
var sphere2=fabric.util.object.clone(canvas.getActiveObject());

What is wrong with my code?

A: The examples over here helped me out. It appeared that you have to define a group first.


text:
Q: Not able to understand why the angles for drawing star using Python's turtle module is The turtle module uses commands like fd (forward) & bk (back) for movement and rt (right) & lt (left) for turning. Most programs I have done, have intuitive angles to turn by.

I tried to draw 2 types of stars (through trial and error). The 1st one is 144 (720 / 5) degrees. Why are the angles for the second star 126 and 54 degrees?

Appreciate any help.
import turtle as t

t.pensize(5)

for i in range(5):
  t.fd(100)
  t.lt(54)
  t.fd(100)
  t.rt(126)

A: Looking at the pentagram image (that also contains the inner lines) from your question or [Wikipedia]: Pentagram (chosen that particular example, but it applies to the generic case) one can see that a star (its outer contour) can be actually looked at:
the legs of N equal isosceles triangles (oriented outwards), each sharing its base with a unique edge of an N sided regular polygon.
Therefore, here are some characteristics of a star:

*

*Number of vertices (number of isosceles triangles and sides of the polygon - N)

*Edge (how big the star is)

*Vertex angle (how sharp its vertices are)

*

*Together with the edge, this determines the regular polygon side length

*Position
So, a star is also a polygon consisting of 2 * N equal sides (N - number of vertices) with alternating angles: vertex angle, outer angle (which can be calculated from the above)
Now, the way the 2 stars in the question were drawn is totally different:

*

*Pentagram: it's a special 5 vertices star. Due to its vertex angle (36°) and special relationships between angles (72°, 108°) in regular pentagon, its "shoulders" (if you will) are located on the same line (axis), and can be drawn (inner lines included) by only 5 lines. For each number of vertices (N >= 5, as it would be an equilateral triangle or square for 3 or 4) there's such a special star (check below for 6), whose (vertex) angle is abs(720 / N - 180)

*The other star can't be drawn as the pentagram. Also, the reason why you got it right is just a coincidental relationship between the vertex and outer angle (their sum is 180°). When drawing segments with [Python.Docs]: turtle - Turtle graphics, if you want the current segment and the next one to have alpha° between them, you have to turn (left or right) by (180 - alpha)°
I created a small (generic, I'd say) example able to draw different stars (based on their properties).
code00.py:
#!/usr/bin/env python

import math
import random
import sys
import turtle

def draw_star(vertices, edge, vertex_angle, center=(0, 0), rotation=0, text=None, verbose=False):
    '''
    - Isosceles triangle:
        - Base angle: (180 - vertex_angle) / 2
    - Regular polygon:
        - Angle: (vertices - 2) * 180 / vertices
    - Outer angle: 360 - Regular polygon angle - 2 * Isosceles triangle base angle
    '''
    out_angle = vertex_angle + 360 / vertices

    va_2 = math.radians(vertex_angle / 2)
    ho = edge * math.cos(va_2)
    side_2 = edge * math.sin(va_2)
    rad = ho + side_2 / math.tan(math.pi / vertices)
    if verbose:
        print("Star: vertices: {:d}, edge: {:d}, vertex angle: {:.3f} (out angle: {:.3f}), center: ({:d}, {:d}), radius: {:.3f}, rotation: {:.3f}{:s}".format(
            vertices, edge, vertex_angle, out_angle, *center, rad, rotation, ", text: '{:s}'".format(text) if text else ""))
    turtle.penup()
    #turtle.goto(center)
    #turtle.write("({:d}, {:d})".format(*center))
    rot = math.pi / 2 - math.radians(rotation)
    turtle.goto(center[0] - rad * math.cos(rot), center[1] + rad * math.sin(rot))
    turtle.pendown()
    turtle.setheading(270 - vertex_angle / 2 + rotation)
    for _ in range(vertices):
        turtle.forward(edge)
        turtle.right(180 - out_angle)
        turtle.forward(edge)
        turtle.left(180 - vertex_angle)
    if text:
        turtle.write(text)

def test_stars():
    distance = 180
    offsetx = 0
    offsety = 0
    edge = 80
    stars = (
        (5, edge, 54, (distance + offsetx, distance + offsety), 0, "Yours"),
        (6, edge, 60, (-distance + offsetx, distance + offsety), 0, "David"),
        (5, edge, 36, (-distance + offsetx, -distance + offsety), 0, "Pentagram"),
        (10, edge, 30, (distance + offsetx, -distance + offsety), 0, ""),
    )
    rot = 180
    for star in stars:
        turtle.pencolor((random.randint(0, 0xFF), random.randint(0, 0xFF), random.randint(0, 0xFF)))
        draw_star(*star[:3], center=star[3], rotation=star[4], text=star[5], verbose=1)
        if rot and (star[0] % 2 == 1):
            turtle.pencolor((random.randint(0, 0xFF), random.randint(0, 0xFF), random.randint(0, 0xFF)))
            draw_star(*star[:3], center=star[3], rotation=star[4] + rot, text=star[5] + " {:d}".format(rot) if star[5] else "", verbose=1)

def test_centered_stars(var_edge=True):
    vertices = 7
    edge = 20 if var_edge else 80
    vertex_angle = 70 if var_edge else 30
    count = 15 if var_edge else 10
    rot = 0
    turtle.hideturtle()
    for i in range(count):
        draw_star(vertices, edge + (5 * i if var_edge else 0), vertex_angle, rotation=rot + (0 if var_edge else 5 * i), verbose=1)
    turtle.showturtle()

def main(*argv):
    turtle.title("SO 75268563")
    turtle.speed(speed=0)
    turtle.setup(width=0.5, height=0.66, startx=None, starty=None)
    turtle.mode(mode="standard")
    turtle.colormode(cmode=0xFF)
    turtle.pensize(3)
    test_stars()
    #test_centered_stars(var_edge=0)
    print("Click on drawing window to exit...")
    turtle.exitonclick()

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q075268563]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" ./code00.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Star: vertices: 5, edge: 80, vertex angle: 54.000 (out angle: 126.000), center: (180, 180), radius: 121.270, rotation: 0.000, text: 'Yours'
Star: vertices: 5, edge: 80, vertex angle: 54.000 (out angle: 126.000), center: (180, 180), radius: 121.270, rotation: 180.000, text: 'Yours 180'
Star: vertices: 6, edge: 80, vertex angle: 60.000 (out angle: 120.000), center: (-180, 180), radius: 138.564, rotation: 0.000, text: 'David'
Star: vertices: 5, edge: 80, vertex angle: 36.000 (out angle: 108.000), center: (-180, -180), radius: 110.111, rotation: 0.000, text: 'Pentagram'
Star: vertices: 5, edge: 80, vertex angle: 36.000 (out angle: 108.000), center: (-180, -180), radius: 110.111, rotation: 180.000, text: 'Pentagram 180'
Star: vertices: 10, edge: 80, vertex angle: 30.000 (out angle: 66.000), center: (180, -180), radius: 140.999, rotation: 0.000
Click on drawing window to exit...

Done.

And the drawing window:

Notes:

*

*draw_star:

*

*Draws a star by going to the left

*Play with different values for to see some interesting shapes:

*

*Note that for some values results might not be expected ones (e.g. vertex angles higher than 90°)

*The examples contain your star (drawn the right way), a couple of well known ones and another (dummy) one. Odd vertices stars are also drawn 180° rotated
Also displaying centered stars output (for visual effect only):


text:
Q: 14MB Increase in Memory Usage - Bringing up Keyboard - iPad Retina I've noticed something strange running an app on a retina iPad under iOS7.
Bringing up the standard keyboard (via the user tapping in a UITextfield) sees a memory spike of 14MB in the Activity Monitor in Instruments, whereas on a non-retina iPad this is around 4MB.
Is this to be expected /normal or should I be checking my code ?


text:
Q: scala - cannot resolve symbol :: I am new to Scala and have some question about why string::List() works List()::s doesn't?I also want to know if ListBuffer works better than  ::?
val columnNames :List[String] = ['foo','bar']
val work :List[String] = List()
for (s <- columnNames) {
  s match {
     //this doesn't compile
     //case workPattern => work :: s
     //this works
     case workPattern => s :: work
     // this also works
     case workPattern => work :: List(s)
}

A: a :: b literally means "add an element a at the beginning of a list b".
It creates new list with a as a head and b as a tail.
To append element to list you can use ++
or something like this
work ::: "foo" :: Nil, the latter isn't very efficient, of course.
For the second part of a question, as stated in the documentation:
Time: List has O(1) prepend and head/tail access.
Most other operations are O(n) on the number of elements in the list.
This includes the index-based lookup of elements, length, append and reverse.
Space: List implements structural sharing of the tail list.
This means that many operations are either zero- or constant-memory cost.

So it depends on size and types of operations you need to perform which is preferable performance-wise.

A: The function you call at s :: work is List.::. Scala String is just an alias for Java's string, hence does not expose operators such as ::. s :: work is equivalent to work.::(s).
For more information you can refer How to add elements to a List in Scala (List, ListBuffer) and Scala List class examples: range, fill, tabulate, appending, foreach, more ... by the great Alvin Alexander.


text:
Q: injecting external js into self created iframe So i am trying to inject and external css and js into a self created iframe to provide an extra security layer, there therefore is no cross domain issues.
here is the code
<!doctype html>

the css file is being inputted but neither of the js files are, can anyone see why? the console.log is outputting.
thanks

A: I think you have to create the script element from the iframe's document object. It should be available as contents[0], which you can pass to insertScript.
It works if you use appendChild directly on your head node (not the jQuery wrapper):
$('iframe').contents().find('head')[0].appendChild(script);

http://jsbin.com/enidiv/1/edit

A: As long as the iframe domain, protocol, and port matches you can add scripts. Otherwise, it is treated as an unsafe attempt to access a different url.


text:
Q: Нет функции gtk_check_button_get_active() Хочу забрать состояние виджета CheckButton с помощью функции gtk_check_button_get_active(), однако такая функция не находится. Для других виджетов подобная функция имеется и работает корректно.

A: Для GTK 3.0
Проблему решил так:
Как сказано в руководстве, Gtk.CheckButton наследуется от Gtk.ToggleButton, следовательно gtk_toggle_button_set_active() и gtk_toggle_button_get_active() наследуются тоже.
По итогу, такая функция gtk_toggle_button_get_active(check_btn) корректно возвращает статус кнопки, хоть IDE и подсвечивает аргумент check_btn, как несовместимый тип.
Если хотите, чтобы при сборке не выдавало предупреждений - сделайте приведение типов таким образом gtk_toggle_button_get_active((GtkToggleButton *) check_btn)
Для GTK 4.0
В GTK 4.0 для Gtk.CheckButton добавлены собственные функции gtk_check_button_get_active() и gtk_check_button_set_active()


text:
Q: Javascript function does not work on onclick of checkbox I try to call a Javascript function through an onclick attribute of a checkbox.
The js should show another checkbox if the first one is checked etc.
Now the function isnt working. I tried to use just an alert() for testing without any result...
  Fitness:<input type="checkbox" id="fitnessCheck" onclick="checkFunction()">
    Beauty:<input type="checkbox" id="beautyCheck">
    Streetwear:<input type="checkbox" id="streetwearCheck">
    Luxus:<input type="checkbox" id="luxusCheck" onClick="checkFunction()">

Datenschutz: <input style="display:none" type="checkbox"  id="datenschutzCheck">
<script>
checkFunction(){
//get Checkboxes
var fitnessCheckbox = document.getElementById("fitnessCheck");
var beautyCheckbox = document.getElementById("beautyCheck");
var streetwearCheckbox = document.getElementById("streetwearCheck");
var luxusCheckbox = document.getElementById("luxusCheck");
var datenschutzCheckbox = document.getElementById("datenschutzCheck");

if(fitnessCheckbox.checked == true || beautyCheckbox.checked == true || streetwearCheckbox.checked == true || luxusCheckbox.checked == true){
    datenschutzCheckbox.style.display ="block";
}
}</script>

A: You have to declare the function checkFunction().
You can do it in many ways such as:
function checkFunction() {
// code here
}

or
var checkFunction = function() {
// code here
}

etc, depending on how you are going to use the function.

A: This is how to define a function in JavaScript.
Correct your function as below;
function checkFunction(){
}

Alternatively, remove the onclick attribute from HTML and put it in the JavaScript as defined below
var fitnessCheckbox = document.getElementById("fitnessCheck");
fitnessCheckbox.onclick() = function() {
// access properties using this keyword
if ( this.checked ) {
    // if checked ...
    alert( this.value );
} else {
    // if not checked ...
}


text:
Q: Zonal Statistics not running in QGIS 3.12 I am working on Nighttime light data from NOAA. The study area is India at state level. After masking the raster, when I am trying to run the zonal statistics with raster and vector polygon layer (screen shot attached), the small window of zonal statistics just flickers and does not run. Though the log section says that 'Algorithm zonal statistics finished' but it does not run. It does not add any new columns in the vector polygon attribute table. The attribute table is as it is as it was before. I have been trying to run this for last two days, but it does not help.
What could be the possible reason for it? I am currently using QGIS version 3.12.


text:
Q: Eyecon datepicker doesn't work in combination with bootstrap and reduced page size I am prototyping the UI with bootstrap. I use the eyecon.ro datepicker.
Basically, it works almost fine. However, there is one problem. The datepicker stops working when I reduce the page size to fit the tablet or mobile format. When I enlarge the page - the control starts to work as it should. Here is the code:

                        Today

Thank you.

A: The plugin is not included in jQuery mobile by default.  Do you have it?
This may also be a duplicate of JQuery mobile datepicker doesn't work


text:
Q: Extracting data from Web One really newbie question.
I'm working on a small python script for my home use, that will collect data of a specific air ticket.
I want to extract the data from skyscanner (using BeautifulSoap and urllib). Example:
http://www.skyscanner.net/flights/lond/rome/120922/120929/airfares-from-london-to-rome-in-september-2012.html
And I'm interested in all the data that are stored in this kind of element, specially the price: http://shrani.si/f/1w/An/1caIzEzT/capture.png
Because they are not located in the HTML, can I extract them?

A: I believe the problem is that these values are rendered through a javascript code which your browser runs and urllib  doesn't - You should use a library that can execute javascript code.
I just googled crawler python javascript and I got the some stackoverflow questions and answers which recommends the use of selenium or webkit. You can use those libraries through scrapy. Here are two snippets:
Rendered/interactive javascript with gtk/webkit/jswebkit
Rendered Javascript Crawler With Scrapy and Selenium RC

A: I have been working on this same exact issue. I have been introduced to Beautifulsoup and later since learned about Scrapy. Beautifulsoup is very easy to use, especially if you're new at this. Scrapy apparently has more "features", but I believe you can accomplish your needs with Beautifulsoup.
I had the same issues about not being able to gain access to a website that loaded information through Javascript and thankfully Selenium was the savior.
A great introduction to Selenium can be found here.
Install: pip install selenium
Below is a simple class I put together. You can save it as a .py file and import it into your project. If you call the method retrieve_source_code(self, domain) and send the hyperlink that you are trying to parse it will return the source code of the fully loaded page when you can then put into Beautifulsoup and find the information you're looking for!
Ex:
airfare_url = 'http://www.skyscanner.net/flights/lond/rome/120922/120929/airfares-from-london-to-rome-in-september-2012.html'

soup = BeautifulSoup(SeleniumWebScraper.retrieve_source_code(airfare_url))

Now you can parse soup like you normally would with Beautifulsoup.
I hope that helps you!
from selenium import webdriver
import requests

class SeleniumWebScraper():

    def __init__(self):
        self.source_code = ''
        self.is_page_loaded = 0
        self.driver = webdriver.Firefox()
        self.is_browser_closed = 0
        # To ensure the page has fully loaded we will 'implicitly' wait
        self.driver.implicitly_wait(10)  # Seconds

    def close(self):
        self.driver.close()
        self.clear_source_code()
        self.is_page_loaded = 0
        self.is_browser_closed = 1

    def clear_source_code(self):
        self.source_code = ''
        self.is_page_loaded = 0

    def retrieve_source_code(self, domain):
        if self.is_browser_closed:
            self.driver = webdriver.Firefox()
        # The driver.get method will navigate to a page given by the URL.
        #  WebDriver will wait until the page has fully loaded (that is, the "onload" event has fired)
        #  before returning control to your test or script.
        # It's worth nothing that if your page uses a lot of AJAX on load then
        #  WebDriver may not know when it has completely loaded.
        self.driver.get(domain)

        self.is_page_loaded = 1
        self.source_code = self.driver.page_source
        return self.source_code

A: You don't even need BeautifulSoup to extract data.
Just do this and your response is converted to a Dictionary which is very easy to  handle.
text = json.loads("You text of the main response content")
You can now print any key value pair from the dictionary.
Give it a try. It is super easy.


text:
Q: Modelling ternary relations in a semantic wiki Standard example to model a binary relation is "Dad likes Mom". In a Wiki I would have two pages for Mom and Dad and a (directed) property "likes".
I need to model "ternary relations". For example:

*

*Peter goes to New York using a bus.

*John goes to Mexico using a car.

Where people, locations be vehicles are entities and usage is the ternary property/relation.
How can I express that in a semantic mediawiki??

A: This cant be done with standard means. The ternary relation needs to be represented as an object in its own right using
https://www.semantic-mediawiki.org/wiki/Help:Type_Record
This is implemented using:
https://www.semantic-mediawiki.org/wiki/Extension:Semantic_Internal_Objects


text:
Q: Swift: How would I add an action to a tab bar item using Interface Builder? I've been able with code-only to add an action to a tab bar item, but I'm more used to coding with the Interface Builder, and am struggling to use what I know about setting up a tab bar controller with an action tab item programmatically to add an action to a tab bar set up in the IB. With a Tab Bar Controller and three View Controllers connected to said TBC in the IB, how would I go about adding an action where when the middle tab bar item is pressed, the View Controller associated would be presented modally? Thanks.

A: You can only set up associated view controllers in tabbar from the storyboard. You can't add an action to a tabbar item.
When you select a tab in tabbar, the tabBarController will automatically show the associated view controller. To prevent that, you have to implement tabBarController(_ tabBarController: UITabBarController, shouldSelect method of UITabBarControllerDelegate in your tabBarController subclass, where you can decide whether to show the selected tabbar item or not.
Don't forget to set the delegate in your UITabBarController subclass.
extension YourTabBarController: UITabBarControllerDelegate {

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

    if (viewController is 'YourViewControllerClass') {
        // code to present the viewcontroller

        return false
    }

    return true
}

}

A: This code Work for me:
import UIKit

class WayTBC: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Tab Bar Customisation
    tabBar.barTintColor = .systemPink
    tabBar.tintColor = .systemTeal
    tabBar.unselectedItemTintColor = .systemGray
    tabBar.isTranslucent = false

    viewControllers = [
        createTabBarItem(tabBarTitle: "Search", tabBarImage: "ic_home_search", viewController: SearchVC()),
        createTabBarItem(tabBarTitle: "Tab 2", tabBarImage: "ic_home_search", viewController: SearchVC()),
        createTabBarItem(tabBarTitle: "Tab 3", tabBarImage: "ic_home_search", viewController: SearchVC()),
        createTabBarItem(tabBarTitle: "Tab 4", tabBarImage: "ic_home_search", viewController: SearchVC())
    ]

    // Do any additional setup after loading the view.
}

func createTabBarItem(tabBarTitle: String, tabBarImage: String, viewController: UIViewController) -> UINavigationController {
    let navCont = UINavigationController(rootViewController: viewController)
    navCont.tabBarItem.title = tabBarTitle
    navCont.tabBarItem.image = UIImage(named: tabBarImage)

    // Nav Bar Customisation
    navCont.navigationBar.barTintColor = .white
    navCont.navigationBar.tintColor = .white
    navCont.navigationBar.isTranslucent = false
    return navCont
}


text:
Q: Python converting excel to text issue I am converting a excel file to a text file with custom delimeter. However, the output is not what I want to achieve.

*

*Instead of getting 1|2|3|, I am getting 1|2|3 instead. How can I add the pipe after the 3?

*the number inside one of the columns of the excel file is 001. However, after conversion it became 1. How can I retain 001?

Please help me with the following queries I have above. I have also attached snippets of my code .Thank you
text_file = pd.read_excel(uploadedFile, sheet_name=0)
text_file.to_csv(name + '.txt', header = False, sep='|'


text:
Q: Comparing two NSDates and ignoring the time component What is the most efficient/recommended way of comparing two NSDates?  I would like to be able to see if both dates are on the same day, irrespective of the time and have started writing some code that uses the timeIntervalSinceDate: method within the NSDate class and gets the integer of this value divided by the number of seconds in a day.  This seems long winded and I feel like I am missing something obvious.
The code I am trying to fix is:
if (!([key compare:todaysDate] == NSOrderedDescending))
{
    todaysDateSection = [eventSectionsArray count] - 1;
}

where key and todaysDate are NSDate objects and todaysDate is creating using:
NSDate *todaysDate = [[NSDate alloc] init];

Regards
Dave

A: I'm surprised that no other answers have this option for getting the "beginning of day" date for the objects:
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay startDate:&date2 interval:NULL forDate:date2];

Which sets date1 and date2 to the beginning of their respective days.  If they are equal, they are on the same day.
Or this option:
NSUInteger day1 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit: forDate:date1];
NSUInteger day2 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:date2];

Which sets day1 and day2 to somewhat arbitrary values that can be compared.  If they are equal, they are on the same day.

A: You set the time in the date to 00:00:00 before doing the comparison:
unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:flags fromDate:date];

NSDate* dateOnly = [calendar dateFromComponents:components];

// ... necessary cleanup

Then you can compare the date values. See the overview in reference documentation.

A: I use this little util method:
-(NSDate*)normalizedDateWithDate:(NSDate*)date
{
   NSDateComponents* components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                              fromDate: date];
   return [calendar_ dateFromComponents:components]; // NB calendar_ must be initialized
}

(You obviously need to have an ivar called calendar_ containing an NSCalendar.)
Using this, it is easy to check if a date is today like this:
[[self normalizeDate:aDate] isEqualToDate:[self normalizeDate:[NSDate date]]];

([NSDate date] returns the current date and time.)
This is of course very similar to what Gregory suggests. The drawback of this approach is that it tends to create lots of temporary NSDate objects. If you're going to process a lot of dates, I would recommend using some other method, such as comparing the components directly, or working with NSDateComponents objects instead of NSDates.

A: I used the Duncan C approach, I have fixed some mistakes he made
-(NSInteger) daysBetweenDate:(NSDate *)firstDate andDate:(NSDate *)secondDate {

    NSCalendar *currentCalendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [currentCalendar components: NSDayCalendarUnit fromDate: firstDate toDate: secondDate options: 0];

    NSInteger days = [components day];

    return days;
}

A: The answer is simpler than everybody makes it out to be. NSCalendar has a method
components:fromDate:toDate:options

That method lets you calculate the difference between two dates using whatever units you want.
So write a method like this:
-(NSInteger) daysBetweenDate: (NSDate *firstDate) andDate: (NSDate *secondDate)
{
  NSCalendar *currentCalendar = [NSCalendar currentCalendar];
  NSDateComponents components* = [currentCalendar components: NSDayCalendarUnit
    fromDate: firstDate
    toDate: secondDate
    options: 0];

  NSInteger days = [components days];
  return days;
}

If the above method returns zero, the two dates are on the same day.

A: From iOS 8.0 onwards, you can use:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSComparisonResult dateComparison = [calendar compareDate:[NSDate date] toDate:otherNSDate toUnitGranularity:NSCalendarUnitDay];

If the result is e.g. NSOrderedDescending, otherDate is before [NSDate date] in terms of days.
I do not see this method in the NSCalendar documentation but it is in the iOS 7.1 to iOS 8.0 API Differences

A: For developers coding in Swift 3
if(NSCalendar.current.isDate(selectedDate, inSameDayAs: NSDate() as Date)){
     // Do something
}

A: With Swift 3, according to your needs, you can choose one of the two following patterns in order to solve your problem.

#1. Using compare(_:to:toGranularity:) method
Calendar has a method called compare(_:to:toGranularity:). compare(_:to:toGranularity:) has the following declaration:
func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult

Compares the given dates down to the given component, reporting them orderedSame if they are the same in the given component and all larger components, otherwise either orderedAscending or orderedDescending.

The Playground code below shows hot to use it:
import Foundation

let calendar = Calendar.current
let date1 = Date() // "Mar 31, 2017, 2:01 PM"
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)! // "Mar 30, 2017, 2:01 PM"
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)! // "Mar 31, 2017, 3:01 PM"

/* Compare date1 and date2 */
do {
    let comparisonResult = calendar.compare(date1, to: date2, toGranularity: .day)
    switch comparisonResult {
    case ComparisonResult.orderedSame:
        print("Same day")
    default:
        print("Not the same day")
    }
    // Prints: "Not the same day"
}

/* Compare date1 and date3 */
do {
    let comparisonResult = calendar.compare(date1, to: date3, toGranularity: .day)
    if case ComparisonResult.orderedSame = comparisonResult {
        print("Same day")
    } else {
        print("Not the same day")
    }
    // Prints: "Same day"
}

#2. Using dateComponents(_:from:to:)
Calendar has a method called dateComponents(_:from:to:). dateComponents(_:from:to:) has the following declaration:
func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents

Returns the difference between two dates.

The Playground code below shows hot to use it:
import Foundation

let calendar = Calendar.current
let date1 = Date() // "Mar 31, 2017, 2:01 PM"
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)! // "Mar 30, 2017, 2:01 PM"
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)! // "Mar 31, 2017, 3:01 PM"

/* Compare date1 and date2 */
do {
    let dateComponents = calendar.dateComponents([.day], from: date1, to: date2)
    switch dateComponents.day {
    case let value? where value < 0:
        print("date2 is before date1")
    case let value? where value > 0:
        print("date2 is after date1")
    case let value? where value == 0:
        print("date2 equals date1")
    default:
        print("Could not compare dates")
    }
    // Prints: date2 is before date1
}

/* Compare date1 and date3 */
do {
    let dateComponents = calendar.dateComponents([.day], from: date1, to: date3)
    switch dateComponents.day {
    case let value? where value < 0:
        print("date2 is before date1")
    case let value? where value > 0:
        print("date2 is after date1")
    case let value? where value == 0:
        print("date2 equals date1")
    default:
        print("Could not compare dates")
    }
    // Prints: date2 equals date1
}

A: There's a new method that was introduced to NSCalendar with iOS 8 that makes this much easier.
- (NSComparisonResult)compareDate:(NSDate *)date1 toDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit NS_AVAILABLE(10_9, 8_0);

You set the granularity to the unit(s) that matter. This disregards all other units and limits comparison to the ones selected.

A: For iOS8 and later, checking if two dates occur on the same day is as simple as:
[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2]

See documentation

A: This is a shorthand of all the answers:
NSInteger interval = [[[NSCalendar currentCalendar] components: NSDayCalendarUnit
                                                                  fromDate: date1
                                                                    toDate: date2
                                                                   options: 0] day];
    if(interval<0){
       //date1<date2
    }else if (interval>0){
       //date2<date1
    }else{
       //date1=date2
    }

A: int interval = (int)[firstTime timeIntervalSinceDate:secondTime]/(60*60*24);
if (interval!=0){
   //not the same day;
}

A: my solution was two conversions with NSDateFormatter:
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd"];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

    NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *todayString=[dateFormat stringFromDate:today];
    NSDate *todayWithoutHour=[dateFormat dateFromString:todayString];

    if ([today compare:exprDate] == NSOrderedDescending)
    {
       //do
    }

A: The documentation regarding NSDate indicates that the compare: and isEqual: methods will both perform a basic comparison and order the results, albeit they still factor in time.
Probably the simplest way to manage the task would be to create a new isToday method to the effect of the following:
- (bool)isToday:(NSDate *)otherDate
{
    currentTime = [however current time is retrieved]; // Pardon the bit of pseudo-code

    if (currentTime < [otherDate timeIntervalSinceNow])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

A: This is a particularly ugly cat to skin, but here's another way to do it. I don't say it's elegant, but it's probably as close as you can get with the date/time support in iOS.
bool isToday = [[NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterNoStyle] isEqualToString:[NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterNoStyle]];

A: NSUInteger unit = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit;
NSDateComponents *comp = [cal components:unit
                                fromDate:nowDate
                                  toDate:setDate
                                 options:0];

NSString *dMonth;
dMonth = [NSString stringWithFormat:@"%02ld",comp.month];
NSString *dDay;
dDay = [NSString stringWithFormat:@"%02ld",comp.day + (comp.hour > 0 ? 1 : 0)];

compare hour as well to fix 1day difference


text:
Q: segment fault in single function mergesort of linked list I am running into a segmentation fault from using the online C++ compiler while doing this single function mergesort all day and I couldn't locate where it possibly be. The other problem is that the way that I don't understand this method of finding the mid of the linked list, why is it assignment operator, is there a better way to do it? Any help will be appreciated.
#include <stdio.h>
#include <stdlib.h>

struct listnode { struct listnode * next; int key; };

struct listnode * sort(struct listnode * a)
{
    struct listnode  *fast, *slow, *mid, *left, *right;
    fast = a; left = a; right = NULL;  mid = NULL;

    //data is null or one node
    if (!a || !a->next)
    {
        return a;
    }

    //find mid by declaring a pointer skipping throw an extra node for each loop

    while (fast)
    {
        if (fast = fast->next) { fast = fast->next; }
        mid = slow;
        slow = slow->next;
    }

    //split the list in recursion
    if (mid != NULL) { mid->next = NULL; }

    a = sort(a); slow = sort(slow);

    //merge
    while (left != NULL && slow != NULL)
    {
        if (left->key < right->key) { left->next = mid; right = left; }
        else
        {
            if (!right)
                a = slow;
            else
            {
                right = slow; right->next = slow;  slow = slow->next; right->next = left;
            }
        }

    }
    if (left == NULL) { right->next = slow; }
    return(a);

}

//test

int main()
{
    long i;
    struct listnode *node, *tmpnode, *space;
    space = (struct listnode *) malloc(500000 * sizeof(struct listnode));
    for (i = 0; i< 500000; i++)
    {
        (space + i)->key = 2 * ((17 * i) % 500000);
        (space + i)->next = space + (i + 1);
    }
    (space + 499999)->next = NULL;
    node = space;
    printf("\n prepared list, now starting sort\n");
    node = sort(node);
    printf("\n checking sorted list\n");
    for (i = 0; i < 500000; i++)
    {
        if (node == NULL)
        {
            printf("List ended early\n"); exit(0);
        }
        if (node->key != 2 * i)
        {
            printf("Node contains wrong value\n"); exit(0);
        }
        node = node->next;
    }
    printf("Sort successful\n");
    exit(0);
}

A: At least one problem is:
while (fast)
{
    if (fast = fast->next) { fast = fast->next; }
    mid = slow;
    slow = slow->next; // <-------- HERE!
}

fast was assigned to non-null value before this loop, so control enters the loop and tries to read slow->next, which is invalid. The slow pointer was not assigned to anything before the loop, so it holds garbage value and does not point to valid memory location. Thus, reading memory by this pointer is very likely to violate process address space. And from the language perspective, reading an uninitialized pointer is an example of undefined behavior.
See also a good explanation in this question.


text:
Q: How to deploy Angular 11 Universal to Ubuntu Nginx I am trying to migrate from my existing CSR Application to Angular Universal SSR and now looking to deploy on production server.
Existing configuration is with Ubunto 18.04 and Nginx with .Netcore 3.1 backend API.
Existing directory structure is:
--html
---All .dotnet assemblies and dlls
---wwwroot
----Angular files

Now after building with cli
npm run build:ssr

As per Angular 11, I have two directories:
server
browser

*

*here I am not clear exactly where to put these directories. Should I put contents of Browser Directory inside wwwroot folder as these files are for Client side rendering?

*where to put server directory?

*Do I need to install nodejs or express on the server?

FYI, I have this configuration which is working perfectly with CSR:
server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443 default ssl;
    server_name website.com;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;
    gzip on;
    gzip_static on;
    gzip_types font/woff2 text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
    gzip_proxied  any;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;

         location / {
           index index.html
         #try_files $uri$args $uri$args/ /index.html;
        #try_files $uri $uri/ /index.php?$args;
         #try_files $uri $uri/ index.html;
        #try_files $uri$args $uri$args/ $uri $uri/ /index.html =404;
        #expires -1;
            add_header Pragma "no-cache";
            add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
            try_files $uri$args $uri$args/ $uri/ /index.html =404;
        root /home/winnie/www/html/wwwroot;
    }

        location /api/ {
             proxy_pass http://localhost:5000;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection keep-alive;
             proxy_set_header Host $host;
             proxy_cache_bypass $http_upgrade;
            proxy_redirect http://localhost:5000 https://website.com;
        root /home/winnie/www/html;
        }

        location /content/ {
             proxy_pass http://localhost:5000;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection keep-alive;
             proxy_set_header Host $host;
             proxy_cache_bypass $http_upgrade;
            proxy_redirect http://localhost:5000 https://website.com;
        root /home/winnie/www/html;
        }

    ssl_certificate /etc/letsencrypt/live/website.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/website.com/privkey.pem; # managed by Certbot
}

I am just looking to tweak into this configuration to handle Angular SSR Request.
Have gone through many articles like
https://github.com/angular/universal-starter/issues/514 comment from m98
But here in my case there is no server.js file.
https://blog.daudr.me/painless-angular-ssr/ article also gives some insight but not with much clarity.
Hope you guys a best way to deploy.


text:
Q: How to get fail % in sql, when the trials are spread across rows? I have a table in sql like below
Test Run Status
---  --- ---
1    1   Pass
1    2   Fail
2    1   Pass
2    2   Pass

I need output like below
Test Fail% Pass%
---  ---   ---
1    50%   50%
2    0%    100%

How do I achieve this with sql commands only?

A: Aggregate function are the key here. and the use of the Case statement to get the conditionals.
Select Test, (Sum(CASE when Status = 'Pass' then 1 else 0 end)/count(*)) *100
From mytable
group by test


text:
Q: How do I generate a package download list? I want to generate a package download list, which can be used to download those packages from another system. (I have a slow connection). I want to use those downloaded files to create a local repository from which I can install/upgrade my system.
How can I achieve this?

A: First Note that, You must have the updated package indexes (these indexes are used by package management softwares to get information about the available packages online). So, you must download at least those index files.
To do so, open a terminal and give this command. (You must have a working internet connection for this step)
sudo apt-get update

After you have the update package index files, use any of the method below:
Terminal way without synaptic
Use this command to generate an list of files needed to upgrade your system
sudo apt-get upgrade --allow-unauthenticated -y --print-uris | grep -o '\'http.*\' | tr "\'" " " > download-list

The file download-list will be created in the current folder of the terminal.
Or, If you want to generate a download script for a specific package, use this command (see the update section below for another command)
sudo apt-get install <package-name> --allow-unauthenticated -y --print-uris | grep -o '\'http.*\' | tr "\'" " " > download-list

replace, <package-name> with actual name of the package. such as gtg for getting-things-gnome etc.
You can now use this file to feed any download manager which support input files with URLs.
For example to use this file with wget use this command below,
wget -c -i ./download-list

assuming download-list file is in the current directory of the terminal. The downloaded files will be stored in the current working directory of the terminal.
Update: I've found another command to generate package download list:
apt-get --allow-unauthenticated -y install --print-uris package-name | cut -d\' -f2 | grep http:// > download-list

Credit of the updated command: answerer of this post

Graphical way using Synaptic
Synaptic package manager has built-in feature to generate package download script and you don't even need to to use wget explicitly in terminal, Only executing the script is sufficient.
The procedure is as follows

*

*Install Synaptic Package Manager using terminal:
 sudo apt-get update
 sudo apt-get install synaptic

(First command is not required, if you have updated package index  files, If you are not sure, use both).

*Then open Synaptic Package Manager by Typing Synaptic in the dash.

*Select a package in the right section of the window, Right Click → Mark it for installation. Alternatively, If you want to generate an upgrade script, push the button Mark All Upgrades in the toolbar. The image below uses the second method.

*When asked if you want to Mark additional required chanages, press the Mark button.

*Then going to File --> Generate package download script, save the script as a file by give it a name and select a directory where to save it. Now, You have a script for package downloads.
If you want to download, Go to the scripts directory and run sh ./<script-name>. For example, if the name of the script is download-list and it is in your Downloads folder, the command is
cd ~/Downloads && sh ./download-list

A: Synaptic also has a menu item to export selected packages to a file.


text:
Q: How to setup HTTPS Mutual Auth between Bluemix and CastIron Virtual Appliance? We have tested the Bluemix API Managment taling to OnPremise CastIron Virtual Appliance using http to work fine.
Now we wanted to enable HTTPS and test the same flow using the certificates.
We are not finding the exact steps of how to get this implemented.
Can you give us some steps to be done in BlueMix, Secure Gateway, Secure gateway Client and Castiron Virtual Appliance which we can try out?
We are now using the Virtual Appliance IP set as Destination in Secure Gateway so we are generating certificates using the IP address?
We assume that might cause the issue. Any insights on how to resolve those issues?
Thanks,
Shemida

A: Can you try if the suggestions in the below link helps ?
https://console.ng.bluemix.net/docs/services/CloudIntegration/CldInt_StdSC_Install.html#CloudInt_installingsecureconnectors

A: Please refer to the following site for additional information besides Bluemix doc.
https://developer.ibm.com/bluemix/tag/secure-gateway/
Especially, I feel these articles are relevant to your question.
https://developer.ibm.com/bluemix/2015/04/17/securing-destinations-tls-bluemix-secure-gateway/
https://developer.ibm.com/bluemix/2015/09/24/ibm-secure-gateway-updates-version-130/
https://developer.ibm.com/bluemix/2015/11/11/secure-gateway-in-production-part1/
I'm not familiar with CastIron Virtual Appliance.  You say you will have an issue with generating certificates with the CastIron Virtual Appliance.  What kind of problem do you have?  Please describe more details.


text:
Q: Use timestamp(or datetime) as part of primary key (or part of clustered index) I use following query frequently:
SELECT * FROM table WHERE Timestamp > [SomeTime] AND Timestamp < [SomeOtherTime] and publish = 1 and type = 2 order by Timestamp

I would like to optimize this query, and I am thinking about put timestamp as part of primary key for clustered index, I think if timestamp is part of primary key , data inserted  in table has write to disk sequentially by timestamp field.Also I think this improve my query a lot, but am not sure if this would help.
table has 3-4 million+ rows.
timestamp field never changed.
I use mysql 5.6.11

Anothet point is : if this is improve my query , it is better to use timestamp(4 byte in mysql 5.6) or datetime(5 byte in mysql 5.6)?

A: Four million rows isn't huge.
A one-byte difference between the data types datetime and timestamp is the last thing you should consider in choosing between those two data types. Review their specs.
Making a timestamp part of your primary key is a bad, bad idea. Think about reviewing what primary key means in a SQL database.
Put an index on your timestamp column. Get an execution plan, and paste that into your question.  Determine your median query performance, and paste that into your question, too.
Returning a single day's rows from an indexed, 4 million row table on my desktop computer takes 2ms.  (It returns around 8000 rows.)

A: 1) If values of timestamp are unique you can make it primary key. If not, anyway create index on timestamp column as you frequently use it in "where".
2) using BETWEEN clause looks more natural here. I suggest you use TREE index (default index type) not HASH.
3) when timestamp column is indexed, you don't need call order by  - it already sorted.
 (of course, if your index is TREE not HASH).
4) integer unix_timestamp is better than datetime both from memory usage side and performance side - comparing dates is more complex operation than comparing integer numbers.
Searching data on indexed field takes O(log(rows)) tree lookups. Comparison of integers is O(1) and comparison of dates is O(date_string_length). So, difference is (number of tree lookups) * (difference_comparison) = O(date_string_length)/O(1))* O(log(rows)) =  O(date_string_length)* O(log(rows))


text:
Q: saving scraped items to json/csv/xml file using scrapy I am learning Scrapy(A web crawling framework) from their official doc.
By following examples and documentation I created my spider to scrape data using sitemap
from scrapy.contrib.spiders import SitemapSpider
from scrapy.selector import Selector
from MyProject1.items import MyProject1Item

class MySpider(SitemapSpider):
    name="myspider"
    sitemap_urls = ['http://www.somesite.com/sitemap.xml']
    sitemap_follow = ['/sitemapbrowsesection\d+']
    count=0
    def parse(self, response):
        self.count=self.count+1
        item=MyProject1Item()
        sel=Selector(response)
        item["exp"]=sel.xpath('/html/head/title/text()').extract()
        print str(self.count)+":\t"+response.url
        print sel.xpath('/html/head/title/text()').extract()
        print "\n\n"

I can see the scraped results on screen with log by running command
scrapy crawl myspider
I can save scraped results to json/csv/xml file by adding option in command
scrapy crawl myspider -o item.json -t json for getting results in json file.
My problem is that scrapy dumps scraped results to item.json only when scrapy is done with crawling. means  have to wait till crawling get over. so for big project I will have to wait for very very long time as I guess scrapy will write scraped results to json file after all the crawling to be done.
I want scrapy to write to json file promptly or almost promptly or in the mid of crawling so I can see the results of sites which have crawled while scrapy is running.
I know there must be something inbuilt in scrapy that I am not able to catch. I tried to get help from http://doc.scrapy.org/en/latest/topics/feed-exports.html
and
http://doc.scrapy.org/en/latest/topics/exporters.html
but not able to solve my problem. so I am looking for some help or example code otherwise I have to add few lines to parse(self, response) function to create json/csv file and write scrapped result into it.

A: That's the way writing to a file works. There is a buffer that gets written to the disk only when it's full.
For example, in one shell open a file with python:
$ ipython

In [1]: fp = open('myfile', 'w')

In another shell monitor the file content:
$ tail -f myfile

Go back to the python shell and write some content:
In [2]: _ = [fp.write("This is my file content\n") for i in range(100)]

In my case, I don't see any content in the tail output. Write more content:
In [3]: _ = [fp.write("This is my file content\n") for i in range(100)]

Now I see the lines in the tail output.
In fact, you can change the file buffering (see [1]). Open again a file:
$ ipython

In [1]: fp = open('myfile', 'w', buffering=0)

Monitor the file content in another shell:
$ tail -f myfile

Write something and see the tail output:
In [2]: fp.write("Hello there\n")

It is good to have the buffering enabled (reduces the disk I/O). You items file will get the output eventually, but you might want to change the format to the default jsonlines (no -t argument needed), with that you get a json object per line. It's a highly used format for streaming.
You can read a jsonlines (.jl extension) easily:
import json

for line in open('items.jl'):
    data = json.loads(line)
    # do stuff with data

And even other tools like head + json.tool or jq (see [2]):
$ head -1 items.jl | python -m json.tool
$ jq -I . items.jl

I haven't seen any problem so far having a large job writing the items to a .jl file (or any other format). Nevertheless, if your job gets killed you will lost the last items in the buffer. This can be solved by storing the items in a db or something similar.
[1] http://docs.python.org/2/library/functions.html#open
[2] http://stedolan.github.io/jq/manual/

A: scrapy crawl myspider -o item.json -t json saves fetched results while crawling only. I wont have to wait for crawling to get finished. I can see content of file item.json while crawler is running
so no need to include code for writing fetched data to file in spider.


text:
Q: Get Product ID throught url in Custom page? I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal.
i created one custom module in my magento,Its working great.
Using this i created that one http://www.phparrow.com/magento/magento-create-a-simple-module/
in my product page i have a link
 Click Here
when i click Click Here its redirecting to http://www.example.com/magenaresh/index.php/hello/ this URL upto here every thing is ok...
But now i want to pass the ProductID along with URL
for this i wrote like this
<?php
    $product_id = $this->getProduct()->getId();
    echo $product_id;
?>

AND
<a href = "http://www.example.com/magenaresh/index.php/hello/<?php echo $product_id ?> ">Click Here

again i clicked on Click Here its showing

Any thing wrong i did here ?
Any Ideas ?

A: Hello check below code
<a href = "http://www.example.com/magenaresh/index.php/hello/index/index/<?php echo $product_id ?> ">Click Here

A: you can add link at you href like
<a href = "http://www.example.com/magenaresh/index.php/hello/index/index/product_id/<?php echo $product_id ?> ">Click Here

And in your  controller can access the URL parameters in the exact same way as before;
$id = $this->getRequest()->get('product_id');

hope this will sure help you.


text:
Q: Why can we treat the Bloch hamiltonian as an effective hamiltonian? Often when looking at topological insulators the hamiltonian is broken down into the Bloch hamiltonian and then analysed ignoring the creation/annhilation operators of the Bloch waves. Why is it okay to just ignore these?
For example for an n-band Bloch Hamiltonian in 2D we have, for each Brillouin zone the effective hamiltonian:
$$H(\mathbf k)=\left[a^\dagger_{\mathbf k, 1}\qquad a^\dagger_{\mathbf k, 2} ....a^\dagger_{\mathbf k, n}\right]\mathcal H(\mathbf k) \begin{bmatrix} a^\dagger_{\mathbf k, 1}\\ a^\dagger_{\mathbf k, 2} \\ a^\dagger_{\mathbf k, n}\end{bmatrix}$$
It is then given that for some $\mathbf k$ we have the eigenstates
$$\mathcal H (\mathbf k)\lvert m(\mathbf k)\rangle=E_m(\mathbf k )\lvert m(\mathbf k)\rangle$$
But what do these eigenstates mean? I don't understand why it means anything since we have redefined what our hamiltonian is.

A: Take e.g. the Rashba Hamiltonian (wiki)
$$H({\bf k})= \frac{\hbar^2k^2}{2m^*} + \alpha(k_y\sigma_x - k_x\sigma_y)$$
which is written in the basis of Bloch states and spin state, $|{\bf k},\sigma\rangle$, $\sigma=\uparrow\downarrow$ and yields to bands. As one can easily see, the spin quantum number is not a good quantum number and $|{\bf k},\sigma\rangle$ is not an eigenstate. Thus, you have to be clear about the representation of the Hamiltonian. In most cases it will not only be $\langle r|{\bf k}\rangle =e^{-i {\bf k}\cdot{\bf r}}$.

A: The important point here is that your Hamiltonian is the one of a  Linear system, ie there is only quadratic term in it. This allow you, when your system is periodic in space, to rewrite you Hamiltonian as a sum of quadratic form:
\begin{equation} H = \sum_k \vec{a}_k^\dagger h(k) \vec{a}_k$ \end{equation}
When you write this equation, what you are saying is that every wave vectors is not coupled to others k. You can treat each wavevectors $k$ separetely.
In the subspace of a fixed $k$, you then only have to diagonlise the matrix $h(k)$. You gets the eigenvectors of $h(k)$: $\vec{v}(k)$. This gives you the eigenmode of your initial Hamiltonian: $\vec{v}_\vec{k}\cdot \vec{a}_\vec{k}$

A: The first thing to note is that the Hamiltonian you are presenting describes non-interacting electrons and it conserves the respective occupation numbers. So there is no real need for the whole machinery of second quantization.
In principle, the single-particle states and energies provide you with all the information you need and this information will be sufficient to deduce all many body properties. So why are some models "effective"?
The exact solution has an infinite number of eigenstates in the thermodynamic limit. But usually you are interested in things which happen close to the energy of the Fermi level. Since the single-electron states don't talk to each other via the Hamiltonian, you simply need to take a snapshot of your band-structure across the energy window you are interested in.


text:
Q: Sharing multiple values or an object through contexts I'm trying to share user-entered form data with a component that shows a "preview" of the formatted content. Similar to StackOverflow showing the markdown preview below this text-entry box, however in my case the data comes from multiple text fields.
To sync the data, I'm using a context (which appears to be the correct approach based on my research) but my problem is that I'm not sure how to share multiple values.
I figured each form field could send data as part of an object that for the receiving component, might look like this:
{
    firstname: (input from first name field component)
    address: (input from address field component)
    other: (input from other field component)
}

The receiving component can then just read this data {preview.firstname}.
When setting the value after a user has updated the field, I use the spread operator to combine existing data into a new object.
However, I get the feeling this is a problematic way to do this. The linter complains that the preview object is not in the useEffect dependencies, but if I put it there, it creates an infinite render loop.
const [field] = useField('firstname');
const { preview, setPreview } = useContext(MyContext);

useEffect(() => {
    setPreview({
        ...preview,
        name: field.value
    });
}, [field.value, setPreview]);

I guess I could create a different context for each form field but that will get verbose and I don't think that's the right solution either.
I'm still learning React/Contexts so I'm unsure what the "right" solution is. Do I use one context for each "state" value I want to share, or can I share a "state" object safely?

A: You can use functional set state:
  setPreview(ps=>({
        ...ps,
        name: field.value
    }));

No need for preview as dependency anymore.


text:
Q: The value of $\lim\limits_{n\to\infty}{\frac{a_n}{n}}$ Let
$$\lim_{n\to\infty}{(a_{n+p}-a_n)}$$
exists, what's the value of
$$\lim_{n\to\infty}{\frac{a_n}{n}}$$
My attempt
$$\lim_{n\to\infty}{(a_{n+p}-a_n)}$$ exists,that is
$$\begin{align}\lim_{n\to\infty}{(a_{n+p}-a_n)}&=\lim_{n\to\infty}{[(a_{n+p}-a_{n+p-1})+(a_{n+p-1}-a_{n+p-2})+...+(a_{n+1}-a_{n})]}\\ &=p\lim_{n\to\infty}{(a_{n+1}-a_{n})}\\ &=\lambda\end{align}$$
We get,
$$\lim_{n\to\infty}{(a_{n+1}-a_{n})}=\frac{\lambda}{p}$$
By Stolz's theorem,
$$\lim_{n\to\infty}{\frac{a_n}{n}}=\lim_{n\to\infty}\frac{a_{n+1}-a_{n}}{(n+1)-n}=\frac{\lambda}{p}$$
My question
Is my answer correct?And if it's wrong? How to prove it?

A: As I mentioned in the comment, one way is to open up the proof of Stolz-Cesàro theorem and apply it to this specific problem. Alternatively, we may rely on the following easy observation:
Observation. Let $p \geq 1$ be a positive integer. Then a sequence $(x_n)$ converges to $x$ as $n\to\infty$ if and only if, $(x_{pn+r})$ converges to $x$ as $n\to\infty$ for each $r \in \{0, \cdots, p-1\}$.
Now by Stolz-Cesàro theorem, for each $r \in \{0, \cdots, p-1\}$,
$$ \lim_{n\to\infty} \frac{a_{pn+r}}{pn+r}
= \frac{1}{p} \lim_{n\to\infty} \frac{a_{pn+r}}{n}
= \frac{1}{p} \lim_{n\to\infty} \left[ a_{pn+r} - a_{p(n-1)+r} \right] = \frac{\lambda}{p}. $$
So, by our observation, $a_n/n \to \lambda/p$ as required.


text:
Q: NONEMPTY behaviour seemingly not limiting results The following script is from this MSDN article http://msdn.microsoft.com/en-us/library/ms145988.aspx
SELECT
  [Measures].[Internet Sales Amount] ON 0,
  NONEMPTY(
     [Customer].[Customer].[Customer].MEMBERS,
     {([Date].[Calendar].[Date].&[20010701], [Measures].[Internet Sales Amount])}
  ) ON 1
FROM [Adventure Works]

I basically took the script and replaced the elements from the above with equivalent elements from our cube.
What would be the reason that my script is not limiting it's results to the date specified in the NONEMPTY function but is returning all customers and their lifetime sales amount?

A: Try this:
SELECT
[Measures].[Internet Sales Amount] ON 0,
NONEMPTY(
[Customer].[Customer].[Customer].MEMBERS
) ON 1
FROM [Adventure Works]
where
[Date].[Calendar].[Date].&[20010701]

A: All the customers might have a non-null internet sales amount for the date you have specified. Moreover the nonempty will just filter out those members where the condition is not met. In your case as all the customers has non-null Internet Sales value, none of the customers are filtered out. And the Internet sales amount in the axis 0 will not be limited to the date that is specified, instead it returns the sales amount for each customer across all the dates.


text:
Q: How can I create a program that stores a numerous amount of names/numbers in an array by clicking a button without the method resetting my counter? public void actionPerformed(ActionEvent e)
{
  int clicked = 0;
 if(arg == "Enter")
 {
     clicked++;
 }

 if (clicked == 0)
{
names[0] = nameField.getText();
numbers[0] = numberField.getText();
}

if( clicked == 1)
{
names[1] = nameField.getText();
numbers[1] = numberField.getText();
}

 if(arg == "Print")
 {
   String name = nameField.getText();
   String number = numberField.getText();
   JOptionPane.showMessageDialog(null,names[0] + numbers[0] + names[1] + numbers[1] + numbers[2] + names[2],"Info",JOptionPane.INFORMATION_MESSAGE);
 }

My program must take multiple names and numbers and be able to enter them into an array. After all of the data is entered, it must be able to be printed. I am having trouble under the Enter method because it continues to reset everytime instead of remaining constant. It only allows me to print the last typed name/number instead of saving all of the content. I am unsure of how to fix this and would be grateful for any suggestions at this point.

A: You could start by moving int clicked out of this function.
Right now your actionPerformed function each time its called reset your clicked to 0 since you are setting it to 0 at the beggining of it.
public void actionPerformed(ActionEvent e)
{
    int clicked = 0;   //HERE is your problem
    if(arg == "Enter");
    ...

Making it a variable of class instead of function should help.
EDIT:
You can do something  like this:
int clicked = 0
public void actionPerformed(ActionEvent e)
{
    if(arg == "Enter"){
         names[clicked] = nameField.getText();
         numbers[clicked] = numberField.getText();
         clicked++;
    }

As it was mentioned you could also use List, since it would save problems if you don't know how big of an array u need.
List<String> names = new ArrayList<String>();
List<String> numbers = new ArrayList<String>();

And in use
    if(arg == "Enter"){
         names.add(nameField.getText());
         numbers.add(numberField.getText());
    }

A: Instead of an array, you could use an ArrayList, it will allow you to add elements without having to supply an index.
Without givening away too much, like this:
ArrayList<String> names = new ArrayList<String>();
...
names.add("Johnny"); // Adds to the end of the list
names.add("Frank");

That way you don't need to keep the 'clicked' count.
You can use .get(i) to get the element at index i. Or just loop over the entire list using a for each loop:
for(String name : names) { // i.e. for each 'name' in 'names'
    System.out.println(name);
    // Or do something else with 'name'
}


text:
Q: REST application design choices in a CDI world I have JAX-RS resource classes calling methods in separate service classes. I chose @RequestScoped for both resource and service classes so that I could easily supply (@Inject a common CDI instance) and pass the response back from the service class to the resource class.
The problem is that the service classes provide methods that would be useful to other classes with either @ApplicationScoped, @Dependent or @Stateless scope. But the injection of the response class no longer helps because there is no @RequestScope context for the backend classes.
I think I have a few choices

*

*Change the service classes to @Stateless or @Dependent and abandon using CDI to share a common response class instance, instead return a generic response from the service class that could be interpreted by any caller (not REST specific). This would be transformed into a REST response by the resource class.

*Create an additional layer by factoring out the bulk of the service classes into @Dependent classes that can be invoked from a @RequestScoped service layer or by the back end @Application/@Dependent classes.

*Something I haven't thought of yet

Could someone share how they might design such an application using CDI?

A: I am going to answer my own question.
The lure of using @RequestScoped seems to simplify the application design, but it's clear in the context of the bigger picture it adds complexity.
Adam Bien demonstrated that making your JAX-RS boundary classes EJBs (@Stateless) yields a better performance than @RequestScoped, so now the problem becomes one of passing results from the service layer back to the request layer or perhaps to another class that is not part of the boundary.
Eliminating the service classes completely and injecting control classes directly into the boundary is probably a better approach. The control classes could be @Dependant, @Stateless or @Application scoped (I presume?).
Also worth noting that @RequestScoped service classes wouldn't buy you anything anyway if you decided to create an alternative resource, e.g. a websocket API because that would not have the same @RequestScope as your service classes had either!


text:
Q: Can't capture duplicate port error in Express All,
I have a simple Express web server on Windows Node. I can't work out how to capture the error if I'm trying to start the server on the same port as another instance of Express already running. The error middleware won't capture it and the usual .on("error", function ()....) doesn't work either, and the whole Node application bombs - I want to capture it gracefully.
Here is the code:
    var express = require('express');
    var compression = require('compression')
    var app = express();
    var __dirname = ""
    app.use(compression({ threshold: 512 }));
    var oneYear = 86400000 * 365;
    app.enable('etag')
    app.use(express.static(__dirname + '../../HAWebClient', { maxAge: oneYear }));
    app.use(function (err, req, res, next) {
         if (!err) return next();
         console.log('<-------Error Occured ----->');
         res.send(500, JSON.stringify(err, ['stack', 'message']));
    });
    app.on("error", function (err) {
         status("SYSTEM/HTTP", "Error with the web server: " + err);
         // Do stuff with error
    });
    app.listen(80);

and I get
events.js:72
    throw er; // Unhandled 'error' event
          ^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Function.app.listen (C:\Users\deandob\Documents\GitHub\PluginMgr\PluginMgr\node_modules\express\lib\application.js:546:24)
at webSvr (C:\Users\deandob\Documents\GitHub\PluginMgr\PluginMgr\PlugMgr.js:298:9)
at Object.<anonymous> (C:\Users\deandob\Documents\GitHub\PluginMgr\PluginMgr\PlugMgr.js:271:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
Press any key to continue...

Don't want to capture this in Node's global error handler (which loses error context) - this error should be able to be captured by app.on("error,....) but I'm obviously missing something here. Thanks for the input!

A: When the port is already in use, app.listen(80); will throw an exception asynchronously (the exception you see in your error log) if you don't have an error handler on the server.  The server, in this case, is the return value from app.listen(), not the app object which is why you attempt at handling the error was not working.
Rather than let that exception go to the system which will shut-down your app, you can catch the error and prevent the exception like this:
var server = app.listen(8080);
server.on('error', function(e) {
    console.log(e);
    // put your code here
});

And, then decide what to do in the error handler.  I have tested this solution in a sample server and it does work.
FYI, the relevant documentation is on the socket object here: https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback


text:
Q: After upgrading to 19.04 gnome-session fails to start Upgraded from 18.10 to 19.04. On boot GDM starts normally, and after I enter my password it fails to start GNOME. It goes back to GDM
This is an Nvidia Optimus laptop. I ran Dingo from USB and installed it into a test partition. It recognizes everything (uses nouveau instead of the Nvidia blob).
Log says:
WARNING: App 'org.gnome.Shell.desktop' exited with code 1
Unrecoverable failure in required component org.gnome.Shell.desktop
WARNING: App 'org.gnome.Shell.desktop'  respawning too quickly
CRITICAL: We failed, but the fail whale is dead. Sorry...

Both mutter sessions using Xorg and Wayland fail the same way. The old metacity "GNOME Flashback" starts ok (but then indicator-datetime-service eats all CPU and memory and won't stop respawning if I kill it).
Tried using lightdm instead of GDM. It fails the same way.
Tried reinstalling gnome-session package. Nothing changed.
All logs obtained via journalct -xe.
Any advice on how to debug this thing will be welcome.
Later, I realised that I had inadvertently enabled the "proposed" repository (in my cosmic install). Downgraded gnome-shell ("3.32.1-1ubuntu1~19.04.1" to "3.32.0+git20190410-1ubuntu1"), mutter and other packages (using pinning priority), but the problem reamins exactly the same.
This is a longer excerpt from the logs (using Budgie now):
may 27 02:04:56 hostname gnome-shell[3334]: JS ERROR: TypeError: b.location.get_timezone(...) is null
                                           _clocksChanged/<@resource:///org/gnome/shell/ui/dateMenu.js:127:20
                                           _clocksChanged@resource:///org/gnome/shell/ui/dateMenu.js:125:9
                                           _connectHandler@resource:///org/gnome/shell/misc/util.js:472:9
                                           watchSetting@resource:///org/gnome/shell/misc/util.js:463:9
                                           WorldClocksSection@resource:///org/gnome/shell/ui/dateMenu.js:102:9
                                           _init@resource:///org/gnome/shell/ui/dateMenu.js:530:28
                                           _ensureIndicator@resource:///org/gnome/shell/ui/panel.js:1116:25
                                           _updateBox@resource:///org/gnome/shell/ui/panel.js:1127:29
                                           _updatePanel@resource:///org/gnome/shell/ui/panel.js:1072:9
                                           _init@resource:///org/gnome/shell/ui/panel.js:873:9
                                           _initializeUI@resource:///org/gnome/shell/ui/main.js:178:13
                                           start@resource:///org/gnome/shell/ui/main.js:127:5
                                           @<main>:1:31
may 27 02:04:56 hostname gnome-shell[3334]: Execution of main.js threw exception: Script <main> threw an exception
may 27 02:04:56 hostname gnome-shell[3334]: Attempting to call back into JSAPI during the sweeping phase of GC. This is most likely caused by not destroyin
may 27 02:04:56 hostname org.gnome.Shell.desktop[3334]: == Stack trace for context 0x55852aa8a230 ==
may 27 02:04:56 hostname gnome-shell[3334]: The offending signal was destroy on Gjs_DateMenuButton 0x55852bdbd810.
may 27 02:04:56 hostname gnome-session[3131]: gnome-session-binary[3131]: WARNING: App 'org.gnome.Shell.desktop' exited with code 1
may 27 02:04:56 hostname gnome-session[3131]: gnome-session-binary[3131]: WARNING: App 'org.gnome.Shell.desktop' respawning too quickly
may 27 02:04:56 hostname gnome-session-binary[3131]: WARNING: App 'org.gnome.Shell.desktop' exited with code 1
may 27 02:04:56 hostname gnome-session-binary[3131]: Unrecoverable failure in required component org.gnome.Shell.desktop
may 27 02:04:56 hostname gnome-session[3131]: gnome-session-binary[3131]: CRITICAL: We failed, but the fail whale is dead. Sorry....
may 27 02:04:56 hostname gnome-session-binary[3131]: WARNING: App 'org.gnome.Shell.desktop' respawning too quickly
may 27 02:04:56 hostname gnome-session-binary[3131]: CRITICAL: We failed, but the fail whale is dead. Sorry....
may 27 02:04:56 hostname gdm-x-session[3117]: session exited with status 1
may 27 02:04:56 hostname at-spi-bus-launcher[3250]: XIO:  fatal IO error 11 (Resource temporarily unavailable) on X server ":0"
may 27 02:04:56 hostname at-spi-bus-launcher[3250]:       after 21 requests (21 known processed) with 0 events remaining.
may 27 02:04:56 hostname ibus-daemon[3309]: GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). See the d
may 27 02:04:56 hostname /usr/lib/gdm3/gdm-x-session[3117]: (**) Option "fd" "26"

-- nachokb

A: Fixed now!
I had tried disabling all extensions, including user extensions, to no avail. Problem was with a built-in extension showing world clocks. I had to reset my World Clocks locations from CLI [1].
It's supposedly fixed (same GitLab issue) so this shouldn't happen in the future.
-- icarrera
[1] https://gitlab.gnome.org/GNOME/gnome-shell/issues/1062


text:
Q: How to change a set to list of different types in java? Now how to store that values of set in a list. Here  the set and list is of different type(ProductAttribute and PersistableProductAttribute).
for(ProductRelationship productrelationship:productRelationshipList)
{
    Product product=productrelationship.getRelatedProduct();
    PersistableProduct ppTem=new PersistableProduct();

    Set<ProductAttribute> aSet = product.getAttributes();
    List<PersistableProductAttribute> aList = new ArrayList<PersistableProductAttribute>();
// I need to store here in a list.
}

A: Its just a simple one I have got it after trying several times by myself.First I need to create a set for PersistableProductAttribute and I have to get the attributes of it using loop and I need to copy that set to list. Now it works fine because the set and list are same type. So we can copy a set to list using add() method in java.
 Set<PersistableProductAttribute> ppaSet = new
 PersistableProductAttribute<>();
 for(ProductAttribute x:aSet)
 {
  // Get all the attributes here using get()
  //and set() methods
  // Copy the set to list as follows,
    aList.add(ppaSet);
  }


text:
Q: Can the output of an L298N be smoothed using a capacitor to reduce buzzing? I'm running some model trains with a Raspberry Pi using L298N modules to control motor speed. Traditionally, this would be done using what is essentially a DC motor speed controller, but I need digital control over the output and this seemed the most sensible way to go.
The problem I'm facing is that the PWM signal is hugely amplified by the motor in the locomotives, and running is often clunky.
My understanding is that the H bridge is taking the PWM input and a voltage source, and producting a relatively bumpy DC output capable of driving the motors, which is amplified by the motor coils.
So, to the question, can the output of that H bridge be smoothed using a non-polarised capacitor? If so, what value and type of capacitor would be recommended given the circumstances?
It will likely be suggested that increasing the frequency outside of audible range will solve the problem but as far as I can tell, the RPi4 peaks at 8kHz. Having tried a few values as low as 50Hz up to 8kHz, I can't find any frequency where the noise is much subdued. At around 100-300Hz it's very quiet, but running is incredibly lumpy and the locomotive inches along a bit at a time.
My concern is mostly around whether the L298N is monitoring its output in some sort of feedback circuit - I don't really know how they work, and don't want to risk letting the smoke out of something.


text:
Q: Parse Push PHP SDK not able to receive on Android device I'm trying to send a parse push message using PHP code and Parse PHP SDK to all the Android Devices which are already registered.
The Parse SDK is available here Parse PHP SDK and I used the Alternative Method provided in the link above.
My PHP File:
<?php
      $APPLICATION_ID = "...";
      $REST_API_KEY = "...";
      $MASTER_KEY = "...";
      require 'autoload.php';
      use Parse\ParsePush;
      use Parse\ParseClient;
      ParseClient::initialize($APPLICATION_ID, $REST_API_KEY, $MASTER_KEY);

      $data = array("alert" => "Test Message");

      // Push
      ParsePush::send(array(
                      "data" => $data
      ));
?>

My environment is WAMP running latest version and followed the instructions given in above website.
But when I open the PHP file in Browser. I get errors like undefined _curl_init()_ shown in screenshot. I did my best searching on Google and stuff but I personally feel the documentation of Parse.com is not good.
I need bit help with this issue.

EDIT : I solved this issue by adding
curl_setopt($rest, CURLOPT_SSL_VERIFYPEER, false); below $rest = curl_init(); in ParseClient.php
Yet I'm unable to receive notification on my device

A: you also use ParseInstallation class
<?php

      $APPLICATION_ID = "...";
      $REST_API_KEY = "...";
      $MASTER_KEY = "...";
      require 'autoload.php';

    use Parse\ParseClient;
    use Parse\ParseUser;
    use Parse\ParseInstallation;
    use Parse\ParsePush;

 ParseClient::initialize($APPLICATION_ID, $REST_API_KEY, $MASTER_KEY);

    // Send Notification For Specific User
    $data = array (
            "alert" => "Test Message"
    );

    ParsePush::send ( array (
            "channels" => ["addChannel"],//add data channel from parse.com Installation class enter code here
            "data" => $data
    ) );
?>


text:
Q: What is the WiX 'KeyPath' attribute? What is the WiX 'KeyPath' attribute? In particular, how does it apply to the following:
<Component Id="ProgramMenuDir" Guid="*">
  <RemoveFolder Id="ProgramMenuDir" On="uninstall" />
  <RegistryValue Root="HKCU" Key="Software\CompName\AppName"
                 Type="string" Value="" KeyPath="yes" />
</Component>

A: As explained by Rob Mensching:

The KeyPath for a Component is a
  single resource that the Windows
  Installer uses to determine if a
  Component "exists" on a machine.

This means that when Windows Installer decides whether to install your component, it will first look whether the keypath resource is already present. If it is, none of the resources in the component are installed.
The presence of the keypath resource also determines whether a component has been damaged or has gone missing when you "repair" an MSI.
When the keypath resource is a versioned file, Windows Installer will consider it to exist only if it finds a file with an equal or higher version.
In your specific example, you have a component which removes a folder on uninstallation. This component will only be installed if the given registry key does not yet exists. Adding a registry key to use as the key path is a common trick when you need a keypath for a component that installs resources that cannot be used as a keypath themselves, like a shortcut.