text:
Q: Derby, SQL and CSV Bear in mind that this is a pretty greenhorn-question, so please, be patient with me.
So as a person who knows little to nothing about databases, undesirable conditions have lead me into a situation where I am to perform a task I know little about how to do.
In my hour of need, I come to you guys/gals.
Firstly, my task requires me to use Apache Derby to achieve the desired goals alongside Eclipse.
I've been given a single database located at res/myCSVFile.csv.
The text file with the CSV extension looks like this:
letter,name
A,alpha-static
B,beta-static
C,charlie-static

Doesn't look too threatening, right?
I know I can build a nice HashMap out of my CSV file like this:
Map<String, myFileType> myHashMap = new HashMap<>();
try(CSVReader rdr = new CSVReader(new FileReader("res/myCSVFile.csv"), ',','"',1)){
    for(String[] row : rdr.readAll()){
        File imagefile = new File(row[1]);
        myHashMap.put(row[0], new myFileType(imagefile, Integer.parseInt(row[2])));
    }
}

I know CSV separates columns by commas, so I assume what I see in this file are two columns, one labeled "letter" with the values "A", "B" and "C" under it, and another labeled "name" with "alpha-static", "beta-static" and "charlie-static" under it.
My situation requires me to use Derby to manipulate the above data as an SQL database. Knowing full well that a CSV file looks nothing like a SQL file, I know there is some conversion involved.
I don't know if Java can (or should) do this for me somehow, but I assume not.
Now, I do presume the SQL variant of my CSV file would look something like:
DROP TABLE possibleSqlTable;
CREATE TABLE possibleSqlTable(
  letter VARCHAR(1) NOT NULL PRIMARY KEY
, name VARCHAR(14)
);
INSERT INTO possibleSqlTable(letter,name) VALUES ('A','alpha-static');
INSERT INTO possibleSqlTable(letter,name) VALUES ('B','beta-static');
INSERT INTO possibleSqlTable(letter,name) VALUES ('C','charlie-static');

That's just my guess in the dark at how this SQL database would look (correct me if I'm wrong). Assume that's saved as res/possibleSqlDatabase.sql.
Now, how do I get Derby in on the action?
Assuming my SQL database is correct as I've guessed above, how do I for example query a statement?
How would I, for example, map "A" to "alpha-static"? Can I do this with a simple HashMap? I'd love to see how, if that'd be possible.
I do have a basic, VERY basic, understanding of how SQL-commands work, but I would love some examples using my database.
When answering, just treat me like a preschooler trying to learn this stuff. I really am that new.

A: Here is an example.
In this case I create a local Database /tmp/test.
Attention: If you want to use Derby as a service, you have to change the URL in getConnection() and start the database by yourself. You also can change the filename of the database at the same position.
The example can read the whole data with getData() or a single value with getOneName(String).
In the constructor we create and fill the database (if necessary), read the whole data, read a single letter and read a non exististing letter.
Hope that helps
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class TestApp {

    public static void main(String[] args) throws SQLException {
        TestApp myTestApp = new TestApp();
    }

    public TestApp() throws SQLException {
        this.createAndFillDatabase();
        Map<String, String> allData = this.getData();
        String oneData = this.getOneName("A");
        String noData = this.getOneName("D");
        System.out.println("allData = " + allData);
        System.out.println("oData   = " + oneData);
        System.out.println("noData  = " + noData);
    }

    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:derby:/tmp/test;create=true");
    }

    private void createAndFillDatabase() throws SQLException {
        try (Connection conn = getConnection()) {
            ResultSet tables = conn.getMetaData().getTables(null, null, "POSSIBLESQLTABLE", null);
            if (!tables.next()) {
                // create table
                Statement stmt = conn.createStatement();
                stmt.execute("CREATE TABLE possibleSqlTable(\n"
                        + "  letter VARCHAR(1) NOT NULL PRIMARY KEY\n"
                        + ", name VARCHAR(14)\n"
                        + ")");
                // insert data
                String[][] data = {{"A", "alpha-static"}, {"B", "beta-static"}, {"C", "charlie-static"}};
                PreparedStatement pstmt = conn.prepareStatement("INSERT INTO possibleSqlTable(letter,name) VALUES (?,?)");
                for (String[] row : data) {
                    pstmt.setString(1, row[0]);
                    pstmt.setString(2, row[1]);
                    pstmt.execute();
                }
                conn.commit();
            }
        }
    }

    private Map<String, String> getData() throws SQLException {
        Map<String, String> result = new HashMap<>();
        try (Connection conn = getConnection()) {
            Statement stmt = conn.createStatement();
            ResultSet results = stmt.executeQuery("select * from possibleSqlTable");
            while (results.next()) {
                result.put(results.getString("letter"), results.getString("name"));
            }
        }
        return result;
    }

    private String getOneName(String letter) throws SQLException {
        String result = null;
        try (Connection conn = getConnection()) {
            PreparedStatement pstmt = conn.prepareStatement("select * from possibleSqlTable where letter = ?");
            pstmt.setString(1, letter);
            ResultSet results = pstmt.executeQuery();
            while (results.next()) {
                result = results.getString("name");
            }
        }
        return result;
    }
}


text:
Q: Indexing nested data with Solr I am trying to index nested data with solr from an existing sql database. The DB has this structure
https://dev.mysql.com/doc/employee/en/images/employees-schema.png
My db-schema.xml is the following:
<document>
    <entity name="employees"
            rootEntity="true"
            query="select emp_no as 'id', first_name, last_name from employees limit 10;">
        <field column="id" />
        <field column="first_name" />
        <field column="last_name" />
        <entity child="true"
                name="dept_emp"
                query="select emp_no, dept_no from dept_emp where dept_emp.emp_no=${employees.id}">
            <field column="dept_no" name='dept_no'/>
        </entity>
    </entity>
  </document>

and my managed-schema.xml for the solr is this:
    <field name="first_name" type="string" indexed="true" stored="true" required="true" multiValued="false" />
    <field name="last_name" type="string" indexed="true" stored="true" required="true" multiValued="false" />
    <field name="dept_no" type="string" indexed="true" stored="true" required="true" multiValued="false" />
    <field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" />

The problem is that I get this error:
org.apache.solr.common.SolrException: [doc=null] missing required field: dept_no

Even if I remove
<field name="dept_no" type="string" indexed="true" stored="true" required="true" multiValued="false" />

I get the error the last_name is missing. If I remove the nested entity everything works fine.
Any idea why this is happening ?

A: this happens cause the fact of requiring a field is applied ALSO to parent docs. So your parent docs need to have those fields too, even if they just make sense for the children.
The same issue will show up with the 'id' field...Just remove the required attribute.
Edit: to keep the required attr, add this (just for dept_no shown here, do the  same for the rest):
<entity name="employees"
        rootEntity="true"
        query="select emp_no as 'id', first_name, last_name, 'DUMMY' as dept_no from employees limit 10;">
    <field column="id" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Blurry and large image barcode being generated using a plugin in Windows Form Going through the steps mentioned here
and using IDAutomationCode39, I am getting the barcode image, however they are very blurr and only scans bigger size images. My barcode id will be upto 30 characters long, which is causing a very wide barcode image. Where could the problem lie? Is it the IDAutomationCode39 or my setting in my button click event below?
private void button1_Click(object sender, EventArgs e)
    {
        string abbre = GenerateProdCodeFromProductName();
        txt2.Text = abbre;

        string barcode = txt1.Text;

        Bitmap bitm = new Bitmap(barcode.Length * 45, 160);
        bitm.SetResolution(240, 240);
        using (Graphics graphic = Graphics.FromImage(bitm))
        {
            Font newfont = new Font("IDAutomationHC39M", 6);
            PointF point = new PointF(5f, 5f);
            SolidBrush black = new SolidBrush(Color.Black);
            SolidBrush white = new SolidBrush(Color.White);
            graphic.FillRectangle(white, 0, 0, bitm.Width, bitm.Height);
            graphic.DrawString("*" + barcode + "*", newfont, black, point);
        }

        using (MemoryStream Mmst = new MemoryStream())
        {
            bitm.Save("ms", ImageFormat.Jpeg);
            pictureBox1.Image = bitm;
            pictureBox1.Width = bitm.Width;
            pictureBox1.Height = bitm.Height;
        }
    }

Thank you.

A: I don't see any PlugIn reference in your code, you are just using a Code39 ASCII font to print a Barcode on a Bitmap.
The problem I see is that the size of the resulting Bitmap is unscaled.
What I mean is, you let the size of the Barcode determine the size of the final graphic image.
It is usually the opposite. You have some defined dimensions for a Bitmap, because of layout constraints: you have to print the barcode to a label, for example.
If the generated Barcode is wider than its container, you have to normalize it (scale it to fit).
Here is what I propose. The size of the Bitmap if fixed (300, 150). When the Barcode is generated, its size is scaled to fit the Bitmap size.
The quality of the image is preserved, using an Bicubic Interpolation in case of down scaling. The resulting graphics is also Anti-Aliased.
(Anti-Alias has a good visual render. May not be the best choice for printing. It also depends on the printer.)
The generated Bitmap is then passed to a PictureBox for visualization and saved to disk as a PNG image (this format because of its loss-less compression).
Here is the result:

string Barcode = "*8457QK3P9*";

using (Bitmap bitmap = new Bitmap(300, 150))
{
    bitmap.SetResolution(240, 240);
    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        Font font = new Font("IDAutomationSHC39M", 10, FontStyle.Regular, GraphicsUnit.Point);

        graphics.Clear(Color.White);
        StringFormat stringformat = new StringFormat(StringFormatFlags.NoWrap);
        graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
        graphics.TextContrast = 10;

        PointF TextPosition = new PointF(10F, 10F);
        SizeF TextSize = graphics.MeasureString(Barcode, font, TextPosition, stringformat);

        if (TextSize.Width > bitmap.Width)
        {
            float ScaleFactor = (bitmap.Width - (TextPosition.X / 2)) / TextSize.Width;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.ScaleTransform(ScaleFactor, ScaleFactor);
        }

        graphics.DrawString(Barcode, font, new SolidBrush(Color.Black), TextPosition, StringFormat.GenericTypographic);

        bitmap.Save(@"[SomePath]\[SomeName].png", ImageFormat.Png);
        this.pictureBox1.Image = (Bitmap)bitmap.Clone();
        font.Dispose();
    }
}


text:
Q: PHP - Get data from SQL database recursively I have 2 tables tl_docs_categories which are the parent table for tl_docs.
Structure of tables is:
tl_docs_categories
[
   id,
   category_name,
   pid (give the posibility to create subcategories / pid = tl_docs_categories.id if have subcategory)
]
tl_docs
[
   id,
   doc_name,
   doc_url,
   pid(id for category)
]

So I have something like this in my database:

What I want is to return all result when I select category which is in red, I want to return all documents and subcategories names, in my view I use a select form to return the id of selected parent category in red.
Here is my php function :
public function checkSQL($id)
{
    if(!empty($id))
    {
        /* SQL CHECK IF HAVE DOCS */
        $sqlDoc = "SELECT category_name, doc_name, doc_url FROM tl_docs_categories dc
                   LEFT JOIN tl_docs d ON dc.id = d.pid WHERE d.pid = " . $id;
        $objDocs = Database::getInstance()->query($sqlDoc);
        if ($objDocs->numRows == 0)
        {
            /* SQL CHECK IF HAVE CHILD */
            $sqlChild = "SELECT dc.id, category_name, doc_name, doc_url FROM tl_docs_categories dc
                         LEFT JOIN tl_docs d ON dc.id = d.pid WHERE dc.pid =" . $id;
            $objDocs = Database::getInstance()->query($sqlChild);
                return $objDocs;
            }
        }
        else
        {
            return $objDocs;
        }
    }
}

I'm a bit lost and I don't have a solution to do it recursively and return datas for each category, subcategory, subsubcategory and more then.
Thank you for your help in advance.

A: I'm not sure about the syntax, but the idea is to call checkSQL on each level, if you want to return all results, then you have to adapt the $objDocs var to be an array.
public function checkSQL($id)
{
    if(!empty($id))
    {
        /* SQL CHECK IF HAVE DOCS */
        $sqlDoc = "SELECT category_name, doc_name, doc_url FROM tl_docs_categories dc
                   LEFT JOIN tl_docs d ON dc.id = d.pid WHERE d.pid = " . $id;
        $objDocs = Database::getInstance()->query($sqlDoc);

        if ($objDocs->numRows > 0) {
            foreach ($objDocs->fetchColumn() as $row) {
                $objDocs = $this->checkSQL($row->id);
            }
        }

        return $objDocs;
    }

    return null;
}


text:
Q: Get only modified values I'm updating a model and need to return ONLY the values that were changed.
const data = request.only(['name', 'email', 'address', 'age'])
const user = await user.findOrFail(data.id)
user.merge({ nome: data.name, email: data.email, endereco: data.address, age: data.age })

await user.save()

merge doesn't return anything so how Could I do that?

A: Basically, it user.dirty property before you await user.save().
To know what attributes were / will be updated, you need to compare the user.$attributes and the user.$originalAttributes before the user model instance saved(). The 'difference' stores in the user.dirty property after you merge.
This screenshot below was taken before I did merge(), you can see user.$attributes is similar to user.$originalAttributes, and the user.dirty property is empty. (user.isDirty = false)

And this screenshot was taken after I did merge(). The user first_name will be updated (to 'first name ---- changed') while the user last_name will be unchanged ('last name'), you can see now user.dirty = {first_name: 'first name --- changed'}, it contains first_name key and its to-be-updated value. (user.isDirty = true)

So. It is:
  const user = await User.findOrFail(1)

  console.log('exists user', user)

  user.merge({
    first_name: 'first name --- updated',
    last_name: 'last name'
  })

  console.log('user before updated', user)

  const output = user.isDirty ? user.dirty : {} // {} mean no attributes will be updated

  console.log('attribute that will be updated', output)

  await user.save()

  return output


text:
Q: Why do we use rt.jar in a java project? What is the necessity of rt.jar ??

A: rt.jar stands for runtime JAR and contains the bootstrap classes, I mean all the classes from Core Java API. I have found that many Java programmer doesn't know what is rt.jar? and often confused with the role of rt.jar file or  why we use of rt.jar file in Java? No surprise, the name is little bit cryptic.
This file always reside inside lib directory of JRE, at least in Windows and Linux. In MacOSX it reside at different location and also has different name i.e. classes.jar, but that is only prior to JDK 1.7. From Java 7 release Apple has stopped distributing Java and if you separately install, it will have same name as rt.jar.
Many developer thinks to include their classes inside rt.jar to solve classpath related problems, but that is a bad idea. You should never be messing with rt.jar, it contains class files which is trusted by JVM and loaded without stringent security check it does for other class files.

A: It contains the Java built-in classes. rt maybe stands for Runtime. Without it you couldn't run Java programs:)

A: It contains all the classes provided in the Java Runtime Environment.
If you don't have it on your classpath you will not have access to any of those classes you need to use like java.lang.String or java.io.File.

A: rt = Run Time
It contains all the java runtime libraries. (Essential)

A: The rt.jar is where all the java packages reside.  For example, if a class file calls for the java.util package, then the JVM can look for it inside the rt.jar, thus enabling it to run correctly.
On a side note: Don't mess around with it.

A: It contains all the standard JDK classes. During the  process of class loading in JVM, this is the first one to  get loaded and is done by the bootstrap class loader, parent of all class loaders.
You  can check it yourself by compiling a java program with this option:
javac -verbose program.java

in  order to  see the sequence of the class loaded.
Sample:
[Loaded sun.security.timestamp.TimestampToken from /usr/lib/jvm/java-8-oracle/jre/lib/rt.jar]
[Loaded sun.security.util.CertConstraintParameters from /usr/lib/jvm/java-8-oracle/jre/lib/rt.jar]
[Loaded sun.security.util.ECKeySizeParameterSpec from /usr/lib/jvm/java-8-oracle/jre/lib/rt.jar]
[Loaded sun.security.util.ECUtil from /usr/lib/jvm/java-8-oracle/jre/lib/rt.jar]
[Loaded sun.security.util.Pem from /usr/lib/jvm/java-8-oracle/jre/lib/rt.jar]

A: The runtime (rt.jar) holds all the (most of the..) java classes that form the Java SE. It is added to the classpath automatically.

A: Cross compilation is one case where you have to explicitly use it.
E.g., if you are on Java 8, and want to compile Java 7 while rejecting Java 8 extensions. So you could try:
javac -source 1.7 Main.java

But then javac will say: warning: [options] bootstrap class path not set in conjunction with -source 1.7, because it might generate error co compile against a different version of the JCL.
So you would need to set rt.jar with:
javac -source 1.7 -bootclasspath /usr/lib/jvm/java-7-oracle/jre/lib/rt.jar Main.java

This was asked at: warning: [options] bootstrap class path not set in conjunction with -source 1.5


text:
Q: Drupal Commerce Product Attributes I am trying, so far unsucessfully to add product attributes to my drupal commerce store.
I have created a product display which displays my title, price, and general product, then a list of products that are each a different color
My product display references my "product reference" and when creating a new display, I am givin the form as expected for title, body, and I can select all my colors, however once saved, there is no drop down for the user to select colors and it always just defaults to whatever color was the first selected when creating the product display
Any help, or tips would be appreciated

A: For choosing colors, can help module Commerce Fancy Attributes


text:
Q: Kubernetes ExternalName Services I have created a Kubernetes Service with type ExternalName, I understand this service act as a proxy and redirect the request to the external service sitting outside the cluster. I am able to create the service but not able to curl it i.e I get 500 error.
I wanna understand how this ExternalName Kubernetes service work.

A: Services with type ExternalName work as other regular services, but when you want to access to that service name, instead of returning cluster-ip of this service, it returns CNAME record with value that mentioned in externalName: parameter of service.
As example mentioned in Kubernetes Documentation:
kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  type: ExternalName
  externalName: my.database.example.com

When you want to do curl -v http://my-service or curl -v http://my-service.default.svc.cluster.local according your namespace(in this example it is default), it will redirect you at the DNS level to http://my.database.example.com
I hope it was useful


text:
Q: How to send my own parameters to AddHandler I'm trying to send my own parameter (Index As Integer instead of sender As Object, e As EventArgs) to an AddHandler. Here's my code:
Dim Button_ as Button
For Index=0 To 9
    Button_ = New Button()
    Button_.Left = 10
    Button_.Top = (Index * 30) + 10
    Button_.Width = 100
    Button_.Height = 20
    AddHandler Button_.Click, AddressOf Button_Click(Index)
    Me.Controls.Add(Button_)
Next

Sub Button_Click(Index As Integer)
    'Do stuff here...
End Sub

Thanks

A: You cannot change signature of Click event handler, but you can detect which button was clicked if you assign it's Name (I assume it's a WinForm button).
Dim Button_ as Button
For Index=0 To 9
    Button_ = New Button()
    Button_.Left = 10
    Button_.Top = (Index * 30) + 10
    Button_.Width = 100
    Button_.Height = 20

    Button_.Name = "Button_" & Index.ToString()

    AddHandler Button_.Click, AddressOf Button_Click
    Me.Controls.Add(Button_)
Next

You can then use standard signature like this:
Sub Button_Click(sender As Object, e As EventArgs)
     Dim Button_ as Button = CType(sender, Button)
     Dim ButtonName = Button.Name
End Sub

You can derive actual index from Name if needed.
Dim Index as Integer = CInt(ButtonName.Substring(7))

A: Along with the other answers, your button has a property called Tag it is defined as an object.  I usually use this property when I need to use a common event handler with a Control Array, you would use it something like this.
Dim Button_ as Button
For Index=0 To 9
    Button_ = New Button()
    Button_.Left = 10
    Button_.Top = (Index * 30) + 10
    Button_.Width = 100
    Button_.Height = 20
    Button_.Tag = Index
    AddHandler Button_.Click, AddressOf Button_Click
    Me.Controls.Add(Button_)
Next

Private Sub Button_Click(sender As Object, e As EventArgs)
    Dim i As Integer = CInt((CType(sender, Button).Tag))
    ' Use your index accordingly
End Sub


text:
Q: C++ code does not work correctly? For the following code I have a problem. I want it to print out the print statement which matches the if statement, but instead, it prints ALL of the statements for each if statement. How do I rectify this? I'm a beginner you see, so sorry for the silly question..
#include <iostream>

using namespace std;

int main()
{
    int x;
    int y;
    int z;

    cout << "Enter your first number" << endl;
    cin >> x;

    cout << "Enter your second number" << endl;
    cin >> y;

    cout << "Enter your third number" << endl;
    cin >> z;

    ////////////Equilateral Triangle. All sides are the same/////////////
    if ((x == y) && (y == z)) {
        cout << "This is an Equilateral triangle" << endl;
    }

    ////////////Isoceles Triangle. Two sides are the same/////////////
    if ((x == y) or (y == z) or (z == x)) {
        cout << "This is an Isosceles triangle" << endl;
    }

    ////////////Scalene Triangle. All sides are different/////////////
    if ((x > y + z)or (y > x + z) or (z > x +y)) {
        cout << "Opps! That didn't work! " << endl;
    }
    else {
        cout << "This is a scalene triangle" << endl;
    }

    return 0; // exit program
}

A: This should work:
if ( x != y and y !=z and z !=x) {
        cout << "This is a scalene triangle" << endl;
    }

You could also assume that if it isn't Equilateral or Isosceles than it is Scalene
////////////Equilateral Triangle. All sides are the same/////////////
if ((x == y) && (y == z)) {
        cout << "This is an Equilateral triangle" << endl;

}

////////////Isoceles Triangle. Two sides are the same/////////////
else if ((x == y) or (y == z) or (z == x)) {
        cout << "This is an Isosceles triangle" << endl;
}

////////////Scalene Triangle. All sides are different/////////////
else {
        cout << "This is a scalene triangle" << endl;
    }


text:
Q: How can I get automatically numbered headings in confluence? Currently it is not possible in confluence to have the headings of the document structure numbered automatically. I am aware that there are (paid) 3rd party plugins available.
How can I achieve continuous numbered headings?

A: TL;DR
Create a bookmark for the following javascript and click it in edit mode in confluence to renumber your headings.
javascript:(function()%7Bfunction%20addIndex()%20%7Bvar%20indices%20%3D%20%5B%5D%3BjQuery(%22.ak-editor-content-area%20.ProseMirror%22).find(%22h1%2Ch2%2Ch3%2Ch4%2Ch5%2Ch6%22).each(function(i%2Ce)%20%7Bvar%20hIndex%20%3D%20parseInt(this.nodeName.substring(1))%20-%201%3Bif%20(indices.length%20-%201%20%3E%20hIndex)%20%7Bindices%3D%20indices.slice(0%2C%20hIndex%20%2B%201%20)%3B%7Dif%20(indices%5BhIndex%5D%20%3D%3D%20undefined)%20%7Bindices%5BhIndex%5D%20%3D%200%3B%7Dindices%5BhIndex%5D%2B%2B%3BjQuery(this).html(indices.join(%22.%22)%2B%22.%20%22%20%2B%20removeNo(jQuery(this).html()))%3B%7D)%3B%7Dfunction%20removeNo(str)%20%7Blet%20newstr%20%3D%20str.trim()%3Bnewstr%20%3D%20newstr.replace(%2F%5B%5Cu00A0%5Cu1680%E2%80%8B%5Cu180e%5Cu2000-%5Cu2009%5Cu200a%E2%80%8B%5Cu200b%E2%80%8B%5Cu202f%5Cu205f%E2%80%8B%5Cu3000%5D%2Fg%2C'%20')%3Bif(IsNumeric(newstr.substring(0%2Cnewstr.indexOf('%20'))))%7Breturn%20newstr.substring(newstr.indexOf('%20')%2B1).trim()%3B%7Dreturn%20newstr%3B%7Dfunction%20IsNumeric(num)%20%7Bnum%20%3D%20num.split('.').join(%22%22)%3Breturn%20(num%20%3E%3D0%20%7C%7C%20num%20%3C%200)%3B%7DaddIndex()%7D)()

Result

How to use
After changes to the structure have been made, clicking the bookmarked javascript renumbers the document.
Limitations are that it only provides n.n.n. numbering, but for many cases that's sufficient. The script can also be customized as required.
Background, explanation and disclosure
I tried this TaperMonkey script that apparently resulted from this post, but it didn't work as is. So I took its source code and stripped it of the integration code, old version compatibility and made some minor adjustments to get this:
function addIndex() {
        var indices = [];

            jQuery(".ak-editor-content-area .ProseMirror").find("h1,h2,h3,h4,h5,h6").each(function(i,e) {
                var hIndex = parseInt(this.nodeName.substring(1)) - 1;
                if (indices.length - 1 > hIndex) {
                    indices= indices.slice(0, hIndex + 1 );
                }
                if (indices[hIndex] == undefined) {
                    indices[hIndex] = 0;
                }
                indices[hIndex]++;
                jQuery(this).html(indices.join(".")+". " + removeNo(jQuery(this).html()));
            });
    }

    function removeNo(str) {
        let newstr = str.trim();
        newstr = newstr.replace(/[\u00A0\u1680\u180e\u2000-\u2009\u200a\u200b\u202f\u205f\u3000]/g,' ');
        if(IsNumeric(newstr.substring(0,newstr.indexOf(' ')))){
            return newstr.substring(newstr.indexOf(' ')+1).trim();
        }
        return newstr;
    }

    function IsNumeric(num) {
        num = num.split('.').join("");
        return (num >=0 || num < 0);
    }

addIndex();

(I'm not a JavaScript developer, I'm sure it can be written nicer/better)
Then I used bookmarklet to convert it into the javascript bookmark at the top, which can be clicked to trigger the functionality.


text:
Q: Multiple Input selection in Rshiny I am trying to build a Rshiny for my project. I am trying to include 2 inputs,
First Input is a dropdown which contains months from Jan-Dec.
Second input can be a drop down or anything that allows me to select multiple items. Second input items are something like -"Assault","Theft","Burglary" etc..
A user can choose only one item from  First Input and multiple items from Second input.
So Basically If I choose Jan from first input and "Assault","Theft" from second input a bar graph depicting the no of Assault and Theft In jan should show up.
Input dataframe looks like this

PrimaryType    Month    count
Assault         Jan      25
Burglary        Jan      30
Tresspass       Feb      23
Assault         Feb      12
Burglary        Feb      34

ui <- fluidPage(

 titlePanel(div(HTML("<em> Crime Rate in Chichago </em>"))),

  tabsetPanel(

  tabPanel(" Frequency of Crime ",
         sidebarLayout(

           sidebarPanel(

             #First Input#

             selectInput(inputId = "Month",
                         label = " Choose a Month",
                         choices = unique(crime$Month))),

           #Second input#
           selectInput(inputId = "Crime",
                       label = " Choose among Crime",
                       choices = unique(crime$`Primary Type`),multiple =
TRUE)),

         #Output#

           mainPanel = (plotOutput("view")
           )
         )
  )
  )

  #Shiny app -Server#
server <- function(input, output) {
  output$view <- renderPlot({
  Monthfilter <- a[a$Month==input$Month,]

crimefilter <- Monthfilter[Monthfilter$`Primary Type` %in% input$Crime,]

ggplot(crimefilter, aes(`Primary Type`,c))+geom_bar(stat="identity")
  })
}

#Shinyapp#
shinyApp(ui = ui, server = server)

I would like a bar graph for a particular month with multiple Primary Types of crime

A: In the future, try and provide some example data in your code so it does not have to be reproduced.
Here are a few errors in your code:

*

*mainPanel should fall within sidebarLayout

*Your dataset is 'crime' not 'a' as you have put in your plot output (a[a$Month==input$Month,])

*You may have set your column header as 'PrimaryType' in your dataset but you have referenced it in your code as 'Primary Type' (with a space)

crime = data.table('Primary Type' = c('Assault','Burglary', 'Tresspass', 'Assault','Burglary'),
                   Month = c('Jan', 'Jan', 'Feb','Feb','Feb'),
                   Count = c(12,13,43,54,11))

ui <- fluidPage(

  titlePanel(div(HTML("<em> Crime Rate in Chichago </em>"))),

  tabsetPanel(

    tabPanel(" Frequency of Crime ",
             sidebarLayout(

               sidebarPanel(
                 #First Input#

                 selectInput(inputId = "Month",
                             label = " Choose a Month",
                             choices = unique(crime$Month)),

                 #Second input#
                 selectInput(inputId = "Crime",
                             label = " Choose among Crime",
                             choices = unique(crime$`Primary Type`),
                             multiple = TRUE)
                 ),

               #Output#

               mainPanel(
                 plotOutput("bar_plot")
               )

              )

    )
  )
)

#Shiny app -Server#
server <- function(input, output) {

  output$bar_plot <- renderPlot({
    Monthfilter <- crime[crime$Month == input$Month,]
    print('hello')
    crimefilter <- Monthfilter[Monthfilter$`Primary Type` %in% input$Crime,]

    ggplot(data = crimefilter, aes(x = `Primary Type`, y = Count)) + geom_bar(stat="identity")
  })
}

#Shinyapp#
shinyApp(ui = ui, server = server)r)


text:
Q: Ошибка компиляции "cannot borrow `X` as mutable because it is also borrowed as immutable" Не получается скомпилировать код и я не понимаю что не нравится компилятору, он выдаёт это:
error[E0502]: cannot borrow `counter` as mutable because it is also borrowed as immutable
  --> src/main.rs:38:17
   |
35 |         for (key, value) in &counter {
   |                             --------
   |                             |
   |                             immutable borrow occurs here
   |                             immutable borrow later used here
...
38 |                 counter.insert(*key, count);
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `variables` due to previous error

Вот сам код:
fn main() {
    let mut vect = vec![1,5,5,9,8,2,4,10];
    println!("{}", foo1(&vect));
    println!("{}", foo2(&mut vect));
    println!("{}", foo3(&vect));
}

fn foo3(keys: &Vec<i32>) -> i32 {
    let mut values = Vec::new();
    let mut i = 0;
    while i <= keys.len() {
        values.push(0);
        i += 1;
    }

    let mut counter: HashMap<_, _> = keys.into_iter().zip(values.into_iter()).collect();

    for i in keys {
        for (key, value) in &counter {
            if *i == **key {
                let count = *value+1;
                counter.insert(*key, count);
            };
        }
    }
    return 0;
}

Я пытался как то поменять код, но я просто не понимаю что делать, потому что меняющаяся скобка здесь:
38 |                 counter.insert(*key, count);
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

открывается в любом случае, но она либо как здесь, либо открывается вторая меняющаяся скобка, как тут:
  error[E0499]: cannot borrow `counter` as mutable more than once at a time
  --> src/main.rs:38:17
   |
35 |         for (key, value) in &mut counter {
   |                             ------------
   |                             |
   |                             first mutable borrow occurs here
   |                             first borrow later used here
...
38 |                 counter.insert(*key, count);
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here

Вторая и первая функции foo работают без ошибок. Помогите пожалуйста решить проблему.

A: Пришлось немного переделать и получился такой код:
fn foo3(keys: &Vec<i32>) -> HashMap<i32, i32> {
    let mut values = Vec::new();
    let mut i = 0;
    while i <= keys.len() {
        values.push(0);
        i += 1;
    }

    let counter: HashMap<_, _> = keys.into_iter().zip(values.into_iter()).collect();
    let mut counter2 = HashMap::new();

    for (key, value) in &counter {
        let mut count = 0;
        for i in keys {
            if *i == **key {
                count += 1;
                counter2.insert(**key, count);
            }
        }
    }

    return counter2;
}

вот функция main:
fn main() {
    let mut vect = vec![1,5,5,5,8,2,4,10];
    println!("{}", foo1(&vect));
    println!("{}", foo2(&mut vect));
    println!("{:#?}", foo3(&vect));
}

А вот вывод, который мне был нужен:
5
5
{
    4: 1,
    10: 1,
    5: 3,
    2: 1,
    8: 1,
    1: 1,
}


text:
Q: What is wrong with this implementation of the knapsack problem? I am getting Some Wierd output for the input of
1
3
4
1 2 3
4 5 1
I am getting output as 12
(HERE w is the capacity of the knapsack)
t=int(input())
while t:
   n=int(input())
   w=int(input())
   profits=tuple(map(int,input().split()))
   weights=tuple(map(int,input().split()))
   dp=[[0]*(w+1)]*(n+1)
   for i in range(n+1):
     for j in range(w+1):
        print()
        if i==0 or j==0:
            dp[i][j]=0
        elif j<weights[i-1]:
            dp[i][j]=max(dp[i-1][j],dp[i][j-1])
        else:
            dp[i][j]=max(dp[i-1][j],dp[i][j-1],profits[i-1]+dp[i-1][j-weights[i-1]])
   print(dp[n][w])
   t-=1

A: There is a bug in line 7, dp=[[0]*(w+1)]*(n+1), notice that in this kind of initialization if you change one element you change all of the elements in this column. Here you can find a full answer about this bug, why is this happening and how to fix it. But at the end what you need to do is:
TL;DR
change dp=[[0]*(w+1)]*(n+1) to dp = [[0] * (w + 1) for _ in range(n + 1)].


text:
Q: How can I retrieve the instrumentation key for an Application Insights instance in an Azure Resource Group Template? Is there any way to retrieve the Instrumentation Key for an Application Insights instance in an Azure Resource Group template ?
I've tried the instructions here to retrieve the list of list* operations available on Azure resources, but Microsoft.Insights/components doesn't appear in the list anywhere. It's making me think that retrieving an Instrumentation Key in the template isn't currently possible

A: Try it (using azure cli)
az resource show -g $RESOURCE_GROUP -n $APP_INSIGHTS --resource-type "microsoft.insights/components" --query properties.InstrumentationKey

A: After some digging and experimenting, this is what I found works:
"outputs": {
    "MyAppInsightsInstrumentationKey": {
        "value": "[reference(resourceId('Microsoft.Insights/components', variables('myAppInsightsInstanceName')), '2014-04-01').InstrumentationKey]",
        "type": "string"
    }
}

A: Instrumentation Key belongs to resource, you can find it in Azure Resource manager template. If you want to find Instrumentation Key, you need to define ResourceType to Microsoft.Insights/components. Try the below code:
$resourcevalue=Get-AzureRmResource -ResourceGroupName Default-ApplicationInsights-*** -ResourceType Microsoft.Insights/components -ResourceName **hdinsights -ApiVersion 2015-05-01
$resourcevalue.Properties.InstrumentationKey


text:
Q: Unable to get position according to pdf page I am using ng2-pdf-viewer for displaying pdf. I need to drop a signature filed upon this pdf and need to get the coordinates of signature where it is dropped. Coordinates must be according to pdf page, not according to Dom i.e bottom-left corner of pdf should be treated as the centre of point.
I have tried the matrial drag and drop events to fetch the coordinates but unable to do so. It is providing the coordinates according to dom. I also tried position and offset but does not work for me.

            <button class="btn btn-primary" (click)="signDocument()">Sign document</button>

   <pdf-viewer [src]="existingPdfSrc" [show-all]="false" [original-size]="false" [autoresize]="true" [(page)]="pageVariable" (after-load-complete)="pdfLoadComplete($event)"></pdf-viewer>

ts code is
const element = event.source.getRootElement();
const boundingClientRect = element.getBoundingClientRect();
const parentPosition = this.getPosition(element);
console.log('boundingClientRect', parentPosition);
console.log('x: ' + (boundingClientRect.x - parentPosition.left), 'y: ' + (boundingClientRect.y - parentPosition.top));
this.positionX = (boundingClientRect.x - parentPosition.left);
this.positionY = (boundingClientRect.y - parentPosition.top);

The coordinates should start from the bottom-left page of pdf i.e bottom-left page should be treated as (0,0)


text:
Q: Empty post response ajax I'm trying to use ajax to geta response from a codeigniter controller method but it doesn't work ,the response it's empty.
    <script type="text/javascript">
            $(document).ready(function(){
                $("#crear").click(function() {
                    //$('#error_msg').html("Error");
                    $.ajax({
                        type:"POST",
                        url:"clase/create",
                        success:function(data){
                            $('#error_msg').html(data);
                        }
                    });
                });
            });
    </script>

and this is the controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Clase extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('clase_model','',TRUE);
   $this->load->helper(array('form'));
 }

 function index()
 {
    if($this->session->userdata('logged_in')){
        $data['title'] = 'Gestión de Clases';
        $data['clases'] = $this->clase_model->getAll();
      $this->load->view('header', $data);
      $this->load->view('clase_view', $data);

     }
     else{

          redirect('login', 'refresh');
     }
 }

 function create(){
    if($this->session->userdata('logged_in')){
      $this->load->library('form_validation');
      $this->form_validation->set_rules('name', 'Nombre', 'trim|min_length[2]|required');
      $this->form_validation->set_rules('info', 'Información', 'trim');

       if($this->form_validation->run() == FALSE){
          $data = array(
            'error_message1' => form_error('name'),
            'error_message2' => form_error('info')
            );
           return $data['error_message1'];
       }
       else{
          if($this->input->post('info')){
             $this->insert2($this->input->post('name'),$this->input->post('info'));
          }
          else{
            $this->insert1($this->input->post('name'));
          }
       }
    }
    else{
          redirect('login', 'refresh');
    }
 }

 function insert2($name,$information){
    $dat = array(
      'nombre'=>$name,
      'info'=>$information
    );
    $this-> db ->insert('clase',$dat);

    echo $name;
    redirect('clase', 'refresh');
 }
 function insert1($name){
    $dat = array(
      'nombre'=>$name,
    );

    $this-> db ->insert('clase',$dat);
    redirect('clase', 'refresh');
 }
}
?>

and the response header
Cache-Control
no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection
Keep-Alive
Content-Length
0
Content-Type
text/html; charset=UTF-8
Date
Sat, 25 Apr 2015 16:04:47 GMT
Expires
Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive
timeout=5, max=100
Pragma
no-cache
Server
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3
Set-Cookie
ci_session=941a601d7eaf9f590d21bd4c0aa8c2ac043faa81; expires=Sat, 25-Apr-2015 18:04:47 GMT; Max-Age=7200
; path=/; httponly
x-powered-by
PHP/5.6.3

Somebody can tell me what is wrong?it's my first time with ajax

A: to response in a ajax request in codeigniter you should use-
echo json_encode('your data');


text:
Q: Implement a timeout in BluetoothSocket inputstream.read() in Android Is it possible to implement a timeout in an inputstream.read() function from a BluetoothSocket in Android?
I've tried using Thread.sleep() but this only pauses my activity.
---Update---
I had an idea, make 2 thread code herereads(t1 & t2) where each thread interrupt other, one of them(t1) do a sleep(5000) then interrupt the other thread(t2), from the other side the other thread(t2) if in read the inputstream detects some character as 0x0D interrupt the other thread(t1), but here is my question, does anybody can help me? because i didn't use interrupt() method of threads, I hope someone can help me, thank you...
---Update---

        public void run(){
        while(true){
            try {
            char r;
            String respuesta = "";
            while (true) {
                    r = (char) mmInStream.read();
                respuesta += r;
                if (r == 0x3e) {
                break;
                    }
                }
            respuesta = respuesta.replaceAll(" ", "");
            Log.d("respuesta", respuesta);
            rHandler.obtainMessage(MESSAGE_READ, -1, -1, respuesta).sendToTarget();
            } catch (IOException readException) {
            Log.e("ServicioGeneral", "Error de lectura", readException);
            this.interrupt();
            connectionLost();
            // posibly break();
            }
        }
    }

This is my implementation when something comes in a different Thread, the problem is that the timeout will be reached if i dont get the 0x3e character from de mmInStream.
I supposed that in the second example i must use a notifyAll(), but, when do I have to start the readThread()?
Thank you, @weeman

A: You could do something like this:
InputStream in = someBluetoothSocket.getInputStream();
int timeout = 0;
int maxTimeout = 8; // leads to a timeout of 2 seconds
int available = 0;

while((available = in.available()) == 0 && timeout < maxTimeout) {
    timeout++;
    // throws interrupted exception
    Thread.sleep(250);
}

byte[] read = new byte[available];
in.read(read);

This way you are able to initially read from a stream with  a specific timeout. If u want to implement a timeout at any time of reading you can try something like this:
Thread readThread = new ReadThread(); // being a thread you use to read from an InputStream
try {
   synchronized (readThread) {
      // edit: start readThread here
      readThread.start();
      readThread.wait(timeOutInMilliSeconds);
   }
catch (InterruptedException e) {}

using this you may need some kind of event handler to notify your application if the thread actually read something from the input stream.
I hope that helps!
----edit:
I implemented an example without using any handlers.
Socket s = new Socket("localhost", 8080);
    final InputStream in = s.getInputStream();

    Thread readThread = new Thread(new Runnable() {
        public void run() {
            int read = 0;
            try {
                while((read = in.read()) >= 0) {
                    System.out.println(new String(new byte[]{ (byte) read }));
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    synchronized (readThread) {
        readThread.start();
        try {
            readThread.wait(2000);

            if(readThread.isAlive()) {
                                    // probably really not good practice!
                in.close();
                System.out.println("Timeout exceeded!");
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

A: A Kotlin extension function for socket read with timeout:
fun InputStream.read(
  buffer: ByteArray,
  offset: Int,
  length: Int,
  timeout: Long
): Int = runBlocking {
    val readAsync = async {
        if (available() > 0) read(buffer, offset, length) else 0
    }
    var byteCount = 0
    var retries = 3
    while (byteCount == 0 && retries > 0) {
        withTimeout(timeout) {
            byteCount = readAsync.await()
        }
        delay(timeout)
        retries--
    }
    byteCount
}


text:
Q: replace hyphens correct regex My string is AusVELS - EAL – Stage A - Reading
I want to convert it to AusVELSEALStageAReading
I have tried the following
 assessment = "AusVELS - EAL – Stage A - Reading";
 trimassessment = assessment.replace(/\s/g, '').replace('/\-/g', '');

It turns out to be AusVELS-EAL–StageA-Reading
can someone tell me the correct regex?

A: trimasssesment = assessment.replace(/[^\w]/g, '')


text:
Q: iOS Webview Elastic Scrolling & Bounce Recently, I bumped into some weird situation. The project I worked on was a web embedded iOS APP. Because it was inside an APP, I didn't expect it to have bounce and elastic scroll like it was in a browser.
For the iOS APP development, the following line was added
webView.scrollView.bounces = NO;

However, the embedded website's CSS still had its work:
When I went with:
.root {
  height: 100%;
  width: 100%;
  overflow: auto;
}

This was okay to achieve what I wanted.
On the other hand, the following failed:
.root {
  height: 100vh;
  width: 100%;
  overflow: auto;
}

I wondered why was that?
I've already learned 100vh was referred to outerHeight of the window, but I still couldn't get why 100vh enabled bounce and elastic scroll.


text:
Q: Passing class member function in non-class member function's parameter How can I pass a class member function to a non-class member function's parameter? I am getting the following compile error:
error: argument of type 'void (MyNamespace::MyClass::)(int*)' does not match 'void (*)(int*)'

Library.h
typedef void (*testCallback)(int* iParam);
void UsingTheFoo(testCallback Callback);

Library.cpp
void UsingTheFoo(testCallback Callback)
{
  int *p_int = new int;
  *p_int = 5;
  Callback(p_int);
}

MyClass.cpp
namespace MyNamespace
{

    void MyClass::fooCB(int* a)
    {
        printf("hey! %d\n", *a);
    }

    void MyClass::testo()
    {
        UsingTheFoo(fooCB);
    }

} // MyNamespace

I can not change the code in "Library", I need to use "UsingTheFoo" in MyClass member functions. I am aware my way is wrong, I searched and found similar questions but couldn't understand (braindead at the end of shift :) ) any of them completely to adapt for my problem.
I've already read: http://www.parashift.com/c++-faq-lite/pointers-to-members.html :S

A: Make method that you wanna to pass as a callback as static. You've got this error because all methods have implicitly first parameter - pointer to an object, this, so their prototype doesn't correspond to callbacks'.

A: A member function isn't a regular function.
Think of it as a function with signature
  (className *pthis,...)
where .. is the signature you would think of.
You can still do this, but you would want std/boost::bind and a function object instead of a callback. Or as others have posted, you can make it static.
so perhaps you might want something like
typedef function<void (int*)> TCallback
void UsingTheFoo(TCallback, Callback);

MyClass class_object

with callback
TCallback cb = bind(std::ref(class_object),MyClass::fooCB);

A: fooCB, in your example, must be a static class member:
class MyClass {
public:
    static void MyClass::fooCB(int* a);
    ...
}


text:
Q: find element in linked list There is a data structure providing iterators with the following interface:
struct iterator {
    T value();
    void next();
    bool isValid();
}

How would you design an algorithm which at the end of the loop returns some value from the list with equal probability for each element? The list can be very long, so length of the list cannot be represented by int or long. The list cannot be modified.
Any ideas?
Thanks.

A: You don't know the length of the list, so you have to iterate it all the way to the end. You need to keep copy of the currently chosen items value (or item, but there seems to be no way to do that in your question). Then for every new item you iterate to, you need to determine if the chosen item should be kept or changed, with decreasing probability.
Since you state that length of list may not fit in a native/primitive data type (I assume you mean that when you talk about int and long, which are programming language and even dialect specific data types, and you don't specify programming language), I take it you mean the list may be arbitrarily long. So you need a bignum library, which can give you arbitrary random numbers.
Pseudocode:
T current = empty value
bignum index = 0
iterator = first item of list
while iterator.isValid()
    index = index + 1
    if bignum_random_below(index) == 0
        # 0 is interpreted as, take value from current index,
        # everything else is interpreted as keep the previous value
        current  = iterator.value()
    end if
    iterator.next()
end while
# index value 0 indicates empty list, even if T doesn't have empty value

From comment of M Oehm: this is called reservoir  sampling.


text:
Q: How to print http response body in Go? I'm using Google Cloud Run to run the application (e.g. sample application) I have the following script in Go:
package main

import (
        "fmt"
        "log"
        "net/http"
        "os"
        "os/exec"
)

func handler(w http.ResponseWriter, r *http.Request) {
        log.Print("helloworld: received a request")

        cmd := exec.CommandContext(r.Context(), "/bin/sh", "script.sh")
        cmd.Stderr = os.Stderr
        out, err := cmd.Output()
        if err != nil {
                w.WriteHeader(500)
        }
        w.Write(out)
}

func main() {
        log.Print("helloworld: starting server...")

        http.HandleFunc("/", handler)

        port := os.Getenv("PORT")
        if port == "" {
                port = "8080"
        }

        log.Printf("helloworld: listening on %s", port)
        log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}

I need to log.print responses body from script.sh commands. How can I do it?

A: In your server

w.Write(out)

sends response from script.sh as []byte. You can add above that line the following
log.Print(string(out))


text:
Q: Lombok builder, build half of the object, then finish building the other half I have a class:
@Builder
public class Foo {
   private String id;
   private String a;
   private String b;
}

I want to build an object with some restrictions. I want all the objects built to have a value a, but I want to make a check, and only if the object's id is in a List, I want to build it's 'b' value.
...

for(Foo foo: foos) {
   Foo.FooBuilder builder = Foo.builder();
   builder.a("bar1");

   if(listOfIds.contains(foo.getId)) {
      builder.b("bar2");
   }
   foo = builder.build();
}
...

That is an example of my code. So, I'm asking if this is the correct way to do it with the builder, or is there a better way to do this using builder.

A: UPDATED
In case you want to modify every element in the list. You can try this code:
for(int i = 0; i < foos.size();i++) {
  Foo.FooBuilder builder = Foo.builder();
  builder.a("bar1");

  if(listOfIds.contains(foo.getId())) {
  builder.b("bar2");
  //TODO: copy other values from `foos.get(i)` to builder. It's your turn
  //update modified to the list at i
  foos.set(i, builder.build());
}

}
=========================
Assume that foo is a Foo object. Then your code will not be compiled. You just need to set property a of the builder like my code. After setting all the properties in the Foo builder, run builder.build() to get your foo.
Foo.FooBuilder builder = Foo.builder();

for(Foo foo: foos) {
  builder.a("bar1");

  if(listOfIds.contains(foo.getId())) {
    builder.b("bar2");
  }

  foo = builder.build();

}


text:
Q: Usage Examples for DynamicWrapper I am looking for practical uses of the function DynamicWrapper . I read documentation and know whatever it says. I would appreciate a clear example of a useful dynamic interface (an app) that would be hard to implement without DynamicWrapper.

A: How about a 'Next page' button that becomes active only if the user has seen or at least scrolled to a particular part of a page, a disclaimer for instance?

EDIT
As requested: this was what I had in mind
texts = ExampleData["Text"];
i = 1;
imax = texts // Length;
bottomSeen = False;
Panel[
 Column[
  {
   Button["Next page", If[i <= imax, i++, i = 1]; bottomSeen = False;,
     Enabled -> Dynamic[bottomSeen]],
   Dynamic[
    Pane[
     Column[
      {
       ExampleData[texts[[i]]],
       ,
       DynamicWrapper["SEEN THIS", bottomSeen = True]
       }],
     ImageSize -> {500, 150}, Scrollbars -> True,
     ScrollPosition -> {1, 1}
     ]
    ]
   }
  ]
 ]

There's one problem I didn't anticipate: a DynamicWrapper placed in a Pane is activated as soon as the Pane is visible even when the DynamicWrapper content is scrolled outside the visible window of the Pane. I haven't solved that yet.

A: It seems to me that it is not so much that something would be hard to implement without DynamicWrapper but that using that function offers an alternative and perhaps cosmetically/aesthetically better option.
My typical usage would be where I need to have an expression or compound expression dynamically evaluate (things that come to mind are evaluations that determine the list for a popup menu). Dynamic needs to display so you could just stick a spacer at the end of Dynamic:
DynamicModule[{a, b},

 Column[{
   Style["Heading", "Section"],
   Dynamic[b = 2 a + 1; Spacer[0]],
   Slider[Dynamic[a]],
   Dynamic[{a, b}]
   }]
 ]

or do something like this:
DynamicModule[{a, b},

 Column[{
   DynamicWrapper[Style["Heading", "Section"], b = 2 a + 1],
   Slider[Dynamic[a]],
   Dynamic[{a, b}]
   }]
 ]

but as per documentation this is the same as writing
DynamicModule[{a, b},

 Column[{
   Dynamic[b = 2 a + 1; Refresh[Style["Heading", "Section"], None]],
   Slider[Dynamic[a]],
   Dynamic[{a, b}]
   }]
 ]

So using DynamicWrapper is just a personal preference (IMO).

A: Suppose we have a Graphics object which depends on some parameters and a controller with which we want to control these parameters. This could be done easily enough using the second argument of Dynamic, for example
gr[pts_, col_, radius_] := Graphics[{col, Disk[#, radius] & /@ pts},
   PlotRange -> {{0, 3}, {0, 3}}, ImageSize -> 200];

contrl = {1, radius};
col = Blue; radius = .1;
pts = RandomReal[3, {10, 2}];

Grid[{{Dynamic[Framed[gr[pts, col, radius]]],
  Slider2D[Dynamic[cntrl,
   (cntrl = #; col = Blend[{Red, Blue}, cntrl[[1]]]; radius = cntrl[[2]])&]]
}}]

However, suppose that we also want a switch which switches the coupling between the controller and the plot on and off. With DynamicWrapper this can be done by doing something like this
Grid[{{Dynamic[Framed[gr[pts, col, radius]]],
  Slider2D[Dynamic[cntrl]],
  Toggler["Off", {DynamicWrapper["On",
      col = Blend[{Red, Blue}, cntrl[[1]]]; radius = cntrl[[2]]],
     "Off"}]
 }}]

By clicking on the label of the slider you can then toggle between coupling or no coupling. The same effect can be achieved without using DynamicWrapper for example
DynamicModule[{state = "Off"},
  Grid[{{Dynamic[Framed[gr[pts, col, radius]]],
    Labeled[Slider2D[Dynamic[cntrl,(cntrl = #;
         If[state === "On", col = Blend[{Red, Blue}, cntrl[[1]]];
         radius = cntrl[[2]]]) &]],
     Toggler[Dynamic[state], {"On", "Off"}], Top]
  }}]
]

but imho the DynamicWrapper solution is more elegant in this case.


text:
Q: Recursive concept/type_traits on tuple-like types Say I was trying to implement a concept meowable that

*

*Integral types are meowable.

*Class types with member function meow are meowable. This is in the final target but the current question doesn't focus on it.

*Tuple-like types with only meowable elements are meowable.

*std::ranges::range with meowable elements are meowable. This is in the final target but the current question doesn't focus on it.
Then I came up with this implementation(simplified as I could):
#include <concepts>
#include <type_traits>
#include <ranges>
#include <utility>
#include <tuple>

template<class T>
concept meowable_builtin = std::integral<T>;

template<class T, std::size_t I>
concept has_tuple_element = requires (T t) {
  typename std::tuple_element<I, T>::type;
  { get<I>(t) } -> std::convertible_to<std::tuple_element_t<I, T>&>;
};

template<class T>
concept tuple_like = requires {
    typename std::tuple_size<T>::type;
    { std::tuple_size_v<T> } -> std::convertible_to<std::size_t>;
  } &&
  []<std::size_t...I>(std::index_sequence<I...>) {
    return (has_tuple_element<T, I> && ...);
  } (std::make_index_sequence<std::tuple_size_v<T>>{});

template<class               T> struct is_meowable:    std::false_type{};
template<meowable_builtin    T> struct is_meowable<T>: std::true_type{};

template<tuple_like T>
struct is_meowable<T>
  : std::bool_constant<
      []<std::size_t...I>(std::index_sequence<I...>) {
        return (is_meowable<std::tuple_element_t<I, T>>::value && ...);
      } (std::make_index_sequence<std::tuple_size_v<T>>{})
    > {};

template<class T>
concept meowable_tuple = tuple_like<T> && is_meowable<T>::value;

template<class T>
concept meowable = is_meowable<T>::value;

static_assert(meowable<int>);
//static_assert(tuple_like<std::tuple<int>>);
static_assert(is_meowable<std::tuple<int>>::value);

But some compilers don't like it (https://godbolt.org/z/5vMTEhTdq):
1. GCC-12 and above:   internal compiler error.
2. GCC-11:             accepted.
3. Clang-13 and above: static_assert fired.
4. MSVC-v19:           accepted.

However, if I uncomment the second last line of code, all compilers are happy. (Instantiation point of concepts?)
So my questions are:

*

*Why this behavior? (compiler bug or something like "ill-formed NDR"?)

*How can I achieve my target?

A:

*

*Why this behavior? (compiler bug or something like "ill-formed NDR"?)

This is apparently a bug of GCC-trunk and Clang-trunk, the issue here is that GCC/Clang doesn't properly handle the template partial specialization based on the concept initialized by the lambda. Reduced
template<class>
concept C = [] { return true; } ();

template<class T>
struct S {};

template<class T>
  requires C<T>
struct S<T> { constexpr static bool value = true; };

// static_assert(C<int>);
static_assert(S<int>::value);

*How can I achieve my target?

Replace lambda with the template function based on the reduced result
template<class T, std::size_t...I>
constexpr bool all_has_tuple_element(std::index_sequence<I...>) {
  return (has_tuple_element<T, I> && ...);
}

template<class T>
concept tuple_like = requires {
  typename std::tuple_size<T>::type;
  { std::tuple_size_v<T> } -> std::convertible_to<std::size_t>;
} && all_has_tuple_element<T>(std::make_index_sequence<std::tuple_size_v<T>>{});

Demo

A: I wrote a GENERIC version (using SFINAE) with customizable predicate that will work with all the specialized tuple-like types (those that have specializations for std::tuple_element and std::tuple_size).
https://godbolt.org/z/Yf889GY6E

#include <cstddef>
#include <type_traits>
#include <tuple>

template <typename, typename = void>
struct is_complete : std::false_type {};

template <typename T>
struct is_complete<T, std::void_t<decltype(sizeof(T))>> : std::true_type {};

// catching all standard (and specialized) tuple-like types
template <typename T>
struct is_tuple_like : is_complete<std::tuple_size<T>> {};

template <typename T, bool = is_tuple_like<T>::value>
struct get_tuple_size
{
    constexpr static size_t value = 0;
};

template <typename T>
struct get_tuple_size<T, true>
{
    constexpr static size_t value = std::tuple_size_v<T>;
};

// generic solution with predicate
template <template <typename> class PredicateT,
    typename T,
    bool = is_tuple_like<T>::value,
    typename = decltype(std::make_index_sequence<get_tuple_size<T>::value>{})>
struct tuple_conjunction : PredicateT<T> {};

template <template <typename> class PredicateT,
    typename T,
    size_t ... I>
struct tuple_conjunction<PredicateT, T, true, std::index_sequence<I...>> :
    std::conjunction<tuple_conjunction<PredicateT, std::tuple_element_t<I, T>>...> {};

////////////////////////////

template <typename T, typename = void>
struct has_meow : std::false_type {};

template <typename T>
struct has_meow<T, std::void_t<decltype(std::declval<T>().mew())>> : std::true_type {};

template <typename T>
using meowable_pred = std::disjunction<std::is_integral<T>, has_meow<T>>;

template <typename T>
using meowable = tuple_conjunction<meowable_pred, T>;

#include <array>

struct cat
{
    void mew() {}
};

struct dummy{};

int main()
{
    static_assert(!is_complete<std::tuple_element<0, cat>>::value);
    static_assert(is_complete<std::tuple_element<0, std::tuple<cat>>>::value);

    static_assert(meowable<int>::value);
    static_assert(meowable<cat>::value);
    static_assert(!meowable<dummy>::value);

    static_assert(meowable<std::tuple<long>>::value);

    static_assert(meowable<std::tuple<int, long>>::value);
    static_assert(meowable<std::tuple<cat, long>>::value);
    static_assert(meowable<std::tuple<int, std::tuple<cat, long>>>::value);

    static_assert(!meowable<std::tuple<int, std::tuple<cat, long>, dummy>>::value);

    // std::array
    static_assert(meowable<std::array<cat, 42>>::value);
    static_assert(meowable<std::tuple<int, std::tuple<cat, long, std::tuple<std::array<cat, 42>>>>>::value);

    return 0;
};

With some adjustments it will also work with C++11.

*

*You can provide any predicate you want for a recursive check. The example shows a usage with meowable_pred predicate.

OLD ANSWER
Here is a simple recursive SFINAE solution for C++17 (and 11 for some adjustments):
https://godbolt.org/z/cezqhb99b

#include <type_traits>

template <typename T, typename = void>
struct has_meow : std::false_type {};

// this is a customization point to deduce tuple-like traits
// you can define some default logic here,
// but for the sake of example let it be false by default
template <typename>
struct is_tuple_like : std::false_type {};

template <typename T>
struct has_meow<T, std::void_t<decltype(std::declval<T>().mew())>> : std::true_type {};

template <typename T>
struct meowable : std::disjunction<std::is_integral<T>, has_meow<T>> {};

template <template <typename...> class TupleT, typename ... T>
struct meowable<TupleT<T...>> : std::conjunction<
                                          is_tuple_like<TupleT<T...>>,
                                          std::conjunction<meowable<T>...
                                       > {};

#include <tuple>
#include <array>

// this will also catch std::pair
template <typename ... T>
struct is_tuple_like<std::tuple<T...>> : std::true_type {};

template <typename T, size_t N>
struct is_tuple_like<std::array<T, N>> : std::true_type {};

struct cat
{
    void mew() {}
};

int main()
{
    static_assert(meowable<int>::value);
    static_assert(meowable<std::tuple<int, long>>::value);
    static_assert(meowable<cat>::value);
    static_assert(meowable<std::tuple<cat, long>>::value);
    static_assert(meowable<std::tuple<int, std::tuple<cat, long>>>::value);

    return 0;
};


text:
Q: Session attribute lost on Wildfly 12 I am working on legacy project, I am just trying to make it running (it is supposed to work). But I found out a problem with the session in my JPSs ( No much settings changed on standalone.xml)
Here is login instruction in my servlet doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    PrintWriter out = response.getWriter();
    try {
        User user = loginService.login(username, password);
        request.getSession().setAttribute("user", user);

    } catch (OAuth2AccessDeniedException e) {
        e.printStackTrace();
    }
    }

And in my main page:
<%if(session.getAttribute("user")==null){ %>

<%}else{
    User user = (User)session.getAttribute("user");
%>

//rest of html page

When I debug, I find that the user is correctly set in the session but in my jsp it is null


text:
Q: Is it possible to extract multiple groups at once when fontifying with font-lock? I'm trying to wrap my head around font-lock-keywords format, particularly MATCH-ANCHORED variant, but I don't see how would I re-use matches generated from one regexp. Below is my setup for illustration:
(defvar fmt-font-lock-keywords
  ;; no-args
  `(("~\\(@:?\\|:@?\\)?[]>()}aswvcp;_]"
     (0 font-lock-keyword-face))
    ;; numeric-arg
    ("~\\([0-9]*\\|#,?\\)\\(@:?\\|:@?\\)?[i*%&|~{[]"
     (0 font-lock-keyword-face))
    ;; decimal
    ("~\\([0-9]*\\|#\\(,[0-9]*\\|#\\)\\{0,3\\}\\)?\\(@:?\\|:@?\\)?[rdbox]"
     (0 font-lock-keyword-face))
    ;; floating-point f
    (,(concat
       "~\\(\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)\\{3\\}\\(,'\\w\\)\\{1,2\\}\\)\\|"
       "\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)\\{0,3\\}\\)\\)"
       "?\\(@:?\\|:@?\\)?f")
     (0 font-lock-keyword-face))
    ;; floating-point e, g
    (,(concat
       "~\\(\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)\\{3\\}\\(,'\\w\\)\\{1,3\\}\\)\\|"
       "\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)\\{0,3\\}\\)\\)"
       "?\\(@:?\\|:@?\\)?[eg]")
     (0 font-lock-keyword-face))
    ;; currency
    (,(concat
       "~\\(\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)\\{2\\}\\(,'\\w\\)\\)\\|"
       "\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)\\{0,2\\}\\)\\)"
       "?\\(@:?\\|:@?\\)?[$]")
     (0 font-lock-keyword-face))
    ;; tabulation
    ("~\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)?\\)?\\(@:?\\|:@?\\)?t"
     (0 font-lock-keyword-face))
    ;; escape
    ("~\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)\\{0,2\\}\\)?\\(@:?\\|:@?\\)?^"
     (0 font-lock-keyword-face))
    ;; logical block
    ("~\\(\\([0-9]*\\|#\\)\\(,\\([0-9]*\\|#\\)\\)\\{0,3\\}\\)?\\(@:?\\|:@?\\)?<"
     (0 font-lock-keyword-face))
    ;; custom function
    (,(concat
       "~\\(\\([0-9]+\\|'\\w\\|#\\)\\(,\\([0-9]+\\|'\\w\\|#\\)+\\)*\\)?"
       "\\(@:?\\|:@?\\)?\\/[^\\s\\n,#@]+\\/")
     (0 font-lock-keyword-face))))

And, when initializing this mode:
(define-derived-mode fmt-mode fundamental-mode
  . . .
  (set (make-local-variable 'font-lock-defaults)
      '(fmt-font-lock-keywords)) . . .)

Sorry, I know it looks like cuneiform, but what it does is actually very simple... it's parsing the Common Lisp format mini-language.
What it does now: it colors all special sub-strings using keyword face, but what I would like to do is to color certain parts differently (numerical arguments would be colored differently, the custom function call would be colored differently, at and colon - maybe differently, character data - maybe differently too).
I could, technically, duplicate these regexps to extract a different group, but it is very inelegant, besides, in cases where it is possible to pass variable number of arguments the writeup will near combinatorial explosion...

I do realize that parsing can be much more easily solved when not using regular expressions, but I don't know how to combine it with font-lock mode. But if you happen to know how to do it w/o regexps, while still using font-lock mechanics for coloring, that would be a great answer too!

A: A quick partial response without looking at your code (sorry) - so it might well miss the boat.

*

*If part of what you are asking is how to leave something highlighted by a f-l-k entry even if it also matches a later f-l-k entry, the answer to that is to use keep.  (See also what t does, which is pretty much the opposite.)

*If part of what you are asking is how to font-lock without using regexps, or without using only regexps, the answer to that is to use a function.
If you haven't already, see the Elisp manual, node Search-based Fontification -- search for keep and FUNCTION.


text:
Q: TypeError: unsupported operand typ i m just new to python and is trying to learn this language. i tried running a code in python but got an error can anyone help me
here is my code:
def cel_to_fahr(c):
    f = c * 9/5 + 32
    return f

c = input("enter the temperature in celcius:")
print(cel_to_fahr(c))

the error i m getting is:
File ".\prg.py", line 6, in <module>
    print(cel_to_fahr(c))
  File ".\prg.py", line 2, in cel_to_fahr
    f = c * 9/5 + 32
TypeError: unsupported operand type(s) for /: 'str' and 'int

'

A: The function input() returns the string value. So convert it to either int or float
c = int(input("enter the temperature in celcius:"))

OR
c = float(input("enter the temperature in celcius:"))

A: You first need to convert your input to number. input() function returns string value
c = input("enter the temperature in celcius:")
print(cel_to_fahr(int(c)))


text:
Q: 3 websites 1 Project We are currently on a plan to develop a website for 3 same company.
The main difference would be just the look and maybe a couple of extra question for one or two company.
Currently each company have their own website and when they required a new function we have to re-code all three website or when one wants a new function just one website update.
What we want to accomplish is to create  ONE website that could house all these 3 website.
Most of these website function are the same like 90% function is the same
I figure out the different look which can be done changing the website style-theme..
But we have problem tackling the functionality of if one company wanted to add something.
So if we wanted to update a function we just want to do a change in one function and that should apply for all.
And if one function is required for one company then just add the new function and assign it to 1 company...
How do you structure something like this?
We want to be able to control what being displayed based on the company and also the functions available.
I just need some direction on how to do this.
Right now Inheritance is on my head to solve all this problem.

A: Put shared functionality in a common assembly, and reference that assembly in your 3 websites. There's not necessarily a trivial solution.

A: I've tried doing this with shared libraries and also by having a single website in IIS and then using the domain to route the requests properly. There are a lot of things with User Controls (ascx) that get really confusing if you try to share them across multiple websites, even though it is possible to embed them as resources in an assembly and load them dynamically.
Once you are hosting all 3 domains in a single IIS site, to enable things to be different between the sites you can write some conditions based on the domain. As a more general point, you can create a class to hold your permissions and resources for features based on the domain so if you add another website in the future you just need to implement that class for the new domain.
If you can isolate the differences in any other way, such as different image directories, css files, text resources, etc. that can also help keep your common features all together so you can just reference those resources that are different as needed while sharing all the common elements.

A: You should be able to resolve most of the issues you want to solve with use of style sheets.  Have each website reference the same style sheet, but then have them also reference their own unique style sheet which contains the differences for each website.


text:
Q: Split Spark DataFrame into two DataFrames (70% and 30% ) based on id column by preserving order I have a spark dataframe which is like
id  start_time   feature
1   01-01-2018   3.567
1   01-02-2018   4.454
1   01-03-2018   6.455
2   01-02-2018   343.4
2   01-08-2018   45.4
3   02-04-2018   43.56
3   02-07-2018   34.56
3   03-07-2018   23.6

I want to be able to split this into two dataframes based on the id column.So I should groupby the id column, sort by start_time and take 70% of the rows into one dataframe and 30% of the rows into another dataframe by preserving the order.The result should look like:
Dataframe1:
id  start_time   feature
1   01-01-2018   3.567
1   01-02-2018   4.454
2   01-02-2018   343.4
3   02-04-2018   43.56
3   02-07-2018   34.56

Dataframe2:
1   01-03-2018   6.455
2   01-08-2018   45.4
3   03-07-2018   23.6

I am using Spark 2.0 with python. What is the best way to implement this?

A: The way I had to do it was to create two windows:
w1 =  Window.partitionBy(df.id).orderBy(df.start_time)
w2 =  Window.partitionBy(df.id)

df = df.withColumn("row_number",F.row_number().over(w1))\
                     .withColumn("count",F.count("id").over(w2))\
                     .withColumn("percent",(F.col("row_number")/F.col("count")))
train = df.filter(df.percent<=0.70)
test = df.filter(df.percent>0.70)


text:
Q: Rails - psql deploy on heroku I have a rails 4 app on heroku with a PSQL database.
This has all been fine in development, but I'm coming to my first attempt at publishing the app with content in the database.
I recently reset the database locally and in heroku. And also did:
heroku ran rake:db migrate

I then created the first article in my articles resource and committed, pushed and pushed to heroku. I expected to see that article displayed (as it is in my local host).
However, when I go on local host in production mode or to the published site, the article is not there.
Is there a step I'm missing for how to push to heroku with the db content you want? Is there something that needs to be done to make the production database recognise the development database? Not sure about the steps for publishing the production db.
In my database.yml file I have:
staging:
  adapter: postgresql
  encoding: unicode
  database: vh_staging
  pool: 5
  #username: vh

  #host: localhost

development:
  adapter: postgresql
  encoding: unicode
  database: vh_development
  pool: 5
  #username: vh

test: &test
  adapter: postgresql
  encoding: unicode
  database: vh_test
  pool: 5
  #username: vh

production:
  adapter: postgresql
  encoding: unicode
  database: vh_production
  pool: 5
  #username: vh

A: You push on heroku only your code, not a database data.

A: Try doing that by seed:
heroku run rake db:push
heroku pg:reset DATABASE
heroku run rake db:seed

You should have your data as ruby code in your the file db/seeds.ru to do that.


text:
Q: mysql join two really complex queries I currently have two really complex queries that I use to bring in scores with ranks.  The first is all the participants and their scores with stage ranks, the second is Grouped by each participant and calculates their overall rank (sum of stage ranks).
First query to get all participants for each stage with scores and ranks
SELECT * FROM (
  SELECT alias, catabbr, sh_dq, raw, sdq, dnf,
@rownum := IF(@stage != stage_name, 1, @rownum + 1) AS rowNum,
@rank := IF(@prevVal != cTime, @rownum, @rank) AS rank,
@stage := stage_name as stage_name,
@prevVal := cTime AS cTime,
id, zeroTime
  FROM
(SELECT @rownum:= 0) rn,
(SELECT @rank:= 1) av,
(SELECT @stage:= '') sv,
(SELECT @prevVal:= 0) pv,
(SELECT s.stage_name stage_name, sc.alias alias, sc.catAbbr catabbr, sc.sh_dq sh_dq, sc.time raw, sc.id id, sc.sdq sdq, sc.dnf dnf,
    IF(sc.time = "0", 1, 0) AS zeroTime,
    ((ROUND(sc.time, 2) + (sc.miss * 5)) + ((sc.proc * 10) + (sc.saf * 10) + (sc.sog * 30)) - (sc.bthPoints)) cTime
    FROM matches m
    LEFT JOIN stages s ON s.match_id = m.id
    LEFT JOIN scores sc ON sc.stage_id = s.id
    WHERE m.matchuuid = 'E13A4C61-A2B8-48E2-BE1B-1FFB77CC5849'
    GROUP BY sc.alias, s.stage_name
    ORDER BY s.stage_name, zeroTime, cTime
) tv
) t
ORDER BY zeroTime, alias, stage_name;

Outputs:
+-----------+---------+-------+-----------------+-----+-----+--------+------+-----------------------+-------+----------+
| alias     | catabbr | sh_dq | raw             | sdq | dnf | rowNum | rank | stage_name            | cTime | zeroTime |
+-----------+---------+-------+-----------------+-----+-----+--------+------+-----------------------+-------+----------+
| Back Bob  | S       | 0     | 52.9799995422   | 0   | 1   | 54     | 54   | Stage 1               | 92.98 | 0        |
+-----------+---------+-------+-----------------+-----+-----+--------+------+-----------------------+-------+----------+
| Back Bob  | S       | 0     | 43.9099998474   | 0   | 0   | 46     | 46   | Stage 2               | 48.91 | 0        |
+-----------+---------+-------+-----------------+-----+-----+--------+------+-----------------------+-------+----------+
| Ben Scal  | ES      | 0     | 26.9699993134   | 0   | 0   | 27     | 27   | Stage 1               | 31.97 | 0        |
+-----------+---------+-------+-----------------+-----+-----+--------+------+-----------------------+-------+----------+
| Ben Scal  | ES      | 0     | 32.8800010681   | 0   | 0   | 38     | 38   | Stage 2               | 42.88 | 0        |
+-----------+---------+-------+-----------------+-----+-----+--------+------+-----------------------+-------+----------+

Second query groups participants by name and sums their ranks for a final rank
SELECT alias, catabbr, SUM(cTime) fTime, SUM(rank) fRank, zeroTime, rank
FROM (
  SELECT alias, catabbr, sh_dq, raw, sdq, dnf,
@rownum := IF(@stage != stage_name, 1, @rownum + 1) AS rowNum,
@rank := IF(@prevVal != cTime, @rownum, @rank) AS rank,
@stage := stage_name as stage_name,
@prevVal := cTime AS cTime,
id, zeroTime
  FROM
(SELECT @rownum:= 0) rn,
(SELECT @rank:= 1) av,
(SELECT @stage:= '') sv,
(SELECT @prevVal:= 0) pv,
(SELECT s.stage_name stage_name, sc.alias alias, sc.catAbbr catabbr, sc.sh_dq sh_dq, sc.time raw, sc.id id, sc.sdq sdq, sc.dnf dnf,
    IF(sc.time = "0", 1, 0) AS zeroTime,
    ((ROUND(sc.time, 2) + (sc.miss * 5)) + ((sc.proc * 10) + (sc.saf * 10) + (sc.sog * 30)) - (sc.bthPoints)) cTime
    FROM matches m
    LEFT JOIN stages s ON s.match_id = m.id
    LEFT JOIN scores sc ON sc.stage_id = s.id
    WHERE m.matchuuid = 'E13A4C61-A2B8-48E2-BE1B-1FFB77CC5849'
    GROUP BY sc.alias, s.stage_name
    ORDER BY s.stage_name, zeroTime, cTime
) tv
) t
GROUP BY alias
ORDER BY zeroTime, fRank, fTime;

Outputs:
+-----------+-----------+-----------+-------+-----------+
| alias     | catabbr   | fTime     | fRank | zeroTime  |
+-----------+-----------+-----------+-------+-----------+
| Back Bob  | S         | 141.89    | 100   | 0         |
+-----------+-----------+-----------+-------+-----------+
| Ben Scal  | ES        | 74.85     | 68    | 0         |
+-----------+-----------+-----------+-------+-----------+

The zeroTime column makes it so I can sort by times that are greater than 0, and correctly calculate the rank.
When I try to join them I get no results or anything. Is there a way to combine/join these two queries into one query so that they will output the following?
+-----------+-----------+-----------+-------+-----------+---------------+---------------+---------------+---------------+
| alias     | catabbr   | fTime     | fRank | zeroTime  | Stage 1 Time  | Stage 1 Rank  | Stage 2 Time  | Stage 2 Rank  |
+-----------+-----------+-----------+-------+-----------+---------------+---------------+---------------+---------------+
| Ben Scal  | ES        | 74.85     | 68    | 0         | 31.97         | 27            | 42.88         | 38            |
+-----------+-----------+-----------+-------+-----------+---------------+---------------+---------------+---------------+
| Back Bob  | S         | 141.89    | 100   | 0         | 92.98         | 54            | 48.91         | 46            |
+-----------+-----------+-----------+-------+-----------+---------------+---------------+---------------+---------------+

This will be going into a php page, so I can loop through and pull in what I need, the main thing I'm trying to do is join these two queries.
My structures and data are too big for a sqlfiddle.
Here is the structure and inserts for matches and stages: http://pastebin.com/YvZevd5j
Here is the structure and inserts for scores: http://pastebin.com/jLBYxMvc
One thing to note too, is that a game could have 1 or more stages and 1 or more particpants.

A: This Answer may not scale well as you would need to know the number of stages, but perhaps you can handle building it with a loop or something in you application. Here's a simplified version, you can modify it to work with your data.
SELECT
  alias,
  catAbbr,
  sum(fTime) as fTime,
  sum(fRank) as fRank,
  sum(zeroTime) as zeroTime,
  sum(Stage_1_Time) as stage_1_Time,
  sum(Stage_1_Rank) as Stage_1_Rank,
  sum(Stage_2_Time) as stage_2_Time,
  sum(Stage_2_Rank) as Stage_2_Rank
FROM (
  SELECT
    alias,
    catAbbr,
    0 as fTime,
    0 as fRank,
    0 as zeroTime,
    Stage_1_Time as stage_1_Time,
    Stage_1_Rank as Stage_1_Rank,
    0 as stage_2_Time,
    0 as Stage_2_Rank
  FROM (query that gets stage 1 info)
  UNION
  SELECT
    alias,
    catAbbr,
    0 as fTime,
    0 as fRank,
    0 as zeroTime,
    0 as stage_1_Time,
    0 as Stage_1_Rank,
    stage_2_Time as stage_2_Time,
    Stage_2_Rank as Stage_2_Rank
  FROM (query that gets stage 2 info)
  UNION
  SELECT
    alias,
    catAbbr,
    fTime as fTime,
    fRank as fRank,
    zeroTime as zeroTime,
    0 as stage_1_Time,
    0 as Stage_1_Rank,
    0 as stage_2_Time,
    0 as Stage_2_Rank
  FROM (query that gets averaged info)
) temp
GROUP BY alias, catAbbt


text:
Q: Can this fetch be done more "elegantly"? I am using jOOQ and I am not quite sure if I am using it the way I am supposed to. I was wondering if my code below can be written more elegantly. By "elegantly" I mean that it is quite annoying to change basically anything regarding the columns. If I add, remove or change the order of the columns I'd have to change all result  and Table<> objects etc. I am quite sure that I'll encounter such requests like below a few more times in the future thus I'd like to know if I can simplify this.
In addition, I noticed that the result of on.fetch() and similar is a Result<Record6<..>>. I took a look at those RecordX classes. There are 22 of them. I don't think that I'll ever need that but what if I wanted to read 23 columns?
public List<StoreItemDTO> getItems(Long storeId) {

  // Get all item_ids for the store

  SelectConditionStep<Record1<Long>> where = this.ctx
    .select(STORE_ITEM.ID)
    .from(STORE_ITEM)
    .where(STORE_ITEM.STORE_ID.eq(storeId));

  // Get all store_item_details (all languages) according to the fetched item_ids

  Table<Record5<Long, Long, String, String, Long>> storeItemDetails = this.ctx
    .select(
        STORE_ITEM_DETAILS.ID,
        STORE_ITEM_DETAILS.STORE_ITEM_ID,
        STORE_ITEM_DETAILS.NAME,
        STORE_ITEM_DETAILS.DESCRIPTION,
        STORE_ITEM_DETAILS.STORE_LANGUAGE_ID
        )
    .from(STORE_ITEM_DETAILS)
    .where(STORE_ITEM_DETAILS.STORE_ITEM_ID.in(where))
    .asTable("storeItemDetails");

  // Join the result and get the items for the store in all languages

  SelectOnConditionStep<Record6<Long, Long, Long, String, String, Long>> on = this.ctx
    .select(
        STORE_ITEM.ID,
        STORE_ITEM.STORE_ID,
        storeItemDetails.field(STORE_ITEM_DETAILS.ID),
        storeItemDetails.field(STORE_ITEM_DETAILS.NAME),
        storeItemDetails.field(STORE_ITEM_DETAILS.DESCRIPTION),
        storeItemDetails.field(STORE_ITEM_DETAILS.STORE_LANGUAGE_ID)
        )
    .from(STORE_ITEM)
    .join(storeItemDetails)
    .on(storeItemDetails.field(STORE_ITEM_DETAILS.STORE_ITEM_ID).eq(STORE_ITEM.ID));

  Result<Record6<Long, Long, Long, String, String, Long>> fetch = on.fetch();

  // ..

  return null;
}

A: If you don't need the type safety, don't use it. E.g. the following works just fine, too
// Get all item_ids for the store
SelectConditionStep<?> where = this.ctx...

// Get all store_item_details (all languages) according to the fetched item_ids
Table<?> storeItemDetails = this.ctx...

// Join the result and get the items for the store in all languages
SelectOnConditionStep<Record6<Long, Long, Long, String, String, Long>> on = this.ctx...

The extended type safety is very nice for the compiler when it can perform type inference, e.g. when you're writing:

*

*UNIONs

*IN predicates

*When you fetch your results into lambda expressions

*etc.

You're probably writing all these types down because you're using IDE auto-completion, and your IDE makes the most specific suggestion first. But using wildcards will work just as well, in the above case like this e.g.:
Result<?> fetch = this.ctx
                     // ..
                     .fetch();

for(Record record : fetch) {
    String value = record.getValue(STORE_ITEM_DETAILS.NAME);
    System.out.println(value);
}

I don't think that I'll ever need that but what if I wanted to read 23 columns?

Nothing significant changes. See also the manual:
http://www.jooq.org/doc/latest/manual/sql-execution/fetching/record-n
You can still choose whether to use explicit record typing (no degree on the record):
Result<Record> result = query.fetch();

... or whether you use a wildcard:
Result<?> result = query.fetch();


text:
Q: Suddenly getting: The HTTP request is unauthorized with client authentication scheme 'Negotiate' During a debugging session of a dotnet framework application I started getting:

The HTTP request is unauthorized with client authentication scheme
'Negotiate'. The authentication header received from the server was
'Negotiate,NTLM,Basic realm=...

after launching the web project successfully for hours on IIS.
My .vs/{solutionName}/config/applicationhost.config has windows auth with negotiate:
<windowsAuthentication enabled="true">
    <providers>
           <add value="Negotiate" />
           <add value="NTLM" />
    </providers>
</windowsAuthentication>

Excatly the same settings for IIS:
C:\Program Files (x86)\IIS Express\AppServer\applicationhost.config
What could have happened to cause me to suddenly get this error?
i have tried clearing the cache for ie, but that did not work
Edit: I tried deleting the repo locally and cloning from remote, but this did not solve the issue, so there must be some local configuration outside of the repo that is causing this

A: This was quite the edge case.
I had attempted to login to a web app, let's call it "BT", with incorrect credentials. This caused Credential Manager on Windows to create a Windows credential for BT with the wrong username+password combination.
The project I am working on authorizes towards BT during launch which resulted in the error. I do not understand how, but apparently the credentials in Credential Manager were used instead of the default "use the logged in users credentials". The solution in my case was to modify/delete the windows credential in the Credential Manager


text:
Q: Write a simple cron job to run a Java class How can I write a cron job start from scratch to run a java class or write a cron job class with embedded Java code to run?
and how can I set the timer to run every one minute (for example) that cron job?
Note: totally beginner with Linux

A: Here is a sample sh file running a test job
#!/bin/bash
export JAVA_HOME=/usr/java/jdk1.6.0_07
echo "Java Home is $JAVA_HOME"
export CLASSPATH=.:..:$CLASSPATH:
echo "Path is is $PATH"
echo "CLASSPATH is is $CLASSPATH"
$JAVA_HOME/bin/java  TestJob
echo "$JAVA_HOME/bin/java  TestJob"

then point to it from your cronjob like so
0 5 * * * . $HOME/.profile; /path/to/command/test/job

A: If you are thinking of a simple cron task, you could use TimerTask
Quartz is also famous for cron jobs in Java.


text:
Q: How to create histogram in R with CSV time data? I have CSV data of a log for 24 hours that looks like this:
svr01,07:17:14,'u1@user.de','8.3.1.35'
svr03,07:17:21,'u2@sr.de','82.15.1.35'
svr02,07:17:30,'u3@fr.de','2.15.1.35'
svr04,07:17:40,'u2@for.de','2.1.1.35'

I read the data with  tbl <- read.csv("logs.csv")
How can I plot this data in a histogram to see the number of hits per hour?
Ideally, I would get 4 bars representing hits per hour per srv01, srv02, srv03, srv04.
Thank you for helping me here!

A: I don't know if I understood you right, so I will split my answer in two parts. The first part is how to convert your time into a vector you can use for plotting.
a) Converting your data into hours:
  #df being the dataframe
  df$timestamp <- strptime(df$timestamp, format="%H:%M:%S")
  df$hours <-  as.numeric(format(df$timestamp, format="%H"))
  hist(df$hours)

This gives you a histogram of hits over all servers. If you want to split the histograms this is one way but of course there are numerous others:
b) Making a histogram with ggplot2
 #install.packages("ggplot2")
  require(ggplot2)
  ggplot(data=df) + geom_histogram(aes(x=hours), bin=1) +  facet_wrap(~ server)
  # or use a color instead
  ggplot(data=df) + geom_histogram(aes(x=hours, fill=server), bin=1)

c) You could also use another package:
 require(plotrix)
 l <- split(df$hours, f=df$server)
 multhist(l)

The examples are given below. The third makes comparison easier but ggplot2 simply looks better I think.
EDIT
Here is how thes solutions would look like
first solution:

second solution:

third solution:

A: An example dataset:
dat = data.frame(server = paste("svr", round(runif(1000, 1, 10)), sep = ""),
                 time = Sys.time() + sort(round(runif(1000, 1, 36000))))

The trick I use is to create a new variable which only specifies in which hour the hit was recorded:
dat$hr = strftime(dat$time, "%H")

Now we can use some plyr magick:
hits_hour = count(dat, vars = c("server","hr"))

And create the plot:
ggplot(data = hits_hour) + geom_bar(aes(x = hr, y = freq, fill = server), stat="identity", position = "dodge")

Which looks like:

I don't really like this plot, I'd be more in favor of:
ggplot(data = hits_hour) + geom_line(aes(x = as.numeric(hr), y = freq)) + facet_wrap(~ server, nrow = 1)

Which looks like:

Putting all the facets in one row allows easy comparison of the number of hits between the servers. This will look even better when using real data instead of my random data.


text:
Q: Roblox Studio 1v1 arena spawning I'm making a 1v1 arena game, but I'm having some issues with spawning players in arenas. I want it so when they click on a button on the menu called "Play Random", it will wait until another player clicks it too, and if so, teleports them both to one arena; one player on 1 spawn point and the second player on the second spawn point. When they finish, they should both be teleported to the menu again so others can play at this arena (I've made 3 arenas).
function Click(mouse)
game.Players.LocalPlayer.TeamColor = BrickColor.new("Black")
wait(5)
for i, v in pairs(game.Teams["Waiting"]:GetPlayers())do
    local randomPlayer = game.Teams["Waiting"]:GetPlayers()
    [math.random(1,#game.Teams["Waiting"]:GetPlayers())]
    randomPlayer.TeamColor = BrickColor.new("Lime green") or BrickColor.new("Toothpaste")
end
end

script.Parent.MouseButton1Down:connect(Click)

This is the script for the Play Random button:
Teams
Main Menu

A: first, put the script into starterpack folder, then open the script (the 1v1 script) and click on your keyboard ALT F4 at the same time, then it will force the script to start at that very moment and should work. Good Luck!


text:
Q: Creating a smooth installer for a C# project I've checked the SO but didn't quite find the answer I'm looking for. I've created an add-in and I'm trying to create an installer using VS10, the Publish option. It works sort-of like supposed to but not fully. I've recognized four areas that I'd like to get more clarity on.

*

*Making the set up process (more) quiet and, preferably, unsupervised.

*Including packages not includable by the default publisher.

*Error during the installation due to not trusted manifest.

*Including only the necessary files and packages.

1. Making the set up process (more) quiet and, preferably, unsupervised.
Right now, the installer goes package-by-package and asks the user at five different occasions if the installation of such-and-such package is accepted and if the conditions are accepted. How can I make the installation quiet (and preferably fully unsupervised) so that the user only needs to double click on a setup file and, maybe, only answer OK once?
2. Including packages not includable by the default publisher.
One of the packages (WIF) is not listed in the list of includables but is still needed for the add-in to run. As of now, I need to ask the end user to manually install WIF before the rest of the installation (that's troublesome already, as described in the previous item) can continue. How can I package it all together?
3. Error during the installation due to not trusted manifest.
I'm getting errors during the installation complaining that the zone Computer doesn't trust my add-on. It's something like: "System.Security.SecurityException: Customized functionality in this application will not work because the certificate used to sign the deployment manifest for OutlookAddIn1 or its location is not trusted." in Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInTrustEvaluator.VerifyTrustPromptKeyInternal and I have no idea how to handle it. Any suggestions?
4. Including only the necessary files and packages.
I'm not entirely sure how to check what packages that are necessary to include in order to guarantee my application to run. I can do it by trial-and-error or guess that the DLLs that are referenced are all that's needed but can i really trust that? I prefer not to get a morning surprise after I've sent the files to the end user.

A: I'm guessing you're run into bigger problems than so but, just in case you got lazy and hasn't checked with Google, there's an installer project inside Visual Studio 2010. I've only used it once, long time ago and under supervision so I'm not going to preach about it but here are the links to a walk-through.

*

*This is how you set up an add-in.

*This is how you set up an installation project.


text:
Q: Check for differences between RDF models with non-deterministic (UUID-based) URIs? A college and I are individually instantiating electronic health records into triples.  We'd like to compare our sets of 10k to 100k triples to see if they have the same shapes.
As a policy, I create URIs based on UUIDs, so nothing semantic is embedded in them.  I'd like to stick with this policy, as my college and I are really trying to holistically compare existing workflows.
I know how to compare two RDF files in TopBraid Composer, but I don't think it will be useful if we have the same data patterns but different URIs.  I store my triples in Ontotext GraphDB but am glad to use any other tool.
For example, the triples about person ...fe54977c174a and person ...4bcdc1c8abf9 should be considered equivalent, but ...fe54977c174a and ...ae00dc86b3bb should not.  Is this feasible?
I would prefer not to spot-check with hand-crafted SPARQL ASK statements.
@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/4f79ea05-2358-4f43-a335-fe54977c174a>
  a <http://example.com/Person> ;
  ns0:gender ns0:Male ;
  ns0:participatesIn ns0:5d2dfc7b-994c-4933-b787-f7971dae397c .

ns0:5d2dfc7b-994c-4933-b787-f7971dae397c
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:a129ca96-c6d2-4a07-a4eb-4cf9ce23a314 .

ns0:a129ca96-c6d2-4a07-a4eb-4cf9ce23a314
  a ns0:Diagnosis ;
  ns0:mentions ns0:Headache .

has the same shape as this (despite the different URIs):
@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/a740d254-084c-4621-b06d-4bcdc1c8abf9>
  a <http://example.com/Person> ;
  ns0:gender ns0:Male ;
  ns0:participatesIn ns0:060d2091-b4f7-406d-ab0d-75b39b400823 .

ns0:060d2091-b4f7-406d-ab0d-75b39b400823
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:bc549711-ed9d-4db6-8cf9-d43022903ef7 .

ns0:bc549711-ed9d-4db6-8cf9-d43022903ef7
  a ns0:Diagnosis ;
  ns0:mentions ns0:Headache .

but this is structurally different (due to the different gender and diagnosis mention):
@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/aa3a977a-999a-4c5c-9524-ae00dc86b3bb>
  a <http://example.com/Person> ;
  ns0:gender ns0:Female ;
  ns0:participatesIn ns0:b31a62a5-337a-454d-a637-85aefef26684 .

ns0:b31a62a5-337a-454d-a637-85aefef26684
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:6566d543-773e-4649-b589-66eb3d0f3165 .

ns0:6566d543-773e-4649-b589-66eb3d0f3165
  a ns0:Diagnosis ;
  ns0:mentions ns0:Nausea .

A: Eclipse Rdf4j (bundled with GraphDB) contains a  graph isomorphism utility: Models.isomorphic. By default it only does blank node to blank node mappings. So you have two options:

*

*do a replace of each IRI in your graphs with a (dictionary-mapped) blank node. This should be fairly easy to do with a HashMap and a bit of looping or streaming-magic.

*have a look at the code for the Models utility and adapt the bit where it does blank node mapping to do IRI mapping instead.