Performing calculations with a catalog of stars The point of my code is to:

Read in the observed data from the a catalog of stars (whitespace separated table).
Do some unit conversions on the observed data (math stuff).
Apply an interstellar correction factor to the observed data (more math).
Compare the scaled observed data to the DUSTY model data using the BC table, using a least-squares approach (comparison of observed data to theoretical models found in a large table).
Find the best fit models for the observed data (should be obvious).

I'm trying to rewrite 'spaghetti code' I was handed, that doesn't function quickly, nor does it allow for easy updating (adding different statistical calculations, etc.). I'm pretty new to Python, so I'm struggling with the idea of classes and this is my attempt at it.

class Stellar_setup:
    Fbol=5.01333e-10
    c=2.99792458e+8
    L=1000
    star_list=[]
    dusty_models=np.array([]) #Array of all the dusty models
    incoming_stars='' #List of incoming stars

    def __init__(self):
        """Initiates the below modules."""
        self.star_catalog()
        self.InputKey()

    def star_catalog(self):
        """Imports the star catalog"""
        try:
            star_catalog=raw_input('Input pathname of stellar catalog: ')
            star_list=[]
            with open(star_catalog) as incoming_stars:
                for line in incoming_stars.readlines():
                    x=[item for item in line.split()]
                    star_list.append(x) #Appends the individual star-IDs to the empty array star_list.
            print 'Stars imported successfully.'
        except IOError:
            print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.'
            sys.exit()

    def InputKey(self):
        """Imports the Input (.inp) file. Historically, InputUt.inp.
        Allows for definition of parameters which are utilized later in the script."""
        input_script=raw_input('Pathname of .inp file: ')
        InputKey=[]
        try:
            with open(input_script) as input_key:
                for line in input_key.readlines():
                    x=[item for item in line.split()]
                    InputKey.append(x)
            if InputKey[0][0]=='1' or InputKey[0][0]=='2':  #Checks to see if .inp file is valid or not by checking the first row/column which should be 1 or 2.
                print 'Your .inp file was successfully imported'
            else:
                print 'Your .inp file import failed. Check the validity of your file.\n Program exiting now.'
                sys.exit()
        except IOError:
            print 'The .inp file import was unsuccessful. Check that your file-path is valid.\n Program exiting now.'
            sys.exit()

    # You probably need to put a module here that pulls in the DUSTY tables.

if __name__=='__main__':
    Stellar_setup()

I was thinking about making about three other classes that:

Identify necessary attributes from the tables (pulling data from columns/rows)
Do analysis of information, and model/data comparison to find the best theoretical models that match up with the observed data. This uses a least-squares approach.

From what I understand classes can 'inherit' attributes from other classes. The way I think I understand this is that my class Stellar_setup will be inherited by my class Attribute_Identification (which haven't been written yet), and so on. I'm not sure if I'm going about this the right way, can anyone clear things up for me.

This looks like procedural code, poorly dressed up in object-oriented style.  Python doesn't require you to write object-oriented code, but if you do, you should model it properly.

Think of objects as "smart" data structures.  If your classes are well designed, you can ask the objects to perform operations on themselves in such a way that you don't have to worry about the details of how it performs the task.

For example, StarCatalog should definitely be a class of its own.  There should probably be a Star class as well.  The outline of those classes might look like:

class Star:
    def __init__(self, id, magnitude, right_ascension, declination):
        ...
    def id(self):
        ...
    def magnitude(self):
        ...
    def coordinates(self):
        ...

class StarCatalog:
    def __init__(self):
        ...
    def add_star(self, star):
        ...
    def remove_star(self, id):
        ...
    def get_star(self, id):
        ...
    def __iter__(self):
        ...

class StarCatalogImporter:
    def __init__(self, catalog):
        ...
    def import_file(filename):
        ...

Once your model is defined, you can start using it!

catalog = StarCatalog()

importer = StarCatalogImporter(catalog)
try:
    importer.import_file(raw_input('Input pathname of stellar catalog: '))
    print 'Stars imported successfully.'
except IOError:
    print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.'
    raise

corrector = InterstellarCorrector(correction_factor=0.2342)
corrected_catalog = corrector.correct(catalog)

result = least_sq_correlator.correlate(corrected_catalog, dusty_model)

Notice how the classes are designed to separate concerns.  The StarCatalogImporter class knows how to add the stars listed in a file into a StarCatalog; once that is done, you can ask the catalog to enumerate its stars.  The StarCatalogImporter interface should be as reusable as possible.  For example, if it encounters an error while importing, it raises an exception, rather than printing a message and exiting.  The code that uses the StarCatalog decides how to handle those situations.  (It might print an error message and exit.  It might be a GUI application, in which case it would display the error in a dialog box.  It might translate the error message into another language.  It might try to load a different catalog instead.)  On the other hand, the code that uses a StarCatalog should make no assumptions about how the star catalog is implemented.  It doesn't know if the StarCatalog internally uses an array, a dict, or a numpy matrix.  Therefore, it should only use the functions exposed by the class.

The class interfaces that you design are what prevent your code from being spaghetti.  If you design your class interfaces well, you will have a loose coupling, such that you will be able to reuse the class in other programs, and modify the inner workings of the class without disturbing the code that uses your class.

A good rule to follow is that each class should represent one thing.  If you can't think of a short, descriptive name for the class, that's a sign that you're on the wrong track.  Also, the class name must be a noun; if it's a verb, you're using procedural rather than object-oriented thinking.


Strategy Pattern for Oracle Database? I'm trying to implement the Strategy Pattern into my current code base. I would like to know if i'm going in the right direction on this?

IOracleDB.cs:

/// <summary>
/// Strategy
/// </summary>
interface IOracleDB
{
    DataSet DatabaseQuery(string query, OracleConnection oracleConnection);
    DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection);
}

OracleDBContext.cs:

/// <summary>
/// Context
/// </summary>
class OracleDBContext
{
    private readonly string _EmailConnectionString = ConfigurationManager
        .ConnectionStrings["EmailConnectionString"].ConnectionString;

    private readonly string _PhConnectionString = ConfigurationManager
        .ConnectionStrings["PhConnectionString"].ConnectionString;

    private readonly IOracleDB _oracleDB;
    private readonly OracleConnection _oracleConnection;

    public OracleDBContext(IOracleDB oracleDB, string table)
    {
        _oracleDB = oracleDB;

        switch (table.ToUpper())
        {
            case "Email":
                _oracleConnection = new OracleConnection(_EmailConnectionString);
                return;

            case "Ph":
                _oracleConnection = new OracleConnection(_PhConnectionString);
                return;

            default:
                return;
        }
    }

    public void ConnectToDatabase()
    {
        _oracleConnection.Open();
    }

    public void DisconnectFromDatabase()
    {
        _oracleConnection.Close();
        _oracleConnection.Dispose();
    }

    public string ConnectionStatus()
    {
        if (_oracleConnection != null)
        {
            return _oracleConnection.State.ToString();
        }
        return "OracleConnection is null.";
    }

    public DataSet DatabaseQuery(string query)
    {
        return _oracleDB.DatabaseQuery(query, _oracleConnection);
    }

    public DataSet DatabaseQuery(string procedure, string parameters)
    {
        return _oracleDB.DatabaseQuery(procedure, parameters, _oracleConnection);
    }
}

EmailTableClass.cs:

/// <summary>
/// Concrete Strategy
/// </summary>
class EmailTableClass : IOracleDB
{

    public DataSet DatabaseQuery(string query, OracleConnection oracleConnection)
    {
        DataSet dataSet = new DataSet();
        OracleCommand cmd = new OracleCommand(query);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = oracleConnection;

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet;
    }

    public DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection)
    {
        throw new NotImplementedException();
    }
}

PhTableClass.cs:

/// <summary>
/// Concrete Strategy
/// </summary>
class PhTableClass : IOracleDB
{

    public DataSet DatabaseQuery(string query, OracleConnection oracleConnection)
    {
        throw new NotImplementedException();
    }

    public DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection)
    {
        DataSet dataSet = new DataSet();
        OracleCommand cmd = new OracleCommand
        {
            CommandText = procedure,
            CommandType = CommandType.StoredProcedure,
            Connection = oracleConnection,
        };

        OracleParameter oracleParameter = new OracleParameter
        {
            ParameterName = parameters
        };

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet;
    }
}

There are several issues that could be improved:

First of all, having concrete classes which are all tied to a specific database (in this case Oracle), is usually completely opposite of what a Data Layer's responsibility should be. Consider changing the classes' names as follows:

OracleConnection --> DbConnection
OracleCommand --> DbCommand
OracleParameter --> DbParameter.

To instantiate a new command, don't use a specific constructor, but rather use the DbConnection.CreateCommand() method (and, likewise, DbCommand.CreateParameter() to create its parameters). That means you only need to change the actual connection instance, if you decide to switch from Oracle to a different db provider one day.
Next, strategy pattern is usually used to abstract a functionality which several different algorithms can execute, while exposing a single (common) interface. Creating a different strategy for different table queries is not appropriate, because the calling code already knows which table it is querying (there are no additional strategical choices your code can do).
I am not sure if the NotImplementedExceptions are thrown deliberately, or you really haven't yet implemented those methods. If you are throwing to indicate that a certain implementation doesn't support that functionality, that is another alarm that these two implementations are not really different strategies for the same task.


Make the awt.Color class constructors except out of range arguments Ok, this might be a very stupid question/idea (I'm still a beginner). Lets say I have a construct like this:

g.setColor(new Color(random.nextInt(5) * speed, 255, speed * 3));

Now it is very likely that the passed arguments will in some cases be out of the expected range, so the code will throw an exception. To circumvent this case I wrote the following helper class:

public class SafeColor {

    static final int INT_MIN = 0;
    static final int INT_MAX = 255;
    static final float FLOAT_MIN = 0;
    static final float FLOAT_MAX = 1;

    public static Color safeIntColor(int r, int g, int b) {
        if (r < INT_MIN) r = INT_MIN;
        if (g < INT_MIN) g = INT_MIN;
        if (b < INT_MIN) b = INT_MIN;

        if (r > INT_MAX) r = INT_MAX;
        if (g > INT_MAX) g = INT_MAX;
        if (b > INT_MAX) b = INT_MAX;

        return new Color(r, g, b);
    }

    public static Color safeIntAlphaColor(int r, int g, int b, int a) {
        if (r < INT_MIN) r = INT_MIN;
        if (g < INT_MIN) g = INT_MIN;
        if (b < INT_MIN) b = INT_MIN;
        if (a < INT_MIN) a = INT_MIN;

        if (r > INT_MAX) r = INT_MAX;
        if (g > INT_MAX) g = INT_MAX;

        // ... and so on ...

Now I can do this:

g.setColor(SafeColor.safeIntColor(random.nextInt(5) * speed, 255, speed * 3));

I guess the question is, does that make any sense? The whole thing looks a bit overdone to me. Is there a better/easier way to accomplish the same thing?

Edit: For anyone interested. I boiled it down to this:

public class SafeColor {

    private static final float FLOAT_MAX = 1;
    private static final float FLOAT_MIN = 0;
    private static final int INT_MAX = 255;
    private static final int INT_MIN = 0;

    private static float safeFloat(float f) {
        return Math.max(Math.min(f, FLOAT_MAX), FLOAT_MIN);
    }

    private static int safeInt(int i) {
        return Math.max(Math.min(i, INT_MAX), INT_MIN);
    }

    public static Color safeColor(float r, float g, float b, float a) {
        return new Color(safeFloat(r), safeFloat(g), safeFloat(b), safeFloat(a));
    }

    public static Color safeColor(float r, float g, float b) {
        return new Color(safeFloat(r), safeFloat(g), safeFloat(b));
    }

    public static Color safeColor(int r, int g, int b, int a) {
        return new Color(safeInt(r), safeInt(g), safeInt(b), safeInt(a));
    }

    public static Color safeColor(int r, int g, int b) {
        return new Color(safeInt(r), safeInt(g), safeInt(b));
    }

}

There is nothing too bad about this, and it is an acceptable pattern to get rid of extra/boilerplate code (for example IOUtils from Apache Commons has a closeQuietly for streams that takes a way a lot of the nested try-catch-finally madness for closing streams).

However, I would argue that it is better to validate your inputs to make sure that they don't exceed the ranges, or at least change the code that generates your values to ensure that they do not generate invalid values.

For example, you could have a method called generateColor(speed) that returns a sane Color instance.

I would also suggest using Math.max and Math.min in this method  instead of using a bunch of ifs.


PyQt5 validator for decimal numbers This class is similar to QDoubleValidator, but it improves slightly on the editing comfort. The comments mention "comma" but it's actually the decimal point of your locale (comma for me).

class DecimalValidator(QDoubleValidator):
    def __init__(self, *args):
        QDoubleValidator.__init__(self, *args)
        self.setNotation(QDoubleValidator.StandardNotation)
    def validate(self, input, pos):
        sep = self.locale().decimalPoint()
        if pos and (input[pos-1]==sep) and (sep in input[pos:]):
            # When we're left of the comma, and comma is pressed,
            # remove the inserted comma and move right of the old comma.
            input = input[:pos-1] + input[pos:]
            pos = input.find(sep)+1
        elif sep in input[:pos] and (len(input.split(sep)[1]) > self.decimals()):
            # When we're right of the comma, and all decimal places are used already,
            # go into overwrite mode (by removing the old digit)
            input = input[:pos] + input[pos+1:]
        return QDoubleValidator.validate(self, input, pos)

I noticed your commenting style and decided it's worthy of it's own answer.

You admit the comma is not always a comma. So don't call it a comma. I went for separator, which is as neutral as it gets. If you think of something better, go for it.

Also, I think your comments would fit better as a docstring than as comments.

class DecimalValidator(QDoubleValidator):
    def __init__(self, *args):
        QDoubleValidator.__init__(self, *args)
        self.setNotation(QDoubleValidator.StandardNotation)
    def validate(self, input, pos):
        '''
        When we're left of the separator, and separator is pressed,
        remove the inserted separator and move right of the old separator.
        When we're right of the separator, and all decimal places are used already,
        go into overwrite mode (by removing the old digit)
        '''
        sep = self.locale().decimalPoint()
        if pos and (input[pos-1]==sep) and (sep in input[pos:]):
            input = input[:pos-1] + input[pos:]
            pos = input.find(sep)+1
        elif sep in input[:pos] and (len(input.split(sep)[1]) > self.decimals()):
            input = input[:pos] + input[pos+1:]
        return QDoubleValidator.validate(self, input, pos)


Tic Tac Toe (2 players) So here we have a little game of Tic Tac Toe I've made. It runs well on TI-83/84 calculators and it doesn't seem to have any problems. However, I'd like to eliminate some of the code that seems bulky and repetitive as well as possibly add some checks so you can't overwrite a square that's already been played and to finish the game when a row of 3 has been made. If anyone could help me I'd appreciate it!

:ClrHome
:ClrDraw
:1->X
:0->I
:0->O
:Horizontal 9
:Horizontal 3
:Horizontal -3
:Horizontal -9
:Vertical 9
:Vertical 3
:Vertical -3
:Vertical -9
:Disp "WHO FIRST X OR O"
:Input F
:Disp "USE 1 THROUGH 9"
:Lbl 1
:Input M
:fPart(M/3)3-2->H
:If H=-2
:1->H
:H*6->H
:-6->V
:If M>3
:0->V
:If M>6
:6->V
:If F
:Then
:Line(H-2,V-2,H+2,V+2)
:Line(H-2,V+2,H+2,V-2)
:Else
:Circle(H,V,2)
:End
:I+1->I
:abs(F-1)->F
:If I=9
:Goto 2
:Pause
:Goto 1
:Lbl 2

Disclaimer: I only have a TI-85, whose commands are slightly different from the TI-83 and TI-84.

User Experience

At first, I was puzzled by the numbering of the squares.  Then I realized that squares 1 to 9 corresponded nicely to the way the calculator number pad is laid out.  Nice!
You could probably do without the lines at ±9, as a tic-tac-toe board is conventionally drawn as #, with no borders.
There's not much point in asking who goes first, in my opinion.
As you noted, you fail to check whether a square is already occupied.  A nine-element list could easily be used to perform that check.

Code

Variables X and O are defined but never used.
I don't know why you chose to name your variables F and M.  I would have picked P for "player" and S for "square".
The two-argument form of the Input command can also display the prompt.
fPart(M/3)3-2→H didn't work for me.  Due to the way precedence of operations works on the TI-85, it is evaluated at fPart((M/3)3)-2→H.  Rewriting it as 3fPart(M/3)-2→H fixes it.
The code to map M to H and V is excessively complicated.  Each assignment should be done in one line:

6(mod(M-1,3)-1)→H
6 int((M-4)/3)→V

The TI-84 has remainder() instead of mod().
The TI-83 has neither remainder() nor mod(), and must use 6(3fPart((M-1)/3)-1)→H.
I believe the latter is works for all three models.
Your use of Goto is unjustified.  I should be initialized, tested, and incremented using a For( loop.
To toggle F between 0 and 1, just do 1-F→F.  You don't need an abs function.
I'm not sure that ClrDraw adequately resets the drawing context.  On the TI-85, I need ClDrw, ZStd (to set the bounds to the standard zoom), and AxesOff (to hide the axes).

Rewrite for the TI-85 dialect

I've noted what I believe the equivalent TI-83 / TI-84 commands are, based on reading the Guidebooks.

:ClLCD                       Equivalent to ClrHome?
:ClDrw                       Equivalent to ClrDraw?
:ZStd                        Equivalent to ZStandard?
:AxesOff
:DrawF -3                    Equivalent to Horizontal?
:DrawF 3
:Vert -3                     Equivalent to Vertical?
:Vert 3
:1→P
:For(I,1,9)
:Input "Square (1-9)? ",S
:6(mod(S-1,3)-1)→H           See portability note above.
:6 int((S-4)/3)→V
:If P
:Then
:Line(H-2,V-2,H+2,V+2)
:Line(H-2,V+2,H+2,V-2)
:Else
:Circl(H,V,2)                Equivalent to Circle?
:End
:Pause
:1-P→P
:End


multi-recursive replacement function I wrote a function for creating all possible translations of a source string, based on a multiple translation map. It works, but generates a lot of intermediate maps (see line marked with *). Is there a better solution? Maybe a more general solution to the "all possible combinations" problem?:

/**
 *
Add to 'targets' all possible variations of 'source', with replacements defined by 'translationsMap'.
 *
For example, after the following call:
 *
addAllReplacements("put the X on the Y", {X => {"cake","egg"}, Y => {"table","chair"}, targets)
 *
targets should contain the following strings:
 *
"put the cake on the table", "put the cake on the chair", "put the egg on the table", "put the egg on the chair"
 */
public static void addAllReplacements (String source, Map<String, Set<String>> translationsMap, Set<String> targets) {
    if (translationsMap.isEmpty()) {
        // no more replacements:
        targets.add(source);
    } else {
        // pick an entry from the map:
        Entry<String, Set<String>> e = translationsMap.entrySet().iterator().next();
        String text = e.getKey();
        Set<String> translations = e.getValue();

        // Create a new translation map, without the currently translated text, for the recursive call:
        HashMap<String, Set<String>> newTranslationMap =
                         new HashMap<String, Set<String>>(translationsMap);  // *
        newTranslationMap.remove(text);

        for (String translation: translations) {
                    addAllReplacements(
                        source.replace(text, translation),
                        newTranslationMap,
                        targets);
        }
    }
}

You are using the Map more like a list...

EDIT: this is NOT working:

You could create an object to hold one translation ({X => {"cake","egg"}) then instead of all the Maps you could use a List (of those translations) and always remove and use the first element and pass the shorter list to the next call of your method.

EDIT: this IS working:

You could use a List with the translation and add an index parameter in you method to know which element from the list use. Then you increment the index once before making the recursive calls...

Here is some code (without constructors getters etc...):

public class Translations {
    final String key;
    final Set<String> translations;
}

public static void addAllReplacements_2 (String source,List<Translations> translationsList, final int index, Set<String> targets) {
    if (index == (translationsList.size())) {
        // no more replacements:
        targets.add(source);
    } else {
        // pick an entry
        Translations translations = translationsList.get(index);
        String text = translations.getKey();
        Set<String> translationValues = translations.getTranslations();

        final int nextIndex = index+1;

        for (String translationValue: translationValues) {
            addAllReplacements_2(
                    source.replace(text, translationValue),
                    translationsList,nextIndex,
                    targets);
        }

    }
}


CSV Creation from two tables with URL for user to click on The code works but with an increase in data it's now slower so needs a tweak so looking for pointers.

'To import into Module
    Dim sConnString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("SQL").ConnectionString
        Dim vDateNow As Date = Now()
    vDateNow = vDateNow.ToString("dd-MMMM-yyyy")
    Dim vDateNowStr As String = Replace(vDateNow, "/", "-")
    Dim vURL As String = "C:\Sites\Website\www\Reports\"

Private Sub PrcBespokeReports(vDateNowStr As String, vURL As String)
        '"#######################################################
        Dim vReportName As String = "Overall Risk Category"
        '"#######################################################
        '"CSV create code
        '"######## Define the string
        Dim str As New StringBuilder
        '"######## Define the string
        '"########Connection code
         Dim dsNames As New SqlDataSource
        dsNames.ConnectionString = sConnString
        Dim sSQL As String = ""
        Dim sSQLAttach As String = ""

'Main code

        sSQL = "SELECT a.ID AS ID,  a.UPRN,p.BuildingNo,p.Street,p.Postcode ,a.ItemRef,a.SurveyDate ,a.OverallRiskCategory ,a.SurveyorsComments FROM TblAsbestos AS a JOIN TblProperty As p on a.UPRN = p.UPRN ORDER BY a.OverallRiskCategory"

        dsNames.SelectCommand = sSQL
        '"########Connection code
        '"########Loop code to get data
        str.Append(Chr(34) & "Report By Site to show ACM: - " & vDateNowStr & Chr(34) & ",")
        str.Replace(",", vbNewLine, str.Length - 1, 1) ' go to next line

        Dim arrNames As New ArrayList
        With arrNames
            .Add("UPRN")
            .Add("BuildingNo")
            .Add("Street")
            .Add("Postcode")
            .Add("ItemRef")
            .Add("SurveyDate")
            .Add("OverallRiskCategory")
            .Add("SurveyorsComments")
        End With

        For i As Integer = 0 To arrNames.Count - 1
            str.Append("=" & Chr(34) & arrNames(i).ToString() & Chr(34) & ",")
        Next

        str.Replace(",", vbNewLine, str.Length - 1, 1) ' go to next line

    'The above sets the headers and the array

        For Each datarow As Data.DataRowView In dsNames.Select(DataSourceSelectArguments.Empty)

            'Create the string / string builder and bring in the datarows
            For i As Integer = 0 To arrNames.Count - 1
                str.Append("=" & Chr(34) & Trim(Replace(If(TryCast(datarow(arrNames(i).ToString).ToString, String), ""), vbTab, " ") & Chr(34) & ","))
            Next
            '"########
            str.Replace(",", vbNewLine, str.Length - 1, 1) ' go to next line
        Next
    'Completed
        str.Append("Searched:" & sSQLAttach)

        '"Create CSV file or totally overwrites all data in CSV file
        My.Computer.FileSystem.WriteAllText((vURL & vDateNowStr & "_" & vReportName & ".csv"), str.ToString & "Created " & vDateNowStr, False)
        'Show CSV Link
        Dim vHyperLinkPath As String
        vHyperLinkPath = "http://Website.Net/Reports/" & vDateNowStr & "_" & vReportName & ".csv"
        CSVLinkName.Visible = vHyperLinkPath
        CSVLinkName.Visible = True

    End Sub

One thing that will help is to replace the ArrayList with a List(Of String).  This will eliminate all the calls to ToString every time you want to get the value of an item in the list.  Also you can build the output string as you add the items, rather than iterating over it again.

Dim arrNames As New List(Of String)
With arrNames
    .Add("UPRN")
    str.Append("=" & Chr(34) & "UPRN" & Chr(34) & ",")
    .Add("BuildingNo")
    str.Append("=" & Chr(34) & "BuildingNo" & Chr(34) & ",")
    .Add("Street")
    str.Append("=" & Chr(34) & "Street" & Chr(34) & ",")
    .Add("Postcode")
    str.Append("=" & Chr(34) & "Postcode" & Chr(34) & ",")
    .Add("ItemRef")
    str.Append("=" & Chr(34) & "ItemRef" & Chr(34) & ",")
    .Add("SurveyDate")
    str.Append("=" & Chr(34) & "SurveyDate" & Chr(34) & ",")
    .Add("OverallRiskCategory")
    str.Append("=" & Chr(34) & "OverallRiskCategory" & Chr(34) & ",")
    .Add("SurveyorsComments")
    str.Append("=" & Chr(34) & "SurveyorsComments" & Chr(34) & ",")
End With

Also in this line:

str.Append("=" & Chr(34) & Trim(Replace(If(TryCast(datarow(arrNames(i).ToString).ToString, String), ""), vbTab, " ") & Chr(34) & ","))

The TryCast is redundant since calling the ToString method will always return some sort of a string.


Batch bash installer script for clean Ubuntu GNOME installation I just finished (I think) writing a bash script to install all my essential software to Ubuntu GNOME. I'll be making more for different distributions but once I have one to go off of, I can do the rest fine.

I am very new to it all, however, and have barely gotten into using the cli so I'm sure that there are a ton of errors below. If you could just read through it and let me know what I can fix/improve, that would be wonderful! This is meant to run a nearly clean install; I'll have to open Firefox and download two files; the script and the extensions list. Other than that, everything is still set to default.

#!/bin/bash
sudo apt-get install -y gnome-tweak-tool
sudo apt-get install -y variety
sudo apt-get install -y hunspell-en-gb
sudo apt-get install -y gdebi
sudo apt-get install -y gparted
sudo apt-get install -y libreoffice-style-breeze
sudo apt-get install -y evolution
sudo apt-get install -y evolution-indicator
sudo apt-get install -y cairo-dock
cd
cd Downloads
mkdir Programs
cd Programs
wget https://steamcdn-a.akamaihd.net/client/installer/steam.deb
sudo dpkg -i steam.deb
sudo apt-get install -f
wget https://atom.io/download/deb
sudo dpkg -i atom*
sudo apt-get install -f
wget https://www.realvnc.com/download/file/vnc.files/VNC-Server-6.2.0-Linux-x64.deb
sudo dpkg -i VNC-Server*
sudo apt-get install -f
wget https://www.realvnc.com/download/file/viewer.files/VNC-Viewer-6.17.731-Linux-x64.deb
sudo dpkg -i VNC-Viewer*
sudo apt-get install -f
sudo cd /usr/share/icons
wget https://dl.opendesktop.org/api/files/download/id/1464728434/164587-bridge.tar.gz
tar -xvzf 164587-bridge.tar.gz
sudo add-apt-repository ppa:papirus/papirus
sudo apt update
sudo apt-get install papirus-icon-theme
sudo apt install numix-gtk-theme
xterm -e "echo Make sure you select Bridge as the cursor, Papirus as the icon theme, and Numix as the GTK+ theme && gnome-tweak-tool"
cd
xterm -e "echo Replace whatever is there with Bridge && sudo gedit /usr/share/icons/default/index.theme"
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-key FDC247B7
echo 'deb https://repo.windscribe.com/ubuntu zesty main' | sudo tee /etc/apt/sources.list.d/windscribe-repo.list
sudo apt-get update
sudo apt-get install windscribe-cli
xterm windscribe login && windscribe start && echo Connect to Windscribe with windscribe connect best
echo All thats left is to do is, if youre using GNOME, enable all of your chosen extensions at extensions.gnome.org
cd
echo Use gedit /Documents/Scripts/Extension_Links to view my links to GNOME Shell Extensions

Wall of code

The script looks like a wall of code.
It would be a lot more pleasant to read if related groups of commands were separated from each other by blank lines, for example:

# install steam
wget https://steamcdn-a.akamaihd.net/client/installer/steam.deb
sudo dpkg -i steam.deb
sudo apt-get install -f

# install atom
wget https://atom.io/download/deb
sudo dpkg -i atom*
sudo apt-get install -f

Displaying info

This is not a very user-friendly (or pretty) way to show a message to the user before opening gnome-tweak-tool:

xterm -e "echo Make sure you select Bridge as the cursor, Papirus as the icon theme, and Numix as the GTK+ theme && gnome-tweak-tool"

Since you are on a Gnome Desktop, you can benefit from zenity,
a scriptable tool to display dialogs, for example like this:

zenity --info --text="Make sure you select Bridge as the cursor, Papirus as the icon theme, and Numix as the GTK+ theme" && gnome-tweak-tool

Pointless command

This command will have no useful effect:

sudo cd /usr/share/icons

In fact, instead of this:

sudo cd /usr/share/icons
wget https://dl.opendesktop.org/api/files/download/id/1464728434/164587-bridge.tar.gz
tar -xvzf 164587-bridge.tar.gz

You probably want to do something like this:

wget -O /tmp/bridge.tar.gz https://dl.opendesktop.org/api/files/download/id/1464728434/164587-bridge.tar.gz
sudo tar -xvzf /tmp/bridge.tar.gz -C /usr/share/icons

That is, download the tarball to a temporary folder,
and extract the content with root into /usr/share/icons.


I want to verify if argument value passed to a function is an instance of X I want to make sure that some arguments are instance of a class.
Here is my code, is there a better approach?

class Object(object):

    @property
    def _attr_classes(self):
        return {'x': str, 'y': int}

    def __init__(self, x=None, y=None):

        self.x = x
        self.y = y

    def __setattr__(self, attr_name, value):

        if attr_name in self._attr_classes:
            correct_instance = self._attr_classes[attr_name]
            if value and isinstance(value, correct_instance) is False:
                raise TypeError('Error for key argument: "{0}", value: "{1}" is not instance of "{2}"'.
                                format(attr_name, value, correct_instance))
        return super(Object, self).__setattr__(attr_name, value)

You have a subtle bug in your line if value and isinstance(value, correct_instance) is False:

First, you should not identity compare to False, just use if value and not isinstance(value, correct_instance):.

Now, what if value is a falsey value, for example consider trying to do obj = Object(); obj.y = "". This will not raise a TypeError, because "" is not a truthy value, so it will never get to the isinstance because of short-circuiting.

I'm not sure why you have it in there in the first place. Were you trying to protect against None values? If that is the case, use if value is not None. Here you want identity comparison (and not equality/truthiness).

As Peilonrayz said in the comments, this is mentioned at the end of PEP8, Python's official style-guide. It is worth a read and actually quite readable.

What is nice about your code is that it allows allowing multiple classes. isinstance takes a tuple of classes to check or a single class.
So you could use {'x': str, 'y': (int, float)} and it should still work.


Parallelized for loop in Bash I am using a Bash script to execute a Python script multiple times. In order to speed up the execution, I would like to execute these (independent) processes in parallel. The code below does so:

#!/usr/bin/env bash

script="path_to_python_script"
N=16 # number of processors
mkdir -p data/

for i in `seq 1 1 100`; do
    for j in {1..100}; do
    ((q=q%N)); ((q++==0)) && wait

    if [ -e data/file_$i-$j.txt ]
    then
        echo "data/file_$i-$j.txt exists"
    else
        ($script -args_1 $i > data/file_$i-$j.txt ;
        $script -args_1 $i -args_2 value -args_3 value >> data/file_$i-$j.txt) &
        fi
    done
done

However, I am wondering if this code follow common best practices of parallelization of for loops in Bash? Are there ways to improve the efficiency of this code?

Some suggestions:

The trailing slash in the mkdir command is redundant.
$(…) is preferred over backticks for command substitution.
Why use seq in one command? They both do the same loop, so you might as well use {1..100} in both places.
Semicolons are unnecessary in the vast majority of cases. Simply use a newline to achieve the same separation between commands.
Use More Quotes™
set -o errexit -o noclobber -o nounset at the start of the script will be helpful. It'll exit the script instead of overwriting any files, for example, so you can get rid of the inner if statement if it's OK that the script stops when the file exists.
[[ is preferred over [.
The whole exercise is probably easier to achieve with some standard pattern like GNU parallel. Currently the script starts N commands, then waits for all of them to finish before starting any more. Unless the processes take very similar time this is going to waste a lot of time waiting.
N (or for example processors for readability) should be determined dynamically, using for example nproc --all, rather than hardcoded.
If you're worried about speed you should probably not create a subshell for your two script commands. { and } will group commands without creating a subshell.
For the same reason you probably want to do a single redirection like { "$script" … && "$script" …; } > "data/file_${i}-${j}.txt"
Since you're "only" counting to 10,000 you don't need to reset q every time. You can for example set process_count=0 outside the outer loop and check the modulo in a readable way such as:

if [[ "$process_count" % "$processors" -eq 0 ]]
then
    wait
fi

The inner code (from the line starting with ((q=q%N))) should be indented one more time.


Finding domain details with bash Here is my code to find the details of the domain. The domain can be feed as following:

bash script.sh domain1.com domain2.com
bash script.sh domains.txt <-- not completed

The output should be in following format:

IP Address: 192.168.101.2
Server Name: servername.com
NS1: ns1.ournameserver.com
NS2: ns2.ournameserver.com
NS3: ns3.ournameserver.com
Datacenter: datacenter-name
Region: datacenter-13
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx
Status: Active

IP Address: 192.168.101.2
Server Name: servername
NS1: ns1.ournameserver.com
NS2: ns2.ournameserver.com
NS3: ns3.ournameserver.com
Datacenter: datacenter-name
Region: datacenter-13
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx
Status: Suspended

If it is in cloudflare:

Domain name: test.com
IP Address: 192.168.101.1
Server ID: N/A
Server Name: N/A
NS1: LYNDA.CLOUDFLARE.COM
NS2: DYN.CLOUDFLARE.COM
Datacenter: OVH
Region: HETZ-C3
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx

Now it is only giving result in normal format, it also needs to be in JSON format

script.sh

#!bin/bash
HIP="$@"
check ()
{
    regexp="^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
    nameserver=('@ns1.ournameserver.com' '@ns2.ournameserver.com' '@ns3.ournameserver.com')

    for j in ${nameserver[@]}
       do
          IPADD=`dig $j $i +noall +answer | grep "A" | awk '{print $5}'`
          if [[ $IPADD =~ $regexp ]]
            then
                echo "IP Address = " $IPADD
                ServerName=`nslookup $IPADD | grep -o -P '(?<=\=).*(?=.)'`
                echo "ServerName = " $ServerName
                DATA=`whois $IPADD | egrep 'org-name|OrgName' | awk '{print $2.$3}'`
                echo "Data Center = " $DATA
                break
          fi
       done
}

check2 ()
{
    Pinging=`ping $i -c 1 | grep 'from' | cut -d$' ' -f4-5| tr '\(|\)' ' '`
    IPADD=`awk '{print $2}' <<< $Pinging`
    echo "IP Address = " $IPADD
    ServerName=`awk '{print $1}' <<< $Pinging`
    echo "Server Name = " $ServerName
}

for i in ${HIP[@]}
do
    echo "Domain Name = " $i;
    nsserver=`nslookup -type=ns $i | grep 'nameserver' |  grep -o -P '(?<=ns.).*(?=.)' | head -n 1`
    if [[ $nsserver == 'cloudflare.com' ]]
    then
            check
        if ! [[ $IPADD =~ $regexp ]]
        then
                echo "This Domain does not belong to this server."
        fi
    else
        check2
    fi

    whois $i | grep "Registrant Name"
    nslookup -type=ns $i | grep nameserver | awk '{print $2,$3,$4}'
    var=`curl -sL $i | grep '<title>' | tr -d ' ' | grep -o -P '(?<=Account).*(?=ed)'`
    if [[ $var == 'Suspend' ]]
        then
        echo "Status = Account Suspended"
        else
        var=`curl -I $i 2>/dev/null | head -n 1 | cut -d$' ' -f2-3`
        echo "Status = " $var
    fi
    printf '%*s' 100 | tr ' ' '#'
    echo ''

done

Shellcheck reports quite a few issues you might want to correct:
shellcheck -f gcc  197939.sh
197939.sh:2:5: warning: Assigning an array to a string! Assign as array, or use * instead of @ to concatenate. [SC2124]
197939.sh:5:24: note: Backslash is literal in "\.". Prefer explicit escaping: "\\.". [SC1117]
197939.sh:5:36: note: Backslash is literal in "\.". Prefer explicit escaping: "\\.". [SC1117]
197939.sh:5:48: note: Backslash is literal in "\.". Prefer explicit escaping: "\\.". [SC1117]
197939.sh:8:14: error: Double quote array expansions to avoid re-splitting elements. [SC2068]
197939.sh:10:17: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:10:22: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:10:25: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:13:38: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:14:28: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:14:38: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:15:38: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:16:22: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:16:29: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:16:38: note: egrep is non-standard and deprecated. Use grep -E instead. [SC2196]
197939.sh:17:39: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:25:13: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:25:19: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:26:11: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:26:33: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:27:26: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:28:16: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:28:38: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:29:27: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:32:10: error: Double quote array expansions to avoid re-splitting elements. [SC2068]
197939.sh:34:27: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:35:14: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:35:33: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:47:11: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:48:23: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:49:9: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:49:19: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:54:13: note: Use $(..) instead of legacy `..`. [SC2006]
197939.sh:54:22: note: Double quote to prevent globbing and word splitting. [SC2086]
197939.sh:55:26: note: Double quote to prevent globbing and word splitting. [SC2086]

Additionally, I recommend making regexp, nameserver, IPADD, ServerName and DATA local within check() (and giving most of them better names, or inlining the single-use ones), and making Pinging, IPADD and ServerName local within check2():
check ()
{
    local regexp='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
    local nameserver=('@ns1.ournameserver.com' '@ns2.ournameserver.com' '@ns3.ournameserver.com')

    for j in "${nameserver[@]}"
    do
        local IPADD
        IPADD=$(dig "$j" "$i" +noall +answer | grep "A" | awk '{print $5}')
        if [[ $IPADD =~ $regexp ]]
        then
            echo "IP Address = $IPADD"
            echo "ServerName = $(nslookup "$IPADD" | grep -o -P '(?<=\=).*(?=.)')"
            echo "Data Center = $(whois "$IPADD" | grep -E 'org-name|OrgName' | awk '{print $2.$3}')"
            break
        fi
    done
}

check2 ()
{
    local Pinging
    Pinging=$(ping "$i" -c 1 | grep 'from' | cut -d$' ' -f4-5| tr '\(|\)' ' ')
    echo "IP Address = $(awk '{print $2}' <<<"$Pinging")"
    echo "Server Name = $(awk '{print $1}' <<<"$Pinging")"
}

Prefer to pass "$i" as an argument to check(), rather than communicating via global variables.  And communicate the $IPADD from the last successful nameserver by other means.
Instead of extracting substrings using grep, then testing them with [[ =~ ]], simply use grep -q for the test.
Improved code
There's still plenty left to work on (for example, repeated whois invocations).
#!/bin/bash

check ()
{
    local regexp='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
    local nameserver=('ns1.ournameserver.com' 'ns2.ournameserver.com' 'ns3.ournameserver.com')

    for j in "${nameserver[@]}"
    do
        local IPADD
        IPADD=$(dig "@$j" "$1" +noall +answer | grep -w 'A' | awk '$4=="A" {print $5}')
        if [[ $IPADD =~ $regexp ]]
        then
            echo "IP Address = $IPADD"
            echo "ServerName = $(nslookup "$IPADD" | grep -o -P '(?<=\=).*(?=.)')"
            echo "Data Center = $(whois "$IPADD" | grep -E 'org-name|OrgName' | awk '{print $2.$3}')"
            return 0
        fi
    done
    return 1
}

check2 ()
{
    local Pinging
    Pinging=$(ping "$1" -c 1 | grep 'from' | cut -d$' ' -f4-5| tr '()' ' ')
    echo "IP Address = $(awk '{print $2}' <<<"$Pinging")"
    echo "Server Name = $(awk '{print $1}' <<<"$Pinging")"
}

for i in "$@"
do
    echo "Domain Name = $i"
    if nslookup -type=ns "$i" | grep -q 'nameserver.*cloudflare.com'
    then
        check "$i" || echo "This Domain does not belong to this server."
    else
        check2 "$i"
    fi

    whois "$i" | grep "Registrant Name"
    nslookup -type=ns "$i" | grep nameserver | awk '{print $2,$3,$4}'
    if curl -sL "http://$i" | grep -q '<title>.*Account.*Suspended'
    then
        echo "Status = Account Suspended"
    else
        echo "Status = $(curl -I "$i" 2>/dev/null | head -n 1 | cut -d$' ' -f2-3)"
    fi
    printf '%*s\n' 100 | tr ' ' '#'
done


Write output file, collating groups of up to 7 input lines I have this code that reads a file and after processing a few lines writes the output to a second file:

num_reads = 7
with open('data.txt') as read_file:
    with open('new_data.txt', 'w') as write_file:

        while (True):
            lines = []
            try:       # expect errors if the number of lines in the file are not a multiplication of num_reads
                for i in range(num_reads):
                    lines.append(next(read_file))  # when the file finishes an exception occurs here

                #do sutff with the lines (exactly num_reads number of lines)
                processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))
                write_file.write(processed + '\n')

            except StopIteration:     # here we process the (possibly) insufficent last lines
                #do stuff with the lines (less that  num_reads)
                processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))
                write_file.write(processed + '\n')
                break

Here is the input file (data.txt):

line1
line2
line3
line4
line5
line7
line8
line9

And this is the output file that has the desired state:

line1 line2 line3 line4 line5 line7
line8 line9

This works correctly but as I wish to do the same processing and writing procedure in both cases (when the number of elements is 7 and when the file finishes and the exception is raised) I think the above code violates DRY principle even if I define a new function and call it once in try block and once in except before break. Any other ordering that I could come up with was either causing an infinite loop or losing the final lines.
I appreciate any comments on handling this issue, as it is not limited to this case and I had faced it in other cases as well.

You should avoid writing code with exception-handling altogether.  Usually, when you want to write a fancy loop in Python, the itertools module is your friend.  In this case, I would take advantage of itertools.groupby() to form groups of lines, assisted by itertools.count() to provide the line numbers.

import itertools

def chunks(iterable, n):
    i = itertools.count()
    for _, group in itertools.groupby(iterable, lambda _: next(i) // n):
        yield group

with open('data.txt') as read_f, open('new_data.txt', 'w') as write_f:
    for group in chunks(read_f, 7):
        print(' '.join(line.rstrip() for line in group), file=write_f)

A few other minor changes:

You only need one with block to open both files.
line.rstrip() is more convenient than lambda x: x.replace("\n", '')
print(…, file=write_file) is slightly more elegant than write_file.write(… + '\n').


Find the max of a list using recursion Hi i needed to find the max int of a list using recursion, I have done it this way I'd like to know if you think is a good way, and I have a couple of questions:

int trovaMassimo(node_t *head){

    int e;
    if(head == NULL){//this can happen just the first time right?
        printf("Lista vuota\n");
        exit(1);
    }

    if(head->next == NULL)
        return head->val;

    e = trovaMassimo(head->next); //what will be assigned to e? doing this way doesn't e get modified all times till the last value? if yes isn't useless that if right under?

    if ( e < head->val )
        return head->val;
    else
        return e;
}

```

You have a portability bug, because names ending in _t are reserved for future Standard Library types.  Rename node_t, perhaps to Node.

This kind of recursion is problematic, because it can't be transformed into iterative form by the compiler.  It needs to keep each call's e value until all the inner recursive calls have completed, before it can do the comparison.

If you can, strive to make your function tail-recursive, which means that it's in the form:

ResultType function(args) {
    ...
    return function(other_args);
}

To make a non-tail recursive function into a tail-recursive one, you generally need to pass the current state into the recursive call.

Here, I'd actually split the function into two: a recursive function to find the node_t with largest value (or NULL if the list is empty), and a wrapper function to call it with the right parameters, extract the result, and handle errors:

/* untested */

static const Node *find_node_max(Node *list, Node *best_so_far)
{
    if (!list) {
       return best_so_far;
    }
    if (!best_so_far || list->val > best_so_far->val) {
        best_so_far = list;
    }
    return find_node_max(list->next, best_so_far);
}

int trovaMassimo(const Node *head) {
    const Node *n = find_node_max(head, NULL);
    if (!n) {
        /* empty list - N.B. message to stderr, not stdout */
        fputs("Lista vuota\n", stderr);
        exit(1);   /* not good in library code */
    }
    return n->val;
}


Custom networked remote manager I've spent my fair share of time criticizing other people's code on this site; but I'm finding out I'm kind of a hypocrite. Almost everything I've written so far has been some program whipped together to do some task for me. I have little experience actually starting out writing maintainable code.

Then today I decided to start a semi-large project. I want to write a sort of custom networked remote manager; a kind of cross-breed between ssh and an all-out remote desktop.

I wrote up the following class while realizing the previous revelations:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

public abstract class Connection implements Runnable {
    private final Socket s;
    private final InputStream is;
    private final OutputStream os;
    private final ArrayList<byte[]> posts;
    private boolean run;
    public Connection(String addr, int port) throws UnknownHostException, IOException {
        s = new Socket(addr, port);
        is = s.getInputStream();
        os = s.getOutputStream();
        posts = new ArrayList<>();
        run = true;
        new Thread(this).start();
    }
    public void post(byte data[]) {
        synchronized (posts) {
            posts.add(data);
        }
    }
    public void stop() {
        run = false;
    }
    public void run() {
        while (run) {
            byte send[] = null;
            synchronized (posts) {
                if (posts.size() > 0) {
                    send = posts.get(0);
                    posts.remove(0);
                }
            }
            if (send != null) {
                try {
                    os.write(send);
                } catch (IOException e) {
                    hasError(e);
                }
            }
            try {
                if (is.available() > 0) {
                    byte data[] = new byte[is.available()];
                    receive(data, is.read(data));
                }
            } catch (IOException e) {
                hasError(e);
            }
        }
    }
    public abstract void receive(byte data[], int len);
    public abstract void hasError(Exception e);
}

It occurred to me I should probably be asking here how maintainable code is actually written. I'm kind of ashamed I haven't done this sort of thing before, but as a self-taught programmer I presume this sort of obstacle is common.

Given the above sample of my idea of how to make maintainable modular code, what sort of pitfalls should I look out for while making the excursion into a legitimate program of larger than two or three files?

new Thread(this).start();

I may be wrong about this, but I don't think this is recommended in the constructor.

ExecutorService implementations exist to provider better/consistent handling of asynchronous tasks. Arguably, a better form will be to extend your abstract class and use it with an ExecutorService instance, instead of having it (Connection) decide when to start running.

Inside your run() method, you may want to consider the following rewrite as it is slightly more expressive and reduces one level of nesting:

while (run) {
    byte send[] = null;
    synchronized (posts) {
        if (posts.isEmpty()) {
            continue;
        }
        send = posts.get(0);
        posts.remove(0);
    }
    // send != null probably not required, as long as post() does not accept null
    // if (send != null) {
    try {
        os.write(send);
    } catch (IOException e) {
        hasError(e);
    }
    // }
    // ...
}

Considering you are doing something like:

posts.get(0);
posts.remove(0);

You might actually be looking for a Queue implementation to simplify this approach. In fact, you may be looking for a thread-safe implementation so that you do not need the explicit synchronized blocks, such as something that implements a BlockingQueue.

  Given the above sample of my idea of how to make maintainable modular code, what sort of pitfalls should I look out for while making the excursion into a legitimate program of larger than two or three files?

A thorough answer for this will be out-of-scope here on CR, so my only advice is to perhaps ask that on Programmers.SE (as long as you can make it on-topic there). :)


Split Django into apps I am thinking about how to split my website into smaller reusable apps.  I've finally figured out something and need your opinion.

My main problem was that each app uses Profile model.  This is of course a snippet of my work with the most important parts.

# App Userdata
class BaseProfile(models.Model):
    city = models.CharField(max_length=100, null=True, blank=True)
    user = models.OneToOneField(User)

class Photo(models.Model):
    profile = models.ForeignKey(BaseProfile)
    url = models.URLField()

# App Social Connect
class SocialConnectProfile(models.Model):
    pass

class SocialConnect(models.Model):
    profile = models.ForeignKey(SocialConnectProfile)

# App Forum
class ForumProfile(models.Model):
    pass

class Question(models.Model):
    profile = models.ForeignKey(ForumProfile)

class Answer(models.Model):
    profile = models.ForeignKey(ForumProfile)
    question = models.ForeignKey(ForumProfile)

# App Base
class Profile(BaseProfile, SocialConnectProfile, ForumProfile):
    pass

What I am worrying about is that there are 5 tables with a one-to-one relationship.
What do you think?  Are there any better options?

Yes, the code has been pretty much simplified. Each app has many models indeed. (BaseProfile has 8, SocialConnect only 1, Forum 18)

My target is to extract them as Python-Django components in future, but I haven't done it before.

I want to project them in this way now to save time in future with new applications or extending existing one, but I am not sure  if it's the best approach.

It depends really on how you will use those models.
For example if you always, always get question object then find the answers that belong to it. there is no point adding profile relation with answers models and keep it to questions only.

If in rare cases (not in loops) you might deal with an answer without getting its question object first, its still ok to do answer.question.profile


Given a monetary amount, calculate the equivalent change I have written a program that takes in some amount of money, and prints the equivalent change (starting at hundred dollars, to fifty, to twenty, down the pennies). Here is the code:

System.out.print("Enter amount of money: ");
Scanner scan = new Scanner(System.in);

double value = scan.nextDouble();
int valueIntegral = (int) value;
int valueFractional = (int) Math.round(100 * value - 100 * valueIntegral);

// Integral values

int hundred = valueIntegral / 100;

int fifty = (valueIntegral % 100) / 50;

int twenty = ((valueIntegral % 100) % 50) / 20;

int ten = (((valueIntegral % 100) % 50) % 20) / 10;

int five = ((((valueIntegral % 100) % 50) % 20) % 10) / 5;

int one = (((((valueIntegral % 100) % 50) % 20) % 10) % 5) / 1;

// Fractional values

int quarter = valueFractional / 25;

int dime = (valueFractional % 25) / 10;

int nickel = ((valueFractional % 25) % 10) / 5;

int penny = (((valueFractional % 25) % 10) % 5) / 1;

System.out.println(hundred + " hundred dollar bills\n" +
                   fifty + " fifty dollar bills\n" +
                   twenty + " twenty dollar bills\n" +
                   ten + " ten dollar bills\n" +
                   five + " five dollar bills\n" +
                   one + " one dollar bills\n" +
                   quarter + " quarters\n" +
                   dime + " dimes\n" +
                   nickel + " nickels\n" +
                   penny + " pennies");

What I want to know is that without using loops or any iterative structures is this an acceptable way to accomplish this task? What would be a more elegant way? (those chains of modulo division are ugly)

Without loops or similar "advanced" structures, there isn't much you can do to simplify this.

You could save the duplication in extra variables. It might look like this:

int hundred = valueIntegral / 100;

int remainderHundred = valueIntegral % 100;
int fifty = remainderHundred / 50;

int remainderFifty = remainderHundred % 50;
int twenty = remainderFifty / 20;

int remainderTwenty = remainderFifty % 50;
int ten = remainderTwenty / 10;

[...]

You have to decide if it's more readable. It's certainly less complex (and mistakes/typos are easier to catch), but it might take away some clarity.

Misc

you have a bit too much vertical space. Not every line needs its own paragraph.
your comments don't add all that much value. The variable names already tell me all the comments do.


How would you better organize/code this basic HTML and CSS? I'm curious to see what any of the more experienced programmers would do instead of methods I took as a learning tool. Any tips/tricks/fixes and reasoning is appreciated!!

http://www.jacobweyer.com

This is the result of the code so far:

<!DOCTYPE html>

<title>Alpha Tau Omega | Theta Omega</title>
<link rel="stylesheet" type="text/css" href="ATOStyle.css" />

Home

Rush

History

Alumni

Calendar

Media

CSS

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, figure, footer, header,&nbsp;hgroup, menu, nav, section, menu,
time, mark, audio, video {
margin:0px;
padding:0px;
border:0px;
outline:0px;
font-size:100%;
vertical-align:baseline;
background:transparent;
}

#navbar ul {
list-style-type: none;
margin: 0px;
padding: 0px;
}

#navbar ul li a {
text-decoration: none;
color: black;
}
#navbar ul li a:hover {
color: white;
}

#navbar ul li {
font-family: Arial, Helvetica, sans-serif;
text-decoration: none;
color: #000000;
display: inline-block;
width: 70px;
height: 40px;
margin: 10px;
}

#banner {
background:url(./pieces/banner.png);
position: absolute;
margin-left: 0px;
min-height: 193px;
min-width: 183px;
background-repeat: no-repeat
}

#title {
position: absolute;
background: url(./pieces/name.png);
margin-left: 190px;
min-height: 75px;
min-width: 285px;
}

#navbar {
position: relative;
top: 80px;
left: 210px;
margin-left: inherit;
}
#social ul li{
display: inline-block;
width: 35px;
height: 35px;
margin: 5px;
}
#social {
position: absolute;
float: left;
right: 180px;
top: -5px;
}
#social ul {
list-style-type: none;
}

#innerheader {
height: 139px;
width: 750px;
margin-right: auto;
margin-left: auto;
position: relative;
}

#header {
background:url(./pieces/headerBar.png);
position: static;
width:100%;
height:139px;
padding:0;
border:0;
z-index: 10000;
}

#pagecenter {
position: static;
margin-right: auto;
margin-left: auto;
height: 50px;
width: 750px;
min-height: 1000px;
background:url(./pieces/mainBG.png);
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
margin-top: -19px;
z-index:50
}
body {
width: 100%;
margin: 0px 0px 0px 0px;
background-color: #808080
}
#footer {
margin-top: 20px;
padding-top: 30px;
background: url(./pieces/footerbar.png);
height: 77px;
width: 100%;
margin-right: auto;
margin-left: auto;
clear: both;
bottom: 0px;
position: static;
}

#footerbanner {
background: url(./pieces/footerbanner.png);
position: absolute;
min-height: 95px;
min-width: 90px;
background-repeat: no-repeat;
margin-top: -30px;
}

A lot of this type of stuff is just personal style, or if you're working on a team, the layout is defined ahead of the project.

The use of classes vs id's is also personal. I've seen people say that they ALWAYS use classes. I've tried both classes and id's on many pages, and I find that I get into fewer problems with mostly classes, reserving id's for truly individual elements.

I've read that the stuff at the top of your CSS can slow things down quite a bit and may not be necessary in many cases.

I formatted the last two parts of your CSS a bit differently. I do that a lot with PHP, but have seen in recently in CSS, and I think it might work nicely in some situations.

But for fun...

<!DOCTYPE html>

  <title>Alpha Tau Omega | Theta Omega</title>
  <link rel="stylesheet" type="text/css" href="ATOStyle.css" />

Home

Rush

History

Alumni

Calendar

Media

CSS

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, figure, footer, header,&nbsp;hgroup, menu, nav, section, menu,
time, mark, audio, video {
  margin: 0px;
  padding: 0px;
  border: 0px;
  outline: 0px;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}
#navbar ul {
  list-style-type: none;
  margin: 0px;
  padding: 0px;
}
#navbar ul li a {
  text-decoration: none;
  color: black;
}
#navbar ul li a:hover {
  color: white;
}
#navbar ul li {
  font-family: Arial, Helvetica, sans-serif;
  text-decoration: none;
  color: #000000;
  display: inline-block;
  width: 70px;
  height: 40px;
  margin: 10px;
}
#banner {
  background:url(./pieces/banner.png);
  position: absolute;
  margin-left: 0px;
  min-height: 193px;
  min-width: 183px;
  background-repeat: no-repeat
}

#title {
  position: absolute;
  background: url(./pieces/name.png);
  margin-left: 190px;
  min-height: 75px;
  min-width: 285px;
}
#navbar {
  position: relative;
  top: 80px;
  left: 210px;
  margin-left: inherit;
}
#social ul li{
  display: inline-block;
  width: 35px;
  height: 35px;
  margin: 5px;
}
#social {
  position: absolute;
  float: left;
  right: 180px;
  top: -5px;
}
#social ul {
  list-style-type: none;
}

#innerheader {
  height: 139px;
  width: 750px;
  margin-right: auto;
  margin-left: auto;
  position: relative;
}

#header {
  background:url(./pieces/headerBar.png);
  position: static;
  width:100%;
  height:139px;
  z-index: 10000;
}

#pagecenter {
  position: static;
  margin-right: auto;
  margin-left: auto;
  height: 50px;
  width: 750px;
  min-height: 1000px;
  background: url(./pieces/mainBG.png);
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  margin-top: -19px;
  z-index:50
}
body {
  width: 100%;
  margin: 0px 0px 0px 0px;
  background-color: #808080
}
#footer {
  margin-top:   20px;
  padding-top:  30px;
  background:   url(./pieces/footerbar.png);
  height:       77px;
  width:        100%;
  margin-right: auto;
  margin-left:  auto;
  clear:        both;
  bottom:       0px;
  position:     static;
}
#footerbanner {
  background:        url(./pieces/footerbanner.png);
  position:          absolute;
  min-height:        95px;
  min-width:         90px;
  background-repeat: no-repeat;
  margin-top:        -30px;
}


DataService data storage I have a DataService, which should talk to the server and store vars (for complicated calls, for example).

Last time, I ended up with this approach (for the example, I'm working with a list):

GetList() - returns cached data (just a property)
SetList() - sets a property
ReadList() - read data from file from IsoStorage
WriteList() - write data to file
PullList() - pull data from the server
PushList() - push data to the server

NB: I'm using my old IsoStorage approach (IsoSettingsManager).

Now, after some time, I understood that I can merge first two stages: caching and writing to IsoStorage. Now I'm thinking of something like

    private int? deliveryId = null;
    public int DeliveryId
    {
        get { return deliveryId ?? IsoSettingsManager.GetProperty<int>("DeliveryId"); }
        set { deliveryId = value; IsoSettingsManager.SetProperty("DeliveryId", value); }
    }

Where setting property is

public static void SetProperty(string propertyName, object content)
    {
        if (System.ComponentModel.DesignerProperties.IsInDesignTool)
            return;

        if (content == null)
            RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);

        isoSettings[propertyName] = content;
        isoSettings.Save();
    }

What do you think about it?

First thing that comes to my mind is to make SetProperty to return the setted value so I'd be able to use it like

public int DeliveryId
{
    set { deliveryId = IsoSettingsManager.SetProperty("DeliveryId", value); }
    ***

unsetting DeliveryId = null; is not working for ints (fair enough), and I couldn't yet find how to push/pull them effectively.

Style

It won't hurt you and makes your code less error prone, if you would use braces {} also for single if statements.

Commented code (// if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);) should be removed completely. You should instead use a code versioning system like svn or git.

Update based on the comments below
It is not about a comment but about commented out code which is just dead code. What value has dead code ? Does it make your live code more readable or does it make your live code easier to understand ? No, it is quite the opposite.

Asume the following

public static void SetProperty(string propertyName, object content)
{
    //if (System.ComponentModel.DesignerProperties.IsInDesignTool)
    //    return;

    //if (content == null)
        RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);

    isoSettings[propertyName] = content;
    isoSettings.Save();
}

this is quite hard to read and understatnd by Mr.Maintainer.

This instead

public static void SetProperty(string propertyName, object content)
{
    RemoveProperty(propertyName);

    isoSettings[propertyName] = content;
    isoSettings.Save();
}

is much better to understand.

If you check something into svn/git you always should add a descriptive message to the commit.

SetProperty() method

if (content == null)
        RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);

    isoSettings[propertyName] = content;
    isoSettings.Save();

this does not make sense to me. If content==null you first remove the property, and then you add it. Next time passing null you just do the same.

You should consider returning after you have removed the property. There is no need to save the setting.

SetProperty() returning setted value

This is in my opinion a bad idea for a method which seems to be like a property setter. A property setter should only set a properties value.


Common styles in React-Native Background:
I am completely new to react-native.

Question:
Is there any reason why I shouldn’t do this from an experienced point of view?

Goal:
- have common styles in my react-native app?
- use advantages of VSCode IntelliSense for development.

#common/styles.js

import { Platform, StyleSheet } from 'react-native';

export const styles = StyleSheet.create({
  fontFamily: {
    ...Platform.select({
      ios: {
        fontFamily: 'Baskerville',
      },
      android: {
        fontFamily: 'Noto Sans',
      },
    }),
  },
});

export const fonts = {
  h2: { fontSize: 80 },
  text: { fontSize: 12 },
};

export const BORDER_RADIUS = 5;

export const colors = {
  blue_primary: '#3F51B5',
  blue_secondary: '#E8EAF6',
  green_primary: '#73C700',
  green_secondary: '#F1F8E9',
  white: '#ffffff',
  grey_primary: '#9E9E9E',
  grey_secondary: '#FAFAFA',
  bluegrey: {
    50: '#eceff1',
    800: '#37474f',
    900: '#263238',
  },
};

Here is a plain component using this common styles:

import React from 'react';
import { View, Text } from 'react-native';
import { colors, styles, fonts } from './common/styles';

const PlainComponent = () => (
  <View style={{ flex: 1, backgroundColor: colors.bluegrey['50'] }}>
    <Text style={[fonts.h2, styles.fontFamily, { color: 'red' }]}>Hello</Text>
  </View>
);

export default PlainComponent;

While sharing styles is possible, I find it a little cumbersome and personally, I would not do it. Instead, I'd recommend going one level higher: do not share styles, share components.

That's what React is about - sharing components. In React Native, you won't have to import a component and styles (and pass the styles to the component), you'll just have to import the component. There will be less duplication.

I'd recommend you take a look at styled-components or glamorous-native, and see their utilities for defining styles, extending them and other utilities. They will make working with styles and components easier.


Assigning card values Is there a better way to do this?

This function takes, as an argument, a natural number, n, which is between 1 and 52 inclusive and returns a list containing the point value associated with that number as an integer. The aces are the numbers 1,14,27,40 in the respective suits and they worth either 1 or 11 points. The regular cards with the numbers 2-10,15-23,28-36,41-49 in their respective suits are worth their face values. The face cards
are represented by the numbers 11-13,24-26,37-39,50-52 in their respective suits and they are each worth 10 points.

def getPoints(n):
    #the ace values
    if n == 1 or n == 14 or n == 27 or n == 40:
        return [1,11]
    #the regular card values
    if 2<=n<=10:
        return [n]
    if n == 15 or n == 28 or n == 41:
        return [2]
    if n == 16 or n == 29 or n == 42:
        return [3]
    if n == 17 or n == 30 or n == 43:
        return [4]
    if n == 18 or n == 31 or n == 44:
        return [5]
    if n == 19 or n == 32 or n == 45:
        return [6]
    if n == 20 or n == 33 or n == 46:
        return [7]
    if n == 21 or n == 34 or n == 47:
        return [8]
    if n == 22 or n == 35 or n == 48:
        return [9]
    if n == 23 or n == 36 or n == 49:
        return [10]
    if 11<=n<=13 or 24<=n<=26 or 37<=n<=39 or 50<=n<=52:
        return [10]

Instead of making a function that maps a number from 1 to 52 you can reduce your domain to 1 to 13, and use modulo 13 to every number. That will reduce 75% of your conditions. It is done with a bit of modulo math.
Then this function becomes quite short:

def getPoints(n):
    n = (n-1) % 13 + 1
    #the ace values
    if n == 1:
        return [1,11]
    #the regular card values
    if 2<=n<=10:
        return [n]
    if 11<=n<=13:
        return [10]


Delete temp files and empty recycle bin I was wondering if someone could help critique this code I put together. It is supposed to delete all temp files and folders and then empty the recycle bin. I had to make some adjustments because using Pyinstaller, I wanted the console to stay open and have the user proceed after reading.

import os
file_size = os.path.getsize('C:\Windows\Temp')
print(str(file_size) + "kb of data will be removed")
import os, subprocess
del_dir = r'c:\windows\temp'
pObj = subprocess.Popen('rmdir /S /Q %s' % del_dir, shell=True, stdout =
subprocess.PIPE, stderr= subprocess.PIPE)
rTup = pObj.communicate()
rCod = pObj.returncode
if rCod == 0:
    print('Success: Cleaned Windows Temp Folder')
else:
    print('Fail: Unable to Clean Windows Temp Folder')
import winshell
winshell.recycle_bin().empty(confirm=False, show_progress=False,
sound=False)
from random import randint
from time import sleep
sleep(randint(4,6))
input("Press any key to continue")

I'm not sure this answer will be sufficient, but some quick things that jump out:

Keep your code organized:

Put imports at the top
Guard any serious code execution in a __name__ == '__main__' block (and usually use a main function as well)
Have blank space every few lines to visually separate logical groups of code
If the code doesn't document itself (and ideally, it should), add comments where necessary

Use consistent, conventionally Pythonic naming, such as using lower-case snake-case for variable names (e.g., return_code instead of rCod)
As a super minor detail, there are better ways to construct strings than adding them. A fairly modern, flexible way to do so is to use .format, or if you can be sure you're using Python 3.6+ then "f-strings" are wonderful)
It's really not clear why you sleep for a random amount of time at the end... If that's important, comment why so, otherwise probably don't do it. If there's something specific you're waiting on, figure out how to wait for it properly so you don't have a possible race condition.
I'm not super familiar with Windows commands and what /S /Q do to the rmdir command, but could you not just use os.rmdir(del_dir)?

Here's what your code might look like using the above suggestions:

import os
import subprocess
import winshell
from random import randint
from time import sleep

def main():
    file_size = os.path.getsize('C:\Windows\Temp')
    print("{} kb of data will be removed".format(file_size))
    del_dir = r'c:\windows\temp'

    # Could this just be os.rmdir(del_dir)???
    process = subprocess.Popen('rmdir /S /Q {}'.format(del_dir), shell=True,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    _ = process.communicate()
    return_code = process.returncode
    if return_code == 0:
        print('Success: Cleaned Windows Temp Folder')
    else:
        print('Fail: Unable to Clean Windows Temp Folder')

    winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False)

    # Is this important?
    # sleep(randint(4, 6))
    input("Press any key to continue")

if __name__ == '__main__':
    main()


Simple Calculator in Java and Swing I'm new at this and I'm almost done with learning basic Java. I made this just to see if I could do it. I just want to know if there's anything I can do to make it better.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.lang.Double.*;

class Calculator {
    private JFrame frame = new JFrame("Simple Calculator");
    private JPanel panel = new JPanel();
    private JTextField inputOne = new JTextField(5);
    private JTextField inputTwo = new JTextField(5);
    private JTextField output = new JTextField(20);
    private String[] symbols = {"\u002b", "\u2212", "\u00f7", "\u00d7"};
    private JComboBox list = new JComboBox(symbols);
    private JButton calculateButton = new JButton("Calculate");

    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        calculator.run();
    }

    public void run() {
        buttonListener buttonListener = new buttonListener();

        calculateButton.addActionListener(buttonListener);
        calculateButton.setFocusPainted(false);
        calculateButton.setBackground(Color.WHITE);
        calculateButton.setForeground(Color.BLACK);

        inputOne.addActionListener(buttonListener);
        inputTwo.addActionListener(buttonListener);
        output.setEditable(false);

        list.setBackground(Color.GRAY);
        list.setForeground(Color.WHITE);
        list.setEditable(false);
        list.setFocusable(false);

        panel.setBackground(Color.DARK_GRAY);
        panel.add(inputOne);
        panel.add(list);
        panel.add(inputTwo);
        panel.add(output);

        frame.getContentPane().add(BorderLayout.SOUTH, calculateButton);
        frame.getContentPane().add(BorderLayout.CENTER, panel);
        frame.setSize(300, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    static double calculate(double a, double b, String c) {
        double result = 0;

        if (c.equals("\u002b")) {
            result = a + b;
        } else if (c.equals("\u2212")) {
            result = a - b;
        } else if (c.equals("\u00f7")) {
            result = a / b;
        } else if (c.equals("\u00d7")) {
            result = a * b;
        }

        return result;
    }

    class buttonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (!inputOne.getText().equals("") & !inputTwo.getText().equals("")) {
                double numberOne = (parseDouble(inputOne.getText()));
                double numberTwo = (parseDouble(inputTwo.getText()));

                String function = (String) list.getSelectedItem();

                output.setText("" + Calculator.calculate(numberOne, numberTwo, function));
            }

        }
    }
}

pros

you don't inherit from JFrame (as too many tutorials out there do...)
you (almost) follow Java naming conventions
your variable names almost express the meaning of the values they hold

cons

you break Java Naming conventions with the ActionListener implementation.
frame.setVisible(true); is not the last line of frame configuration.
you use literal strings instead of constants with meaningful names
you use a static method.
you use an if/else cascade instead using polymorphism to find the calculation.

suggestions

Naming conventions

start class names with an uppercase letter.
start names of variables and methods with lower case letter
chose nouns to name classes and variables
start names of methods with a verb maybe followed by nouns.

position of frame.setVisible(true);

The problem with that is that modifications to the Layout may not be visible if dome after frame.setVisible(true);. Therefore you should get used to write it ata position where you cannot write something behind it by accident.

One way to asure this is to do the configuration in a method where you pass the JFrame as parameter and call  frame.setVisible(true); after that method like this:

   public static void main(String[] args) {
        JFrame frame = new JFrame("Simple Calculator");
        Calculator calculator = new Calculator();
        calculator.configureGui(frame);
        frame.setVisible(true);
   }

variable names

some of your names are already good, but others need improvement
 e.g.:  list -> operators

static method

You need a static method for a technical reason. This is because you don't know (yet) the differences between inner classes, anonymous inner classes and top level classes in same file and their consequences for the visibility of variables and methods.

In your case the Action listener should be an anonymous inner class so that is has full access to the members (variables and methods) of the containing class:

public void run() {
    ActionListener buttonListener = new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            if (!inputOne.getText().equals("") & !inputTwo.getText().equals("")) {
                double numberOne = (parseDouble(inputOne.getText()));
                double numberTwo = (parseDouble(inputTwo.getText()));
                String function = (String) list.getSelectedItem();
                // calculate is accessible as member from here...
                output.setText("" + calculate(numberOne, numberTwo, function));
            }
        }
     };
     // ...

But on the other hand there is the MVC (or MVVC) pattern to separate User Interface (UI = View) the data structure (model) and the business logic (controller). This pattern works with (public) top level classes accessing public methods.

if / else cascade -> polymorphism

To resolve this we need to introduce an interface, that all the operations can implement so that we can do the same call on any operation:

interface Operation {
   double  calculate(double term1, double term2);
}

This could be declared within the Calculator class just as you did with your ActionListener implementation.

Then we need to create and store implementations of this interface and map them with their symbols. The best solution for this is: --- a Map.
Therefor we change your variable symbols to a HashMap:

 private Map<String,Operation> symbols = new HashMap<>();

In your configuration method we initialize this Map.

// literals replaced with constants...
symbols.put(PLUS, new Operation(){
     public double calculate(double summand1, double summand2){
        return summand1+summand2;
     }
});
// same as Java8 Lambda
symbols.put(MINUS, (minuend, subtrahend) -> minuend-subtrahend);
//...

having this your calculate method would change to this:

 double calculate(double a, double b, String symbol) {
   if(symbols.containsKey(symbol))
     return symbols.get(symbol).calculate(a,b);
   else
     throw new IllegalOperationException("symbol "+symbol+" unknown!");
 }

isn't that nice?


Calculate a payment due after X age I have inherited a function which calculates a first payment due after a certain age.
Using the function I typically pass in database values to custom calculate certain dates:

    Dim result = FPDA("#1/12/1952#", "9/29/1948", 1, 55)
    MsgBox(result) 'in this example, I am returning first payment due after age 55

As far as the parameters, EffDate is the date the account became active, DOB is date of birth, mode is a payment mode value and age is the attained age to check. The function looks like this:

Public Function FPDA(ByVal EffDate As Date, ByVal DOB As Date, ByVal Mode As Integer, ByVal Age As Integer) As Date
    'FUNCTION TO CALCULATE THE FIRST PAYMENT DUE AFTER SPECIFIED AGE.

    Select Case Mode
        Case "1"
            Do Until EffDate > DateAdd("yyyy", Age, [DOB])
                EffDate = DateAdd("yyyy", 1, EffDate)
            Loop

        Case "2"
            Do Until EffDate > DateAdd("yyyy", Age, [DOB])
                EffDate = DateAdd("m", 6, EffDate)
            Loop

        Case "4"
            Do Until EffDate > DateAdd("yyyy", Age, [DOB])
                EffDate = DateAdd("q", 1, EffDate)
            Loop

        Case "12"
            Do Until EffDate > DateAdd("yyyy", Age, [DOB])
                EffDate = DateAdd("m", 1, EffDate)
            Loop

    End Select

    Return EffDate

End Function

Is there a better or more efficient way than to achieve this?

This is going to be a brain dump -type review. Feel free to jump straight to TL;DR if my thinking out loud gets annoying :)

Let's start with the function's signature:

Public Function FPDA(ByVal EffDate As Date, ByVal DOB As Date, ByVal Mode As Integer, ByVal Age As Integer) As Date

You're taking all parameters ByVal, which is good - it means the function cannot alter these values if it tried, it's receiving a copy of what the caller gave it.

I can live with EffDate, DOB and Age identifiers. But as I've mentioned in the comments, Mode is a no-no, especially if it's a magic Integer variable.

Looking at the body of the function I think what Mode is really about is something more like this:

Public Enum TimeSpanType
    Year
    HalfYear
    Quarter
    Month
End Enum

So we can have a body like this:

Select Case Mode
    Case TimeSpanType.Year
        Do Until EffDate > DateAdd("yyyy", Age, [DOB])
            EffDate = DateAdd("yyyy", 1, EffDate)
        Loop

    Case TimeSpanType.HalfYear
        Do Until EffDate > DateAdd("yyyy", Age, [DOB])
            EffDate = DateAdd("m", 6, EffDate)
        Loop

    Case TimeSpanType.Quarter
        Do Until EffDate > DateAdd("yyyy", Age, [DOB])
            EffDate = DateAdd("q", 1, EffDate)
        Loop

    Case TimeSpanType.Month
        Do Until EffDate > DateAdd("yyyy", Age, [DOB])
            EffDate = DateAdd("m", 1, EffDate)
        Loop

End Select

Return EffDate

It's more readable and less error-prone, but it's doing the exact same thing. It gives another meaning to the received parameter EffDate, which might work now, but it's error-prone, and this is where ByVal is saving you.

I would make a copy of EffDate:

Dim result As Date
result = EffDate

And change the last line to:

Return result

Now every branch looks like a Copy+Paste party. How about this:

Dim interval As String

Select Case Mode
    Case TimeSpanType.Year
        interval = "yyyy"

    Case TimeSpanType.HalfYear
        interval = "m"

    Case TimeSpanType.Quarter
        interval = "q"

    Case TimeSpanType.Month
        interval = "m"

End Select

And then you can just do:

Do Until result > DateAdd(interval, Age, [DOB])
    result = DateAdd(interval, 1, result)
Loop

But this is rather ugly. DateAdd lives in the Microsoft.VisualBasic namespace, which only exists to make VB6 developers happy with transition to the Wonderful World of .NET... but by using that namespace, you're missing out on everything the Wonderful World of .NET has to offer!

Date is just a language alias for System.DateTime, which exposes the .NET way of life - exposing methods like AddMonths, which is really all you need here:

Dim monthsToAdd As Integer

Select Case Mode
    Case TimeSpanType.Year
        monthsToAdd = 12

    Case TimeSpanType.HalfYear
        monthsToAdd = 6

    Case TimeSpanType.Quarter
        monthsToAdd = 3

    Case TimeSpanType.Month
        monthsToAdd = 1

End Select

Or better yet - get rid of the Select...Case altogether, because Enums are Integers under the hood:

Public Enum TimeSpanType
    Year = 12
    HalfYear = 6
    Quarter = 3
    Month = 1
End Enum

TL;DR

And then you can just do this:

Dim interval As Integer
interval = CType(Mode, Integer)

Do Until result > DOB.AddMonths(interval*Age)
    result = result.AddMonths(1)
Loop

And now that you've got code that's easy to read, follow and maintain, you can start thinking about how the loop could be simplified.

Strive to get rid of Imports Microsoft.VisualBasic anywhere you see it. VB.NET is .NET, not VB6. Your code will only get better.


Finding which users have the most questions with unaccepted answers I was looking at a few profiles this afternoon and noticed a few users had plenty of open questions.  This led me to wonder which users actually had the highest amount of questions with unaccepted answers (both in size and percent).  So with all the hoopla I kept seeing in the 2nd monitor about SEDE queries, I decided to try my hand at writing one.

with unanswered as (
  select
    posts.Id as PostId
  from
    posts
  where posts.PostTypeId = 1            -- questions
    and posts.OwnerUserId is not null   -- user exists
    and posts.AcceptedAnswerId is null  -- no answer selected
    and posts.ClosedDate is null        -- still open
  group by posts.Id
),

percentages as (
  select
    users.Id as UserId,
    count(posts.Id) as Questions,
    count(unanswered.PostId) as UnansweredQuestions,
    (count(unanswered.PostId) * 100.0 / count(posts.Id)) as UnansweredPct
  from
    users left outer join
    posts on users.Id = posts.OwnerUserId
          left outer join
    unanswered on posts.Id = unanswered.PostId
  where
    posts.PostTypeId = 1
  group by
    users.Id
)

select top ##MaxRowsToSelect:int?100##
  UserId as [User Link],
  UnansweredQuestions as [Unanswered Questions],
  Questions,
  round(UnansweredPct, 1) as [Unanswered %]
from percentages
where UnansweredPct > ##MinUnansweredPct:int?40##
  and UnansweredQuestions > ##MinUnansweredQuestions:int?10##
order by UnansweredPct desc;

This is essentially a good, clear and effective query. The only feedback I can offer is minor and somewhat subjective.

In the first CTE, unanswered, I personally would use distinct rather than grouping by posts.id. I group by when I am using an aggregate function; since there's no aggregate, distinct expresses the intention clearer to me.
I'm not intimately familiar with SEDE but I think you can inner join between users and posts in the percentages CTE. This is likely to be more performant, and again it expresses the intention clearer.  The left outer join to unanswered still makes sense because you want to include the count of answered as well as unanswered posts. (Personally, I write left join rather than left outer join - less typing, totally equivalent).
I'm not a huge fan of your layout and indentation style. Wholly subjective (and I don't know if I'm in the minority or you are) but I usually start each new query clause (select, from, joins, where, etc) on a new line, and leave a blank line between each clause.
I recommend aliasing all tables/rowsets for clarity, e.g. ...from users as U..., and referring to the alias e.g. select U.Id....  So long as you choose sensible aliases (never just A, B, C etc) this is clear and more compact.
Your final ordering, by UnansweredPct, doesn't guarantee the same order between re-runs (as two users could and do have the same value in that column). I'd order by more columns to ensure consistent ordering - it isn't the end of the world in this particular query, but in some cases consistency can be really important, so it's a good habit to have.
I am not a fan of using top in any "long term" SQL queries (in the context of my day job, any query which will be used in production rather than just ad-hoc code). Whether you consider your query to be the former or the latter is up to you ;-) My "production" approach would be to add a Row_Number() function, ordering by UnansweredPct (and other columns, see above), then restrict where RowNo <= ##MaxRowsToSelect:int?100## instead of the top.  This also means you can just order by RowNo.


Concatenating optional strings in Scala I have two optional strings, any of them can be None. I want to create their combination with a delimiter between them if they both exist.
I expect to be able to come with a more concise and nicer solution.
val seq = (Some("abc"), None)
val none = (None, None)
val both = (Some("abc"), Some("x"))

def concat(s: (Option[String], Option[String])): Option[String] = {
  s match {
    case (Some(a), Some(b)) => Some(a + ", " + b)
    case (a, None)          => a
    case (None, b)          => b
  }
}

concat(seq)
concat(none)
concat(both)

Can this be rewritten somehow in a more elegant way? The input can be changed from Tuple to Seq if desired.

As you seem to have already noticed yourself, the fact that the input to the function is a pair of strings is somewhat awkward. It violates the Zero-One-Infinity Rule.
You might be worried about YAGNI or the Rule Of Three, but I would argue that it is okay to fudge those guidelines here a little bit, since

the extension from two to many is obvious,
simplifies the code, and
is in service to another guideline.

One main question you need to ask yourself, which I feel is not really answered in the specification you gave in your question nor in the code snippet you are asking to have reviewed, relates to this statement from your question [bold emphasis mine]:

I want to create their combination with a delimiter between them if they both exist.

What, precisely do you mean by "if they both exist"? If we are looking at ways that an Option[String] in Scala can exist or maybe not exist, I can think of many different scenarios:

It can be null. (Unfortunately, since Scala is designed to tightly integrate with the underlying platform, and all of the "interesting" underlying platforms all have a concept of null, it is hard to get rid of this.)
It can be None.
It can be Some(""), i.e. the empty string.
It can be Some("  "), i.e. a string consisting purely of U+0020 Space characters.
It can be Some("  "), i.e. a string consisting purely of whitespace characters other than U+0020 Space. (There are at least 16 different whitespace characters that are not U+0020 which I have found in about 30s of research.)
It can be Some(""), i.e. a string consisting purely of zero-width characters. (Note, this is not an empty string! It contains a U+200B Zero-width space. For added fun, this particular character is not considered Whitespace by the Unicode standard!)

And these are just some of the things I can think of off the top of my head.
For example, both your original code in the question and your revised code in the answer will return Some(", ") when passed two empty strings, or Some(" ,  ") when passed two strings consisting of one space character.
If you are willing to accept a very broad definition, then a very simple implementation could be something like this:
def concat(s: Option[String]*) = s.flatten.mkString(", ")

However, this will always give you a String, it will not give you an Option[String]. For your None, None example, it will give you the empty string:
concat(None, None)
//=> ""

[Scastie link]
Any specification more complex than this very simple one, including the one from your question, will complicate the code, there is not much you can do about that. There is no getting around the fact that text processing looks deceptively simple (everybody knows what an "empty string" or a "character" is, right?) but is actually very complex.

<script src="https://scastie.scala-lang.org/JoergWMittag/1EScnd33SZ68MEXCCXjTQg.js"></script>


Showing different icons on hover I have 30 icons, and after hover, different icons are shown. How can I write this shorter?

jQuery

$('#iconTech01').hover(
        function() {
            $('#iconTechBig01').stop(true, true).fadeIn("slow");
            $('#iconTech01 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig01').stop(true, true).fadeOut("slow");
            $('#iconTech01 img').stop(true, true).fadeIn("slow");
    });

    $('#iconTech02').hover(
        function() {
            $('#iconTechBig02').stop(true, true).fadeIn("slow");
            $('#iconTech02 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig02').stop(true, true).fadeOut("slow");
            $('#iconTech02 img').stop(true, true).fadeIn("slow");
    });

    $('#iconTech03').hover(
        function() {
            $('#iconTechBig03').stop(true, true).fadeIn("slow");
            $('#iconTech03 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig03').stop(true, true).fadeOut("slow");
            $('#iconTech03 img').stop(true, true).fadeIn("slow");
    });

    $('#iconTech04').hover(
        function() {
            $('#iconTechBig04').stop(true, true).fadeIn("slow");
            $('#iconTech04 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig04').stop(true, true).fadeOut("slow");
            $('#iconTech04 img').stop(true, true).fadeIn("slow");
    });

    $('#iconTech05').hover(
        function() {
            $('#iconTechBig05').stop(true, true).fadeIn("slow");
            $('#iconTech05 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig05').stop(true, true).fadeOut("slow");
            $('#iconTech05 img').stop(true, true).fadeIn("slow");
    });

HTML

Certainly, assign a class to each tech icon (I'm assuming they're divs), use a JQuery selector to select all DOM element with the assigned class and then use each() to step through each item.


Counting lowercase and uppercase letters in a string in Python I am writing a program to count the number of uppercase and lowercase letters in a string. I came up with something that works, but as I am still a beginner I have a feeling writing the code this way is probably considered "clumsy."

Here is what I have:

stri = input("Give me a phrase:")
stri_up = 0
stri_lo = 0
for i in stri:
    if i.isupper():
        stri_up += 1
    if i.islower():
        stri_lo += 1
print("The number of uppercase letters in your phrase is:", stri_up)
print("The number of lowercase letters in your phrase is:", stri_lo)

Output:

Give me a phrase: tHe Sun is sHininG
The number of uppercase letters in your phrase is: 4
The number of lowercase letters in your phrase is: 11

I would like to learn how to write neat, beautiful code so I am wondering if there is a more efficient and elegant way to code this.

Your code is mostly fine. I'd suggest more meaningful names for variables, e.g. i is typically a name for integer/index variables; since you're iterating over letters/characters, you might choose c, char, let, or letter. For stri, you might just name it phrase (that's what you asked for from the user after all). You get the idea. Make the names self-documenting.

Arguably you could make it look "prettier" by performing a single pass per test, replacing:

stri_up = 0
stri_lo = 0
for i in stri:
    if i.isupper():
        stri_up += 1
    if i.islower():
        stri_lo += 1

with:

stri_up = sum(1 for let in stri if let.isupper())
stri_lo = sum(1 for let in stri if let.islower())

That's in theory less efficient, since it has to traverse stri twice, while your original code only does it once, but in practice it's likely faster; on the CPython reference interpreter, sum is highly optimized for this case and avoids constructing a bunch of intermediate int objects while summing.