text:
Q: What are good resources providing a history of statistics?
*

*What are good online or offline resources that give an overview of the history of statistics and the main breakthrough in statistics until now?

I have read the page on History of Statistics on Wikipedia.

A: David Salsburg "The Lady Tasting Tea: How Statistics Revolutionized Science in the Twentieth Century" is an easy and entertaining read. It might not be focused on breakthroughs per se, but it tells the story featuring the Pearsons, Gosset, Fisher, Neyman and others.

A: Read Stephen Stigler's books, The History of Statistics and Statistics on the Table.  This will give you an overview of the field from 1750 through about 1930.  For pre-1750 history, Anders Hald is well known (but I haven't read his work).
The edited volumes of seminal papers, Breakthroughs in Statistics, provide reprints of key papers along with short introductions by eminent modern statisticians explaining the meaning and impacts of these papers.
There are incredible primary resources, especially in Europe, for researching statistical history, especially the more difficult-to-find sources prior to 1750.  For example, you can find Fermat's collected works, Huygens' 17th century treatise on probability,  and high-resolution scans of 16th and 15th century treatises, such as Tartagia's General trattato di numeri, et misure.  Be prepared to read old French, old Italian, Latin, and even Dutch.  (Those with a modest command of the modern versions of these languages won't have difficulties.)
Additional information can be obtained at the Journal for the History of Probability and Statistics and in early reviews of the history of probability and statistics.  But your best bet is to search.  Searches turned up all these resources several years ago, and several of them I had to search for again because their URLs had changed.

A: I recommend the work of Stephen Stigler.

A: In addition to Stigler's excellent work, there is a book The Science of Conjecture: Evidence and Probability before Pascal by James Franklin; very interesting, less technical than Stigler's books, at least in part because the material wasn't as technical.


text:
Q: ELASTICSEARCH - Aggregations not working on string field Elastic search extraction query is returning expected results in hints section of output but aggregation on field returning empty response
output without aggregation
{
    "_shards": {
        "total": 45,
        "failed": 0,
        "successful": 45,
        "skipped": 0
    },
    "hits": {
        "hits": [
            {
                "_index": "logstash-wander-2022.08.17",
                "_type": "fluentd",
                "_source": {
                    "outboundResponseStatus": "SERVICE_UNAVAILABLE"
                },
                "_id": "Y2NlNjkzZmEtNjZlMi00NWY4LTllNWUtOWZmNWRhMjRkMzA3",
                "sort": [
                    1660695790244
                ],
                "_score": null
            },
            {
                "_index": "logstash-wander-2022.08.17",
                "_type": "fluentd",
                "_source": {
                    "outboundResponseStatus": "CONFLICT"
                },
                "_id": "OWNmZTFiOWEtYWQ2Mi00OGViLWFmY2EtMGQ4ZDg1NzRiYWNk",
                "sort": [
                    1660695781810
                ],
                "_score": null
            }
        ],
        "total": 25,
        "max_score": null
    },
    "took": 506,
    "timed_out": false
}

But adding below aggregation along with query returning empty response
"aggregations": {
        "outboundResponseStatus": {
            "significant_terms": {
                "field": "outboundResponseStatus",
                "keyed": true
            }
        }
    }

Below is the query
{
    "size": 500,
    "query": {
        "bool": {
            "must": [
                {
                    "query_string": {
                        "query": "search string",
                        "default_field": "*",
                        "fields": [],
                        "type": "best_fields",
                        "default_operator": "or",
                        "max_determinized_states": 10000,
                        "enable_position_increments": true,
                        "fuzziness": "AUTO",
                        "fuzzy_prefix_length": 0,
                        "fuzzy_max_expansions": 50,
                        "phrase_slop": 0,
                        "analyze_wildcard": true,
                        "escape": false,
                        "auto_generate_synonyms_phrase_query": true,
                        "fuzzy_transpositions": true,
                        "boost": 1
                    }
                },
                {
                    "match_phrase": {
                        "message": {
                            "query": "search string",
                            "slop": 0,
                            "zero_terms_query": "NONE",
                            "boost": 1
                        }
                    }
                },
                {
                    "range": {
                        "@timestamp": {
                            "from": "now-10m",
                            "to": "now",
                            "include_lower": true,
                            "include_upper": true,
                            "format": "epoch_millis",
                            "boost": 1
                        }
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1
        }
    },
    "version": true,
    "_source": {
        "includes": [
            "outboundResponseStatus",
            "outboundUri",
            "message"
        ],
        "excludes": []
    },
    "stored_fields": "*",
    "script_fields": {},
    "sort": [
        {
            "@timestamp": {
                "order": "desc",
                "unmapped_type": "boolean"
            }
        }
    ]
}

How to get aggregations based on field in hints results?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Data isolation between pure abstract class against its implmentation and the true meaning of pure abstract class? In Bjarne Stroustrup's book "The C++ Programming Language", it is stated that a derived class from a super class in a class hierarchy, in many case, gets access to the data of the super class. The book suggests this is a problem, because the sharing between "two related, but different, sets of data is asking for trouble. Sooner or later someone will get them out of sync. Also, experience shows that novice programmers tend to mess with protected data in ways that are unnecessary and that cause maintenance problems". The question here is, how can having access to private data from the ancestor class is asking for trouble? It sounds like having inherited assets from your parent is a bad deal.
As a consequence, the pure abstract class mechanism allows the separation between the abstract class and its implementation. Note that the implementation includes data members, because if the data members are defined in an abstract class, the abstract class contains implementation details (the defined members), thus it is not well decoupled between abstraction and the implementation. Why is such separation needed? One of the reason, as stated in here, is "a way of forcing a contract between the class designer and the users of that class. The users of this class must declare a matching member function for the class to compile." Another important reason, as stated in the book, is to protect against changes from the implementation. Having an abstract class hierarchy, you can protect against the changes which requires compilation of an entire class hierarchy.
For example, if you have a normal class, and the class contains 10 data members and 20 member functions, and is inherited by a dozen of classes with several layers below the root class. A few changes to the implementation of member functions (function signature remains unchanged) of the root class, and you have to recompile the entire class hierarchy to apply changes its terminal classes, otherwise the program breaks. With abstract class hierarchy, unless the function signature is changed, if an implementation of a terminal class changes, only that terminal class needs to be recompiled. Therefore, most of the code are protected to the maximum. Is my understanding correct?
I think his example (the Ival_box example) in combination with the Bridge Design Pattern tries, and is powerful, since Bridge Pattern leaves the abstract tree completely, and have another class hierarchy for implementation. Pure abstract class can be consider equivalent to Interface in Java, except in Java the explanation usually is the abstract class can be inherited once, while interface allow multiple inheritances, thus having shared behaviors encapsulated in a shared interface between multiple classes. That answer, I think, is not valid in this context, since C++ allows multiple inheritance.
The last question is, how is a derived class compiled and exist in the binary image? Does the compiler fill the inherited information into the derived class, considered it to be an isolated class afterward and then compiled? (Similar to preprocessing)
tl;dr:
How can having access to private data from the ancestor class is asking for trouble?
Is pure abstract class (aka Interface in Java) a way to protect source code against changes, with the separation of abstraction tree and implementation tree?
How is abstract class/super class compiled in C++? Does it turn the derived class into a single class by filling in the information from superclass, then compiles

A: Meta-note: Your questions could have been asked as multiple, separate questions.

how can having access to private data from the ancestor class is asking for trouble?

Non-orthogonality. When the protected part of the ancestor class is changed, all derived classes have to be changed, too. This is error-prone, because the programmer changing the ancestor might not have the derived classes in his mental scope.

With abstract class hierarchy, unless the function signature is changed, if an implementation of a terminal class changes, only that terminal class needs to be recompiled.

Technically correct, but you are missing the main point. Recompilation is not nice, but also not terribly costly, because computers do it. The real cost is human work induced by non-orthogonality. When a class has a public or protected data member, people are going to use it, and when it changes, things break and have to be fixed.
BTW, "is inherited by a dozen of classes with several layers below the root class" is usually a sign of bad design. Keep inheritance hierarchies flat and concise. Prefer members over base classes: When you decide to use functionality of a class Foo in a class Bar, and there is no compelling reason to let Bar inherit Foo, rather use a member of type Foo.

That answer, I think, is not valid in this context, since C++ allows multiple inheritance.

In C++, the distinction between interfaces and classes is not reified (made into a thing), but still used. It is very useful in many cases to build interfaces, e.g classes consisting of abstract virtual functions, because they avoid many of the troubles of the much-dreaded multiple inheritance.

how is a derived class compiled and exist in the binary image?

This is compiler-specific. Don't worry about it just yet - first understand the language, then it's implementation.

A: Your understanding regarding the need to recompile everything if an exposed member of the root class changes is correct.
Also, your understanding of how a derived class is compiled is correct. As a matter of fact, the first C++ compiler was just a fancy C preprocessor.
Having access to private data from the ancestor class is asking for trouble because this way the descendants are built dependent on implementation details of the ancestor. If the ancestor needs to change the way it works, (even if its interface and functionality is to remain the same,) all descendants break.

A:
How can having access to private data from the ancestor class is
  asking for trouble?

Imagine if an ancestor class has certain features, state, and methods that it maintains. Assume that certain combinations of member data are invalid (aka violate the class invariants). Then imagine that a child class could change the ancestor data without maintaining the invariants. You wind up in a case with invalid state and not only that, the parent doesn't even know what happened so it has no chance to throw an exception or recover in any way. Not only that but even if it ends up in a valid state the ancestor class may still be "confused" about the state its in if it's been mutated outside the class (public/protected) interface.

Is pure abstract class (aka Interface in Java) a way to protect source
  code against changes, with the separation of abstraction tree and
  implementation tree?

A pure abstract class is used to represent an interface concept. It doesn't inherently protect source code against changes. Often as long as the interface is appropriate and the implementation can be written to the interface easily, client code won't have to change although it may have to rebuild. The separation of interface and implementation is definitely be desirable and can be improved further with the use of a non-virtual interface that delegates to a virtual pimpl implementation (or by using the nonvirtual interface pattern).

How is abstract class/super class compiled in C++? Does it turn the
  derived class into a single class by filling in the information from
  superclass, then compiles

The superclass is treated as a portion of the derived class. The precise details of this vary slightly by implementation.

A: Having worked with several O.O. languages, there are a few things that I have learn, that help to program in C++. And that apply to your question.
Its a long, boring question, but, it may worth the time.
Concrete Classes, first
I usually start with concrete classes, and when several classes share common features, as methods or fields, then, I design a common superclass. Many developers ( in any language ) seems to jump straight to doing superclasses, and later child concrete classes.
Design of O.O. programs, may seem that superclasses, wheter abstract or not, where designed first. But, in real world, most classes start as concrete, and the superclasses come later. Even if in design, U.M.L. or code superclasses appear first.
So this example, including data & methods:

//  ....

#include <iostream>

class Employee {
  public:
    Employee();                         // constructor;

    void SayHello();
    void Work();
};

class Student {
  public:
    Student();                          // constructor;

    void SayHello();
    void Study();
};

//  ....

Becomes this:

//  ....

#include <iostream>

class Person {
  public:
    Person();                         // constructor;

    virtual void SayHello() = 0;
};

class Employee {
  public:
    Employee();                         // constructor;

    virtual void SayHello();
    void Work();
};

class Student {
  public:
    Student();                         // constructor;

    virtual void SayHello();
    void Study();
};

//  ....

These previous example only shows methods, not data, but the same principle applies.
Avoid private fields or methods
Something, that I usually do, its to avoid "private" sections. If I need to hide, I use "protected", instead.
So, this:

//  ....

#include <iostream>
#include <cstring>

class Person {
  private:
    char[512] Name;

  public:
    Person();                         // constructor;

    virtual void SayHello() = 0;
};

//  ....

Becomes this:

//  ....

#include <iostream>
#include <cstring>

class Person {
  protected:
    char[512] Name;

  public:
    Person();                         // constructor;

    char[512] Name;

    virtual void SayHello() = 0;
};

//  ....

If you are working with a class, abstract or not, you may consider that, you or other developers may code a subclass and access the parent class fields or methods.
Use properties (with accesor methods), instead, of plain data fields
Some thing that really bothers me, its the absence of "real properties", in "C++" & "Java".
One of the ways to access, modify, control or update data from an object, its thru, properties, that is, fields accesed using methods called accesors.
Properties can be implemented in C++, using templates, or just coding methods by hand.
So this, direct non isolated field example:

//  ....

#include <iostream>
#include <cstring>

class Person {
  public:
    Person();                         // constructor;

    char[512] Name;

    virtual void SayHello() = 0;
};

int main (...) {
  Person thisPerson = new Person();

  strcpy(thisPerson.Name, "John Doe");

  cout << thisPerson.Name << "\n";

  delete thisPerson;
}

//  ....

Becomes, this isolated property example:

//  ....

#include <iostream>
#include <cstring>

class Person {
  protected:
    // isolated data field
    char[512] Name;

  public:
    Person();                         // constructor;

    virtual void SayHello() = 0;

    // public data field accesor reader method or "getter"
    const char* getName();

    // public data field accesor writer method or "setter"
    void setName(const char* AName);
};

const char Person::getName() {
  char char* Result = this.FName;

  return Result;
}

void setName(const char* AName) {
  bool IsValid = false;

  // do some validation before actually modifing field
  // ...

  if (IsValid)
  {
    strcpy(this.FName, AName);
  }
}

int main (...) {
  Person thisPerson = new Person();

      // should be read as "thisPerson.Name = "John Doe";"
  thisPerson.setName("John Doe");

      // should be read as "cout << thisPerson.Name;"
  cout << thisPerson.getName() << "\n";

  delete thisPerson;
}

//  ....

Many C++ developers, doesn't like "properties", because, of lack of control. I think you should used to access data as your question, but as any feature, should be "properly used".
Properties accesor methods should be virtual
In some languages the concept of properties can be implemented, accesing directly a data field of an object, reading and writing thru methods, or mixing both approaches. To make things more complicated, methods can be "virtual" or "non virtual".
When I use properties, I always use virtual methods to access them. There is a penanalty in speed & memory, but, it worths it. Properties with virtual overriden methods allows to control & access the data of objects.
Summary
Your question relate how to implement data, how to isolate data, & how access data in a class, and how to implement such features in child classes.
I have read similar questions in Stackoverflow, but, I get to the conclusion, that several questions relate to the absence of "real properties" in C++.
You may want to manage your data acces & isolation thru the use of "properties".
And, may want to try to learn other O.O., where the concept of "properties" its implemented, such as: VB (.NET), C#, Delphi, D or Vala.
And later, try to implement, this concept, in your C++ programs, when required. I have class in C++ that have plain data fields, fields treated as "properties", like Java does with accesor methods, or mixing both, when required.
That doesn't mean you rewrite the application you are working, or trying to probe which programming language its better, just learning something from others programming languages that may help your work.


text:
Q: ASP.Net MVC And Validation Messages I'm trying to get to grips with the Validation messages in ASP.Net MVC. I have the following view
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"  Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

Create User

    <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

    <% using (Html.BeginForm()) {%>

        <fieldset>
            <legend>Fields</legend>

                Username : <%= Html.TextBox("Username") %>

                Forename : <%= Html.TextBox("Forename") %>
                <%= Html.ValidationMessage("Forename", "*") %>

                Surname : <%= Html.TextBox("Surname","") %>
                <%= Html.ValidationMessage("Surname", "*") %>

                <input type="submit" value="Create" />

        </fieldset>

    <% } %>

        <%=Html.ActionLink("Back to List", "Index") %>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
    <title><%= ViewData["ProjectTitle"] %> - Create User</title>
</asp:Content>

I then have this post method in my controller that is supposed to display an error message if the surname field is blank, I realise there is no other logic in this function im just trying to get my head round validation.
  [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection formValues)
    {
        if (formValues["Surname"] == string.Empty)
            ViewData.ModelState.AddModelError("Surname", "No way");
        return View("Create");
    }

When I run this and click to save a user the Create method runs fine and adds the error, but then the application falls over, it hightlights the line in the view that creates the surname textbox and says "Not set to an instance of object". It runs fine if I put something in the surname textbox and the error does not get added.
I'm guessing I'm missing something really simple but can work out what.
Any ideas?
Thanks
Gavin

A: Did you try to remove the second argument on TextBox? It will look for the empty key in ViewData.
the line below
Surname : <%= Html.TextBox("Surname","") %>

needs to be like
Surname : <%= Html.TextBox("Surname") %>

A: I think I've found a solution adding the setModelValue line below to my method above the line that sets the error makes it work.
            ModelState.SetModelValue("Username", new ValueProviderResult(ValueProvider["Username"].AttemptedValue, formValues["Username"], System.Globalization.CultureInfo.CurrentCulture));
            ModelState.AddModelError("Username", "Invalid Username");

If anyone could explain why this works that would be great, If not I'll accept this answer tommorow.  I'd rather not have to do this for ever field I validate unless I really have to.

A: You should test for Null or empty in your if statement,
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string Username, string Surname,  string Forename)
{
  if (String.IsNullOrEmpty(Surname))
  {
     ModelState.AddModelError("Surname", "No way");
  }

  return View();
}


text:
Q: How to convert bytearray in python 2.7 to decimal string? I have the following byte array
>>> string_ba
bytearray(b'4\x00/\t\xb5')

which is easily converted to hex string with the next 2 lines:
hex_string = [chr(x).encode('hex') for x in string_ba]
hex_string = ''.join(hex_string)

that return
>>> hex_string.lower()
'34002f09b5'

which is expected. (This is an RFID card signature)
I convert this to decimal by doing the above and then converting from hex string to decimal string (padded with zeroes) with the next line. I have a limit of 10 characters in string, so I'm forced to remove the first 2 characters in the string to be able to convert it to, at most, 10 character decimal number.
dec_string = str(int(hex_string[2:], 16)).zfill(10)
>>> dec_string
'0003082677'

which is correct, as I tested this with an online converter (hex: 002f09b5, dec: 3082677)
The question is, if there's a way to skip converting from bytearray to hex_string, to obtain a decimal string. In other words to go straight from bytearray to dec_string
This will be running on Python 2.7.15.
>>> sys.version
'2.7.15rc1 (default, Apr 15 2018, 21:51:34) \n[GCC 7.3.0]'

I've tried removing the first element from bytearray and then converting it to string directly and joining. But this does not provide the desired result.
string_ba = string_ba[1:]
test_string = [str(x) for x in string_ba]
test_dec_string = ''.join(test_string).zfill(10)

>>> test_dec_string
'0000479181'

To repeat the question is there a way to go straight from bytearray to decimal string

A: You can use struct library to convert bytearray to decimal. https://codereview.stackexchange.com/questions/142915/converting-a-bytearray-into-an-integer maybe help you

A: A number (let's call it X) consisting of n digits (in a base, let's refer to it as B) is written as:
Dn-1Dn-2Dn-3...D2D1D0 (where each Di is a digit in base B)
and its value can be computed based on the formula:
VX = Σin=-01(Bi * Di) (notice that in this example the number is traversed from right to left - the traversing sense doesn't affect the final value).
As an example, number 2468 (B10) = 100 * 8 + 101 * 6 + 102 * 4 + 103 * 2 (= 8 + 60 + 400 + 2000).
An ASCII string is actually a number in base 256 (0x100), where each char (byte) is a digit.
Here's an alternative based on the above:

*

*It only performs mathematical operations on integers (the conversion to string is done only at the end)

*The traversing sense (from above) is helpful with the restriction (final (decimal) number must fit in a number of digits, and in case of overflow the most significant ones are to be ignored)

*The algorithm is simple, starting from the right, compute the partial number value, until reaching the maximum allowed value, or exhausting the number digits (string chars)

code.py:
#!/usr/bin/env python

import sys

DEFAULT_MAX_DIGITS = 10

def convert(array, max_digits=DEFAULT_MAX_DIGITS):
    max_val = 10 ** max_digits
    number_val = 0
    for idx, digit in enumerate(reversed(array)):
        cur_val = 256 ** idx * digit
        if number_val + cur_val > max_val:
            break
        number_val += cur_val
    return str(number_val).zfill(max_digits)

def main():
    b = bytearray("4\x00/\t\xb5")
    print("b: {:}\n".format(repr(b)))
    for max_digits in range(6, 15, 2):
        print("Conversion of b (with max {:02d} digits): {:}{:s}".format(
            max_digits, convert(b, max_digits=max_digits),
            " (!!! Default case - required in the question)" if max_digits == DEFAULT_MAX_DIGITS else ""
        ))

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

Outpput:

(py_064_02.07.15_test0) e:\Work\Dev\StackOverflow\q054091895>"e:\Work\Dev\VEnvs\py_064_02.07.15_test0\Scripts\python.exe" code.py
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32

b: bytearray(b'4\x00/\t\xb5')

Conversion of b (with max 06 digits): 002485
Conversion of b (with max 08 digits): 03082677
Conversion of b (with max 10 digits): 0003082677 (!!! Default case - required in the question)
Conversion of b (with max 12 digits): 223341382069
Conversion of b (with max 14 digits): 00223341382069


text:
Q: Liquibase diff generate wrong primary keys I have a problem when I use liquibase to generate my changeset on an entity with @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
pom.xml
<plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>3.6.2</version>
            <configuration>
                <!--<propertyFile>src/main/resources/liquibase.properties</propertyFile>-->
                <username>synchroad_adm</username>
                <password>changeme</password>
                <url>jdbc:postgresql://localhost:5432/synchroad?currentSchema=synchroad_adm</url>
                <referenceDefaultSchemaName>synchroad_adm</referenceDefaultSchemaName>
                <defaultSchemaName>synchroad_adm</defaultSchemaName>
                <referenceUrl>hibernate:spring:com.demo?dialect=org.hibernate.dialect.PostgreSQLDialect</referenceUrl>
                <driver>org.postgresql.Driver</driver>
                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                <changeLogFile>${project.basedir}/src/main/resources/db/liquibase/app/db.changelog.xml</changeLogFile>
                <diffChangeLogFile>target/changelog-diff.xml</diffChangeLogFile>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.liquibase.ext</groupId>
                    <artifactId>liquibase-hibernate5</artifactId>
                    <version>3.6</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-jpa</artifactId>
                    <version>2.0.4.RELEASE</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                    <version>${spring.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                    <version>${spring.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                    <version>${spring.version}</version>
                </dependency>
                <dependency>
                    <groupId>javax.validation</groupId>
                    <artifactId>validation-api</artifactId>
                    <version>2.0.1.Final</version>
                </dependency>
                <dependency>
                    <groupId>org.javassist</groupId>
                    <artifactId>javassist</artifactId>
                    <version>3.23.1-GA</version>
                </dependency>
            </dependencies>
        </plugin>

Class java
@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class MyTable {

    @Id
    @TableGenerator(name = "agent_generator", table = "agent_ids", pkColumnName = "seq_id", valueColumnName = "seq_value")
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "agent_generator")
    @Column(name = "id")
    private Long id;
}

@Entity
@Table(name = "table_one")
public class TableOne extends MyTable {

}

@Entity
@Table(name = "table_two")
public class TableTwo extends MyTable {

}

I am using Liquibase to generate my changeset.
mvn clean install liquibase:diff

but Liquibase generate 2 createTable with same primaryKeyName
diff.xml
<changeSet author="mvallet (generated)" id="1535684993363-2">
  <createTable tableName="table_one">
    <column name="id" type="BIGINT">
      <constraints primaryKey="true" primaryKeyName="MyTablePK"/>
    </column>
  </createTable>
</changeSet>
<changeSet author="mvallet (generated)" id="1535684993363-2">
  <createTable tableName="table_two">
    <column name="id" type="BIGINT">
      <constraints primaryKey="true" primaryKeyName="MyTablePK"/>
    </column>
  </createTable>
</changeSet>

So when I launch
mvn clean install liquibase:update

I have an error Error: ERROR: relation "MyTablePK" already exists.
If I do not use liquibase but I let do hibernate to generate the tables I have not the problem.
Anyone have an idea? thx

A: try remove the @Entity from MyTable class
if you are using hibernate what is the PKN generated?
why u need to persist MyTable?


text:
Q: A classical optimization problem - what's the *most* general approach? Consider the following problem:
A factory has to produce some amount of a certain mixture, which is made of three substances, A, B and C. This mixture should contain at least 30 kg of substance A, at least 20 kg of substance B and at most 25 kg of substance C. The factory is going to use two intermediate products P1 and P2. Intermediate product P1 is 70% substance A, 10% substance B and 20% substance C, whereas intermediate product P2 -- 30% of A, 30% of B and of C. The price of one kilogramme of these intermediate products is 25 dollars and 15 dollars, respectively.
The question is: how much of intermediate products should the factory buy to fulfill the requirements and minimize the cost?
My approach is as follows: let's denote the amount of intermediate products P1 and P2 by $X$ and $Y$ respectively. The cost of the purchase is then:
$$ 25\cdot X+15\cdot Y$$
We have to find the minimum of this function with the following constraints:
$$0.7\cdot X+0.3\cdot Y\ge 30$$
$$0.1\cdot X+0.3\cdot Y\ge 20$$
$$0.2\cdot X+0.3\cdot Y\le 25$$
My question is: how does one determine the minimum of such function knowing the constraints? Is there any method other than ''plot the inequalities and try to fit the line''?

A: Let's scale the numbers to avoid fractions:
\begin{align}
\min\quad &25x + 15y\\
\mathrm{s.t.}\quad &7x+3y\geqslant30 \tag 1\\
\quad &x + 3y \geqslant20 \tag 2\\
\quad &2x+3y\leqslant 25 \tag 3\\
\quad &x,y\geqslant0.
\end{align}
If $x=0$, from constraint $(1)$ we see that $y\geqslant 10$, which violates constraint $(3)$. If $y=0$, then from constraint $(2)$ we see that $x\geqslant 20$, which again violates constraint $(3)$. Because there are two variables, there must be at least two binding constraints. There are three possibilities - $(1)$ and $(2)$, $(1)$ and $(3)$, and $(2)$ and $(3)$. Only the first is a feasible solution, and hence we solve
\begin{align}
7x + 3y&=30\\
x+3y&=20
\end{align}
which yields $x=\frac53$, $y=\frac{55}9$ for an objective value of $\frac{400}3$.


text:
Q: Issues Binding ContextMenu to ItemsSource I want to bind my ListView's ContextMenu to an ItemSource 'GetContextMenu' specified in the ViewModel which the entire UserControl is using for it's DataContext. I have tried specifying it in multiple different ways, including using the RelativeSource and currently trying to bind by name to either the ClientsListView or ClientsTab. All which I have tried failed. The specific error I am getting is:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=ClientsListView'. BindingExpression:Path=DataContext.GetContextMenu; DataItem=null; target element is 'ContextMenu' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')

It's worth mentioning that my binding for the SelectionChanged event that you'll see below in the XAML works just fine, so I really have no clue what's going on.
<UserControl x:Class="ServerUI.Views.MainWindowViews.ClientsTabView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800"
             Name="ClientsTab">
    <Grid>
        <ListView x:Name="ClientsListView" ItemsSource="{Binding ClientViewModels}">
            <ListView.ContextMenu>
                <ContextMenu ItemsSource="{Binding ElementName=ClientsListView, Path=DataContext.GetContextMenu}"/>
            </ListView.ContextMenu>
            <ListView.View>
                <GridView>
                    <GridViewColumn x:Name="OnlineStatusHeader" Header="Online Status" DisplayMemberBinding="{Binding Online}" />
                    <GridViewColumn x:Name="NameHeader" Header="Computer/User" DisplayMemberBinding="{Binding ComputerUser}" />
                </GridView>
            </ListView.View>
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding UpdateSelectedClientsCommand}" CommandParameter="{Binding ElementName=ClientsListView, Path=SelectedItems}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ListView>
    </Grid>
</UserControl>

namespace ServerUI.ViewModels.MainWindowViewModels
{
    public class ClientsTabViewModel : ObservableObject
    {
        public ObservableCollection<ClientViewModel> ClientViewModels { get; } = new();
        public IEnumerable<ClientViewModel> SelectedClients { get; set; }

        public ICommand CloseConnectionCommand
            => new RelayCommand(() => ExecuteCloseConnectionCommand());

        public ICommand ConfigureClientCommand
            => new RelayCommand(() => ExecuteConfigureClientCommand());

        public ICommand UpdateSelectedClientsCommand
            => new RelayCommand<object>(e => ExecuteUpdateSelectedClientsCommand(e));

        public ICommand OpenServerModuleCommand
            => new RelayCommand<object>(e => ExecuteOpenServerModuleCommand(e));

        public List<FrameworkElement> GetContextMenu
        {
            get
            {
                List<FrameworkElement> menuItems = new();

                menuItems.Add(new MenuItem() { Header = "Configure Client", Command = ConfigureClientCommand });
                menuItems.Add(new MenuItem() { Header = "Close Connection", Command = CloseConnectionCommand });
                menuItems.Add(new Separator());

                foreach(var client in SelectedClients)
                {
                    foreach(var module in client.Client.LoadedServerModules)
                    {
                        menuItems.Add(new MenuItem() { Header = module.ModuleName, Command = OpenServerModuleCommand, CommandParameter = module });
                    }
                }

                return menuItems;
            }
        }

        void ExecuteUpdateSelectedClientsCommand(object param)
        {
            System.Collections.IList items = (System.Collections.IList)param;
            SelectedClients = items.Cast<ClientViewModel>();
        }

A: You can try like this:
<ListView Tag="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">
    <ListView.ContextMenu>
        <ContextMenu
            DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"
            ItemsSource="{Binding GetContextMenu}"
            />
    </ListView.ContextMenu>
</ListView>


text:
Q: Symbolizing lines based average value of point (start, middle, end) in ArcGIS Desktop? There are three points in each line of road network, each point has weight and I want to give the average weight of these three points to corresponding line and symbolized all the lines accordingly. Any idea how to do it?! To remind you both points and lines are two different shape files.
Point values are centrality measures!


text:
Q: SLURM: Embarrassingly parallel program inside an embarrassingly parallel program I have a complex model written in Matlab. The model was not written by us and is best thought of as a "black box" i.e. in order to fix the relevant problems from the inside would require rewritting the entire model which would take years.
If I have an "embarrassingly parallel" problem I can use an array to submit X variations of the same simulation with the option #SBATCH --array=1-X. However, clusters normally have a (frustratingly small) limit on the maximum array size.
Whilst using a PBS/TORQUE cluster I have got around this problem by forcing Matlab to run on a single thread, requesting multiple CPUs and then running multiple instances of Matlab in the background. An example submission script is:
#!/bin/bash
<OTHER PBS COMMANDS>
#PBS -l nodes=1:ppn=5,walltime=30:00:00
#PBS -t 1-600

<GATHER DYNAMIC ARGUMENTS FOR MATLAB FUNCTION CALLS BASED ON ARRAY NUMBER>

# define Matlab options
options="-nodesktop -noFigureWindows -nosplash -singleCompThread"

for sub_job in {1..5}
do
    <GATHER DYNAMIC ARGUMENTS FOR MATLAB FUNCTION CALLS BASED ON LOOP NUMBER (i.e. sub_job)>
    matlab ${options} -r "run_model(${arg1}, ${arg2}, ..., ${argN}); exit" &
done
wait
<TIDY UP AND FINISH COMMANDS>

Can anyone help me do the equivalent on a SLURM cluster?

*

*The par function will not run my model in a parallel loop in Matlab.

*The PBS/TORQUE language was very intuitive but SLURM's is confusing me. Assuming a similarly structured submission script as my PBS example, here is what I think certain commands will result in.

*

*--ncpus-per-task=5 seems like the most obvious one to me. Would I put srun in front of the matlab command in the loop or leave it as it is in the PBS script loop?

*--ntasks=5 I would imagine would request 5 CPUs but will run in serial unless a program specifically requests them (i.e. MPI or Python-Multithreaded etc). Would I need to put srun in front of the Matlab command in this case?

A: I am not a big expert on array jobs but I can help you with the inner loop.
I would always use GNU parallel to run several serial processes in parallel, within a single job that has more than one CPU available. It is a simple perl script, so not difficult to 'install', and its syntax is extremely easy. What it basically does is to run some (nested) loop in parallel. Each iteration of this loop contains a (long) process, like your Matlab command. In contrast to your solution it does not submit all these processes at once, but it runs only N processes at the same time (where N is the number of CPUs you have available). As soon as one finishes, the next one is submitted, and so on until your entire loop is finished. It is perfectly fine that not all processes take the same amount of time, as soon as one CPU is freed, another process is started.
Then, what you would like to do is to launch 600 jobs (for which I substitute 3 below, to show the complete behavior), each with 5 CPUs. To do that you could do the following (whereby I have not included the actual run of matlab, but that trivially can be included):
#!/bin/bash
#SBATCH --job-name example
#SBATCH --out job.slurm.out
#SBATCH --nodes 1
#SBATCH --ntasks 1
#SBATCH --cpus-per-task 5
#SBATCH --mem 512
#SBATCH --time 30:00:00
#SBATCH --array 1-3

cmd="echo matlab array=${SLURM_ARRAY_TASK_ID}"

parallel --max-procs=${SLURM_CPUS_PER_TASK} "$cmd,subjob={1}; sleep 30" ::: {1..5}

Submitting this job using:
$ sbatch job.slurm

submits 3 jobs to the queue. For example:
$ squeue | grep tdegeus
         3395882_1     debug  example  tdegeus  R       0:01      1 c07
         3395882_2     debug  example  tdegeus  R       0:01      1 c07
         3395882_3     debug  example  tdegeus  R       0:01      1 c07

Each job gets 5 CPUs. These are exploited by the parallel command, to run your inner loop in parallel. Once again, the range of this inner loop may be (much) larger than 5, parallel takes care of the balancing between the 5 available CPUs within this job.
Let's inspect the output:
$ cat job.slurm.out

matlab array=2,subjob=1
matlab array=2,subjob=2
matlab array=2,subjob=3
matlab array=2,subjob=4
matlab array=2,subjob=5
matlab array=1,subjob=1
matlab array=3,subjob=1
matlab array=1,subjob=2
matlab array=1,subjob=3
matlab array=1,subjob=4
matlab array=3,subjob=2
matlab array=3,subjob=3
matlab array=1,subjob=5
matlab array=3,subjob=4
matlab array=3,subjob=5

You can clearly see the 3 times 5 processes run at the same time now (as their output is mixed).
No need in this case to use srun. SLURM will create 3 jobs. Within each job everything happens on individual compute nodes (i.e. as if you were running on your own system).

Installing GNU Parallel - option 1
To 'install' GNU parallel into your home folder, for example in ~/opt.

*

*Download the latest GNU Parallel.

*Make the directory ~/opt if it does not yet exist
mkdir $HOME/opt

*'Install' GNU Parallel:
tar jxvf parallel-latest.tar.bz2
cd parallel-XXXXXXXX
./configure --prefix=$HOME/opt
make
make install

*Add ~/opt to your path:
export PATH=$HOME/opt/bin:$PATH

(To make it permanent, add that line to your ~/.bashrc.)

Installing GNU Parallel - option 2
Use conda.

*

*(Optional) Create a new environment
conda create --name myenv

*Load an existing environment:
conda activate myenv

*Install GNU parallel:
conda install -c conda-forge parallel

Note that the command is available only when the environment is loaded.

A: While Tom's suggestion to use GNU Parallel is a good one, I will attempt to answer the question asked.
If you want to run 5 instances of the matlab command with the same arguments (for example if they were communicating via MPI) then you would want to ask for --ncpus-per-task=1, --ntasks=5 and you should preface your matlab line with srun and get rid of the loop.
In your case, as each of your 5 calls to matlab are independent, you want to ask for --ncpus-per-task=5, --ntasks=1. This will ensure that you allocate 5 CPU cores per job to do with as you wish. You can preface your matlab line with srun if you wish but it will make little difference you are only running one task.
Of course, this is only efficient if each of your 5 matlab runs take the same amount of time since if one takes much longer then the other 4 CPU cores will be sitting idle, waiting for the fifth to finish.

A: You can do it with python and subprocess, in what I describe below you just set the number of nodes and tasks and that is it, no need for an array, no need to match the size of the array to the number of simulations, etc... It will just execute python code until it is done, more nodes faster execution.
Also, it is easier to decide on variables as everything is being prepared in python (which is easier than bash).
It does assume that the Matlab scripts save the output to file - nothing is returned by this function (it can be changed..)
In the sbatch script you need to add something like this:
#!/bin/bash
#SBATCH --output=out_cluster.log
#SBATCH --error=err_cluster.log
#SBATCH --time=8:00:00
#SBATCH --nodes=36
#SBATCH --exclusive
#SBATCH --cpus-per-task=2

export IPYTHONDIR="`pwd`/.ipython"
export IPYTHON_PROFILE=ipyparallel.${SLURM_JOBID}

whereis ipcontroller

sleep 3
echo "===== Beginning ipcontroller execution ======"
ipcontroller --init --ip='*' --nodb --profile=${IPYTHON_PROFILE} --ping=30000 & # --sqlitedb
echo "===== Finish ipcontroller execution ======"
sleep 15
srun ipengine --profile=${IPYTHON_PROFILE} --timeout=300 &
sleep 75
echo "===== Beginning python execution ======"

python run_simulations.py

depending on your system, read more here:https://ipyparallel.readthedocs.io/en/latest/process.html
and run_simulations.py should contain something like this:
import os
from ipyparallel import Client
import sys
from tqdm import tqdm
import subprocess
from subprocess import PIPE
def run_sim(x):
    import os
    import subprocess
    from subprocess import PIPE

    # send job!
    params = [str(i) for i in x]
    p1 = subprocess.Popen(['matlab','-r',f'"run_model({x[0]},{x[1]})"'], env=dict(**os.environ))
    p1.wait()

    return

##load ipython parallel
rc = Client(profile=os.getenv('IPYTHON_PROFILE'))
print('Using ipyparallel with %d engines', len(rc))
lview = rc.load_balanced_view()
view = rc[:]
print('Using ipyparallel with %d engines', len(rc))
sys.stdout.flush()
map_function = lview.map_sync

to_send = []
#prepare variables  <-- here you should prepare the arguments for matlab
####################
for param_1 in [1,2,3,4]:
    for param_2 in [10,20,40]:
        to_send.append([param_1, param_2])

ind_raw_features = lview.map_async(run_sim,to_send)
all_results = []

print('Sending jobs');sys.stdout.flush()
for i in tqdm(ind_raw_features,file=sys.stdout):
    all_results.append(i)

You also get a progress bar in the stdout, which is nice... you can also easily add a check to see if the output files exist and ignore a run.


text:
Q: some errors on our Spark, our spark yarn model can not work any away The system report the error log tips under the lines, it saying that we have some problems in our hive system, but i had reviews so many times on my hive conf file, don't find any problems:
 ================================== Traceback (most recent call last):   File "/data/spark/python/pyspark/sql/utils.py", line 63, in deco
     return f(*a, **kw)   File "/data/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line
 319, in get_return_value py4j.protocol.Py4JJavaError: An error
 occurred while calling o22.sessionState. :
 java.lang.IllegalArgumentException: Error while instantiating
 'org.apache.spark.sql.hive.HiveSessionState':
         at org.apache.spark.sql.SparkSession$.org$apache$spark$sql$SparkSession$$reflect(SparkSession.scala:981)
         at org.apache.spark.sql.SparkSession.sessionState$lzycompute(SparkSession.scala:110)
         at org.apache.spark.sql.SparkSession.sessionState(SparkSession.scala:109)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
         at java.lang.reflect.Method.invoke(Method.java:606)
         at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
         at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
         at py4j.Gateway.invoke(Gateway.java:280)
         at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
         at py4j.commands.CallCommand.execute(CallCommand.java:79)
         at py4j.GatewayConnection.run(GatewayConnection.java:214)
         at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
         at org.apache.spark.sql.SparkSession$.org$apache$spark$sql$SparkSession$$reflect(SparkSession.scala:978)
         ... 13 more Caused by: java.lang.IllegalArgumentException: Error while instantiating
 'org.apache.spark.sql.hive.HiveExternalCatalog':
         at org.apache.spark.sql.internal.SharedState$.org$apache$spark$sql$internal$SharedState$$reflect(SharedState.scala:169)
         at org.apache.spark.sql.internal.SharedState.<init>(SharedState.scala:86)
         at org.apache.spark.sql.SparkSession$$anonfun$sharedState$1.apply(SparkSession.scala:101)
         at org.apache.spark.sql.SparkSession$$anonfun$sharedState$1.apply(SparkSession.scala:101)
         at scala.Option.getOrElse(Option.scala:121)
         at org.apache.spark.sql.SparkSession.sharedState$lzycompute(SparkSession.scala:101)
         at org.apache.spark.sql.SparkSession.sharedState(SparkSession.scala:100)
         at org.apache.spark.sql.internal.SessionState.<init>(SessionState.scala:157)
         at org.apache.spark.sql.hive.HiveSessionState.<init>(HiveSessionState.scala:32)
         ... 18 more Caused by: java.lang.NoSuchMethodException: org.apache.spark.sql.hive.HiveExternalCatalog.<init>(org.apache.spark.SparkConf,
 org.apache.hadoop.conf.Configuration)
         at java.lang.Class.getConstructor0(Class.java:2892)
         at java.lang.Class.getDeclaredConstructor(Class.java:2058)
         at org.apache.spark.sql.internal.SharedState$.org$apache$spark$sql$internal$SharedState$$reflect(SharedState.scala:164)
         ... 26 more


text:
Q: Corrupted project workspace settings in Android Studio This message appears when I open Android Studio project.

Cannot load settings from file
  (C:\Users\User\AndroidStudioProjects\"AndroidStudioProjectName".idea\workspace.xml):
  Error on line 1: Content is not allowed in prolog. Please correct the
  file content.

A: Delete the workspace file, and then don't open the project but import it. In the launcher, click on Import project and give it the projects path.


text:
Q: OpenGL light example not working using equivalent code in LWJGL I am learning the "light.c" example described at http://www.glprogramming.com/red/chapter05.html
After successfully run the example written in C, I modified it to draw a box instead of a sphere.  After that, I also translated the C code into Java using LWJGL.  However, the Java version doesn't work at all.
Both the C and Java versions are pasted at https://gist.github.com/stfairy/d2aa2f48a9a5801ae72e
The screenshot below is the expected result (which is generated by the C version, but the Java version only gives a black window)

A: After posting this question to LWJGL forum, I got a response and now I have a fix now.
I figured out it is because I didn't understand how nio.Buffer works.  After writing the values into the buffer, we also need to reset the cursor position by calling rewind(), otherwise it is using zeros for the material stuff and the light position.  Final code listed below.
private FloatBuffer floatBuffer(float... values) {
    FloatBuffer buffer = BufferUtils.createFloatBuffer(Math.max(4, values.length));
    buffer.put(values);
    return (FloatBuffer) buffer.rewind();
}


text:
Q: Severe Lag in Ubuntu 18.04 I have a brand new laptop with dual boot. The Windows partition is really fast, but Ubuntu is lagging extremely hard in some applications. The worst is Spyder, where I can barely work at all. This also has been getting worse lately.
I think I have a pretty strong system(16 GB RAM, SSD, i5) and I get the lags even though I do not have high load:
$ vmstat 10 4
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 1  0      0 7884892 260872 4138888    0    0    42    35  452  305  3  1 95  0  0
 0  0      0 7887948 260888 4138848    0    0     0    14 4341  934  1  1 97  0  0
 1  0      0 7888704 260900 4138848    0    0     0    23 4299  831  1  1 97  0  0
 0  0      0 7879632 260908 4139096    0    0     0     7 4758 1432  4  2 94  0  0

I checked some other questions here and tried things like updating my NVIDIA driver, using Unity instead of GNOME, or using powertop, but nothing helped. I checked my system logs and my CPU gets throttled from time to time, but, as I am not actually running anything demanding, I think this is more a symptom of the underlying problem than the real cause for the lags.
Is it possible that the cause for this is that I have multiple large file systems mounted via sshfs?
I am hoping someone here can point me towards some log file which will allow tackling of my specific problem.

A: Although this might not be entirely an answer, it might help you narrow down your problem, this is what recently happened to me.
My story
I have an i5 Laptop which I had dual boot on (i5 SSD, 8GB RAM). I loaded an Ubuntu 18.04 alongside a Windows 10. The first 2 weeks everything was wonderful. I then started picking up weird issues, and by weird I mean packages going missing, sections of my settings menu disappearing (exactly...weird). Part of my problem was also excruciating lag at times. I started perusing forums and tried all sorts of fixes and it basically came down to my installation had somehow become corrupted. Some of the core packages were missing and irrespective of what I did, I could not get it fixed.
What I did
I created a virtual machine within my Ubuntu (which surprisingly worked) and I played around with a fresh Ubuntu 18.04 VM as well as some other distros and I was unable to recreate any of the issues. I eventually backup-up all my data and dedicated a Saturday and 3 or 4 cups of coffee and started over using a spare HDD I had lying around with a fresh install of Ubuntu 18.04 ONLY (i.e. no dual boot).
What I discovered
When I loaded a fresh install on a new HDD (without the dual boot) I found my boot times dropping drastically. My installation also seemed to install perfectly and my performance in the OS was MUCH better. This was indeed weird and I couldn't explain it but then a colleague of mine who had the same setup as I experienced the same problem with Ubuntu 18.04 and dual boot. I suggested to him to try the same and he wiped his SSD. He installed Ubuntu 18.04 without the dual boot and he too did not experience any of the afore-mentioned issues. He then wiped his SSD again and went back to a dual boot setup and within a week his troubles started again.
What I ended up doing
During my VM escapades I tried XUbuntu and I came to like it far more than stock Ubuntu (I prefer a less flashy GUI). Consequently, I then wiped my laptop SSD, created a fresh XUbuntu 19 installation. Since then I have never had any issues, I don't experience lag any-more, my packages do not go missing and my settings menu does not disappear. Its been almost 6 months now and I have never had any issues. I recently needed to do work on Windows so I created a Virtual-Box VM within my XUbuntu and created a Win-10 VM. I have only been doing this for a out 2 weeks now but so far everything seems fine. My Windows performance is alright and my XUbuntu never gives any issues.
As I said at the start, this might not be an answer but perhaps my experience could assist you.
P.S.
Your question is similar to this post.


text:
Q: Erro variável dentro da função Estou tendo problemas e pelo que procurei nos fóruns da internet, outros tem a mesma dúvida que eu.
Não consigo usar variáveis PHP dentro da função de transação. Como faço para setar uma variável?
Por exemplo, isto não funciona:
$id = $_POST["id_saida"];
$nome = $_POST["nome_produto"];
$valor   = $_POST["valor_final"];

class CreatePaymentRequestLightbox
{
public static function main()
{

Original:
$paymentRequest->addItem('0001', 'Notebook prata', 1, 430.00); //original

Como gostaria que funcionasse:
$paymentRequest->addItem($id, $nome, $n, $valor); // como gostaria

Só que dá erro, vem vazia. O que fazer?
<?php

require_once "includes/ps/PagSeguroLibrary/PagSeguroLibrary.php";
$form = $_GET['form'];
if ($form == "pagseg"){
echo "ok";
$id_transfer = $_POST["id_transfer"];
$id = $_POST["id_saida"];
$nome = $_POST["nome_produto"];
$valor   = $_POST["valor_final"];

$v1 ="teste";

/**
* Class with a main method to illustrate the usage of the domain class
PagSeguroPaymentRequest
*/
class CreatePaymentRequestLightbox
{
    public static function main()
    {
        // Instantiate a new payment request
        $paymentRequest = new PagSeguroPaymentRequest();

        // Set the currency
        $paymentRequest->setCurrency("BRL");

        // Add an item for this payment request
        $paymentRequest->addItem($v1, 'Notebook prata', 1, 430.00);

        // Set a reference code for this payment request, it is useful to identify this
      payment
        // in future notifications.
        $paymentRequest->setReference("REF123");

        // Set shipping information for this payment request
        $sedexCode = PagSeguroShippingType::getCodeByType('SEDEX');
        $paymentRequest->setShippingType($sedexCode);
        $paymentRequest->setShippingAddress(
            '01452002',
            'Av. Brig. Faria Lima',
            '1384',
            'apto. 114',
            'Jardim Paulistano',
            'São Paulo',
            'SP',
            'BRA'
        );

        // Set your customer information.
        $paymentRequest->setSender(
            'João Comprador',
            'email@comprador.com.br',
            '11',
            '56273440',
            'CPF',
            '156.009.442-76'
        );

        // Set the url used by PagSeguro to redirect user after checkout process ends
        $paymentRequest->setRedirectUrl("http://www.lojamodelo.com.br");

        // Add checkout metadata information
        $paymentRequest->addMetadata('PASSENGER_CPF', '15600944276', 1);
        $paymentRequest->addMetadata('GAME_NAME', 'DOTA');
        $paymentRequest->addMetadata('PASSENGER_PASSPORT', '23456', 1);

        // Another way to set checkout parameters
        $paymentRequest->addParameter('notificationURL', 'http://www.lojamodelo.com.br/nas');
        $paymentRequest->addParameter('senderBornDate', '07/05/1981');
        $paymentRequest->addIndexedParameter('itemId', '0003', 3);
        $paymentRequest->addIndexedParameter('itemDescription', 'Notebook Preto', 3);
        $paymentRequest->addIndexedParameter('itemQuantity', '1', 3);
        $paymentRequest->addIndexedParameter('itemAmount', '200.00', 3);

        try {

            /*
             * #### Credentials #####
             * Replace the parameters below with your credentials
             * You can also get your credentials from a config file. See an example:
             * $credentials = PagSeguroConfig::getAccountCredentials();
             */

            // seller authentication
            $credentials = new PagSeguroAccountCredentials("fabioh.rangel@gmail.com",
                "EDC2E4A8E6B246D29C713FB97C26808E");

            // application authentication
            //$credentials = PagSeguroConfig::getApplicationCredentials();

            //$credentials->setAuthorizationCode("E231B2C9BCC8474DA2E260B6C8CF60D3");

            // Register this payment request in PagSeguro to obtain the checkout code
            $onlyCheckoutCode = true;
            $code = $paymentRequest->register($credentials, $onlyCheckoutCode);

            self::printPaymentUrl($code);
        } catch (PagSeguroServiceException $e) {
            die($e->getMessage());
        }
      }

      public static function printPaymentUrl($code)
      {
        if ($code) {
            echo "
Criando requisição de pagamento
";
            echo "
Code: $code
";
            echo "";

        }
      }
     }
}
CreatePaymentRequestLightbox::main();

A: Não sei se você colocou código e informação suficiente para indicar com clareza onde está o problema mas certamente tem uma coisa que vai ajudar ou resolver o problema. Provavelmente basta transferir a declaração das variáveis que estão "soltas" na página e colocar dentro do método onde você precisa delas, no caso o main da classe CreatePaymentRequestLightbox. Eu tenho minhas dúvidas se você precisa desta classe. Provavelmente você está copiando um código que você não entende o que faz.
<?php
require_once "includes/ps/PagSeguroLibrary/PagSeguroLibrary.php";
class CreatePaymentRequestLightbox {

public static function main() {
    $form = $_GET['form'];
    $id_transfer = $_POST["id_transfer"];
    $id = $_POST["id_saida"];
    $nome = $_POST["nome_produto"];
    $valor   = $_POST["valor_final"];
    $v1 ="teste";

    $paymentRequest = new PagSeguroPaymentRequest();
    $paymentRequest->setCurrency("BRL");
    $paymentRequest->addItem($v1, 'Notebook prata', 1, 430.00);
    $paymentRequest->setReference("REF123");
    $sedexCode = PagSeguroShippingType::getCodeByType('SEDEX');
    $paymentRequest->setShippingType($sedexCode);
    $paymentRequest->setShippingAddress(
        '01452002',
        'Av. Brig. Faria Lima',
        '1384',
        'apto. 114',
        'Jardim Paulistano',
        'São Paulo',
        'SP',
        'BRA'
    );
    $paymentRequest->setSender(
        'João Comprador',
        'email@comprador.com.br',
        '11',
        '56273440',
        'CPF',
        '156.009.442-76'
    );
    $paymentRequest->setRedirectUrl("http://www.lojamodelo.com.br");
    $paymentRequest->addMetadata('PASSENGER_CPF', '15600944276', 1);
    $paymentRequest->addMetadata('GAME_NAME', 'DOTA');
    $paymentRequest->addMetadata('PASSENGER_PASSPORT', '23456', 1);
    $paymentRequest->addParameter('notificationURL', 'http://www.lojamodelo.com.br/nas');
    $paymentRequest->addParameter('senderBornDate', '07/05/1981');
    $paymentRequest->addIndexedParameter('itemId', '0003', 3);
    $paymentRequest->addIndexedParameter('itemDescription', 'Notebook Preto', 3);
    $paymentRequest->addIndexedParameter('itemQuantity', '1', 3);
    $paymentRequest->addIndexedParameter('itemAmount', '200.00', 3);
    try {
        $credentials = new PagSeguroAccountCredentials("fabioh.rangel@gmail.com",
            "EDC2E4A8E6B246D29C713FB97C26808E");
        $onlyCheckoutCode = true;
        $code = $paymentRequest->register($credentials, $onlyCheckoutCode);
        self::printPaymentUrl($code);
    } catch (PagSeguroServiceException $e) {
        die($e->getMessage());
    }
  }

  public static function printPaymentUrl($code) {
    if ($code) {
        echo "
Criando requisição de pagamento
";
        echo "
Code: $code
";
        echo "";
    }
  }
 }
}
CreatePaymentRequestLightbox::main();

Coloquei no GitHub para referência futura.

A: As varíaveis que você está tentando utilizar no método do objeto $paymentRequest devem ser inicializadas dentro do método principal (main), assim elas serão reconhecidas no escopo.

A: Pra você usar esses parâmetros em toda a aplicação (ou em mais de uma classe), o melhor, na minha opnião, é criar uma constante. Exemplo:
define("ID", $_POST["id_saida"]);
define("NOME", $_POST["nome_produto"]);
define("VALOR", $_POST["valor_final"])  ;

class CreatePaymentRequestLightbox
{
    public static function main()
    {
        $id = ID;
        $nome = NOME;
        $valor   = VALOR;
    }
}


text:
Q: Definition of nonstandard $\omega$ I would like to know what is THE definition of a "nonstandard $\omega$", or to be exact of "the model $M$ (of set-theory) has a nonstandard $\omega$" (if there is one agreed definition). Is it one of the following statements?

*

*$\omega^M$ is ill-founded.

*There is $x\in M$ such that  $M\vDash x\in \omega$ and for every $n\in \omega$, $M\vDash \mathbf{n}<x$ (where $\mathbf{n}$ is the term $1+\dots+1$ $n$ times).

*$\omega^M\ne\omega$.

*$\omega^M$ is not order isomorphic to $\omega$. [added following Andres's comment]

I'm quite sure 1 and 2 are equivalent, and I think that also 3. If that is so, can I give either one as the definition?

A: Fix a model $M$ of a theory for which it makes sense to talk about $\omega$ ($M$ does not need to be a model of set theory, it could even be simply an ordered set with a minimum in which every element has an immediate successor and every element other than the minimum has an immediate predecessor; in this case we could identify $\omega^M$ with $M$ itself).
We say that $\omega^M$ is non-standard if and only if (by definition) $\omega^M$ is not order-isomorphic to $\omega$.
By induction (in the ambient theory) there is a unique order embedding from (true) $\omega$ onto a unique initial segment of $\omega^M$. That $\omega^M$ is non-standard thus means precisely that this embedding is not surjective. If $k$ is an element of $\omega^M$ not in its range, then its immediate predecessor is also not in the range, and it follows that $\omega^M$ is ill-founded. (Conversely, if $\omega^M$ is ill-founded, obviously it is not order isomorphic to $\omega$.)
Identifying the elements of the range with their preimages, this gives us your condition 2 as well (without needing to have a $+$ operation in the structure; naturally, if your $M$ is such that we can discuss the $+$ of $\omega^M$ and expect it to satisfy basic first-order properties of the $+$ of true $\omega$, then the image of any $n\in\omega$ under the unique embedding we are discussing is precisely the ${\mathbf n}$ of your formulation of condition 2).
On the other hand, condition 3 (that $\omega^M\ne\omega$) is too strong a requirement, since usually we only care about structures up to isomorphism. It is true, as Asaf pointed out in a comment, that in some (but definitely not all) situations we may want to identify the well-founded part of a model with its transitive collapse (meaning, given $M$ we effectively replace it with an isomorphic $M'$ obtained by replacing the well-founded part of $M$ as indicated, and then proceed to discuss $M'$ exclusively rather than $M$). If this is the case, then yes, of course condition 3 is also equivalent to the other conditions.
But note that even in the context of set theory, even when considering well-founded models, there are natural circumstances when we want to discuss models that are not transitive. For example, it is common in infinitary combinatorics to argue about elementary substructures $M$ of (some initial segment of) the universe. These structures are automatically well-founded, but you do not want to replace them with their transitive counterparts. (It is also true, however, than in this specific example $\omega^M=\omega$, but I hope the point is clear.)


text:
Q: Log when a sequence is called for the next value I would like to know if there is a way to create a trigger or insert data in a log table when a sequence is called for the next value.
For example, we have a sequence Product Value that is shared between many environments and people is getting the next value for different things, when someone calls the NEXTVAL, I want to be notified with a trigger, log table or extended event that this happens.


text:
Q: Oracle trigger to insert value from another table in a cycle In tableA I have an ID field that I want to be a value from tableB when inserting into tableA. It should however cycle through all values in tableB for each record entered. So if I have id's in tableB of 0, 1, 2, 3 then on first insert to tableA it would assign tableB value 0, on 2nd insert it should use tableB 1, then 2, then 3, then back to 0, and just loop in a cycle like this.
I'm guessing I'd need a table to track which one should be the next value and then in my trigger use that value then get the next value to use for the next insert trigger. Would there be any other ways that someone can think about doing this outside of a stored proc?

A: From what I have understand is you trying to load the data from TableB into TableA looping through IDs from TableB.
If the data in TableB is historical data that you want to load it on to TableA, then you need stored procedure with cursor inside so that you can do initial delta load from B to A. you dont need another table here in that case since you are using Cursor in Stored Procedure.
If you want TableA to be populated when there is an insert or update on TableB then you can use trigger on TableB.


text:
Q: Select column with maximum value in another column but with aggregate SUM calculation For each name, I need to output the category with the MAX net revenue and I am not sure how to do this. I have tried a bunch of different approaches, but it basically looks like this:
SELECT Name, Category, MAX(CatNetRev)
FROM (
SELECT Name, Category, SUM(Price*(Shipped-Returned)) AS "CatNetRev"
FROM a WITH (NOLOCK)
    INNER JOIN b WITH (NOLOCK) ON b.ID = a.ID
    ...
    -- (bunch of additional joins here, not relevant to question)
WHERE ... -- (not relevant to question)
GROUP BY Name, Category
) a GROUP BY Name;

This currently doesn't work because "Category" is not contained in an aggregate function or Group By (and this is obvious) but other approaches I have tried have failed for different reasons.
Each Name can have a bunch of different Categories, and Names can have the same Categories but the overlap is irrelevant to the question. I need to output just each unique Name that I have (we can assume they are already all unique) along with the "Top Selling Category" based on that Net Revenue calculation.
So for example if I have:

Name:
Category:
"CatNetRev":

A
1
100

A
2
300

A
3
50

B
1
300

B
2
500

C
1
40

C
2
20

C
3
10

I would want to output:

Name:
Category:

A
2

B
2

C
1

What's the best way to go about doing this?

A: Having to guess at your data schema a bit, as you didn't alias any of your columns, or define what table a vs b really was (as Gordon alluded). I'd use CROSS APPLY to get the max value, then bind the revenues in a WHERE clause, like so.
DECLARE @Revenue TABLE
(
    Name        VARCHAR(50)
    ,Category   VARCHAR(50)
    ,NetRevenue DECIMAL(16, 9)
);

INSERT INTO @Revenue
(
    Name
    ,Category
    ,NetRevenue
)
SELECT  Name
        ,Category
        ,SUM(a.Price * (b.Shipped - b.Returned)) AS CatNetRev
FROM    Item AS a
        INNER JOIN ShipmentDetails AS b ON b.ID = a.ID
WHERE   1 = 1
GROUP BY
        Name
        ,Category;

SELECT  r.Name
        ,r.Category
FROM    @Revenue AS r
        CROSS APPLY (
                        SELECT  MAX(r2.NetRevenue) AS MaxRevenue
                        FROM    @Revenue AS r2
                        WHERE   r.Name = r2.Name
                    ) AS mr
WHERE   r.NetRevenue = mr.MaxRevenue;

A: you can use window functions:
select * from
  (
    select * , rank() over (partition by Name order by CatNetRev desc) rn
    from table
  ) t
where t.rn = 1


text:
Q: Como posso separar os itens de um sharedPreferences em uma Array? Estou com uma dúvida, fiz um checkbox em itens de uma listview que quando marcadas são armazenadas como SharedPreferences.
Então criei um botão (Favoritos) para acessar os itens marcados pelo checkbox, mas os itens marcados vão para o Favoritos eu criei novamente uma nova listview para receber os itens, mas vários itens vem somente com um item na listview Favoritos, gostaria de separa-los.
Segue meu código:
SharedPreferences sharedPreferences = getSharedPreferences("arquivoPreferencia", MODE_PRIVATE);

       String fraseR = String.valueOf(sharedPreferences.getAll());

            // CRIANDO O ARRAY

            final String[] frasesFavoritoArray =
                    {
                            fraseR
                    };

Creio que o problema está justamente no Array que está recebendo todos os itens no 'fraseR', mas não saberia separa-los.
Existe alguma solução para isso?
Muito Obrigado.

A: Troque o seu código por esse:
SharedPreferences sharedPreferences = getSharedPreferences("arquivoPreferencia", MODE_PRIVATE);
List<String> frasesFavoritoArray = new Arraylist<>();
Map<String, ?> allEntries = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
   frasesFavoritoArray.add(entry.getValue().toString());
}


text:
Q: Angular await service between components, Behavior Subject I have an issue in my Angular web store when i refresh the window, i create a service that takes the user data from the server and then inject to the 'products' section with BehaviorSubject, my goal is to make just one request to the server:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private userId = new BehaviorSubject<any>('');
  currentUserId = this.userId.asObservable();

  constructor() { }

  sendUserId(message: string){
    this.userId.next(message)
  }
}

This works fine but the problem is when i refresh the window in products section, in console i can see that the service takes the user data but when i getProducts() it throws an error, it seems like getProducts() makes the request before the service had the response, i need the user Id to make the products request. My question: Is there a way to await the response of BehaviorSubject and then make the getProducts() request?. This is the code in the products section:

ngOnInit(): void {
    this._dataService.currentUserId.subscribe(userId => this.userId = userId);

    if(this.userId.length === 0){
      this.userService.getUserProfile().subscribe(
        res => {
          this.userDetails = res['user'];
          this.userId = this.userDetails._id;
          this.getProducts();
        },
        err => {
          console.log(err);
        }
      );
    } else {
      this.getProducts();
    }
  }

As you can see, i do a condition to check if userId exists, if not i have to make a new user request, this fix the bug but i think there's a better way to solve this. Thanks in advance.

A: How about placing all your logic within the observer's next function as below:
this._dataService.currentUserId.subscribe(userId => {
  if (userId.length === 0)
  {
    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res['user'];
        this.userId = this.userDetails._id;
        this.getProducts();
      },
      err => {
        console.log(err);
      }
    );
  } else
  {
    this.getProducts();
  }
});


text:
Q: how to update OSGI @Reference List if my service starts earlier than half of referenced ones That's one more attempt to make a dig at the theme "there is no order of OSGI bundles activation".
I have 4 services (bundles) which implement the same interface DataProvider meaning they implement it literally and also have it as service = { DataProvider.class } at their @Component annotations. This interface provides something like diagnostic data from these services. I want to collect this data from all 4 services and to print it on the GUI, which is also an OSGI bundle in my big framework. In order to do that I created such a reference in my GUI bundle:
@Reference
private volatile List<DataProvider> dataProvider;

and then I want to iterate over that list and append to the GUI's textframe everything I need.
The problem is that at the moment when GUI bundle starts, only two of four services are activated, so my list will contain only two service objects instead of all four and print only them. The last two services are loaded after my GUI Bundle has been already activated, because they also wait until their own references become fully satisfied (where some network operations are done, so it takes some time, around 10 seconds). Of course I want my GUI to show the diagnostic data from all 4 services. What could I do for that?
I tried to add policyOption = ReferencePolicyOption.GREEDY to the @Reference annotation, I expected it would force to reactivate GUI bundle each time this List<DataProvider> dataProvider receives a new member, but no, it didn't happen.
P.S. yes there is certainly a straightforward solution: just to add Thread.sleep() to the GUI Bundle with some appropriate value, so to the time of awakening the discussed above list will be full. But this is really bad thing, I don't want the user waits like 10 seconds before GUI appears, not to speak about the situations, when something goes wrong.

A: You can specify the minimum cardinality in the configuration. In your case, this is specified with the dataProvider.minimum.cardinality property in the configuration for your component. (See section 112.6.2.2 Minimum Cardinality Property.)
package com.example;
@Component
public class Diagnostics {
    @Reference
    List<DataProvider> dataProvider;
}

So then you need to add a configuration record for PID com.example.Diagnostics:
dataProvider.minimum.cardinality = 4

This model of using configuration works very well with the Configurator Specification. With this specification, you can specify the configuration of an application in a bundle.
Alternatively, you can create 4 references and distinguish the services by a property, using the target annotation method to specify a filter.


text:
Q: Modifying scripts based on the current scene I am creating a game with a multiplayer and a single player mode, each having a separate scene. Many scripts I have such as the UI script I created, are used in both scenes. However, in the single player mode I want the UI script to control a wave banner whereas I do not want this to be the case in multiplayer mode. How would make the UI script do slightly different things in two different scenes.
NOTE. I have already thought of the possibility of:
string sceneName = SceneManager.GetActiveScene().name;

if(sceneName == "Singleplayer"){
    //control wave banner
}

and was just wondering if there would be a better way of doing this as I would have to do it for multiple scripts.

A: Asking for a string compare sounds a bit cumbersome.
I would suggest to implement a enum. This is more reliable:
public enum GameMode {
    Singleplayer,
    Multiplayer
}

And then use it in your code:
// you need to rewrite your code to get the enum
// e.g.
var gameMode = SceneManager.GetActiveScene().GameMode;

switch (gameMode)
{
    case GameMode.Singleplayer:
        // Specific Logic for Singleplayer
        break;
    case GameMode.Multiplayer:
        // Specific Logic for Multiplay
        break;
    default:
        throw new ArgumentOutOfRangeException();
}


text:
Q: Change TTL from application on linux is there a way to set ttl from application? Using c++ rh, not using boost. In /etc/sysctl.conf file value net.ipv4.ip_default_ttl is not present, in /proc/sys/net/ipv4/ip_default_ttl written 64. I am sending traffic to multicast group and see TTL=1. Would like to increase it to 3.
Thanks.

A: You can configure it per socket, using the IP_MULTICAST_TTL  setsockopt() flag. Take a look at the man pages for ip and setsockopt.
Something like the following:
void setttl(int sock, uint8_t ttl)
{
    int ret = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(uint8_t));
    if (ret != 0)
        printf("Failed to setsockopt(): %s\n", strerror(errno));
}


text:
Q: In python how do I preform addition/subtraction on a custom base defined by lists? There is probably a term for what I want to do, I will edit my question with the proper term when I find it out.
Assume 3 lists:
a = ["alpha", "beta", gamma"]
b = ["a", "b", "c", "d"]
c = ["one", "two", "three" "four", "five"]

My custom base has the following sequence:
alpha-a-one, alpha-a-two, ..., alpha-a-five, alpha-b-one, ..., alpha-d-five, beta-a-one, ..., gamma-d-five

I want to be able to define num1 and num2 so that I can calculate addition and subtraction. For example
>>> num1 = alpha-b-two
>>> num2 = alpha-a-four
>>> num1-num2
3

and
>>> num = alpha-a-four
>>> num+3
alpha-b-two

How can I do that? (and what is the term for this?)

A: If I understand what the OP means, then this is just a matter of creating the required list in the relevant order, and then doing opperations on the indexes.
For instance, the following exemplifies the minus operation, but can be generalized rather easily -
from itertools import product
a = ["alpha", "beta", "gamma"]
b = ["a", "b", "c", "d"]
c = ["one", "two", "three", "four", "five"]

ordered_combos = list(map(lambda x: '-'.join(x), product(a, b, c)))

def weird_minus(x, y):
    assert x in ordered_combos and y in ordered_combos
    return ordered_combos.index(x) - ordered_combos.index(y)

num1 = 'alpha-b-two'
num2 = 'alpha-a-four'
print(weird_minus(num1, num2))
# 3

Not sure there a well known term. You're just enumerating a cartesian product of lists and then speaking about their respecting locations in said list.

A: Do you mean "base" as in each digit has a different domain, and so your arithmetic combines base 3, base 4, and base 5 for different slots? This seems like a quite mangled way to do ... whatever it is you are hoping to accomplish. Having said that, simply mapping the symbols back to regular integers would easily do what you seem to be asking.
a = ["alpha", "beta", "gamma"]
b = ["a", "b", "c", "d"]
c = ["one", "two", "three", "four", "five"]

def mapping():
    i = 0
    key = {}
    for _a in a:
        for _b in b:
            for _c in c:
                key["-".join([_a, _b, _c])] = i
                i += 1
    return key

key = mapping()
reverse = {v: k for k, v in key.items()}

num1 = key["alpha-b-two"]
num2 = key["alpha-a-four"]
print(num1-num2)

print(reverse[key["alpha-a-four"] + 3])

Demo: https://ideone.com/GJ1jw6
You could use the global symbol table instead of a separate dictionary, but that tends to result in confusion, and you can't use dashes in symbol names anyway.


text:
Q: I have a contact form that on the css styles that fit mobile devices it won't let me input data So I can fill out the form on the desktop size but when I got to fill it out on mobile sizes (640, 480, and 320) it doesn't let me.  I found out something by trying things and just happen to have my cursor outside my contactform div that has the form inside it. Then it let me type in everything but the message box unless I use tab and am still outside the div. I find it odd?
benlevywebdesign.com
The bottom of the page is where the form is for you to test out the mobile layouts for 640, 480, and 320.
Here is the contact form
<form id="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

        <fieldset>

                Name
                <input type="text" name="name" id="name" size="30" />

                Email
                <input type="text" name="email" id="email" size="30" />

                Website
                <input type="text" name="web" id="web" size="30" />

        </fieldset>
        <fieldset>

                Message
                <textarea name="message" id="message" cols="30" rows="10"></textarea>

        </fieldset>

<button name="submit" type="submit">Send</button>

    </form>

Here is my css style for 480 and 320
@media screen and (max-width:480px){

@media screen and (max-width:320px){

#form1{
    padding-top:5px;
    }

#form1 fieldset{
    margin:0;
    padding:0;
    border:none;
    float:left;
    display:inline;
    width:190px;
    margin-left:15px;
    }

#form1 legend{display:none;}
#form1 p{margin:.5em 0;}
#form1 label{display:block;}
#form1 input, #form1 textarea{
    width:175px;
    border:1px solid #B7B7B7;
    background:#fff;
    padding:3px;
    background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #EEEEEE), to(#FFFFFF));
background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE 1px, #FFFFFF 25px);
    }

#form1 textarea{
    height:120px;
    width:175px;
    overflow:auto;
    }

#form1 p.submit{
    clear:both;
    padding:0 25px 5px 25px;
    margin:0;
    text-align:right;
    }

#form1 button{
    font-family:Trebuchet MS;
    font-size:14px;
    width:105px;
    height:35px;
    border:none;
    background-color:#484749;
    color:#fff;
    border-radius:4px;
    cursor:pointer;
    text-align:center;
    }

A: Have you tried resizing your browser and viewing your site on a PC (I'm using FF), it goes all kinds of screwy. Also Firebug says you have 15 errors and 10 warnings - might be worth trying to fix these first before going back to mobile devices.
Heres a short video of the issues: http://screencast-o-matic.com/watch/clhwo4GGI


text:
Q: Getting capture date of heic image I am using the nokiatech heif api (github.com/nokiatech/heif) to process heic files produced by the IOS betas.
I am able to get the tiles and metadata like rotation and dimensions, but I am unable to locate the capture date of the image. I found some timestamp functions but they complain about "Forced FPS not set for meta context" which leads me to think these functions are related to tracks and not items.
Any help would be appreciated.
EDIT:
So there is a typo in the documentation for getReferencedToItemListByType (and getReferencedFromItemListByType), it says it takes "cdcs" as a referenceType parameter. It is ofcource "cdsc" (Content Describe).
So to get the metadata blob from a stil image as of now you can do the following:
reader.getItemListByType(contextId, "grid", gridItemIds);
ImageFileReaderInterface::IdVector cdscItemIds;
reader.getReferencedToItemListByType(contextId, gridItemIds.at(0), "cdsc", cdscItemIds);
ImageFileReaderInterface::DataVector data;
reader.getItemData(contextId, cdscItemIds.at(0), data);

Then you need to decode the exif. You can easily use Exiftool cli or an api like exiv2.


text:
Q: Getting CERTIFICATE_VERIFY_FAILED. How to pass pem file to tinys3 ? I am trying to upload to aws s3. My python program using version 2.7.12
import tinys3
S3_ACCESS_KEY=''
S3_SECRET_KEY=''
conn = tinys3.Connection(S3_ACCESS_KEY,S3_SECRET_KEY,tls=True)

f = open('D:\\poc\\dicomimage','rb')
conn.upload('D:\\poc\\sampleimage',f,'development/system')

But i am getting below error:
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
I cannot set tls=False.
I tried below things but getting same error all the time

*

*added cert=cert_path, pip.ini

*Also executed - pip uninstall -y certifi && pip install certifi==2015.04.28, as mentioned in various posts.

How can i pass my pem file to tinys3 or any setting to fix the issue.
PS: I am a full time java developer, fortunately/unfortunately this is my first python program. So, please explain how things are working here.

A: You should specify the endpoint of your bucket
conn = tinys3.Connection(S3_ACCESS_KEY,S3_SECRET_KEY,tls=True,endpoint='s3-us-east-1.amazonaws.com')

change your endpoint to match the endpoint of your bucket, check AWS list of region endpoint


text:
Q: How can I write recursive XSLT code I have dynamic XML data and I use following xslt code to generate html. XML structure contains chapter, subchapter, checklist and summary nodes.

*

*<chapter> contains <subchapter> and <checklist>

*<subchapter> contanins <subchapter> and <checklist>

*<checklist> contains
My code works but, all the time subchapter's content added before checklist.  If chapter involves checklist,subchapter nodes (first checklist), subchapter content created first.
How can I correct this or how can I rewrite the following code as recursive?
  <xsl:template match="chapter">
    <xsl:apply-templates select="chapter"/>
  </xsl:template>

  <xsl:template match="chapter">

            <xsl:value-of select="@name"/>

      <xsl:apply-templates select="subchapter"/>
      <xsl:apply-templates select="checklist"/>

  </xsl:template>

  <xsl:template match="subchapter">

            <xsl:attribute name="name">
              <xsl:value-of select="@value"/>
            </xsl:attribute>
            <xsl:value-of select="@name"/>

      <xsl:apply-templates select="subchapter"/>
      <xsl:apply-templates select="checklist"/>

  </xsl:template>

  <xsl:template match="checklist">

            <xsl:attribute name="name">
              <xsl:value-of select="@value"/>
            </xsl:attribute>

            <xsl:value-of select="@name"/>

      <xsl:apply-templates select="summary"/>

  </xsl:template>

  <xsl:template match="summary">

          <xsl:copy-of select="*"/>

  </xsl:template>

A: I am guessing (without seeing the input and the expected output, I can only guess), that instead of:
<xsl:apply-templates select="subchapter"/>
<xsl:apply-templates select="checklist"/>

you want :
<xsl:apply-templates select="subchapter | checklist"/>

If chapter contains only subchapter and checklist you can shorten that to:
<xsl:apply-templates/>


text:
Q: Mysql: Insert into JSON column type with GROUP_CONCAT I'm trying to insert a list of words into a column with the JSON type:
create table my_table (
    ...
    synonyms JSON
    ...
)

My query looks like this:
INSERT into my_table (id, synonyms)
SELECT id, GROUP_CONCAT(DISTINCT synonyms) as synonyms from (
  SELECT id, name1,name2, GROUP_CONCAT(DISTINCT name1) as synonyms
  FROM products
  GROUP BY id

  UNION

  SELECT id, name1,name2, GROUP_CONCAT(DISTINCT name2) as synonyms
  FROM products
  GROUP BY id
) t group by id;

If run without the INSERT in line one, the synonyms column returns a list of comma separated words:
id       name1    name2    synonyms
------------------------------------
1        one      a,b      one,a,b
2        two      c        two,c

I want to insert those synonyms as a JSON_ARRAY.  However, the INSERT fails when the individual words are not double quoted.  If I add JSON_ARRAY in my select:
SELECT name1,name2,id, JSON_ARRAY(GROUP_CONCAT(DISTINCT synonyms)) ...

I get the following result:
name1    name2    synonyms
----------------------------
one      a,b      ["one,a,b"]
two      c        ["two,c"]

When what I want is this (so it can be inserted directly into the synonyms column):
name1    name2    synonyms
----------------------------
one      a,b      ["one","a","b"]
two      c        ["two","c"]

Is there a way to do this with SQL, or is it better handled within application code?

A: Use JSON_ARRAYAGG() instead of GROUP_CONCAT(). - akina
It is available only in 5.7.22+
Does it have an implicit DISTINCT? I don't know...if not, subquery with DISTINCT will help.

A: You can add a concat inside the group_concat to achieve this, like in this sample:
SELECT name1, name2, id,
       CONCAT(
          '[',
          GROUP_CONCAT(
             CONCAT(
                '"',
                synonyms,
                '"'
             )
          ),
          ']'
       )

A: Query like this
SELECT
   campaign_id,
   CAST( CONCAT('[', GROUP_CONCAT(id),']') AS JSON ) AS posts
FROM
  posts
WHERE
     campaign_id IS NOT NULL
GROUP BY campaign_id

will return

campaign_id
posts

4
[1005, 1006, 1007]

5
[1002, 1003, 1004]


text:
Q: Java date iterator factory, with rules specifying how to calculate the intervals I am looking for a Java class where I can specify a set of date rules, such as "every 3rd sunday" and "the first occurrence of a monday every second month". I want to be able to get something like an infinite iterator out of it (.next() would return the next date matching the rules set).
I think I'd be able to build it myself - but calendars are a hassle, and it feels like something similar should exist already. I hate being the one to reinvent a crappier wheel.
Is anyone aware of something like this? I have been looking at JODA, and it seems to lay the groundwork for it, but does not appear to give the full functionality I want..

A: I don't think there's any readily made iterators for joda-time or Java Calendar API for that matter, however with joda it's so easy that you should just go with it. For example after re-familiarizing myself with joda after a few months pause I made this in about 10 minutes:
public class InstantIterator implements Iterator<Instant>,
                                        Iterable<Instant> {

    private Instant current;
    private final Instant original;
    private Duration skip;
    private List<Instant> skipThese;

    public InstantIterator(Instant startFrom, Duration skip) {
        this.current = original = startFrom;
        this.skip = skip;
        skipThese = new Vector<Instant>();
    }

    public boolean hasNext() {
        return true;
    }

    public Instant next() {
        Instant currentNext = current.toInstant();
        current = current.plus(skip);
        while (skipThese.contains(currentNext)) {
            currentNext = current.toInstant();
            current = current.plus(skip);
        }
        return currentNext;
    }

    public void remove() {
        skipThese.add(current.toInstant());
    }

    public Iterator<Instant> iterator() {
        return this;
    }

    public void rewind() {
        current = original.toInstant();
    }

    public void resetRemoved() {
        skipThese.clear();
    }

    public void resetIterator() {
        rewind();
        resetRemoved();
    }
}

Joda Time is awesome :-)

A: My company has something very much like you want but it's for .NET so it probably won't do you any good.

A: You could have a look at Quartz which is designed for job scheduling.

A: tl;dr
Easy, with java.time.
For 3rd Thursday:
LocalDate.now().with(                                             // Get today's date, then adjust.
    TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.THURSDAY )  // Define adjuster to move to third Thursday of same month.
)                                                                 // Instantiates another `LocalDate` object (java.time uses immutable objects).

java.time
The troublesome old date-time classes bundled with the earliest versions of Java are now obsolete, supplanted by the java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2018 , Month.FEBRUARY , 17 ) ;

For any LocalDate, you can adjust into the ordinal occurrence of a day-of-week within the same month (ex: third Thursday, 2nd Tuesday, etc.). Specify the day-of-week using DayOfWeek enum.
To make the adjustment, use a TemporalAdjuster implementations found in the TemporalAdjusters class.
TemporalAdjuster thirdThursdayAdjuster = TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.THURSDAY ) ;  // Third-Thursday.

Apply that adjuster to any LocalDate, producing another LocalDate object.
LocalDate thirdThursday = ld.with( thirdThursdayAdjuster ) ;

something like an infinite iterator out of it (.next() would return the next date matching

Simply move from one LocalDate to another. You could call LocalDate::addMonths. Or if dealing with a month at a time, use the YearMonth class.
TemporalAdjuster thirdThursdayAdjuster = TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.THURSDAY ) ;  // Third-Thursday.
List<LocalDate> dozenThirdThursdays = new ArrayList<>( 12 ) ;
YearMonth start = YearMonth.of( 2018 , Month.MARCH ) ;
for( int i = 1 ; i <= 12 ; i ++ ) {
    YearMonth ym = start.plusMonths( i ) ;
    LocalDate firstOfMonth = ym.atDay( 1 ) ;
    LocalDate thirdThursday = firstOfMonth.with( thirdThursdayAdjuster ) ;
    dozenThirdThursdays.add( thirdThursday ) ;
}

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.