Q: How Do I Draw Two Overlapping JPanels such that the Graphics Drawn On Both Of Them Display On The Screen? I have two JPanels. One panel has a 100x100 rectangle drawn at 0,0. And the other has a 100x100 rectangle drawn at 100, 100. My problem is that when both JPanels are drawn on the JFrame's content pane, one JPanel (the last one drawn) covers the other, hiding its graphics. Below is oversimplified code drawing two rectangles and the things I've tried.
package playground;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Playground{

    public Playground(){
        JFrame frame = new JFrame("My Frame");
        frame.setSize(400, 400);

        JPanel backPanel = new JPanel(){;

                @Override
                public void paintComponent(Graphics g){
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    Rectangle2D rect = new Rectangle2D.Double(0, 0, 100, 100);
                    g2.draw(rect);
                }
        };
        JPanel frontPanel = new JPanel(){

            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                Rectangle2D rect = new Rectangle2D.Double(150, 150, 100, 100);
                g2.draw(rect);
            }
        };
        frontPanel.setOpaque(true); //Does nothing
        frontPanel.setBackground(new Color(0, 0, 0, 0)); //Does nothing
        frontPanel.setForeground(new Color(0, 0, 0, 0)); //Erases the rectangle drawn

        frame.getContentPane().add(backPanel);
        frame.getContentPane().add(frontPanel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args){
        System.out.println("Hello World");
        new Playground();
    }

}

If anyone cares why I want to do this,
I'm creating the game breakout. I am a novice programmer and I have no knowledge of gaming theory. So I decided the smartest way to avoid a lot of rendering and buffering is to have four JPanels. A static JPanel at the very back with an image drawn on it (fun background image). A JPanel with the paddle drawn on it. A JPanel with bricks drawn on it. And a JPanel with a ball drawn on it. My rationale is that I won't have to redraw the paddle if it is not being moved, the background, and bricks that are not being hit. If a brick lets say is hit, I will update an arrayList of bricks and call repaint on the corresponding JPanel.

A:
I am a novice programmer and I have no knowledge of gaming theory.

Ok, we can work with that.

So I decided the smartest way to avoid a lot of rendering and buffering is to have four JPanels.

You've just unnecessarily complicated your program.
Think of a JPanel as a canvas.  You want to draw the entire Breakout game; bricks, paddle, and ball, on one JPanel canvas.  Don't worry, you'll be able to redraw the entire canvas fast enough to get 60 frames per second if you want.
The way to do this is to create a Brick class, a Paddle class, and a Ball class.  You create a Game Model class that contains one instance of the Paddle class, one instance pf the Ball class, and a List of instances of the Brick class.
The Brick class would have fields to determine its position in the wall, the number of points scored when the ball collides with the brick, the color of the brick, and a draw method that knows how to draw one brick.
The ball class would have fields to determine its x, y position, its direction, its velocity, and a draw method that knows how to draw the ball.
The Paddle class would have fields to determine its x, y position, its direction, its velocity, and a draw method that knows haw to draw the paddle.
The Game Model class would have methods to determine when the ball collides with a brick, determine when the ball collides with a brick, determine when the ball collides with a wall, and a draw method that calls the other model class draw methods to draw a ball, a paddle, and a wall of bricks.
This should be enough for now to get you started going in the right direction.
Edited to answer questions:

How would I implement a draw method in all these classes?

Here's an example Ball class.  I haven't tested the moveBall method, so it might need some adjustment
import java.awt.Graphics;
import java.awt.geom.Point2D;

public class Ball {

    private Point2D position;

    /** velocity in pixels per second */
    private double  velocity;

    /**
     * direction in radians
     *

     *
0 - Heading east (+x)

     *
PI / 2 - Heading north (-y)

     *
PI - Heading west (-x)

     *
PI * 3 / 2 - Heading south (+y)

     *

     * */
    private double  direction;

    public Point2D getPosition() {
        return position;
    }

    public void setPosition(Point2D position) {
        this.position = position;
    }

    public double getVelocity() {
        return velocity;
    }

    public void setVelocity(double velocity) {
        this.velocity = velocity;
    }

    public double getDirection() {
        return direction;
    }

    public void setDirection(double direction) {
        this.direction = direction;
    }

    public void moveBall(long milliseconds) {
        Point2D oldPosition = position;

        // Calculate distance of ball motion
        double distance = velocity / (1000.0D * milliseconds);

        // Calculate new position
        double newX = distance * Math.cos(direction);
        double newY = distance * Math.sin(direction);

        newX = oldPosition.getX() + newX;
        newY = oldPosition.getY() - newY;

        // Update position
        position.setLocation(newX, newY);
    }

    public void draw(Graphics g) {
        int radius = 3;
        int x = (int) Math.round(position.getX());
        int y = (int) Math.round(position.getY());

        // Draw circle of radius and center point x, y
        g.drawOval(x - radius, y - radius, radius + radius, radius + radius);

    }

}

The draw method draws the ball wherever it actually is located.  That's all the draw method does.
Actually moving the ball is the responsibility of the Game Model class.  The method for moving the ball is included in this class because the information necessary to move the ball is stored in the Ball class.
I gave the ball a radius of 3, or a diameter of 6 pixels.  You may want to make the ball bigger, and use the fillOval method instead of drawOval.

should I just call repaint() at a 30ms interval

Basically, yes.
In psudeocode, you create a game loop
while (running) {
    update game model();
    draw game();
    wait;
}

First, you update the game model.  I gave you a Ball class.  You would have similar classes for the paddle and bricks.  They all have draw methods.
Your Game model class calls all of these draw methods in the proper order.  In Breakout, you would draw the boundaries first, then the bricks, then the paddle, and finally, the ball.
Your JPanel (canvas) calls the one draw method in the Game Model class.
I don't have an example game to show you, but if you read the article Sudoku Solver Swing GUI, you'll see how to put together a Swing GUI and you'll see how model classes implement draw methods.
I suggest that you stop working on Breakout for a while and go through the Oracle Swing Tutorial.  Don't skip any sections in your haste to write a program.  Go through the entire tutorial so you understand how Swing works before you try and use it.


Q: Complex numbers- elementary question How can I calculate the argument of the complex number $z= (\frac{1}{2}+ \frac{i\sqrt{3}}{2}) \cdot (1+i)$?
I always get $\tan^{-1}(-2-\sqrt{3})$, but the book answer is $7 \pi/12$.

A: You're given the two numbers as a multiplication. Recall that $r_1e^{i\theta} \cdot r_2e^{i \phi} = r_1r_2e^{i(\theta + \phi)},$ which is to say that arguments get added together when multiplying.
Now, note that $\frac12 + \frac{\sqrt3}2$ has argument $\frac\pi3$, while $1 + i$ has argument $\frac\pi4$. The argument of their product, then, is $\frac\pi3 + \frac\pi4 = \frac{7\pi}{12}$.
You're not wrong when you say that the argument is $\tan^{-1}(-2 - \sqrt{3})$, because
\begin{align*}
\tan \frac{7\pi}{12} &= \tan \left(\frac\pi3 + \frac\pi4\right) \\
&= \frac{\sqrt{3} + 1}{1 - (\sqrt{3})(1)} \\
&= \ldots \\
&= -2 - \sqrt{3}
\end{align*}
using the identity for $\tan(\alpha + \beta)$. It's just that it's not at all obvious that $\tan^{-1}(-2 - \sqrt{3}) = \frac{7\pi}{12}$, unlike for nicer angles whose tangents you've probably memorized!
So in this case, the "arguments get added" approach is the way to go.

A: It is $\arctan(\sqrt{3})+\arctan(1)  = \frac{\pi}{3}+\frac{\pi}{4}$.

A: I)  Tedious:  $z= (\frac{1}{2}+ \frac{3^{1/2}i}{2}) * (1+i)= (1/2 - \sqrt{3}/2) + (1/2 + \sqrt 3/2) i = $.  Arg($z$) = $\arctan (1+ \sqrt{3})/(1-\sqrt{3}) = -5\pi/12 = 7\pi/12$.
(To be fair, I made data entry errors the first six times I tried to enter this into a calculator.)
II) Easier (albeit it notation intimidating):  $\arg (1+i) = \pi/4$ so $i+1 = r*e^{\frac{\pi}4 i}$.  ($r = \sqrt 2$ but we don't give a toss.)  $\arg (1/2 + i\sqrt{3}/2) = \pi/3$ so $1/2 + i\sqrt{3}/2 = s*e^{\frac{\pi}3 i}$.  ($s = 1$ but we don't give a toss.)
So  $z= (\frac{1}{2}+ \frac{3^{1/2}i}{2}) * (1+i) = r*e^{\frac{\pi}4 i}*s*e^{\frac{\pi}3 i} = rse^{(\pi/3 + \pi/4)i}$ so $\arg(z) = \pi/3 + \pi/4 = 7\pi/12$.
====
Post Script: $\frac {1 + \sqrt 3}{1 - \sqrt 3}= \frac{(1 + \sqrt 3)^2}{1 - 3} = \frac {4 + 2\sqrt 3}{-2} = -2 - \sqrt 3$ so your first answer was absolutely correct.  Why did you doubt yourself?  Why did you assume $\tan^{-1}(-2 - \sqrt{3}) \ne 7\pi/12$?


Q: jQuery: I need to show consecutive fields in a form at each new click I have 5 upload fields but I need to hide them except the first. Then at each click to show them one by one.
I created the following script but it seems like item.show() is not displaying the hidden fields.10x
first = $('.webform-client-form').find('div[id$="-ajax-wrapper"]').first();
    first.after('[+] Add more');
    $('.webform-client-form').find('div[id$="-ajax-wrapper"]').each(function(){
            $(this).hide();
            first.show();
    });

    var c = 1;//counter
    $('#addmore').bind('click', function(e) {
        item = $('edit-submitted-file'+c+'-ajax-wrapper');
        item.show();
        ++c;
    if (c == 5) {
      $('#addmore').hide();
      return false;
    }
  });

A: shouldn't this:
var item = $('edit-submitted-file'+c+'-ajax-wrapper');

be
var item = $('#edit-submitted-file'+c+'-ajax-wrapper'); //if using id
or
var item = $('.edit-submitted-file'+c+'-ajax-wrapper'); //if using class

A: You need to prepend '#' to the selector for -ajax-wrapper because you are selecting it by ID.
The counter needs to start at 2 and hide addmore on 6.  The return false (should actually be e.preventDefault() should be outside of that conditional.
addmore should be added after the last of the file input rows, not the first.

A: Just use the next() function and :visible selector
Example:
HTML
File <input type="file" />
File <input type="file" />
File <input type="file" />
...

JQuery
$('label:gt(0)').hide(); // hide all except the first one
$('label:visible').click($(this).next('label').show()); // show the following

:visible is not necessary, as you can't click on hidden elements, but it's just an optimisation.


Q: Find Instance ID for Azure Servers In AWS we have instance IDs to identify machines. What's the equivalent in Azure and how do I find that?
I'd like to list the instance ID in powershell so I can put that into a script.

A: If I have not misunderstood, I suppose you want to get the InstanceId of the VM in the Azure VM Scale set.
You could try to use Get-AzureRmVmssVM to get it.
Get-AzureRmVmssVM -ResourceGroupName <ResourceGroupName> -VMScaleSetName <VMScaleSetName>

Update:
If you want to get the ResourceId of azure resource, you could use Get-AzureRmResource to do it, just specify the properties what you want.
For example:
1.Get ResourceId of the specific resource:
$resource = Get-AzureRmResource -ResourceGroupName <ResourceGroupName> -ResourceType <ResourceType> -ResourceName <ResourceName>
$resource.ResourceId

2.Get ResourceIds of all resources in the specific resource group
$resource = Get-AzureRmResource -ResourceGroupName <ResourceGroupName>
$resource.ResourceId

3.Get ResourceIds of all resources under your subscription.
$resource = Get-AzureRmResource
$resource.ResourceId

The result will like(actual result will decided by your properties):


Q: What is the best approach to upload a file using Jersey client? I want to upload a file (a zip file to be specific) to a Jersey-backed REST server.
Basically there are two approaches (I mean using Jersey Client, otherwise one can use pure servlet API or various HTTP clients) to do this:
1)
 WebResource webResource = resource();
    final File fileToUpload = new File("D:/temp.zip");

    final FormDataMultiPart multiPart = new FormDataMultiPart();
    if (fileToUpload != null) {
        multiPart.bodyPart(new FileDataBodyPart("file", fileToUpload, MediaType.valueOf("application/zip")));
    }

    final ClientResponse clientResp = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(
        ClientResponse.class, multiPart);
    System.out.println("Response: " + clientResp.getClientResponseStatus());

2)
File fileName = new File("D:/temp.zip");
        InputStream fileInStream = new FileInputStream(fileName);
        String sContentDisposition = "attachment; filename=\"" + fileName.getName() + "\"";
        ClientResponse response = resource().type(MediaType.APPLICATION_OCTET_STREAM)
            .header("Content-Disposition", sContentDisposition).post(ClientResponse.class, fileInStream);
        System.out.println("Response: " + response.getClientResponseStatus());

For sake of completeness here is the server part:
@POST
    @Path("/import")
    @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_OCTET_STREAM})
    public void uploadFile(File theFile) throws PlatformManagerException, IOException {
        ...
    }

So I am wondering what is the difference between those two clients?
Which one to use and why?
Downside (for me) of using 1) approach is that it adds dependency on jersey-multipart.jar (which additionally adds dependency on mimepull.jar) so why would I want those two jars in my classpath if pure Jersey Client approach 2) works just as fine.
And maybe one general question is whether there is a better way to implement ZIP file upload, both client and server side...

A: Approach 1 allows you to use multipart features, for example, uploading multiple files at the same time, or adding extra form to the POST.
In which case you can change the server side signature to:
@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadMultipart(FormDataMultiPart multiPart) throws IOException {
}

I also found that I had to register the MultiPartFeature in my test client...
public FileUploadUnitTest extends JerseyTest {
@Before
    public void before() {
        // to support file upload as a test client
        client().register(MultiPartFeature.class);
    }
}

And server
public class Application extends ResourceConfig {
    public Application() {
        register(MultiPartFeature.class);
    }
}

Thanks for your question, it helped me write my jersey file unit test!


Q: Can you have WPF references in an XNA project for xbox 360 I'm writing a XNA project in both Windows and Xbox 360 and the Windows side of it has a console I bring up written as a WPF application.  What I was wondering is if I leave this in my library code with the references to WPF, will the dll still work on the 360?

A: No.  You're limited to using the .NET Compact Framework on the XBOX 360.  This will not include WPF.
In fact, you're limited to the XBOX 360's implementation of the Compact Framework, which is built off the .NET 2.0 Compact Framework.  This means that any .NET 3.0/3.5 specific classes will not work.  MSDN lists the entire collection of the supported namespaces, types, and members for the XBOX 360.


Q: Is there any problem with using HTML5's "data-*" attributes for older browsers? I want to associate some custom data with some HTML nodes. I was going to use the new HTML5 style 'data-*' attributes. e.g.: <tr class="foo" data-typeid="7">…, and then I was going to select this HTML node and show/hide it etc. by reading the value with $(node).attr("data-typeid").
However this web page needs to work with older browsers aswell. I'm not using the data-* attribute as a special attribute, but I'd like to know if older browsers will ignore, wipe, or make inaccessible this attribute since it's not valid HTML4.

A: There isn't really, they're not 100% correct/valid usage in HTML4 of course....but they don't cause problems either, so they're still a great way to solve the "I need an attribute for this" problem.
If it helps, I've used these while supporting IE6 and have had zero issues thus far, and I can't recall a single SO question reporting any either.

A: Internet Explorer and Microsoft has added several custom attributes that are not valid HTML4. Browsers don't check the element attributes against a specification, you can name an attribute roryscoolinfo="hello" if you like (though you shouldn't).
The Dojo Toolkit adds its custom dojo* attributes.
It's fine to use data- today, with a HTML5 doctype.


Q: How to visualize CGAL resutls with VTK library I am new in this forum.
I have a problem in my project in c++.
I used vtk and Itk and Qt, but the mesh was not perfect so I tried to include CGAL with cmake.
I can do everything using CGAL, but I can't visualize the object created with CGAL. I have tried to export the results (coordinates, vertices, triangles...) to a generic file like xml or txt to be able to read it from vtk and render it.
Please can you help me to find a way to visualize the CGAL operations?
Thank you

A: There is a mesh to vtk converter which I used a while ago.


Q: mysql delete and then insert. Does not insert into delete line for AI table! Why? I am not sure I am correct in this.
I have insert 5 rows with values with id as primary key and autoincrement.
Then I delete row number 2-4.
when I insert on a new line with none id, the new id becomes "6". Is this normal?
How is it possible if you want the mysql to insert in the deleted row? what are the settings?

A: Yes, this is normal. If you want to insert with a specific ID number you have to specify that number on your insert statement.
The idea of auto increment is for the value to continually increase.

A: This is normal, though for some database engines you might receive 2, but usually it will be 6.  In MSSQL it is possible to specify a value for an autoinc field with particular setting. Not sure what it is in mysql.

A: That's the expected behavior. Autoincrement primary keys are designed to be unique and continually increasing - so they are not assigned again.
If you TRUNCATE a table the autoincrement value is being reset while it stays as it is if you delete all rows with an DELETE query - that's a subtle but sometimes important difference.
As webdestroya suggested, the only possibility to reuse old and deleted autoincrement values is to set them specifically on the INSERT statement.


Q: Zapier Javascript: Unexpected token ] - working in IDE, Repl.it, & Node v6.3.1 The Solution:
Thanks to @Kunal Mukherjee for the help.
const pattern = /\](,)\s{2,}?/gm
let res = inputData.rows.replace(pattern, (match, group1, offset, string) => "]")
            .split(/\s{2,}/gm)
            .map(x => JSON.parse(x));

res = res[0];   //reassign to scrape an array layer
let resultString = '';

for (let i = 0; i < res[0].length; i += 1) {
  let cv = res[0][i];
  if (cv.length === 0) resultString += `    ${res[1][i]}: ${inputData.rows[2][i]}\n`
  else resultString += `${cv}\n    ${res[1][i]}: ${res[2][i]}\n`;
}

output = {KPI: resultString};

Original Post:
The problem
In a Zapier Zap, I'm extracting data from Google Sheets and using JS to prettify it to later send in an email. I'm bumping into an error with the following message:
SyntaxError: Unexpected token ]
  stringOfArraysToArrayOfArrays (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:22:52)
  theFunction (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:29:18)
  eval (eval at <anonymous> (/var/task/index.js:52:23), <anonymous>:51:20)
  Domain.<anonymous> (/var/task/index.js:53:5)
  Domain.run (domain.js:242:14)
  module.exports.handler (/var/task/index.js:51:5)

What I've tried
I've successfully run this code from the most current version of Node back to Node v6.3.1 in different environments - local IDE, Repl.It IDE, and an online IDE set to Node v6.3.1. They all clear. I've also tried clearing the code of all ES6+ syntax (sans the example data)
Example of data
let inputData = {
  rows: `["Prioritized Tasks", "", "", "", "Operational Tasks", "", "", "", "Eight Dimensions", "", "", "", "", "", "", "", "Burn-Out", "", "", "", "", "", "", "", "", "", "Violations"],
    ["Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Emotional", "Environmental", "Financial", "Intellectual", "Occupational", "Physical", "Social", "Spiritual", "Feeling Stressed", "Feeling Depleted", "Having Trouble Concentrating", "Feeling Forgetful", "Wanting to avoid social situations", "Feeling pessimistic", "Feeling cynical", "Feeling apathetic or disinterested", "Not feeling engaged with my work", "My overall energy level", "Temperance", "Silence", "Order", "Resolution", "Frugality", "Industry", "Sincerity", "Justice", "Moderation", "Cleanliness", "Tranquility", "Chastity", "Humility"],
    ["70.33", "4", "6.67", "380", "3.67", "3.67", "66.67", "100", "8", "5.33", "5.67", "4.67", "4", "5", "4.67", "6.67", "1.33", "4", "5", "4.67", "3.33", "3.33", "1.33", "5", "6", "5.67", "0.3333333333", "0.3333333333", "0.3333333333", "0", "1", "0", "0", "0", "0", "0.3333333333", "0.3333333333", "0.3333333333", "0.3333333333"]`
}

Code producing the error
function stringOfArraysToArrayOfArrays(string) {
  let arrayPointers = [0, 1];
  let arrOfArr = [];

  for (let i = 0; i < string.length; i += 1) {
    let cv = string[i];
    if (cv === "[") arrayPointers[0] = i;
    else if (cv === "]") {
      arrayPointers[1] = i + 1;
      arrOfArr.push(string.slice(arrayPointers[0], arrayPointers[1]));
      arrOfArr[arrOfArr.length - 1] = eval(arrOfArr[arrOfArr.length - 1]);
    }
  }

  return arrOfArr;
}

inputData.rows = stringOfArraysToArrayOfArrays(inputData.rows);

let resultString = '';

for (let i = 0; i < inputData.rows[0].length; i += 1) {
  let cv = inputData.rows[0][i];
  if (cv.length === 0) resultString += '    ' + inputData.rows[1][i] + ':  ' + inputData.rows[2][i] + '\n';
  else resultString += cv + '\n    ' + inputData.rows[1][i] + ':  ' + inputData.rows[2][i] + '\n';
}

output = {KPI: resultString};

Expected results
I'm expecting for the code to run, first off, then I'm expecting output.KPI to be a prettified string.
Thanks for the time & help :)

A: This approach may be a little functional.
You need to first replace the ], in every row to an empty string I have used this Regex to split it.
After that, I split the strings by whitespaces which are more than 2 characters.
Then finally I used .map to project over the splitted items to parse it back and make an array of array.

const inputData = {
  rows: `["Prioritized Tasks", "", "", "", "Operational Tasks", "", "", "", "Eight Dimensions", "", "", "", "", "", "", "", "Burn-Out", "", "", "", "", "", "", "", "", "", "Violations"],
    ["Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Completion Rate", "Avg Completed", "Avg Total Scheduled", "Avg Time Spent", "Emotional", "Environmental", "Financial", "Intellectual", "Occupational", "Physical", "Social", "Spiritual", "Feeling Stressed", "Feeling Depleted", "Having Trouble Concentrating", "Feeling Forgetful", "Wanting to avoid social situations", "Feeling pessimistic", "Feeling cynical", "Feeling apathetic or disinterested", "Not feeling engaged with my work", "My overall energy level", "Temperance", "Silence", "Order", "Resolution", "Frugality", "Industry", "Sincerity", "Justice", "Moderation", "Cleanliness", "Tranquility", "Chastity", "Humility"],
    ["70.33", "4", "6.67", "380", "3.67", "3.67", "66.67", "100", "8", "5.33", "5.67", "4.67", "4", "5", "4.67", "6.67", "1.33", "4", "5", "4.67", "3.33", "3.33", "1.33", "5", "6", "5.67", "0.3333333333", "0.3333333333", "0.3333333333", "0", "1", "0", "0", "0", "0", "0.3333333333", "0.3333333333", "0.3333333333", "0.3333333333"]`
};

const pattern = /\](,)\s{2,}?/gm
const res = inputData.rows.replace(pattern, (match, group1, offset, string) => "]")
            .split(/\s{2,}/gm)
            .map(x => JSON.parse(x));

const output = { KPI: res };

console.log(output);


Q: HTML nested numbered list with starting index In my application I have a page which lists some data grouped by categories.
Each item on the list can have subitems.
So I'd it to look like this:

*

*List item
1.1 List item
1.2 List item

*List item
2.1 List item
2.2 List item
I can achieve this easily using this three lines of css code:
OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, ".") " "; counter-increment: item }

However on this page I have tabs for each category, which contains such nested list of items and I want to make index of first item of next tab to be x+1-th item, where x is number of last item from previous tab ( category ).
#tab 1
 1. List item

   1.1 List item

   1.2 List item
 2. List item

   2.1 List item

   2.2 List item

#tab 2
 3. List item

   3.1 List item

   3.2 List item
 4. List item

   4.1 List item

   4.2 List item

So I need functionality to provide starting index to
 tag. I found out that there is attribute start="x", however it doesn't work with these 3 lines of css code for nested lists.
Any idea how to do something like this?

A: From http://www.w3.org/TR/css3-lists/#html4:
/* The start attribute on ol elements */
ol[start] {
    counter-reset: list-item attr(start, integer, 1);
    counter-increment: list-item -1;
}

Adding this to the CSS allowed the start attribute to be recognized in my tests.
EDIT:
Instead of using the start attribute, you can use CSS classes for each new starting point.  The downside is that this will require more maintenance should you need to change anything.
CSS:
ol.start4
{
    counter-reset: item 4;
    counter-increment: item -1;
}

ol.start6
{
    counter-reset: item 6;
    counter-increment: item -1;
}

HTML:

Item 1

Item 2

Item 1

Item 2

Item 3

Item 1

Item 2

Item 4

Item 1

Item 2

Item 5

Item 6

Item 7

Item 1

Item 2

A: Just remove the css, and correctly close and reopen
 tags.
If you need to split the list in two separate tabs, you have to close the first
 inside the first tab. Then, reopen the new list with the start parameter inside the second tab:
.
Working fiddle - (I set start="5" to show it's working; for your purposes, just set it to 3 or what you need)
UPDATE:
Keep the CSS, and wrap all the tabs in the main
 and
, so the counter doesn't reset.
http://jsfiddle.net/qGCUk/227/


Q: Debian: On same NIC, bridge plus distinct IP address, with different MACs Debian host.  I have a single NIC that's supposed to sit on two networks; on 172.16.0.0/24 and 10.0.80.0/24.

*

*On the 172.16.0.0/24 network, there should be a bridge, so that local KVM hosts can attach to it; the host machine should be available at 172.16.0.99.

*On the 10.0.80.0/24 network, no need for a bridge, and machine should be available at 10.0.80.99.

A cheap D-Link switch is linked to that NIC; it may be confused by multiple IP addresses associated with the same MAC.
I've tried aliasing the NIC (e.g. adding a enp1s0:0 device), aliasing the bridge (e.g. vmbr0:0), but every permutation I've tried failed, and all I can find in search engines deals only with one aspect at a time (two IPs on same NIC, bridge aliases, MAC address mangling).
For reference, this is the setup for the bridge; how can I add a 10.0.80.99 address to the same NIC, ideally forcing a different MAC address for it?
iface enp1s0   inet manual

auto  vmbr0
iface vmbr0 inet static
        address      172.16.0.99/24
        gateway      172.16.0.1
        bridge_ports enp1s0
        bridge_stp   off
        bridge_fd    0

A: Your concern is wrong.
It is pretty typical in IP networks to have several IP addresses associated with the same MAC, though switches don't bother with this. I mean, any address from a network behind the router could be only associated with a router MAC. Also same situation happens in case of proxy ARP (which is a kind of "hacky routing"); and again, everything works, and if ever problem arise, they aren't related to switches.
A cheap D-Link switch only examines Ethernet header and trailer of packet and considers everything else as a payload. It parses a header, looks for a packet length to know how many bytes to forward, it looks for a destination MAC and forwards a packet to the associated port or floods it to all ports except ingress if there's still no associated port for that MAC; at the same time, it extracts a source MAC and associates it the with ingress port (the one packet came from). It doesn't know what IP address is and where it is in the packet, and all this process will work even if there'll be non-IP Ethernet packets. IPv6, IPX, AoE, anything you can think of — all of them would work, even at the same time within the same Ethernet segment through the same cheap D-Link switch. Also having more that one IP network in the same Ethernet segment is pretty normal, it would work perfectly and nothing will be confused. Don't worry.
Therefore, you have absolutely no need to set up another IP address with another MAC. Exact opposite is true: by not using an additional redundant MAC you only can make life easier for your switch. This way you fill its (reasonably small) MAC address table less, have less probability for collisions and so on. For a switch, less MAC addresses in the network, easier to work! Although this benefit is only theoretical, one more MAC wouldn't make any noticeable difference, but still you have think of it.
Just go with this configuration:
auto  vmbr0
iface vmbr0 inet static
        address      172.16.0.99/24
        gateway      172.16.0.1
        bridge_ports enp1s0
        bridge_stp   off
        bridge_fd    0

iface vmbr0 inet static
    address 10.0.80.99/24

Or follow the link above and try a "manual configuration" (the next header).

In case you absolutely sure you need to have a single server with two different MACs, you may use a macvlan virtual interface:
auto  vmbr0
iface vmbr0 inet static
        address      172.16.0.99/24
        gateway      172.16.0.1
        bridge_ports enp1s0
        bridge_stp   off
        bridge_fd    0

auto vmbr0mv1
iface vmbr0mv1 inet static
    pre-up ip link add vmbr0mv1 link vmbr0 type macvlan mode bridge
    address 10.0.80.99/24
    post-down ip link del vmbr0mv1

it will be created with random MAC address, but you can add another pre-up line which will set any MAC address you want.
But again, don't do this just for "not to confuse a cheap D-Link switch". With this you're confusing it more instead. This is designed for completely different things, for example, for putting a macvlan interface into another network namespace, for containers to have "their own" network interfaces with least possible overhead.


Q: Construct center of circle without using its interior I need to find the center of a circle using compass and ruler (or preferably just a straightedge) without using the interior of the circle. In other words, no line or point can be used which is inside the circle. All lines and points used in the construction must be outside the circle.
The center can be defined by points outside the circle. For example, you could identify 4 points outside the circle. The intersection of the lines going through each pair of points indicates the center.

A: Choose any two points on the circle.  Set the radius of your compasses larger than the diameter of the circle, and draw a circle centered on each point.  These circles intersect in two points that form a line through the required center.
If the compasses are too small, or collapse when you lift them off the paper, construct a hexagonal grid of points until you have two points diametrically opposite each other.

A: Choose any two points on the edge of your circle. Connect these two points with a line segment, this forms a chord in your circle.
You can show that the perpendicular bisector of any chord of a circle goes through the center of the circle.
Therefore, to find the circle center, construct two different chords of the circle, and find the perpendicular bisector of each chord. The circle center is where these bisectors meet.


Q: How to get object dictionary representation in Python I have objects message of type azure.servicebus.common.message.Message. I can print it and get representation that looks like dictinorary.
print(message)
{b'Type': b'TEST', b'Subtype': b'subtype'}
print(type(message))
<class 'azure.servicebus.common.message.Message'>
print(dict(message))
TypeError: 'Message' object is not iterable

I would like to add dictionary representation of this object to the list, not the object like below
batch.append(message)

How to convert representation of the object to dictionary ?


Q: ASP.net IdentiyServer 3 AuthorizationCodeReceived not firing when a user authenticates with Identity Server 3, AuthorizationCodeReceived never fires.  RedirectToIdentityProvider  does get fired but thats it.  I am trying to call a function that will get the users email or windows ID, and then add a custom claim.  But without the AuthorizationCodeReceived method being called, I am not sure how to do that.  Anyone have experience with this?  Not sure if it matters, but my code is ASP.net windows form (not MVC)
Here is my code:
    Public Sub ConfigureAuth(app As IAppBuilder)
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = New Dictionary(Of String, String)

        app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
            .AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
        })

        Dim OpenIdAuthOption = New OpenIdConnectAuthenticationOptions() With {
           .Authority = "https://myidentityserver.azurewebsites.net/core/",
           .ClientId = "adfafasfasdfa",
           .RedirectUri = "https://localhost:44321/default.aspx/",
           .ResponseType = ("access_token"),
           .RequireHttpsMetadata = False,
           .SignInAsAuthenticationType = "Cookies",
           .Notifications = New OpenIdConnectAuthenticationNotifications() With {

                .AuthorizationCodeReceived = Function(ctx)
                                                 Dim claimPrincipal As ClaimsPrincipal = ctx.AuthenticationTicket.Identity.Claims
                                                 TransformClaims(claimPrincipal)
                                                 Return Task.FromResult(0)
                                             End Function,
                .RedirectToIdentityProvider = Function(context)
                                                  RedirectLogin(context)
                                                  Return Task.FromResult(0)
                                              End Function
                }
        }
        app.UseOpenIdConnectAuthentication(OpenIdAuthOption)
    End Sub


Q: How do you completely reset monitor configuration (e.g. what used to be dpkg-reconfigure xserver-xorg)? Using unity 11.04. I have a secondary monitor (actually two, one at home, one at work). The home twin monitor set up works perfect (Viewsonic monitor). At work, I get very buggy behaviour, such as full screen applications 'ghosting' when maximized, and other strange effects. I would like to try and completely reset the monitor configurations (not unity or compiz), before doing anything else. In 10.10 this would be accomplished:
dpkg-reconfigure xserver-xorg

A: If you think it's some user preferences settings, then you can create a new user "temp", login as a "temp" and see if it's ok.
You can also try xrandr --auto.


Q: Why is the Binding Format event called twice? I am playing around with data binding and noticed that the Binding Format is called twice upon loading the form in the code below.  I thought it would only happen once when the test class TextBoxText property is fist bound to textbox1.  Is this normal?  If not, then what can I do to prevent it? Note, when I press button1 and it changes the TextBoxText property of the test class, the format event fires once as expected.
public partial class Form1 : Form
{
    Test _test = new Test();
    public Form1()
    {
        InitializeComponent();
        Binding binding = new Binding("Text", _test, "TextBoxText");
        binding.Format += new ConvertEventHandler(Binding_Format);
        this.textBox1.DataBindings.Add(binding);
    }

    private void Binding_Format(object sender, ConvertEventArgs e)
    {
        Debug.WriteLine("Format");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _test.TextBoxText = "test1";
    }
}

class Test : INotifyPropertyChanged
{
    private string _text;

    public string TextBoxText
    {
        get { return _text; }
        set
        {
            _text = value;
            OnPropertyChanged(new PropertyChangedEventArgs("TextBoxText"));
        }
    }

    private void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged(this, e);
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

A: The simple answer:  "Because that is the way Microsoft implemented it".
The goal is to just respond to the event... whenever it happens... however often it occurs.  We can't make any assumptions.  There are cases where you might get called six times on the same event.
We just have to roll with it and continue to be awesome.


Q: delphi7 converted to delphi tokyo app taskbar icon does not like to move to second screen app my delphi7 apps always show in the primary screen monitor taskbar , Now in delphi 10.2 If I move the app to the second screen the taskbar icon move to that seconds screen .
So now my issue is with the old delphi7 apps which I open and compile with delphi 10.2, they still have the old behavior . So how can I solve that??

A: In Delphi 7, all TForm windows are owned by the hidden TApplication window at runtime, which is the window that actually manages the app's Taskbar button. That window remains on the primary monitor when you move your Forms to other monitors. That is why you don't see the app's Taskbar button move to other monitors.
In Delphi 2007 and later, TForm windows are no longer owned by the hidden TApplication window by default on Vista+. This behavior is controlled by the TApplication.MainFormOnTaskBar property, which did not exist yet in Delphi 7.  Being owned by the hidden TApplication window causes all kinds of problems in Vista+ for the Taskbar, the Task switcher, Aero, etc, so ShowMainFormOnTaskBar should always be set to true.
When you upgrade your Delphi 7 project to Delphi 10.2, be sure to set Application.MainFormOnTaskBar := true; in the app's main startup code so the app interacts with Vista+ properly.  MainFormOnTaskBar is false by default when migrating a pre-D2007 project.


Q: jQuery UI - make div not resizable I have a div that is made resizable using jQuery UI. How can I dynamically make it not resizable anymore?
I tried calling resizable({ disabled: true }) but the handle still showed.

A: Use this code:    .resizable( "destroy" )

A: Try .resizable("option", "disabled", true);
http://jqueryui.com/demos/resizable/#option-disabled
Your solution is not working because, as per the documentation you need use the setter that I mentioned, if you want to disable it after initialization (you code will only work if its an initialization call)

A: Oops...
I was disabling "resizable" before I enabled it...


Q: Consuming an XML API in CakePHP I have a web application that involves calling a number of different XML/API webservices.  The application has already been implemented in old school procedural code (by my predecessor) and I have managed to convince the IT director that it needs to be coded into a more robust framework.  I've settled on CakePHP because it's the framework I am most familiar with.
I have Googled extensively for advice on how to consume an XML/API.  One blog post did it in the controller, but I feel it belongs more in the model.  Perhaps I could create a behaviour that handles the transfers and then code methods in the Model that will strip out the information I need from the returned XML?
Does anybody have some advice on this or a pointer?

A: I imagine you are using it to get database like data or config data, this is normally done in the model, though there is not restriction in where you do it. You could do the extracting and preparing of the data in the model and the logic in the controller. Something like loading the config parameters and putting them in variables and then using this variables in the controller.
Also you may use cakephp XML library to do all this. Since is a library you MAY do it either in controller or model.
Hope this helps you :)


Q: Convert Apple Emoji (String) to UIImage I need all Apple Emojis. I can get all the emojis and put them into a String by copying them from the site getemoji but in my app i need the emojis in the right order as images.
Is there a nice way to convert the emojis I copy into a String to a UIImage?
Or a better solution to get all the Apple emojis in the right order?

A: Updated @Luca Angeletti answer for Swift 3.0.1
extension String {

    func image() -> UIImage? {
        let size = CGSize(width: 30, height: 35)
        UIGraphicsBeginImageContextWithOptions(size, false, 0);
        UIColor.white.set()
        let rect = CGRect(origin: CGPoint(), size: size)
        UIRectFill(CGRect(origin: CGPoint(), size: size))
        (self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

}

A: Swift 4.2
I really liked @Luca Angeletti solution. I hade the same question as @jonauz about transparent background. So with this small modification you get the same thing but with clear background color.
I didn't have the rep to answer in a comment.
import UIKit

extension String {
    func emojiToImage() -> UIImage? {
        let size = CGSize(width: 30, height: 35)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.clear.set()
        let rect = CGRect(origin: CGPoint(), size: size)
        UIRectFill(CGRect(origin: CGPoint(), size: size))
        (self as NSString).draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 30)])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

A: Swift 5: ( with optional fontSize, imageSize and bgColor)
use it like this:
let image      = "".image()
let imageLarge = "".image(fontSize:100)
let imageBlack = "".image(fontSize:100, bgColor:.black)
let imageLong  = "".image(fontSize:100, imageSize:CGSize(width:500,height:100))

import UIKit

extension String
{
    func image(fontSize:CGFloat = 40, bgColor:UIColor = UIColor.clear, imageSize:CGSize? = nil) -> UIImage?
    {
        let font = UIFont.systemFont(ofSize: fontSize)
        let attributes = [NSAttributedString.Key.font: font]
        let imageSize = imageSize ?? self.size(withAttributes: attributes)

        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
        bgColor.set()
        let rect = CGRect(origin: .zero, size: imageSize)
        UIRectFill(rect)
        self.draw(in: rect, withAttributes: [.font: font])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

A: Updated version of @Luca Angeletti's answer using UIGraphicsImageRenderer:
extension String {
    func image() -> UIImage? {
        let size = CGSize(width: 100, height: 100)
        let rect = CGRect(origin: CGPoint(), size: size)
        return UIGraphicsImageRenderer(size: size).image { (context) in
            (self as NSString).draw(in: rect, withAttributes: [.font : UIFont.systemFont(ofSize: 100)])
        }
    }
}

A: Here's an updated answer with the following changes:

*

*Centered: Used draw(at:withAttributes:) instead of draw(in:withAttributes:) for centering the text within the resulting UIImage

*Correct Size: Used size(withAttributes:) for having a resulting UIImage of size that correlates to the actual size of the font.

*Comments: Added comments for better understanding

Swift 5
import UIKit
extension String {
    func textToImage() -> UIImage? {
        let nsString = (self as NSString)
        let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here
        let stringAttributes = [NSAttributedString.Key.font: font]
        let imageSize = nsString.size(withAttributes: stringAttributes)

        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) //  begin image context
        UIColor.clear.set() // clear background
        UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size
        nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect
        let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context
        UIGraphicsEndImageContext() //  end image context

        return image ?? UIImage()
    }
}

Swift 3.2
import UIKit
extension String {
    func textToImage() -> UIImage? {
        let nsString = (self as NSString)
        let font = UIFont.systemFont(ofSize: 1024) // you can change your font size here
        let stringAttributes = [NSFontAttributeName: font]
        let imageSize = nsString.size(attributes: stringAttributes)

        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) //  begin image context
        UIColor.clear.set() // clear background
        UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) // set rect size
        nsString.draw(at: CGPoint.zero, withAttributes: stringAttributes) // draw text within rect
        let image = UIGraphicsGetImageFromCurrentImageContext() // create image from context
        UIGraphicsEndImageContext() //  end image context

        return image ?? UIImage()
    }
}

A: Same thing for Swift 4:
extension String {
    func emojiToImage() -> UIImage? {
        let size = CGSize(width: 30, height: 35)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.white.set()
        let rect = CGRect(origin: CGPoint(), size: size)
        UIRectFill(rect)
        (self as NSString).draw(in: rect, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 30)])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

A: Updated for Swift 4.1
Add this extension to your project
import UIKit

extension String {
    func image() -> UIImage? {
        let size = CGSize(width: 40, height: 40)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.white.set()
        let rect = CGRect(origin: .zero, size: size)
        UIRectFill(CGRect(origin: .zero, size: size))
        (self as AnyObject).draw(in: rect, withAttributes: [.font: UIFont.systemFont(ofSize: 40)])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

The code above draws the current String to an Image Context with a white background color and finally transform it into a UIImage.
Now you can write

Example
Given a list of ranges indicating the unicode values of the emoji symbols
let ranges = [0x1F601...0x1F64F, 0x2702...0x27B0]

you can transform it into a list of images
let images = ranges
    .flatMap { $0 }
    .compactMap { Unicode.Scalar($0) }
    .map(Character.init)
    .compactMap { String($0).image() }

Result:

I cannot guarantee the list of ranges is complete, you'll need to search for it by yourself

A: This variation is based on @Luca's accepted answer, but allows you to optionally customize the point size of the font, should result in a centered image, and doesn't make the background color white.
extension String {
    func image(pointSize: CGFloat = UIFont.systemFontSize) -> UIImage? {
        let nsString = self as NSString
        let font = UIFont.systemFont(ofSize: pointSize)

        let size = nsString.size(withAttributes: [.font: font])
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        let rect = CGRect(origin: .zero, size: size)
        nsString.draw(in: rect, withAttributes: [.font: font])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}


Q: Equivalence of two statements $ (\forall y0)(\exists m\in A:x-\epsilonLet $A\subseteq \mathbb{R}$ and $x\in \mathbb{R}$. How would you explain that the following expressions are equivalent?
$$
(\forall y<x)(\exists m\in A:y<m)
$$
and
$$
(\forall \epsilon>0)(\exists m\in A:x-\epsilon<m)
$$
What I thought so far: In order to get from the below one to the upper one, I assume the below condition holds, and let $y<x$ be given, and put $\epsilon = x-y$. Since $\epsilon>0$, and $x-\epsilon = y$, the upper condition is reached. To go from the upper one to the below one, I assume the upper condition holds, and let $\epsilon>0$ be given, and put $y=x-\epsilon$, then $y<x$, so the below condition is reached.
Is this how it should be proved? If not, how then?


Q: How do you choose where to put information based on an index into a pandas DataFrame? In MATLAB, the loop I create looks like:
header_names = {'InvoiceNo','Customer',...}

for i = 1:length(x)
    entry(index+i,:) = [InvoiceNo, Customer,...]
end
% Create a table from the data.
fin_table = cell2table(entry,'VariableNames',header_names);

% Write to the finish file.
writetable(fin_table,finish);

With the table values and headers, I will end up getting something that looks like:

InvoiceNo
Customer

1000
Jimmy

1001
Bob

1002
Max

1003
April

1004
Tom

...
...

...
...

...
...

...
...

I would like to know how to accomplish this in Python. My main question is how do I create the entry? How do I put a table in a for loop and ask it to print information on the next row for each iteration?
In Python, I currently have the following:
        for i in range(len(item)):
            entry = pd.DataFrame(
                [InvoiceNo, Customer, invoice, due, terms, Location, memo, item[i], item[i], quan[i], rate[i], taxable,
                 tax_rate, invoice, email, Class],
                columns=['InvoiceNo', 'Customer', 'InvoiceDate', 'DueDate', 'Terms', 'Location', 'Memo', 'Item',
                         'ItemDescription', 'ItemQuantity', 'ItemRate', 'ItemAmount', 'Taxable', 'TaxRate',
                         'ServiceDate', 'Email', 'Class'])
        # Increment the index for entry values to be correct.
        index += len(item)

Any help would be awesome!

A: Although I do not get your question completely, I will try to give you some tools that might be useful:
To get input value you can use (and put this inside of a 'for' loop depending on the number of rows you want to create)
new_InvoiceNo= input("Enter InvoiceNo:\n")
new_Customer= input("Enter Customer:\n")
new_invoice = input("Enter invoice:\n")
...

then you can either append these values as list into the main DF :
to_append = [new_InvoiceNo, new_Customer, new_invoice, ...]
new_values = pd.Series(to_append, index = df.columns)
df = df.append(new_values , ignore_index=True)

or , you can use '.loc' method:
to_append = [new_InvoiceNo, new_Customer, new_invoice, ...]
df_length = len(df)
df.loc[df_length] = to_append

Try to implement this in your code and report it back here.


Q: MultiThreading with searchbox I have a listbox with list of persons (first name ,last name , addresses...) and a searchbox (TextBox with TextChaned event
the thing is i'm running a search throw database and it take a long time and the UI freeze for seconds ...so,how can I make it responsive ?

A: Assuming that you are working with DataTables, here is what you can do:
private async void btnSearch_Click(object sender, EventArgs e) // async is important
{
    DataTable dt = await Task.Run(() => // await is important (avoids the UI freeze)
    {
        return GetData(); // Fetch your data from DB
    });
    // Fill your listbox with the data in dt
}


Q: How to enable and disable button accordingly if i select the dropdown options in Angular js If I click on the dropdown which is marked inside the blue border, I want the buttons below to be enabled/disabled according to the condition.
If I select first dropdown value. I want the 3rd and 4th button to disabled and 1st and 2nd should be active.
I was looking some angular js code (ng-disabled or ng-class)

A: The selector must be binded to some ng-model, which keep track of the current value. Supposing you have something like this:
<select ng-model="FooBar">
    Some options... (with their respectives value)
</select>

you can enable or desable multiple buttons using this var "FooBar":
<input ng-disabled="FooBar !== desiredEnableValue">


Q: Is it worth mitigating against the effects of garbage collection? I have an application where the memory profile looks something like this:

(source: kupio.com)
The slow upwards crawl of memory usage is caused by the allocation of lots and lots of small, simple, transient objects. In low-memory situations (This is a mobile app) the GC overhead is noticeable when compared to less restrictive memory amounts.
Since we know, due to the nature of the app, that these spikes will just keep on coming, I was considering some sort of pool of multitudinous transient objects (Awesome name). These objects would live for the lifetime of the app and be re-used wherever possible (Where the lifetime of the object is short and highly predictable).
Hopefully this would mitigate against the effects of GC by reducing the number of objects collected and improve performance.
Obviously this would also have its own performance limits since "allocation" would be more expensive and there would be an overhead in maintaining the cache itself.
Since this would be a rather large and intrusive change into a large amount of code, I was wondering if anyone had tried something similar and if it was a benefit, or if there were any other known ways of mitigating against GC in this sort of situation. Ideas for efficient ways to manage a cache of re-usable objects are also welcome.

A: This is similar to the flyweight pattern detailed in the GoF patterns book (see edit below). Object pools have gone out of favour in a "normal" virtual machine due to the advances made in reducing the object creation, synchronization and GC overhead. However, these have certainly been around for a long time and it's certainly fine to try them to see if they help!
Certainly Object Pools are still in use for objects which have a very expensive creation overhead  when compared with the pooling overheads mentioned above (database connections being one obvious example).
Only a test will tell you whether the pooling approach works for you on your target platforms!
EDIT - I took the OP "re-used wherever possible" to mean that the objects were immutable. Of course this might not be the case and the flyweight pattern is really about immutable objects being shared (Enums being one example of a flyweight). A mutable (read: unshareable) object is not a candidate for the flyweight pattern but is (of course) for an object pool.

A: Normally, I'd say this was a job for tuning the GC parameters of the VM, the reduce the spiky-ness, but for mobile apps that isn't really an option. So if the JVms you are using cannot have their GC behavioure modified, then old-fashioned object pooling may be the best solution.
The Apache Commons Pool library is good for that, although if this is a mobile app, then you may not want the library dependency overhead.

A: Actually, that graph looks pretty healthy to me.  The GC is reclaiming lots of objects and the memory is then returning to the same base level.  Empirically, this means that the GC is working efficiently.
The problem with object pooling is that it makes your app slower, more complicated and potentially more buggy.  What is more, it can actually make each GC run take longer.  (All of the "idle" objects in the pool are non-garbage and need to be marked, etc by the GC.)

A: Does J2ME have a generational garbage collector? If so it does many small, fast, collections and thus the pauses are reduced. You could try reducing the eden memory space (the small memory space) to increase the frequency and reduce the latency for collections and thus reduce the pauses.
Although, come to think of it, my guess is that you can't adjust gc behaviour because everything probably runs in the same VM (just a guess here).

A: You could check out this link describing enhancements to the Concurrent Mark Sweep collector, although I'm not sure it's available for J2ME.  In particular note:
"The concurrent mark sweep collector, also known as the concurrent collector or CMS, is targeted at applications that are sensitive to garbage collection pauses."
... "In JDK 6, the CMS collector can optionally perform these collections concurrently, to avoid a lengthy pause in response to a System.gc() or Runtime.getRuntime().gc() call. To enable this feature, add the option"
-XX:+ExplicitGCInvokesConcurrent

A: Check out this link. In particular:

Just to list a few of the problems
  object pools create: first, an unused
  object takes up memory space for no
  reason; the GC must process the unused
  objects as well, detaining it on
  useless objects for no reason; and in
  order to fetch an object from the
  object pool a synchronization is
  usually required which is much slower
  than the asynchronous allocation
  available natively.

A: You're talking about a pool of reusable object instances.
class MyObjectPool {
    List<MyObject> free= new LinkedList<MyObject>();
    List<MyObject> inuse= new LinkedList<MyObject>();
    public MyObjectPool(int poolsize) {
        for( int i= 0; i != poolsize; ++i ) {
           MyObject obj= new MyObject();
           free.add( obj );
        }
    }
    pubic makeNewObject( ) {
        if( free.size() == 0 ) {
            MyObject obj= new MyObject();
            free.add( obj );
        }
        MyObject next= free.remove(0);
        inuse.add( next );
        return next;
   }
   public freeObject( MyObject obj ) {
       inuse.remove( obj );
       free.add( obj );
   }
}
        return in

A: Given that this answer suggests that there is not much scope for tweaking garbage collection itself in J2ME then if GC is an issue the only other option is to look at how you can change your application to improve performance/memory usage. Maybe some of the suggestions in the answer referenced would apply to your application.
As oxbow_lakes says, what you suggest is a standard design pattern. However, as with any optimisation the only way to really know how much it will improve your particular application is by implementing and profiling.


Q: HTML: Accept-Charset attribute and Accept attribute I'm using angularJS, and when i try to set there Accept-Charset attribute i get: Refused to set unsafe header "Accept-Charset", but when i set manually something like:
    headers: {
      'Content-Type': 'text/csv',
      'Accept': 'application/json, text/plain; charset=WIN-1251'
    }

all is ok
so... question)
Is there any difference between this two attributes?
or server will recognize my accept with charset, and i do not need Accept-Charset anymore?


Q: Does Windows still keeps old versions of files after each update Does Windows still keeps old versions of files after each update or remove all old redundant files?

A: When Windows Update replaces a file, the previous version is not saved in the
Recycle Bin, so no redundant files.
When one installs a new Windows version, or if you do an
In-place Upgrade,
the old Windows files go into the folder Windows.old.
However, most of them are deleted after 28 days.


Q: Menu flow is wrong in android mobile phones I have one word-press site ,the menu flow of the site is working fine in desktop and i-phone , but flow is wrong in all android phones .
the problem is :
i have a main menu "courses" and sub menu under courses is "school programs".
when ever i click "courses" then the page "school programs" will load aromatically instead of "courses" page .
and i am clear that this problem is with android mobiles only .
code is :

  Courses

School Programs

Women’s self defence

Security Programs

Business Workshops

Krav Maga Instructor Course

site URL : http://www.kravmagaoz.com.au/
any help .

A: Actually there is some overlapping of your div of
 tag so you need to check the css and add updated code in @media query.
Thanks


Q: Javacard form factors I'm totally new in the Smartcard world, and would really appreciate some clarifications regarding Javacard form factors and interfaces, as I've found it very hard to research the different options.
Ideally I would like to find a contactless Javacard 2 (or 3) chip + antenna that is not encased in plastic, because I want to put it inside another product. I want it to be as small as possible, and therefore just contactless, not dual interface.
However all the Javacards I've found that's sold by manufacturers, seem to only have the "business card" form factor. Does anyone know if this is available at all or if not, or at least theoretically possible to produce? Does the Javacard version make any difference in feasibility of this form factor (My applet only requires Javacard 2+)?
If anyone knows what a reasonable bulk price per chip with such a form factor would be, that would also be very interesting to hear.
Thank you!

A: The reason that you find these chips only in smart cards is that that is the best method of developing on them without hassle. There are also form factors for use in e.g. key fobs, which is probably what you're after. That means smaller antenna space and less chance of a good response. These chips and antenna's are tricky to get right so that all distances and orientations work well.
Paper smart cards are commonly not smart cards but throw away memory cards like MiFare or MiFare ultra-light. Usually smart cards come in credit card form, like -uh- those in credit cards. And then they are in plastic (PVC) or polycarbonate for the higher end cards. Demo cards are usually plastic though. Manufacturers aren't shy of not putting any chips or antenna's in there at all when it comes to demo cards (they might be showing off their printing capabilities instead).
The classic Java cards can be in any form factor. However, the more memory the larger the die may be. That can be an issue with some packaging, the small container that the IC is put in and to which the antenna's are connected. Although Java Card 3 is somewhat of a jump in functionality, most cards capable of version 2 would also be OK to run version 3 of Java Card.
The failed web-based "connected" Java Card requires a lot of memory and if you can find it, it will probably be limited to specific form factors. Java Card 3.1 seems to be another jump in functionality for the common "classic" platform and I would expect for high end smart cards to lead the way.

Generally we don't talk prices here. If you are interested in bulk pricing for specific form factors then you need to contact the resellers, not us. But I would first try and read into it. There are some great general purpose books out there on smart cards. That way you'd at least know a bit what you're talking about when contacting such vendor, and in that case you're more likely to be taken seriously.


Q: How to nest transactions in EF Core 6? I am already using transactions inside my repository functions in some cases because I sometimes need to insert data into two tables at once and I want the whole operation to fail if one of the inserts fails.
Now I ran into a situation where I had to wrap calls to multiple repositories / functions in another transaction, but when one of those functions already uses a transaction internally I will get the error The connection is already in a transaction and cannot participate in another transaction.
I do not want to remove the transaction from the repository function because this would mean that I have to know for which repository functions a transaction is required which I would then have to implement in the service layer. On the other hand, it seems like I cannot use repository functions in a transaction when they already use a transaction internally. Here is an example for where I am facing this problem:
// Reverse engineered classes
public partial class TblProject
{
    public TblProject()
    {
        TblProjectStepSequences = new HashSet<TblProjectStepSequence>();
    }

    public int ProjectId { get; set; }

    public virtual ICollection<TblProjectStepSequence> TblProjectStepSequences { get; set; }
}

public partial class TblProjectTranslation
{
    public int ProjectId { get; set; }
    public string Language { get; set; }
    public string ProjectName { get; set; }

    public virtual TblProject Project { get; set; }
}

public partial class TblProjectStepSequence
{
    public int SequenceId { get; set; }
    public int ProjectId { get; set; }
    public int StepId { get; set; }
    public int SequencePosition { get; set; }

    public virtual TblStep Step { get; set; }
    public virtual TblProject Project { get; set; }
}

// Creating a project in the ProjectRepository
public async Task<int> CreateProjectAsync(TblProject project, ...)
{
    using (var transaction = this.Context.Database.BeginTransaction())
    {
        await this.Context.TblProjects.AddAsync(project);
        await this.Context.SaveChangesAsync();
        // Insert translations... (project Id is required for this)
        await this.Context.SaveChangesAsync();
        transaction.Commit();

        return entity.ProjectId;
    }
}

// Creating the steps for a project in the StepRepository
public async Task<IEnumerable<int>> CreateProjectStepsAsync(int projectId, IEnumerable<TblProjectStepSequence> steps)
{
    await this.Context.TblProjectStepSequences.AddRangeAsync(steps);
    await this.Context.SaveChangesAsync();

    return steps.Select(step =>
    {
        return step.SequenceId;
    }
    );
}

// Creating a project with its steps in the service layer
public async Task<int> CreateProjectWithStepsAsync(TblProject project, IEnumerable<TblProjectStepSequence> steps)
{
    // This is basically a wrapper around Database.BeginTransaction() and IDbContextTransaction
    using (Transaction transaction = await transactionService.BeginTransactionAsync())
    {
        int projectId = await projectRepository.CreateProjectAsync(project);
        await stepRepository.CreateProjectStepsAsync(projectId, steps);

        return projectId;
    }
}

Is there a way how I can nest multiple transactions inside each other without already knowing in the inner transactions that there could be an outer transaction?
I know that it might not be possible to actually nest those transactions from a technical perspective but I still need a solution which either uses the internal transaction of the repository or the outer one (if one exists) so there is no way how I could accidentally forget to use a transaction for repository functions which require one.

A: You could check the CurrentTransaction property and do something like this:
var transaction = Database.CurrentTransaction ?? Database.BeginTransaction()

If there is already a transaction use that, otherwise start a new one...
Edit: Removed the Using block, see comments. More logic is needed for Committing/Rollback the transcaction though...

A: I am answering the question you asked "How to nest transactions in EF Core 6?"
Please note that this is just a direct answer, but not an evaluation what is best practice and what not. There was a lot of discussion going around best practices, which is valid to question what fits best for your use case but not an answer to the question (keep in mind that Stack overflow is just a Q+A site where people want to have direct answers).
Having said that, let's continue with the topic:
Try to use this helper function for creating a new transaction:
public CommittableTransaction CreateTransaction()
    => new System.Transactions.CommittableTransaction(new TransactionOptions()
    {
        IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
    });

Using the Northwind database as example database, you can use it like:
public async Task<int?> CreateCategoryAsync(Categories category)
{
    if (category?.CategoryName == null) return null;
    using(var trans = CreateTransaction())
    {
        await this.Context.Categories.AddAsync(category);
        await this.Context.SaveChangesAsync();

        trans.Commit();

        return category?.CategoryID;
    }
}

And then you can call it from another function like:
/// <summary>Create or use existing category with associated products</summary>
/// <returns>Returns null if transaction was rolled back, else CategoryID</returns>
public async Task<int?> CreateProjectWithStepsAsync(Categories category)
{
    using var trans = CreateTransaction();

    int? catId = GetCategoryId(category.CategoryName)
                ?? await CreateCategoryAsync(category);

    if (!catId.HasValue || string.IsNullOrWhiteSpace(category.CategoryName))
    {
        trans.Rollback(); return null;
    }

    var product1 = new Products()
    {
        ProductName = "Product A1", CategoryID = catId
    };
    await this.Context.Products.AddAsync(product1);

    var product2 = new Products()
    {
        ProductName = "Product A2", CategoryID = catId
    };
    await this.Context.Products.AddAsync(product2);

    await this.Context.SaveChangesAsync();

    trans.Commit();

    return catId;
}

To run this with LinqPad you need an entry point (and of course, add the NUGET package EntityFramework 6.x via F4, then create an EntityFramework Core connection):
// Main method required for LinqPad
UserQuery Context;

async Task Main()
{
    Context = this;
    var category = new Categories()
    {
        CategoryName = "Category A1"
        // CategoryName = ""
    };
    var catId = await CreateProjectWithStepsAsync(category);
    Console.WriteLine((catId == null)
           ? "Transaction was aborted."
           : "Transaction successful.");
}

This is just a simple example - it does not check if there are any product(s) with the same name existing, it will just create a new one. You can implement that easily, I have shown it in the function CreateProjectWithStepsAsync for the categories:
int? catId = GetCategoryId(category.CategoryName)
            ?? await CreateCategoryAsync(category);

First it queries the categories by name (via GetCategoryId(...)), and if the result is null it will create a new category (via CreateCategoryAsync(...)).
Also, you need to consider the isolation level: Check out System.Transactions.IsolationLevel to see if the one used here (ReadCommitted) is the right one for you (it is the default setting).
What it does is creating a transaction explicitly, and notice that here we have a transaction within a transaction.

Note:

*

*I have used both ways of using - the old one and the new one. Pick the one you like more.

A: Just don't call SaveChanges multiple times.
The problem is caused by calling SaveChanges multiple times to commit changes made to the DbContext instead of calling it just once at the end. It's simply not needed. A DbContext is a multi-entity Unit-of-Work. It doesn't even keep an open connection to the database. This allows 100-1000 times better throughput for the entire application by eliminating cross-connection blocking.
A DbContext tracks all modifications made to the objects it tracks and persists/commits them when SaveChanges is called using an internal transaction. To discard the changes, simply dispose the DbContext. That's why all examples show using a DbContext in a using block - that's actually the scope of the Unit-of-Work "transaction".
There's no need to "save" parent objects first. EF Core will take care of this itself inside SaveChanges.
Using the Blog/Posts example in the EF Core documentation tutorial :

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public string DbPath { get; }

    // The following configures EF to create a Sqlite database file in the
    // special "local" folder for your platform.
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer($"Data Source=.;Initial Catalog=tests;Trusted_Connection=True; Trust Server Certificate=Yes");
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; } = new();
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

The following Program.cs will add a Blog with 5 posts but only call SaveChanges once at the end :

using (var db = new BloggingContext())
{
    Blog blog = new Blog { Url = "http://blogs.msdn.com/adonet" };
    IEnumerable<Post> posts = Enumerable.Range(0, 5)
                                       .Select(i => new Post {
                                            Title = $"Hello World {i}",
                                            Content = "I wrote an app using EF Core!"
                                         });
    blog.Posts.AddRange(posts);

    db.Blogs.Add(blog);

    await db.SaveChangesAsync();
}

The code never specifies or retrieves the IDs. Add is an in-memory operation so there's no reason to use AddAsync. Add starts tracking both the blog and the related Posts in the Inserted state.
The contents of the tables after this are :
select * from blogs

select * from posts;
-----------------------

BlogId  Url
1   http://blogs.msdn.com/adonet

PostId  Title   Content BlogId
1   Hello World 0   I wrote an app using EF Core!   1
2   Hello World 1   I wrote an app using EF Core!   1
3   Hello World 2   I wrote an app using EF Core!   1
4   Hello World 3   I wrote an app using EF Core!   1
5   Hello World 4   I wrote an app using EF Core!   1

Executing the code twice will add another blog with another 5 posts.
PostId  Title   Content BlogId
1   Hello World 0   I wrote an app using EF Core!   1
2   Hello World 1   I wrote an app using EF Core!   1
3   Hello World 2   I wrote an app using EF Core!   1
4   Hello World 3   I wrote an app using EF Core!   1
5   Hello World 4   I wrote an app using EF Core!   1
6   Hello World 0   I wrote an app using EF Core!   2
7   Hello World 1   I wrote an app using EF Core!   2
8   Hello World 2   I wrote an app using EF Core!   2
9   Hello World 3   I wrote an app using EF Core!   2
10  Hello World 4   I wrote an app using EF Core!   2

Using SQL Server XEvents Profiler shows that these SQL calls are made:
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Blogs] ([Url])
VALUES (@p0);
SELECT [BlogId]
FROM [Blogs]
WHERE @@ROWCOUNT = 1 AND [BlogId] = scope_identity();
',N'@p0 nvarchar(4000)',@p0=N'http://blogs.msdn.com/adonet'

exec sp_executesql N'SET NOCOUNT ON;
DECLARE @inserted0 TABLE ([PostId] int, [_Position] [int]);
MERGE [Posts] USING (
VALUES (@p1, @p2, @p3, 0),
(@p4, @p5, @p6, 1),
(@p7, @p8, @p9, 2),
(@p10, @p11, @p12, 3),
(@p13, @p14, @p15, 4)) AS i ([BlogId], [Content], [Title], _Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([BlogId], [Content], [Title])
VALUES (i.[BlogId], i.[Content], i.[Title])
OUTPUT INSERTED.[PostId], i._Position
INTO @inserted0;
SELECT [i].[PostId] FROM @inserted0 i
ORDER BY [i].[_Position];
',N'@p1 int,@p2 nvarchar(4000),@p3 nvarchar(4000),@p4 int,@p5 nvarchar(4000),@p6 nvarchar(4000),@p7 int,@p8 nvarchar(4000),@p9 nvarchar(4000),@p10 int,@p11 nvarchar(4000),@p12 nvarchar(4000),@p13 int,@p14 nvarchar(4000),@p15 nvarchar(4000)',@p1=3,@p2=N'I wrote an app using EF Core!',@p3=N'Hello World 0',@p4=3,@p5=N'I wrote an app using EF Core!',@p6=N'Hello World 1',@p7=3,@p8=N'I wrote an app using EF Core!',@p9=N'Hello World 2',@p10=3,@p11=N'I wrote an app using EF Core!',@p12=N'Hello World 3',@p13=3,@p14=N'I wrote an app using EF Core!',@p15=N'Hello World 4'

The unusual SELECT and MERGE are used to ensure IDENTITY values are returned in the order the objects were inserted, so EF Core can assign them to the object properties. After calling SaveChanges all Blog and Post objects will have the correct database-generated IDs


Q: How to convert byte[] to float[] and back in Java? I'm reading data from .wav files through InputStream, and read() returns bytes. A sound processing library I use, only accepts float[] to process. After it it done it gives me a float[] back. Now I need to write to the Android's AudioTrack in byte format again.
How do I convert these bytes to floats[], and back to byte[]? I've searched a bit, but everything seemed to be kinda a different situation to mine, and all problems seemed to be solved in different ways... so i'm kinda lost right now.
If something like this conversion is already offered in some kind of library, i'd be glad to hear about that too!
Thanks!

A: You can use of java.nio.ByteBuffer. It has a lot of useful methods for pulling different types out of a byte array and should also handle most of your issues.
        byte[] data = new byte[36];
        ByteBuffer buffer = ByteBuffer.wrap(data);
        float second = buffer.getFloat(); //This helps to
        float x = 0;
        buffer.putFloat(x);

A: You just need to copy the bits.
Try using BlockCopy.
 float[] fArray = new float[] { 1.0f, ..... };
 byte[] bArray= new byte[fArray.Length*4];
 Buffer.BlockCopy(fArray,0,bArray,0,bArray.Length);

The *4 is since each float is 4 bytes.


Q: ASP.NET MVC3 - Redirect to a different directory We have a bunch of published URLs that reference a directory called "events"
http://www.mysite.com/anniversary/events/
http://www.mysite.com/anniversary/events/[...]

They now want to rename "events" to "events1" so I need to redirect all URLs that look like this:
http://www.mysite.com/anniversary/events/[...]

To:
http://www.mysite.com/anniversary/events1
http://www.mysite.com/anniversary/events1/[...]

I've done these in Apache - Not sure if I am on the right track?
<rule name="events1" stopProcessing="true">
        <match url="^/anniversary/events(/.+)?$" />
        <action type="Redirect" url="http://www.mysite.com/aniverssary/events1{C:1}" redirectType="Found" />
</rule>

What should this look like?
Thanks

A: Well, it turns out that IIS has a really nice rewrite rule pattern tester. I found this tutorial extremely helpful. If you use the IIS URL Rewrite GUI, you can create a test redirect and then the URL Rewrite will write the redirect into web.config. You can then look in there and check your syntax.


Q: Finding a bijection from $[0,1]$ to $(0,1)$ $f(\frac{1}{3^n})=\frac{1}{3^{n+1}}$ , for $n\in\{0,1,2,...\}=I$;  $f(1-\frac{1}{2^{m}})=1-\frac{1}{2^{m+1}}, m\in I$ and $f(x)=x$ elsewhere in $[0,1]$. Does this work?
Note:
$\frac{1}{3^n}=1-\frac{1}{2^m} \implies 2^m+3^n=2^m3^n$, an impossibility, since LHS is odd and RHS is even.

A: Your proof works, but it is a bit overly complicated. A simpler way to do it is to choose some sequence $a_n$ of distinct elements of $[0,1]$, with (say) $a_0=0,a_1=1$, and then define $f(a_n)=a_{n+2}$ and $f(x)=x$ otherwise. This works whenever you add any finite number of elements to an infinite set.


Q: Finding argmax indices along a dimension and negate the corresponding values if the index is 1 Given a tensor in size DxCx2xHxW I try to find the argmax indices for the third dimension (between two values) and if the index is 0 I'll keep it or if it is 1 I'll negate the value and reduce the tensor to size DxCxHxW with the modified values and ignoring the non argmax indices.
Could you suggest a way to do this correctly? Thanks in advance for any further comment...
Here also my first stupid attempt that might give some insights about what am I trying to do.
max_val = self.pool_function(input_reshaped, axis=self.axis + 1) //input_rehshaed in size DxCx2xHxW
max_arg = T.argmax(input_reshaped, axis= self.axis+1)            //find argmax indices for the third dimension
return ifelse(T.lt(max_arg, 1), max_val, -max_val)               //negate argmax indices > 0 and return modified matrix ignoring the nonargmax indices

A: For the potential benefit of other people, this question was answered on the theano-users mailing list: https://groups.google.com/forum/#!topic/theano-users/6P5KxLph2I8
The recommended solution, by Pierre Luc Carrier, was:
mask = input_reshaped.argmax(axis=3).astype("float32") * -2 + 1
return input_reshaped.max(axis=3) * mask


Q: Github Action trigger on release not working on tag I've created a "publish" workflow in new repository that publish my project on new release with this trigger
on:
  release:
    types:
    - created

In my local machine I created a tag and pushed it:
git tag v0.0.1 main
git push origin v0.0.1

Now I see that my repo contains 1 tag and 1 release, but the workflow did not run.
Why the release trigger did not fire when new release created with the tag?

A: This is confusing in the GitHub Actions documentation on the "Events that Trigger Workflows." https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#release
It states that Activity Types are "published," "unpublished," and "prerelease" but it doesn't tell you how to invoke these activities.  You need to create a GitHub "Release" Event by either using the web portal or the gh CLI.  Follow this documentation: https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository
If that link changes look for the Release button in the GitHub web portal.  Just creating a git tag is not enough.
From the gh CLI the command is like: gh release create v1.3.2 --title "v1.3.2 (beta)" --notes "this is a beta release" --prerelease
In short git tag is not the event that triggers a GitHub Release event.


Q: Find coefficient in this expression I want to find the coefficient of $x^{21}$ in this expression: $(x^3+x^4+x^5+\ldots +x^{10})^4$. The first thing I did was $(x^3+x^4+x^5+\ldots +x^{10})^4=(x^3)^4(1+x+x^2+\ldots+x^7)^4$. So the problem is reduced to finding the coefficient of $x^9$ in the expression $(1+x+x^2+\ldots+x^7)^4$. However, I am not able to find that coefficient :/

A: $\mathbf{\text{HINT}}:$Remember that $$(1+x+x^2 +...+x^7)^4= \bigg(\frac{1-x^8}{1-x}\bigg)^4$$ , so you have binomial expressions.
So, $(1-x^8)^4 (1-x)^{-4}$ , then $(1+(-x^8))^4 (1-x)^{-4}$ ,
you will just find coefficients of binomial expressions such that
For $(1+(-x^8))$ : $\binom{4}{m}(-x^8)^m$
For $(\frac{1}{1-x})^4$ : $\binom{n+4-1}{n}x^n$ , where $8m+n=9$
Find all $m,n$ values satisfying the equation such as $(0,9),(1,1)$ , then put them into formulas.
Then , $$1 \times\bigg( \binom{9+4-1}{9}\bigg)+ (-4)\times \bigg(\binom{1+4-1}{1}\bigg)=204$$


Q: Is the map mask register used to do plane switching in VGA? I've got an understanding problem when it comes to the memory mapping of VGA. So I think I've got a wrong assumption somewhere.
From what I've understood, I think that a VGA adapter has 256 KB of memory but usually only exposes 64 KB to the host at any given time. So if you like to have a resolution of 640x480 pixels with 16 colors then you would need 153 600 bytes of the memory. But since the host can only access 64 KB it needs to swap the planes/banks behind the 64 KB window to access different parts of the 256 KB of video memory.
So when I set a mode I write the value 0001|b to the map mask register to select plane #0. When the OS asks my miniport driver for the bank switching code then I return some code that changes the value in the map mask register to 0010|b for example to switch to plane #1.
Now my problem is, that I seem to be the only person who does this. For example, when I looked at how Microsoft sets a mode, I noticed that they write 1111|b in the map mask register and when it comes to providing the code for the bank switching they simply provide a return-instruction with the comment that this function should never be called anyway. When a miniport driver sets a mode they even overwrite the map mask register right afterwards to make sure it contains 1111|b. When I looked at ReactOS I noticed that they haven't even implemented the function that provides the bank switching code.
But how is this possible?


Q: Is Spring Cache clusterable? I've got an application that uses Spring Cache (Ehcache), but now we need to add a 2nd node (same application). Can the cache be shared between the nodes or each with their own instance but synched?
Or do I need to look at a different solution?
Thanks.

A: That depends on your cache implementation - not on Spring, which only provides an abstract caching API. You are using EhCache as your caching implementation, which comes with a Terracotta server for basic clustering support and is open source. See http://www.ehcache.org/documentation/3.1/clustered-cache.html#clustering-concepts for more details


Q: Is there an API that will return how many results there are based your query search? Is there an api that returns how many results/logs there are based off your query search? or like a built in feature with NEST that will tell you how many results there is like i.e. count? Because I have a NEST query search that will do the following:
var response = await _elasticClient.SearchAsync<EsSource>(s => s
                  .Size(3000) // must see about this
                  .Source(src => src.Includes(i => i
                                    .Fields(f => f.timestamp,
                                            fields => fields.messageTemplate,
                                            fields => fields.message)))
                  .Index("customer-simulation-es-app-logs*")
                  .Query(q => +q
                      .DateRange(dr => dr
                          .Field("@timestamp")
                              .GreaterThanOrEquals("2021-06-07T17:13:54.414-05:00")
                              .LessThanOrEquals(DateTime.Now))));

but I realized that the search api cannot go past 10,000 results because the array is empty when you paginate beyond 10,000 results.  search api
So, if there is an api or a feature that will let you know how much results there is based on your index or if you are doing a monthly query search as I am above; with knowing that number I can then create a forloop to paginate through each of those documents say the first 10,0000 hits I can view then the next iteration for the next 10,000 hits and so on. Hope this makes sense, i'll clarify if needed.

A:
Is there an API that will return how many results there are based your query search?

I'm not aware of any ES API that will return an exact count. At high values, it becomes very approximate.

array is empty when you paginate beyond 10,000 results.

First, returning >10k search results is highly unusual. It sounds like you're trying to use ElasticSearch as a database, which you can do for some things, but don't go depending on ACID or anything like that.
To page over large result sets in ElasticSearch, create a point in time and pass that to the search API with the search_after parameter.


Q: Django or Nodejs or Ruby on Rails? I want to learn web development, I know little bit Python and Nodejs.
I dont have any knowledge on Ruby.
So, In the below 3, which one should I choose for Web Development?

*

*Django

*Nodejs

*Ruby on Rails

Thanks in advance.

A: Of course this question will be opinionated because it's fairly broad. Everyone has their own preferred choice. Though if you are a beginner to web programming and you'd like to use python I'd say start with flask.


Q: Amcharts5 chart add tooltip to circle I`m trying to add a tooltip to my chart but it doesn't work. I've added it both to bullet and to series as well.
There is no enough info in docs about how to add tooltip in this case.
When I add tooltip to series in which graphic is based everything works perfectly
Can you help?
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

am5.ready(function() {

  // Create root element
  // https://www.amcharts.com/docs/v5/getting-started/#Root_element
  var root = am5.Root.new("chartdiv");

  // Set themes
  // https://www.amcharts.com/docs/v5/concepts/themes/
  root.setThemes([
    am5themes_Animated.new(root)
  ]);

  // Create chart
  // https://www.amcharts.com/docs/v5/charts/xy-chart/
  var chart = root.container.children.push(am5xy.XYChart.new(root, {
    panX: true,
    panY: true,
    wheelY: "zoomXY",
    pinchZoomX: true,
    pinchZoomY: true
  }));

  chart.get("colors").set("step", 2);

  // Create axes
  // https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
  var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
    renderer: am5xy.AxisRendererX.new(root, {}),
    maxDeviation: 0.3,
  }));

  var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
    renderer: am5xy.AxisRendererY.new(root, {}),
    maxDeviation: 0.3,
  }));

  var tooltip = am5.Tooltip.new(root, {
    labelText: "MCaPos: {valueY}\nRN: ${valueY}",
    getFillFromSprite: false,
    getStrokeFromSprite: false,
    autoTextColor: false,
    getLabelFillFromSprite: false,
  });

  tooltip.get('background').setAll({
    fill: am5.color('#ffffff'),
    strokeWidth: 0,
  })

  tooltip.label.setAll({
    fill: am5.color('#000000')
  });

  console.log(tooltip)

  // Create series
  // https://www.amcharts.com/docs/v5/charts/xy-chart/series/
  var series0 = chart.series.push(am5xy.LineSeries.new(root, {
    calculateAggregates: true,
    xAxis: xAxis,
    yAxis: yAxis,
    valueYField: "y",
    valueXField: "x",
    valueField: "value",
    tooltip: am5.Tooltip.new(root, {
      labelText: "{valueY}"
    })
  }));

  // Create series
  // https://www.amcharts.com/docs/v5/charts/xy-chart/series/
  var series = chart.series.push(am5xy.LineSeries.new(root, {
    name: "Series 1",
    xAxis,
    yAxis,
    valueYField: "y",
    valueXField: "x",
    tooltip: am5.Tooltip.new(root, {
      labelText: "{valueY}"
    })
  }));
  series.strokes.template.setAll({
    strokeWidth: 2,
    strokeDasharray: [3, 3]
  });

  series.data.setAll([{
    "x": 0.01,
    "y": 1409090.91
  }, {
    "x": 0.06,
    "y": 1589743.59
  }, {
    "x": 0.11,
    "y": 1823529.41
  }, {
    "x": 0.16,
    "y": 2137931.03
  }, {
    "x": 0.21,
    "y": 2583333.33
  }, {
    "x": 0.26,
    "y": 3263157.89
  }, {
    "x": 0.31,
    "y": 4428571.43
  }, {
    "x": 0.36,
    "y": 6888888.89
  }, {
    "x": 0.41,
    "y": 15500000
  }]);

  var circleTemplate = am5.Template.new({});

  series0.bullets.push(function() {
    var graphics = am5.Circle.new(root, {
      fill: am5.color('#31DB42'),
    }, circleTemplate);
    return am5.Bullet.new(root, {
      sprite: graphics,
      radius: 1
    });
  });

  // Add heat rule
  // https://www.amcharts.com/docs/v5/concepts/settings/heat-rules/
  series0.set("heatRules", [{
    target: circleTemplate,
    min: 3,
    max: 35,
    dataField: "value",
    key: "radius"
  }]);

  // Add bullet
  // https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
  var starTemplate = am5.Template.new({});

  series0.strokes.template.set("strokeOpacity", 0);
  series0.set('tooltip', tooltip);

  // Add cursor
  // https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
  chart.set("cursor", am5xy.XYCursor.new(root, {
    xAxis,
    yAxis,
    snapToSeries: [series0, series]
  }));
  series0.data.setAll([{
    "x": 0.09271021903999942,
    "y": 2712290
  }]);
  series0.appear(1000);

  // Make stuff animate on load
  // https://www.amcharts.com/docs/v5/concepts/animations/
  series.appear(1000);
  chart.appear(1000, 100);

}); // end am5.ready()


Q: Firebase query hex codes contained within randomly generated keys I would like to query a particular child from the array of color hex codes.
Here's a snapshot of my database structure:

How do I query a particular hex code and obtain the entire array of its parent object?

A: You cannot query whether a specific value exists in a list. This is one of the many reasons why the Firebase documentation recommends against using arrays in the database.
But in this case (and most cases that I encounter), you may likely don't really need an array. Say that you just care about what colors your user picked. In that case, you can more efficiently store the colors as a set:
palettes
    -KSmJZ....A5I
        "0x474A39": true
        "0xbA9A7C": true
        "0xDEDEDF": true
        "0x141414": true
        "0x323E35": true

A: I did it in a different way,
made a function that does this:
let databaseRef = FIRDatabase.database().reference()
        let HEX1 = hex1.text! as String
        let HEX2 = hex2.text! as String
        let HEX3 = hex3.text! as String
        let HEX4 = hex4.text! as String
        let HEX5 = hex5.text! as String
        let URL = url.text! as String

        // First set
        let colorArray1 = [HEX2, HEX3, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX1).setValue(colorArray1)

        // second set
        let colorArray2 = [HEX1, HEX3, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX2).setValue(colorArray2)

        // third set
        let colorArray3 = [HEX1, HEX2, HEX4, HEX5, URL]
        databaseRef.child("palette").child(HEX3).setValue(colorArray3)

        // fourth set
        let colorArray4 = [HEX1, HEX2, HEX3, HEX5, URL]
        databaseRef.child("palette").child(HEX4).setValue(colorArray4)

        // fifth set
        let colorArray5 = [HEX1, HEX2, HEX3, HEX4, URL]
        databaseRef.child("palette").child(HEX5).setValue(colorArray5)

so that when I target any of the 5 hexes, it will bring me back the whole array together with it.


Q: program "killed" as soon as it runs Ubuntu 12.04
I have success with make, and output a program name algo.
When I type ./algo,the terminal just directly shows
'killed'

And I searched the var/log/message or syslog kern.log. I don't see any information about this kill. And dmesg also shows nothing about this.
Then I try 'sudo algo'. There is no output at the terminal and log.
I know there is perhaps an out of memory manager (OOM). But I want to get some information to confirm what happened. What should I do?


Q: NNET Multinomial Regression - Error in looping through multiple independent variables and extracting coefficients/std.errors I have a scenario in which I'm using multinom (from NNET package) to perform multinomial regression over a set of 100+ genes (a given gene is an independent variable in each multinomial regression). I have the following setup for generating the models, which runs successfully.
formulas <- sapply(iv_list, function(x) as.formula(paste0("Outcome ~","`",x,"`","+ Covariate")))

models <- lapply(formulas, function(x){multinom(x, data = Data)})

My Q is how to extract the beta coefficient and standard errors for the set of 100+ genes
I tried the below...
summaries <- lapply(models,summary)

...it yields the following error:
Error in formula.character(object, env = baseenv()) :
invalid formula "CAPN9": not a call
CAPN9 being one of the gene names for which a multinomial model was fit
I'd really appreciate any help!

A: Try:
models <- lapply(formulas, function(x){multinom(x, data = Data, Hess = TRUE)})

When you don't ask for the Hessian matrix (to get sampling variance-covariance) it has to be produced when calling summary.  R is trying to reproduce the call and run the multinom model again to get the Hessian.  The formulas provided are not parsing right as they were passed through lapply (which records them as x if you look at each model's result object/list).  nnet is using that x formula to try to work backwards and re-run the model, but it is failing to parse right, which is causing the error.
All this is avoided by obtaining the Hessian up-front in the initial model call.