One try with multiple catch blocks vs nested try

If you are not going to handle each exception differently just use a multicatch:

public static void main(String[] args) {
    try (FileReader file = new FileReader("Doc.csv")) {
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) {
            System.out.println(sc.nextLine());
        }
    } catch (IllegalStateException | NoSuchElementException | IOException e) {
        System.out.println(e);
    }
}

The FileNotFoundException is not catched since alternatives in a multi-catch statement cannot be related by subclassing (FileNotFoundException is a subclass of IOException).


Finding the first non-repeating character in a string

Let's try a solution that doesn't use an array with all the required bookkeeping.  The following code works, and bypasses the problems others have pointed out.

First, a quick template function that searches for duplicates given a char:

template <typename T>
inline bool repeated(char c, T first, T last) {
    size_t count = 0;
    while (first != last) {
        if (*first == c) ++count;
        if (count > 1) return true;
        ++first;
    }
    return false;
}

Now we create a set of unique characters and then scan the string to see if there are any duplicates.  If there are, we remove the char from the set and continue to the next one.

char FirstNonRepeatedchar(const char* str, int len) {
    auto uniq = std::set<char>(str, str + len);
    auto first = str;
    auto last = str + len;
    while (first != last) {
        if (auto it = uniq.find(*first) != uniq.end()) {
            if (!repeated(*first, str, str + len)) return *first;
            uniq.erase(it);
        }
        ++first;
    }
    return '@';
}


Do you think my choice of deque as a data structure (container) is appropriate?

Seems good.

  I want the retrieve (from anywhere) / add (to end)/ remove (from anywhere) to be O(1)O(1).

See: What are the complexity guarantees of the standard containers?

So std:: deque does not provide a O(1) erase (remove).

  I use deque because unlike vector it does not have to copy all the data from beginning of the array in case the memory grows and have to allocate new slab of contiguous memory. Since deque is made of small chunks of contiguous memory not all chunks need to be copied (at least that is what I think of). Also the retrieve and add to end is O(1)O(1) in case of deque. I know remove is O(n)O(n): nn being size of one of the chunk of contiguous memory the item reside in.

All that is correct. Just does not make removal O(1). Because the chunks can be large m. The removal of an item is O(m) where m is the size of the chunk.

  I think I could also use HashMap (unordere_map)

That does support all the requirements you need.

  but I read somewhere that hash_map does not necessarily give O(1)O(1) because of collision when data gets huge and also my student number will definitely grow hugely (e.g. 100,000 and up also for sake of argument).

Yes collisions will add time. But they do not change the complexity. It still remains O(1).

  I also heard that implementing hash function to avoid collision is complex.

It is exceedingly complicated to do correctly and you should never do this. Use the standard one. Only implement a hash function if that is your actual job (or you are some kind of maths genius). This is too easy to get wrong so use a good well known hash (the one provided by the standard is fine).

  I also think I can't use std::map since retrieval is O(ln)O(ln).

Correct.

  Do you think the use of shread_ptr inside the deque for memory management is a good design choice?

No. Given the choice between dynamic/automatic variables you should always prefer automatic variables.

But you don't provide enough details to provide a good answer either. Personally I would have one entity that owns all the students (say the University). Then you classes can contain references to the object owned by the university (ie they could iterators as a reference).

  I used sharad_ptr so that I don't have to do the manual delete of the allocated memory.

That's a good thing and correct usage if you are using dynamic memory. But as stated above I don't think dynamic memory is the correct solution.

  I also make the class store the shared_ptr rather than a copy of the student because the Student class may contain other information that might be costly to copy.

Sure. You should not have two copies of the same data. That will just introduce consistency issues. But that still does not require dynamic memory allocation. The class store can store so other type of reference to the object (Note: I use the term reference at the conceptual level not the C++ language level).

  Also a student can be in more then one class ( This way instead of creating multiple copy shared_ptr will only increase the count - Here also I am not sure is it really necessary to increase count because since there will only be one copy I was also thinking about passing by const ref so that we dont have the overhead of increasing the count itself).

Don't do that. The whole point of using the shared pointer is to make sure it correctly exists when you access it. If you do this it could be destroyed and then you try and access it via a class and get undefined behavior. A better solution here would be to use a std::weak_ptr. But I still prefer my technique of using a reference (even if that means more work cleaning up).

  Is there a container which gives O(1)O(1) for retrieval, adding to the end and removal from anywhere in the container (of-course except hash map as I discussed about it above) or anything that is close enough that provide these features?

See the provided link above.


Command line utility to convert image formats of photos

Specific suggestions:

I generally find that ordering functions by their importance is helpful. Moving get_arguments just above or below main would allow readers to get into the functionality immediately. Others prefer to write methods in call order, but this feels a bit arbitrary (should main be first or last?) and not always achievable, because with branching it's possible to have a cycle of callers.
*nix tools usually support any number of paths as their last arguments, operating on each of them. This would certainly be useful here, and means you could even avoid the whole if/else in main because all inputs should be file paths.
argparse has a file type which you can use.
Don't rely on file extensions to correspond to file formats. I would instead rely on PIL to detect the file type and to throw an exception if it doesn't know it.
Abbreviations like inname make the code harder to read. One way to avoid the urge to shorten everything is to use an IDE, because it'll help you auto-complete everything which is in scope.
In the end this script is a small convenience wrapper around PIL. This is one of those rare occasions when I would suggest replacing it with a small shell script.

General suggestions:

black can automatically format your code to be more idiomatic.
isort can group and sort your imports automatically.
flake8 with a strict complexity limit will give you more hints to write idiomatic Python:

[flake8]
max-complexity = 4
ignore = W503,E203

I would then recommend adding type hints everywhere and validating them using a strict mypy configuration:

[mypy]
check_untyped_defs = true
disallow_untyped_defs = true
ignore_missing_imports = true
no_implicit_optional = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_ignores = true


Static variable representing program state accessed with multiple functions

Since it's a single-threaded algorithm, I think you could simplify things a bit to avoid all the state-checking. Unless you're reading the state from another thread, you don't really need to keep track of it at all. You could simply make perform_check_needed_for_algorithm return a bool:

for (;;)
{
    /* info.state = FIRST_STATE; */
    perform_first_state_function();
    /* info.state = SECOND_STATE; */
    perform_second_state_function();
    /* info.state = THIRD_STATE; */
    if (perform_check_needed_for_algorithm())
    {
        /* info.state = FINAL_STATE; */
        break;
    }
}

The commented-out state assignments are just there to show what's happening at each stage. Although a state machine's inner functions ought to be responsible for updating the state, in an example as simple as this, it's arguably more readable to update the state in the outer function.

If you need access to the state from another thread, then you'll need to update it using atomic operations, and mark it as volatile.

Afterthought:
perform_second_state_function doesn't always advance the state. It fails once ALLOWED_ATTEMPTS is exceeded. However, it dumps you back into the outer loop, and dives straight back into perform_second_state_function because state.info is still SECOND_STATE. Bit of a design error there IMO - it will keep trying no matter what.


Reduce list manipulation for QGIS layer tree

Your lists manipulations are indeed messy. It seems like you are trying to perform multiple things at once and thus you end up mixing variables that serve different purposes into the same loops.

Instead, you should try to extract logical steps to perform, such as:

extract informations you need from the internals of QGis to a similar but simpler representation;
compute the data you need out of this simplified representation;
format the data you computed for presentation;
use the formatted data to update your visual presentation.

Here the second and third step are simple enough they can be made at once.

But first, we will need an helper function to simplify the inner working of the first double for loop:

def is_visible_layer(layer, root):
    node = root.findLayer(layer.id())
    try:
        return node.isVisible() == Qt.Checked
    except AttributeError:
        return False

Now I’m not QGis expert, but I’m wondering if the root is really necessary to get the meta-information about the node. Isn't it possible to write it like:

def is_visible_layer(layer):
    try:
        return layer.isVisible() == Qt.Checked
    except AttributeError:
        return False

?

This let us write the for loop like:

for group in main_group.children():
    layer_list = []
    for child in group.children():
        if is_visible_layer(child.layer(), root):
            layer_data.append(child.layerName())
            layer_list.append(child.layerName())
    layer_count.append(len(layer_list))

Which can be simplified using list-comprehensions:

for group in main_group.children():
    layer_list = [child.layerName() for child in group.children() if is_visible_layer(child.layer(), root)]
    layer_data.extend(layer_list)
    layer_count.append(len(layer_list))

Now recall what I said about performing several things at once? Here you already try to count things while extracting the informations from the QGis internals. Let's get that for later and simplify the loop once again to build a list of list of layer names:

layers = [
    [
        child.layerName()
        for child in group.children()
        if is_visible_layer(child.layer(), root)
    ]
    for group in root.findGroup(main_group).children()
]

and then, only after you can start counting. And as it is much easier using this structure, you can start converting the list of list into a single list of couples that will mimic the table layout:

table = [
    (layer, len(group))
    for group in layers
    for layer in group
]

Turning this list of couples into an N × 2 table is then really easy. The whole code should look like:

def is_visible_layer(layer, root):
    node = root.findLayer(layer.id())
    try:
        return node.isVisible() == Qt.Checked
    except AttributeError:
        return False

def refresh_table(root, qTable, main_group='Main group'):
    # Get names of relevant layers, as a list of list of names
    layers = [
        [
            child.layerName()
            for child in group.children()
            if is_visible_layer(child.layer(), root)
        ]
        for group in root.findGroup(main_group).children()
    ]

    # Convert the layer list to the table layout i.e. a list of couples
    table = [
        (layer, len(group))
        for group in layers
        for layer in group
    ]

    # Configure output table
    qTable.setRowCount(len(table))
    qTable.setColumnCount(2)
    qTable.verticalHeader().setVisible(False)

    # Insert data into table
    for row, (layer, count) in enumerate(table):
        name_item = QTableWidgetItem(layer)
        name_item.setFlags(QtCore.Qt.ItemIsEnabled)
        count_item = QTableWidgetItem('{:.1f}'.format(1./count))
        qTable.setItem(row, 0, name_item)
        qTable.setItem(row, 1, count_item)

Call it like

refresh_table(
    QgsProject.instance().layerTreeRoot(),
    self.dockwidget.tableWidget)


Deleting nodes having greater value on right side

In appendNode(), you have to provide a pointer to node to sizeof() and typecast its return value to struct node*:

void appendNode (struct node** headRef, int data)
{
    struct node* newNode = (struct node*)malloc(sizeof(struct node*));

    newNode->data = data;
    newNode->next = *headRef;
    *headRef = newNode;
}


Creating Two-Dimensional String Array for Plane Seats

Here are a few optimization suggestions:

You can get rid of alphabetPos because it is always equals to i.
In fact, while you are at it, your code will be more readable if you rename i to row and j to col or column.

You can also get rid of columnToString and just rely on Java's string concatenation overloads.

 seatArray[i][j-1] = alphabet[alphabetPos] + j;

Note that you use j multiple times as index, subtracting one, and only once as string.
It would make your code more readable if you used zero based index, and only added 1 for the string composition.

You may want to use string formatting.

for (int col = 0; col < this.getNumOfColumns(); col++) {
        seatArray[row][col] = String.format("%s%d", alphabet[row], col + 1);

        if (this.getNumOfColumns() == 4) {
            if (col == 1) {
                System.out.print(seatArray[row][col] + "       ");
            } else {
                System.out.print(seatArray[row][col] + " ");
            }
        } else {
            if (col == 2) {
                System.out.print(seatArray[row][col] + "       ");
            } else {
                System.out.print(seatArray[row][col] + " ");
            }
        }
}

You can simplify your array printing by splitting it in to two parts: printing the seat number and printing the spacer.
The first part is always the same, so no need to repeat it 4 times.
The second part changes only when col and row have certain values, so one condition is enough.

System.out.print(seatArray[row][col] + " "); //this part is always printed the same

//just add a few more spaces if this is an isle seat
if ((getNumOfColumns() == 4 && col == 1) || (getNumOfColumns() != 4 && col == 2)) {
    System.out.print("      ");
}

Finally, to save memory, you can get rid of the alphabet array all together, since the seat letters are sequential and rows 26 and above just have the same letter twice:

String rowStr = String.format("%c", 'a' + (row % 26));
if (row > 25) rowStr += rowStr;
seatArray[row][col] = String.format("%s%d", rowStr, col + 1);


Show and Hide group of classes based on data attributes

Instead of looping over the showClasses and hideClasses you can do a regex search and replace, then add/remove the class names:

var trimRegex = /^\s+|\s+$/g,
    selectorRegex = /(^| +)([-_a-zA-Z0-9]+)/g,
    callback = function(match, $1, $2) {
        if ($1) {
            return ", ." + $2;
        } else {
            return "." + $2;
        }
    },
    hideSelector = this.getAttribute("data-group")
        .replace(trimRegex, "")
        .replace(selectorRegex, callback),
    showSelector = this.getAttribute("data-target")
        .replace(trimRegex, "")
        .replace(selectorRegex, callback);

$(hideSelector).removeClass("show");
$(showSelector).addClass("show");

Secondly, since the document object exists the moment JavaScript begins executing, there is no need to wait for the document to load:

$(document).on("click", ".showHide", function() { ... });


Invoking functions using a function pointer approach

You don't have to define your own functions for these arithmetic operations. These functions already exist in the operator module.

from operator import add, mul

operations = {
    'add': add,
    'mul': mul
}

In Python snake-case is preferred over camelCase for variable names.
Don't use import * imports. Import only the items you need. import * based imports can be helpful in shell for debugging and you may sometimes see them in a package's __init__.py to help define a clean public API.

  Is there a way like in C to export all the functions before-hand, so
  that I can define the mapping dictionary in the beginning (See
  examples below). Or what would be the most pythonic approach to do
  this?

There's no way to import only functions. The pythonic way is to import only the functions you need not everything.

  It makes the dictionary definition to be the last segment of the code
  which doesn't look neat.

The dictionary approach is recommended in Python as there's no switch statement in Python and it's better than a bunch of if-elif-else. You could also create the dict in a1.py based on the imported functions. Though I don't find its definition in a2.py okay.

Another option can be to fetch the functions from a2 module object itself if they can be re-named add, mul etc. This way you won't need a dict.

import a2

def arithmeticOps():
    getattr(a2, 'add')(6, 1)
    getattr(a2, 'mul')(6, 4)


Code that rotates images in a set of divs

The first thing I see in your code are the strings who represents an HTML element (in this case an img and an anchor element).

This is a bad practice. Instead of appending a whole element to your HTML just update the src or href attribute.

The second thing I noticed is your implementation of a new array. Instead of using:

var image = new Array ();
 image[0] = "";

Use this approach:

var image = [
       "https://placehold.it/200/09f/fff.png?text=image1",
       "https://placehold.it/200/09f/fff.png?text=image2"
];

Also the naming of your variables is badly. The name:

 var image = new Array ();

and

var link = new Array ();

Suggests that they are holding exactly one image and one link. Actually they are  holding multiple links and images. Try to use names that describes what you can expect inside the variable. So use images and links instead.

Goodluck!

(Sorry for bad english, not a native speaker)


Converting Shell input into Windows DOS compliant input

First some comments:

using Exception to control flow of the program is considered to be
a bad programming style - exceptions represent an exceptional state
and checking the condition of being at the end of the string is not
an exception
command line arguments' names are actually constant as long as the
interface they represent remains unchanged, so they should be
represented as constants and not string literals.
there is also only a limited set of them, so they should be
implemented as an Enum.

I assume you get the arguments as a String array - given the above you should first transform it into a Map - the most efficient would be an EnumMap, but I would suggest using a LinkedHashMap which will preserve the order of the arguments.

This will also validate the input and only accept valid arguments, thus preventing the program to crash because of an invalid input.

Now what you actually do to the beanName is basically enclosing a single or double apostrophe within a pair of apostrophes. There is a way to do it without iterating over the string variable character by character - use a regular expression, all you need is:

beanName = beanName.replaceAll("([\"]{1,2})", "\"$1\"")

Now this means "find all groups of single or double apostrophes and replace each of them a with starting apostrophe followed by the found group and an ending apostrophe". This works only for single or double apostrophes - so does probably the right thing for your use case.

To enclose any number of input apostrophes in a pair of the same, you'd use:

beanName = beanName.replaceAll("([\"]+)", "\"$1\"")

meaning "find all groups consisting of one or more apostrophes and replace each of them a with starting apostrophe followed by the found group and an ending apostrophe". Now try to do this without a regular expression - it would require much more complicated code.

All this will reduce the very act of processing the beanName to a mere one liner if you exclude checking for null:

public static enum Param {
  SRV("-srv"), USR("-usr"), PWD("-pwd"), BEAN("-b");

  private final String paramString;

  private Param(String paramString) {
    this.paramString = paramString;
  }

  public String getParamString() {
    return paramString;
  }

  public static Param paramOfValue(String value) {
    for (Param p : values()) {
      if (p.paramString.equals(value)) {
        return p;
      }
    }
    return null;
  }
}

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

  // the bean name to test
  String bean = "hostName=\"localhost\",name=\"foobar\"\"";

  // input is always a String array
  String[] params = new String[] { "-srv", "localhost:1234", "-usr", "foo", "-pwd", "bar", "-b", bean };

  // convert the String array to a Map - only elements which have a predecessor
  // being a valid argument are being put into the map
  Map<Param, String> paramsMap = new LinkedHashMap<>();
  Arrays.stream(params).reduce((first, second) -> {
    Param param = Param.paramOfValue(first);
    if (param != null) {
      paramsMap.put(param, second);
    }
    return second;
  });
  // process the bean's name if present
  String beanName = paramsMap.get(Param.BEAN);
  if (beanName != null) {
    paramsMap.put(Param.BEAN, beanName.replaceAll("([\"]{1,2})", "\"$1\""));
  }
  System.out.println(paramsMap);

  // create a String array out of the map
  String[] processedParams = paramsMap
      .entrySet()
      .stream()
      .map(e -> Stream.of(e.getKey().getParamString(), e.getValue()))
      .flatMap(e -> e)
      .collect(Collectors.toList())
      .toArray(new String[0]);
  System.out.println(Arrays.toString(processedParams));
}

The output is:

{SRV=localhost:1234, USR=foo, PWD=bar, BEAN=hostName="""localhost""",name="""foobar""""}
[-srv, localhost:1234, -usr, foo, -pwd, bar, -b, hostName="""localhost""",name="""foobar""""]

The code above is less efficient performance-wise since it does more - yet it is safer and much more readable (and IMO elegant :-)). Simplicity and readability reduces errors and thus testing and maintenance costs.

If you refactor processing of the input parameters (validation, conversion into a map) and creating the String array out of the method it gets very short, very straightforward and more efficient. Since the input validation should be done anyway its cost shouldn't actually be taken into account.

Now the command line processing is pretty ad-hoc, there are better ways to do it - for example using org.apache.commons.cli.


These are just some quick thoughts, not a detailed analysis.

Comments.  Enough said.
If a conditional jump (like jge) is not taken, execution just continues with the next instruction.  So this seems redundant (likewise with numsetup1):

    jge lxisetup1
    jmp lxisetup2
lxisetup1:

could be written as:

    jl lxisetup2

You are repeatedly moving -1 into registers and using it in other ways.  Why not make use of an additional register (say si)?  Set it to -1 at the top of this routine (remember to push/pop it if your calling convention requires it) and use it as needed: mul si, mov ax, si.
A common shortcut for zeroing registers is xor ax, ax.  Produces slightly smaller code.
Looking at your final loop, you have:

lloopstart:
    cmp dx, lnumpix
    jg lloopend
    inc dx
    jmp lloopstart
lloopend:

This means that you will be doing 2 jumps in a row (jmp lloopstart, jg lloopend).  An alternative might be:

    cmp dx, lnumpix
    jg lloopend
lloopstart:
    inc dx
    cmp dx, lnumpix
    jle lloopstart
lloopend:

Instead of having your loop count up (for x=0 to 10), sometimes having your loop count down to zero (for x=10 to 0) can produce (slightly) more efficient code (not sure it would work in this case):

mov dx, lnumpix
lloopstart:
    dec dx
    jnz lloopstart


ToString() does too many things, it should only be calling _xDoc.ToString(); it has side-effects that make it dangerous to call more than once:

var foo = builder.ToString()
Console.WriteLine(builder.ToString());
Console.ReadLine();

Will not produce the expected output, and will not throw an exception either, resulting in an XML document with _queryNode showing up as many times as ToString() was called.


A good general performance rule of thumb is to avoid hitting the DOM (the HTML-manipulating stuff) more than necessary. Most DOM properties aren't just static properties that get set from somewhere else as things change. Invoking them tends to involve buildup and tear-down and examining of internal state, etc. Anything that actually alters HTML is 99.99% likely to cause reflow calculations.

Why have two classes? Just let the lack of an 'available' when checked for with .hasClass('available') represent 'unavailable'. That way you only hit the DOM when you add 'available' and do the attribute checks with both of those className changes setting off reflow calculations.

A note on the second approach. It looks more concise but it's doing a lot of looping and DOM access under the hood. It's important to understand what JQuery does when invoking it. In this line for instance,

$allSwatchItems.removeClass("available").addClass("unavailable");

JQ is going to have to run down the collection of DOM elements with an internal loop access the className property, do a replace operation on it, set the className property, then access the className property again match for 'unavailable' and add it on if it isn't there.

People tend to shy away from using the class attribute as a place to tie things to data but I'm of the opinion that you're always binding to something in the HTML. Why not use the most efficient thing that's easiest to share with other concerns? And no, I do not consider HTML an exclusive property of the view in MVC and similar patterns. It also represents content and document structure. Leave HTML out of your JavaScript modeling conventions. It has too much overlap with other concerns and other domains. Think of DOM API stuff as low-level and view modeling as higher-level stuff that buries the DOM stuff.

Here's how I'd do it - I'll let you sort out what's worth haggling over with your team/tools where control over HTML/CSS is concerned but by baking things into your HTML structure the right way, it can save  a lot of work.

HTML like this with unavailable as default sharing with class with data_val classes if needed (classes can have multiple properties separated by spaces):

...

...
...

build your available selector:

var swatchSelector = '.data_val_' + config.join(', .data_val_'),
//#value-list step to reduce brutal IE8 DOM tomfoolery
$availableSwatchItems = $('#value-list').find(swatchSelector);

$availableSwatchItems.addClass('available'); //.remove('unavailable') if you must

It's not a minor thing to not have control over your HTML and CSS. By structuring to your advantage, you can drastically reduce code and improve performance. Any tool or back-end dev who makes this impossible is like a stick in the eye for a client-side dev. That's your domain. You should have control over it. As for custom attributes, when browsers have access methods as fast as className and ID for other attributes I don't really care what people use for attributes in HTML5 but for now, it's a pointless performance-hamperer, IMO.


Storing and retrieving student scores in three subjects

PEP 8, the official Python style guide, specifies four spaces per level of indentation.  Since whitespace is significant in Python, that is a pretty strong convention.

The challenge states that the first line contains N, the number of students.  So, don't call that value a in the code, and don't use the variable n to mean something else.  It's confusing.

The variable i is never used.  It is customary to use _ as the name of a "throwaway" variable whose value does not matter.

Clearing f and n at the end of the loop is cumbersome and unnecessary.  Avoid cryptic variable names like f and n whose meanings are not obvious.  Even names like nam and per are unnecessarily unfriendly.  (Learn from Ken Thompson's biggest regret.)

For this problem, there is no need to store the scores for each subject separately.  You can just store the average right away.

scores = {}
n = int(input())
for _ in range(n):
    line = input().split()
    name = line.pop(0)
    scores[name] = sum(float(score) for score in line) / len(line)
print("%.2f" % scores[input()])


If you look at your code for this exercise as well as the one about approximating the square root and the one about finding epsi, you'll notice a common pattern:

You have a function which performs a single step and a predicate which tells you when you're done. You then apply the stepping function until the predicate is met. When you encounter a common pattern like this, the best thing to do is usually to abstract it. So let's define an apply-until function which takes a stepping function, a predicate and an initial value and applies the function to the value until the predicate is met:

(define (apply-until step done? x)
  (if (done? x) x
      (apply-until (step x) step done?)))

You can now define your cuberoot function using apply-until instead of cuberoot-iter:

(define (cuberoot x)
  (apply-until (lambda (y) (improve-guess y x)) (lambda (guess) (goodenough? guess)) 1.0))

You can also move your helper functions as local functions into the cuberoot function. This way they don't need to take x as an argument (as they will close over it) and can thus be passed directly to apply-until without using lambda:

(define (cuberoot x)
  (define (improveguess y)
    ; y is a guess for cuberoot(x)
    (/ (+ (/ x (expt y 2)) (* 2 y)) 3))

  (define (goodenough? guess)
    (< (/ (abs (- (cube guess) x)) guess) 0.0001))

  (apply-until improveguess goodenough? 1.0))


A general physical layout guideline: Put all public members, functions as well as variables, first, followed by protected members, and private members at the end. You want users to see public members first, followed by protected members. Hopefully, they don't have to see private members at all.

I added white spaces around functions to make them more readable.

class MemoryWriter {

   public:

      MemoryWriter(DWORD address) {
         _currentIndex = 0;
         _targetAddress = (LPVOID)address;
      }

      template<typename T>
         void write(T data)
         {
            editMemory<T>(((DWORD)_targetAddress + _currentIndex), data);
            _currentIndex += sizeof(T);
         }

      template<typename T>
         void write(LPVOID address, T data)
         {
            editMemory<T>((DWORD)address, data);
            _currentIndex = (DWORD)address;
         }

      void reset(LPVOID newAddress = NULL)
      {
         _currentIndex = 0;

         if (newAddress)
            _targetAddress = newAddress;
      }

   protected:

   private:

      USHORT _currentIndex;
      LPVOID _targetAddress;

      template<typename T>
         static void editMemory(DWORD address, T data)
         {
            DWORD oldProtection;
            VirtualProtect((LPVOID)address, sizeof(T), PAGE_EXECUTE_READWRITE, &oldProtection);
            *((T*)address) = data;
            VirtualProtect((LPVOID)address, sizeof(T), PAGE_EXECUTE_READWRITE, NULL);
         }
};


Restart network-manager service if connection down on wake shell script

Welcome to Code Review.  Thanks for asking for a review.  Overall I think you did a great job, even for an experienced scripter.

good things

consistent indentation
helpful comments about installation
you didn't forget the #! line
using if to check for return values without creating extra variables
I'm a fan of bash and prefer it in most cases, but specifying an older shell will help this be portable to environment without bash like embedded systems.

suggestions

include a comment explaining what the purpose of the script is.  The file name is pretty descriptive, but someone might rename it accidentally.  So including the filename in the comment would not be too redundant.
run shell code through shellcheck.  Lucky for you it didn't find any issues with this code
it is a good practice to include a *) in your case to catch the unexpected.
I like for there to be a space before the ) in the case matches and a blank line after the ;;.  The space before the ) makes it clearer what is part of the pattern and what isn't.  case statements can get longish so having the extra space after the ;; may annoy you if you have a small screen, but I find it makes it easier to follow the flow when it is more separated.

main gripe

Why did you include $2 in your case?  Since you didn't cross a function call boundary there's nothing in the case statement that will prevent access from $2 inside.  I've integrated these suggestions into a rewrite I haven't tested.  But it should work and seems cleaner to me:

#!/bin/sh

# restart-network-on-wake.sh - systemd/Ubuntu helper

# INSTALLATION
#
# The script should live in /lib/systemd/system-sleep/...
#   sudo mv restart-network-on-wake.sh /lib/systemd/system-sleep/
#   sudo chmod a+x /lib/systemd/system-sleep/restart-network-on-wake.sh

case $1 in
    pre )
        echo "Going to $2..."
        exit 0
        ;;

    post )
        echo "Waking up from $2..."
        if ! ping -q -c 1 -W 1 8.8.8.8 > /dev/null; then
            echo "IPv4 is down, restarting network-manager"
            service network-manager restart
        fi
        ;;

    * )
        echo "ERROR: got $1 which is not expected"
        exit 1
        ;;
esac


Recursive comment function echoes HTML inside function

I would split up the function into 2 parts

fetch comments and recurse
render html for comment

To me it is easier to see the looping logic without all the html in place

You could then also look at templating engine if you are going to be doing lots of this sort of thing, there are various options available, smarty, twig, mustache, blades to name a few.

function display_comments($article_id, $parent_id = 0, $level = 0)
{
    // TODO handle sql connection error
    $comments = fetch_article_comments($article_id, $parent_id);

    foreach ($comments as $comment) {
        display_comment_html($comment);

        display_comments($article_id, $comment->comment_id, $level + 1);
        echo '
 ';
    }

}

function display_comment_html($comment)
{
    $comment_id = $comment->comment_id;
    $member_id = $comment->member_id;
    $comment_text = $comment->comment_text;
    $comment_timestamp = $comment->comment_timestamp;  //get timeAgo

// RENDER
    ?>

    <?= timeAgoInWords($comment_timestamp); ?>

    <?= $comment_text ?>

    <a href="#" class="replyLink" data-comment-id="<?= $comment_id ?>"> reply
    <a href="recursive.php?delete=<?= $comment_id ?>"> delete

    <form action="recursive.php" method="post" class="uk-form comment_form" id="<?= $comment_id ?>">
        <fieldset data-uk-margin>
            <input type="hidden" name="id" value="<?= $article_id ?>"/>
            <input type="hidden" name="parent" value="<?= $comment_id ?>"/>
            <input type="text" placeholder="Comment" name="svar">
            <button class="uk-button">Comment</button>
        </fieldset>
    </form>
    <?php
}


Simplifying calculation with min value in C#

Well, the most simple way would be to use Math.Max() like so

result.Calculation_VK = Math.Max(input.km_past_year * 0.040m, 300) * Constant.MWST

which could be as well in a method like

public static decimal CalculateVK(decimal pastYear, decimal factor, decimal minValue)
{
    return Math.Max(pastYear * factor, minValue) * Constant.MWST;
}

and be called like

result.Calculation_VK = CalculateVK(input.km_past_year, 0.040m, 300);


You're visiting and printing the tree elements in a depth-first manner, so depthFirstPrint would be a much better name than "recursive" (which is always a terrible name for any recursive function).

You didn't need this cast:

TreeViewItem item = (TreeViewItem) itr.next();

because you correctly declared the iterator as Iterator<TreeViewItem> itr

As of Java 1.5, you can use a for-each loop, which is simple and elegant:

for (TreeViewItem item : treeNode.getItems()) {
    depthFirstPrint(item);
}


Things you should change:

Sort() is explicitly returning at the end (return;). The return statement is implicit once you reach the end of a void function, so should not appear.
Pay attention to the spacing between the = sign. In some places you have b=c; while in others you have a = b; Be consistent with the spacing. I suggest the latter, as it seems more readable to me.
You don't have to return 0 from main. For main(), the return zero is implicit if not added.

This is also a great opportunity for you to learn about C++ templates. I will suggest you a base implementation that you can study, test, and better understand the awesomeness of this language feature:

template<typename T>
void swap_if_greater(T& a, T& b)
{
    if (a > b)
    {
        T tmp(a);
        a = b;
        b = tmp;
    }
}

template<typename T>
void sort(T& a, T& b, T& c)
{
    swap_if_greater(a, b);
    swap_if_greater(a, c);
    swap_if_greater(b, c);
}

Just as in the example provided by @EngieOP, I've added a swap function to reuse more code.
I've also better separated common code by moving the conditional inside the swap function (swap_if_greater()), since it is common to all inputs.

sort() is now a template function, meaning is can operate on any type, including int, float, double, char, ... It is a generic function, just as many of the functions in the standard C++ library. This concept promotes great code reuse and low redundancy of functionality.


Yes. I like it because it will make maintenance easier.
If you change the type of the container then you only need to change it in one place in the code. I would even go and define other things in relation to the typedef.
// For example:
typedef ItemTable::iterator         Iter;
typedef ItemTable::const_iterator   CIter;

But I would not expose the internal object with this:
const Inventory::ItemTable& Inventory::items() const

Any object that uses this method not becomes very tightly bound to this interface. I would question the need for this functionality. I prefer to expose methods that manipulate the object as a whole.
An alternative is to expose the iterators. Iterators are a much looser coupling.
As a result I would make ItemTable a private type. While the Iter and CIter would be public.
Edit:
class X
{
    typedef std::vector<int>            Cont;
    Cont        data;

    public:
        typedef Cont::iterator          Iter;
        typedef Cont::const_iterator    CIter;

        Iter begin()        { return data.begin();}
        Iter end()          { return data.end();}

        CIter begin() const { return data.begin();}
        CIter end()   const { return data.end();}
};


There's a CircularBuffer type in DataStructures, which does pretty much the same.  Have a look at its code for some inspiration.  Or reuse it, if it fits your needs and you don't hesitate to add that dependency.
Regarding the point before, I'd especially recommend to implement the common interfaces, and probably iterate as well.  remember! makes sense semantically, but push! is the standard name for this functionality.  You could implement remember! in terms of push! and export both, or just use push! and mention it in the docs.
There isn't really a need to be so specific about types.  I'd just use

struct Memory{T}
   max_size::UInt32
   experiences::Vector{T}
end

Nothing is lost by generalizing in this way, since you never use information about the content.  But who knows, maybe you later want switch to different types for experiences, eg. StaticVectors.
I would doubt whether using UInt32 saves more than it complicates.  Int is pretty much standard for everything of this kind: lengths, indices, offsets, etc.
Depending on the sizes of your use case, it might be better to preallocate experiences as Vector{T}(undef, max_size) and use just indexing (and keeping track of the actual length), instead of push!ing until full -- see the DataStructures implementation.  If not, calling sizehint!(experiences, max_size) might be good, if you expect to always exhaust the full capacity.
Instead of providing sample, I'd recommend hooking into rand, thereby getting more methods for free.  In the simplest case, this just consists of defining

Random.rand(rng::Random.AbstractRNG, s::Random.SamplerTrivial{Memory{T}}) where {T} = rand(rng, s[].experiences)

which gives you all variations: rand(m), rand(m, N) (corresponging to your sample), rand(rng, m),  etc.  Especially the form with a provided RNG is relevant if you want to write reproducible experiments.  The rand! methods seem not to work by default, but can be added easily if you need them.  (If you switch to a preallocation + indexing solution, you need to make sure to sample only from @view experiences[1:length].)

And note that you can directly sample from an array a using rand(a).


Overall, this seems like a pretty straightforward implementation of the FSM you show. It's understandable, which is great!
Document What It Is
The only thing is, what if someone reading this has never seen the image of the FSM? You should, at the very least, include a comment with a URL showing where the FSM comes from! Or, if you can easily explain it in words, do that.
Don't Do Nothing
What is the point of the fsm and fsmstart macros? They do nothing. I don't mind that you're starting new scope with each one, but an empty macro seems pointless. You could just as easily use a comment. It would be confusing to someone reading the code for the first time, thinking they did something.
Be Careful With Macros
While we're no the subject of macros... What's the point of the other macros? The fsmSTATE macro saves you no typing at all, and doesn't appear to have any other function. Just use the label directly in your code. The fsmGOTO label saves you a little typing but doesn't really seem all that useful. Macros are known to have a number of dangerous issues, so it's best to avoid them if at all possible.
Don't Use Magic Numbers
What is state 6? State 4? What is the significance of the numbers? Reading the linked page, it sounds like they are character classes or something like that. Would it be possible to have named constants that make this more obvious?
Be Careful With Multiple Statements in a Single Line
You have a lot of places where you've written several statements on the same line, like this:
s++; if ( *s < 0x80 || 0xbf < *s) fsmGOTO(invalid);

This can be problematic for a number of reasons. First, it's difficult to debug. When you're stepping through the code in a debugger, it can be very difficult to tell which statement had what effect. Second, it's hard to read.


I am not familiar with AndEngine, but here are some things that I saw:

Inside your refreshSprites method you call detachSelf and attachChild in unsynchronized way. So either make sure this method is called from updateThread or make all those operation in your Runnable class. Here is an example of the second choice.

private void refreshSprites(Sprite pSprite1, Sprite pSprite2){
        final Sprite oldSprite1 = sprite1;
        final Sprite oldSprite2 = sprite2;
        final Sprite newSprite1 = pSprite1;
        final Sprite newSprite2 = pSprite2;

        sprite1 = sprite2 = null;

        runOnUpdateThread(new Runnable() {
                            @Override
                            public void run() {
                                oldSprite1.detachSelf();
                                oldSprite2.detachSelf();
                                attachChild(newSprite1);
                                attachChild(newSprite2);
                            }
                        });

    }

Pay attention to the final that I am using, otherwise those values will not be available in the oldSprite1 inner class.

And some small things

sprite1 = sprite2 = null; you should place in it's own method, call it reset or some thing similar. It will improve your method Single responsibility principle
Pay attention to my choice of variables names: oldSprite, I think it explain the meaning of the variable better than tmp.


Generate all possible numbers which can be representated as the sum of 2 cubes below N

Except for error checking

Error checking would be nice, and can easily be done, so why not add it to the top of your method:

    if (n < 0) {
        throw new IllegalArgumentException("number must not be negative");
    }

  what else can be improved?

your formatting, especially your spacing, which seems very random, and thus makes the code hard to read. Just use an IDE to fix this for you.
define variables in as small a scope as possible. For example, sum can be declared inside the loop as long sum = cubes.get(i);.
don't print in your method, but return the values instead. This makes the next point a lot easier, and makes your method reusable in general.
write unit tests to verify the functionality of your code, and to make it a lot easier to make changes without being afraid of breaking the code.


Welcome to Code Review. There are already excellent answers, I am adding an alternative solution running in \$O(n)\$ and relatively simple to understand.
private static void printFirstNonRepeatedChar(String str) {
    // LinkedHashMap maintains the insertion order
    Map<Character, Integer> freq = new LinkedHashMap<>();

    // Create map of frequencies
    for (Character c : str.toCharArray()) {
        if (freq.containsKey(c)) {
            freq.put(c, freq.get(c) + 1);
        } else {
            freq.put(c, 1);
        }
    }

    // Find first character with frequency 1
    for (Entry<Character, Integer> entry : freq.entrySet()) {
        if (entry.getValue() == 1) {
            System.out.println(entry.getKey());
            break;
        }
    }
}

The map freq contains the frequencies of the characters. For example, given the string aabbc, the map will be:

a -> 2
b -> 2
c -> 1

LinkedHashMap maintains the insertion order so after building the map it's enough to find the first entry with frequency 1.
This is the same but using Streams:
private static Character findFirstNonRepeatedChar(String str) {
    Map<Character, Long> freq = str.codePoints()
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(Function.identity(),
                                           LinkedHashMap::new,
                                           Collectors.counting()));
    return freq.entrySet().stream()
            .filter(e -> e.getValue()==1)
            .map(Map.Entry::getKey)
            .findFirst().orElse(null);
}

Time complexity
Your solution runs in \$O(n^2)\$, where \$n\$ is the length of the input string. I highlighted in your code the relevant parts:
static void printFirstNonRepeatedChar(String str){
    // O(n)
    for(char c : str.toCharArray()){
        // isRepeated runs in O(n)
        if(! isRepeated(str, c)){
           // O(1)
        }
    }
    //..
}

As @Joop Eggen said, for small input strings you need to benchmark the solutions to really see the difference, but for large inputs the Big O notation must be considered.
Testing and reusability
Generally, it's better to return a result instead of printing in the method. It's easier to test and reuse. In your case the method could return the character or null. For example:
static Character printFirstNonRepeatedChar(String str){
    //...
        if(! isRepeated(str, c)){
            return c;
        }
        return null;
}

Now the method is easy to test:
@Test
public void findFirstNonRepeatedCharTest() {
    assertEquals(Character.valueOf('c'),findFirstNonRepeatedChar("aabbc"));
    assertNull(findFirstNonRepeatedChar("aa"));
}

Minor changes

In the method printFirstNonRepeatedChar you can just return; instead of using the flag found and break.


Converting seconds to hours, minutes and seconds

Your usage of auxiliary functions is not consistent: Some computations are
done inline, e.g.

int hours = totalSeconds / MINUTES_IN_AN_HOUR / SECONDS_IN_A_MINUTE;

and other (equally simple) computations are done using the functions
hoursToSeconds() and minutesToSeconds().

But my main point is that the calculation is too complicated, and extending
it to more time units (e.g. days) would make it even more complicated.

It is easier if you compute the lowest time unit first (seconds)
using the remainder operator %,
and then proceed to the higher time units (minutes, then hours).

Then you don't need additional functions for the conversion and therefore you
can restrict the scope of the conversion constants to
the timeConversion() function.

private static String timeConversion(int totalSeconds) {

    final int MINUTES_IN_AN_HOUR = 60;
    final int SECONDS_IN_A_MINUTE = 60;

    int seconds = totalSeconds % SECONDS_IN_A_MINUTE;
    int totalMinutes = totalSeconds / SECONDS_IN_A_MINUTE;
    int minutes = totalMinutes % MINUTES_IN_AN_HOUR;
    int hours = totalMinutes / MINUTES_IN_AN_HOUR;

    return hours + " hours " + minutes + " minutes " + seconds + " seconds";
}


# array is list to sort, array is going to be passed by reference, this is new to me, try not to suck
# l is the left bound of the array to be acte on
# r is the right bound of the array to act on

A comment like that would be better as a docstring.

if r == -1:
    r = len(array)

You wrote that twice.  The second time is dead code.

piviot = int((r-l)*random.random()) + l

The correct spelling is pivot.  To generate the random integer, use random.randrange(l, r).

def swap(array, a, b):
    # a and b are the indicies of the array to be swapped

    a2 = array[a]
    array[a] = array[b]
    array[b] = a2

    return

The correct spelling is indices.

The return is superfluous.  I would omit it.

The swap can be written more simply as array[a], array[b] = array[b], array[a].  That is simple enough that it might be better not to write a swap() function at all.


Implementation of portscanner for a host

Use getaddrinfo only once, to resolve the host.  Do the port number iteration directly yourself.  While it might be more complicated, it also doesn't call for repeated hostname resolutions.  This also allows you to eliminate convert_int_to_string()
If you don't want IPv4 and IPv6 (which seems to be indicated by specifying AF_INET, you might be better off using the older functions.  This eliminates the complexity noted before.
As the last step in the loop, you MUST close the socket.  Otherwise, you will wind up with 1027 open descriptors.  Since current linux systems have a limit of 1024 open descriptors, your program will terminate early without this.  Other OSes will have similar limits.  Since you only ever need 4 open descriptors (or maybe 5 depending on getaddrinfo()), you should do the cleanup.
I suggest localizing variables where possible.
In convert_int_to_string(), if you start at the end of the buffer and work backwards, you can return the point in the buffer that you have reached instead of reversing the text.  Alternatively, snprintf(a, sizeof(a), "%d", num); works well.
Passing errno to error() is a mistake if errno isn't set.  This includes the wrong number of arguments error (no number) and the call to getaddrinfo() (which returns an error number and has its own function to make it a string).


I assume that your code produces the desired output, so I'll comment on the code style only here.

While doing everything in the main method may work for small programs, it's not a good idea in general. Ideally, one method should do one thing. Moreover, exactly the same code that prints the matrix is used twice in your solution. It's a very good reason to create a separate method for it. In general, I would split your program into at least three separate methods: one of them would read the matrix, the other one would perform a required transformation and the last one would print the matrix to the standard output. It looks roughly like this:

int[][] readMatrix() {
    ...
}

void swapDiagonal(int[][] matrix) {
    ...
}

void printMatrix(int[][] matrix) {
    ...
}

The comments inside the method (like //Swapping) are an indicator that a piece of code this comments corresponds to should be probably factored out to a separate method (of course, it's not always the case. It is the case here, though). Once or code calls the swapDiagonal method, there is no need for such comments anymore. The code becomes self-documented, which is a great thing as comments can become obsolete if you change the code in the future. There's no way to ensure that the piece of code followed by the //Swapping comment actually swaps anything after changes are made (again, it's not a big deal for a such a small program, but it can become a serious issue if you implement a larger program using the same practices).
You can get rid of magic constants (like 3 and 2) in your code by creating a constant variable for them (for instance, you can set final static int MATRIX_SIZE = 3 and use it everywhere in your code. It communicates the intent more clearly and makes possible future changes easier (you need to change just one constant instead of looking for all 3's and 2's around your code).
Keeping the scope of each variable as small as possible is a good practice. The declaration of loop counters outside the loop is not just unnecessary, it's also sort of misleading (as it's normally done only when the value of the counter is used outside the loop, which is not the case here). That is, the only variable you need to declare in the begging of the method is the array to hold the matrix. The loops are usually implemented this way:

for (int i = 0; i < MATRIX_SIZE; i++) {
    for (int j = 0; j < MATRIX_SIZE; j++) {
        // do something with the (i, j) element here
    }
}

Variable naming. It's conventional for the names of variables to start with a lowercase letter. Moreover, a Number doesn't look like a good name for a matrix to me. It's confusing. You could call matrix, for instance.
Code formatting. It's conventional to surround binary operators with whitespaces. The opening curling bracket shouldn't go to the next line according to the Java coding conventions. It is also common to use int[][] array, not C-style int array[][] in Java (it has the same semantics, though).
You could also get rid of redundant variables and assignments (I'm not talking about performance, I' talking about communicating your intent as clearly as possible):

m = scanner.nextInt();
Number[i][j] = m;

looks quite strange. Why not use:

Number[i][j] = scanner.nextInt();

instead?


A closable footer bar with a floating info box

OK here's a few pointers on the above code:

IDs in css are not a good idea. The problem is that an ID can only be over-ridden by an ID, inline style or !important declaration. It's pretty well established best practice to use classes rather than IDs as a way of hooking in your css. It's great you aren't using the HTML tags themselves as selectors.
It's very interesting how you've grouped your css properties. I think you've gone for logical groupings rather than the arbitrary alphabetical order that is preferred by many. This might be contentious, but I think it's better to make logical groups.
JS variables are not name-spaced. This is fine in tiny examples, but will be very problematic in larger sites. For example, the very generic closeButton variable in the JS could easily be over-written somewhere else, by someone else and cause a tricky and unnecessary bug.

The same applies with css and while we're here, separating out JS hooks from class attributes used for styling will help edits to styles effecting JS functionality on the page.

Consider this as an alternative:

var FooterPopup = {
  closeButton: document.getElementById('#js-footer-popup__close-button');
}

.footer-popup__close-button {
  /* styles */
}

Where FooterPopup.closeButton will access the close button within the context of the object and the page. You can now port the FooterPopup anywhere else and re-use it.

Note, the js- prefix makes it very clear that the hook is used by javascript. The double underscore is nicked from BEM notation and I've used it here to define a block and it's element in a way that is clear to read and shouldn't be hit anywhere else in the site and over-ridden.

Addition of hard-coded styles in the JS. You use the .style.display JS declaration to hide the element and close it. This is problematic because everywhere you want to add this functionality you'll have to directly define it. There are literally 100s of ways of closing something when you consider all the interface nuances designers might want to introduce so isolating this and making it re-usable is a good idea.

A way to do this is to use a utility class then add and remove that using JS. Then you define the closed style in css - recommended at the bottom of the file so the styles over-ride any that might be added to the element generally. Note that this has other benefits - if you wanted something to load on the page hidden you could just add this class to the element rather having to add all the properties copied from JS to the css for that element.

Here's a simple example:

.element {
  opacity: 1;
  top: 0;
  transition: all 0.2s;
}

.is-hidden {
  opacity: 0;
  top: -50px;
}

$('.element').addClass('is-hidden'); (I've used JQuery here - it's a robust, common library that takes some of the pain out of DOM manipulation, you may have considered it however and it's very informative and ultimately better, if a little harder to start with, to tackle the raw JS).

Here is the more complicated way to add and remove classes with just JS.

Finally, check out JSFiddle or CodePen. Here's a link to your code in JSFiddle: https://jsfiddle.net/ujLjr0kp/1/ - it's really useful front-end playground and very good for sharing code on Stack Exchange :-)


Code behaviour: Working object orientated with a database

Without reading any documentation, huh? Well let me read you your code as I see it then.

Create new Author
Give it a name(instead of title? or is that really the book too?)
Add it to the database.
Create a new Book
Give it a title
Assign it an author using initiated author class
Print Author's books, which is empty
Add book to database
Now, maybe with an update, I would expect Author to have the new book

Your second bit of code is just confusing. Why would you allow your properties to be reassigned? The author isn't going to change. If there are multiple authors, then I would expect you to have a setAuthors() method that accepted an array, or multiple arguments.

Otherwise this looks fine.

Edit

Still not sure if I understand, and changing the example didn't help. If anything it confused matters. Don't delete contents or drastically change it. Just add an Update or Edit section like I've done in my post. Let's see if I can clear up some of these misunderstandings.

Your main question seems to be how I would expect the contents of $UserGroup to be updated. You are right, I originally misunderstood you. So long as I am not misunderstanding you now, this update should help. Anything that caches information, even just temporarily in local scope, I would expect to need to check periodically for updates. Because the content of $UserGroup is "cached" (or should be), I would not expect any change to be immediately available to it. That being said, I also would not expect $User to be responsible for this. $User is a completely separate class and should not be concerned with $UserGroup at all. Instead $UserGroup should explicitly request new data from the database when it anticipates that the data may have changed.

Your comment leads me to believe you also would like to know how this update method would look. I think I just explained it, but essentially it will do what you are already doing when you first initialize the object, it should fetch the new data from the database to replace the old. To be efficient, you should have some sort of check to see if any changes were actually made before requesting the new data. In other words, you would reinitialize the object.

Next you ask the same question again, but say you are using a different method from when you first asked the question. I'm assuming this is a typo from when you updated your question, so I'll skip over this.

The problem with updating the $UserGroup immediately, through the $User object, is that the $UserGroup has no control over it. This means that information could change in some other part of the application, and you would never know because you did not expect it. An example of how this might be a problem: Say you have initialized this object and call another method, and, unbeknownst to you, it changes the information in your object. You didn't expect it, so you continue using it and now indices could be messed up and, using the new example you gave, you could be giving out someone's password to a completely different user. This is why I said earlier that $UserGroup should be concerned with its own data, nothing else should touch it. The best way to do this is to just not load the data until after you have already made all the changes you need to make.

The last two statements about referencing the data is just confusing. Of course you should be using internal indices. When you fetch data from a database, it is no longer associated with that database. It will now have its own reference pointers you should use, usually array indices. When its time to update the database with the new data, then you will use references common to both. For instance, in the $UserGroup database, you might use a user's username or ID to reference the proper cell in the database. These are pretty typical primary keys because they are unique.

I hope this better answers your question. I'm sorry I can't help more, but I"m having difficulties understanding what you are trying to say. I'm assuming because of some language barrier.


HTML and CSS word styling and screen reader usability

You could try using a formating tag such as  or  instead of .

        The
        Community
        Space


Prepared PHP statement to fetch posts for some category

$foo2 = strpos($foo, '\'');
if ($foo2 > 0) { Header("Location: default.php"); }

Creating another variable for this, especially with a generic name like "foo2", is superfluous and should be avoided. if (strpos(..) > 0) will do just fine.
Just redirecting with a header does not stop the script execution. Your script will continue to run, making this rather pointless. You need to exit explicitly.
This check will fail if the quote is the first character, since strpos returns 0 in that case.
Why are you worrying about quotes in particular at all? There's really no point to this.

What you may want to check for instead is whether the value is defined at all.

$foo_cat = $foo;

There's no point in reassigning this variable yet again.

$result_cat_title = $stmt->prepare($cat_title_sql);
if(!$result_cat_title) ...

Using yet another rather mis-named variable is pretty superfluous, again.

trigger_error(..)

If you're using a (poorly) user-defined error handler (or somebody who may be using this code in the future adds one), your script may not actually exit when you trigger an error. You should either still explicitly exit after this, or perhaps switch to exceptions.

$count_cat = $stmt->num_rows;

Again a rather superfluous variable assignment.

Header("Location: ../default.php");

Again a header which does not terminate script execution.
You should also consider indicating a 404 Not Found error instead of a silent redirect.

else if ($result)

Why are you checking $result here? That was a variable used in completely different context. Also, since the previous header statement was supposed to terminate the script, you can skip this check entirely.

while ($stmt->fetch())

You're only expecting a single result, no need for a loop.

$cat_ttl = $fld_title;

Yet another superfluous variable assignment.

<title><?php echo $cat_ttl?></title>

You should take care of HTML injection/syntax issues and HTML-encode your output appropriately.

Beyond this indentation and variables names are often sub-optimal.

In summary:

<?php

if (!isset($_GET['tag'])) {
    header('HTTP/1.0 400 Bad Request');
    exit;
}

/* connection string up here */

$stmt = $conn->stmt_init();

$query = 'SELECT ld_title FROM j_oracle_cat WHERE ld_tag = ? LIMIT 1';
if (!$stmt->prepare($query)) {
    throw new Exception("Error preparing statement: $stmt->error, SQL query: $query");
}

if (!$stmt->bind_param('s', $_GET['tag'])) {
    throw new Exception("Error binding parameter: $stmt->error");
}

$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows == 0) {
    header('HTTP/1.0 404 Not Found');
    exit;
}

$stmt->bind_result($title);
$stmt->fetch();

?>
<title><?php echo htmlspecialchars($title); ?></title>


For your inner for-loop you have

for (int j = i; i * j <= n; j++) {
                isPrimeArray[i * j] = false;
            }

Once you find a prime number, you can start knocking out factors at i*i, since any multiple of i less than that would be a multiple by an existing smaller prime you already ran elimination on in a previous iteration!

Also, you have to go through the entire array, so your ending point would be j<=n

And lastly, you are iterating over multiples of i! So your loop can increment at j+=i at each step. Leaving the final fixed loop to be:

for (int j = i*i; j < n; j+=i) {
                isPrimeArray[j] = false;
            }

This should cut down on plenty of iterations.

Also you may want to consider breaking your outer loop into two for-loops.
First a for loop for multiples of 2

for(int i = 4; i < n; i+=2) //set to false

Since 2 is the only even prime, this means that in your main code (your old outer loop) can be rewritten to only go over odd numbers, cutting down half the iterations!

Another time saving tip is to also process your loop up to Math.sqrt(n) because once you hit the square root, anything after that is prime because multiples of those numbers fall outside of your sieve.

int limit = (int)Math.sqrt(n) + 1
for(int i = 3; i < limit ; i+=2) //inner loop revised above

So now you are not only skipping even numbers, but also only going up to the square root of n, rather than n itself.

Other than that your spacing and naming seems to be fine. Though I would recommend you separate the tasks out into different methods. Namely split your function into a generateSieve() function that makes the sieve, and then a sumOfPrimes function that takes the sieve as a parameter and outputs the sum.

I say this because the sieve itself is a widely used technique for Project Euler problems, and you won't just want to find the sum! So I recommend making generateSieve() (or whatever you may name it) it's own function.


Instead of iterating over a vector I'd use std::find().
Even better, instead of std::vector I'd use std::set:

#include <iostream>
#include <set>
#include <string>

using namespace std;

int main(int argc, const char * argv[])
{
    string bad[] = {"poop", "balls"};
    set<string> bad_words(bad, bad + sizeof(bad) / sizeof(string));

    string input;
    while(cin >> input)
    {
        if(bad_words.find(input)!=bad_words.end()){
            cout << "bleep! ";
        }
        else {
            cout << input << " ";
        }
    }
}


There's not really much to review here, but a few quick items:

This is going to sound weird at first glance, but you have a route() method that takes a path instead of depending directly on the request uri.

A router's job is to route.  By hard coding the $_SERVER['REQUEST_URI'], you've made it limited to one data source.
route($path) would be much more flexible, and it would mean that one object could be used for routing more than 1 time.
Think about test driven design.  How would you test a hard coded $_SERVER['REQUEST_URI']?  (Other than putting a hacky assignment to it somewhere)

Never assume that array indexes exist

If someone goes to index.php or /foo, so on, then $URLElements might not have 2 elements

As it is, your class does nothing useful -- you probably know that though :)

A major improvement would be making it actually do something :)


A good addition is to add a check at the start of your function to check if your parameters are correct. This way you don't need extra if statements which helps for readability.

const isValidNum = (n) => typeof n === "number" && n >= 0;

const sumAll = function(lowEnd, highEnd) {
  if (!isValidNum(lowEnd) || !isValidNum(highEnd)) return "ERROR";

  let total = [];
  let sum = 0;

  if (lowEnd <= highEnd) {
    for (let i = lowEnd; i <= highEnd; i++) {
      total.push(i);
    }
  } else {
    for (let i = highEnd; i <= lowEnd; i++) {
      total.push(i);
    }
  }

  for (let i = 0; i < total.length; i++) {
    sum += total[i];
  };

  return sum;
}

console.log(sumAll(1, 4));
console.log(sumAll(4, 1));
console.log(sumAll("1", 4));
console.log(sumAll(1, "4"));
console.log(sumAll(1, -4));
console.log(sumAll(-1, -4));

Another option is to check for the highest and lowest number via Math.min() and Math.max(). This way the order of input doesn't matter and you don't have to write the loop twice.

const isValidNum = (n) => typeof n === "number" && n >= 0;

const sumAll = function(lowEnd, highEnd) {
  if (!isValidNum(lowEnd) || !isValidNum(highEnd)) return "ERROR";

  let total = [];
  let sum = 0;

  const lowest = Math.min(lowEnd, highEnd);
  const highest = Math.max(lowEnd, highEnd);

  for (let i = lowest; i <= highest; i++) {
    total.push(i);
  }

  for (let i = 0; i < total.length; i++) {
    sum += total[i];
  };

  return sum;
}

console.log(sumAll(1, 4));
console.log(sumAll(4, 1));
console.log(sumAll("1", 4));
console.log(sumAll(1, "4"));
console.log(sumAll(1, -4));
console.log(sumAll(-1, -4));

At last you could add a formula to calculate the total sum of a range of numbers. Which removes the need of loops. (More info about the formula here)

const isValidNum = (n) => typeof n === "number" && n >= 0;

const sumRange = (low, high) => ((high - low + 1) * (low + high)) / 2;

const sumAll = function(lowEnd, highEnd) {
  if (!isValidNum(lowEnd) || !isValidNum(highEnd)) return "ERROR";

  const lowest = Math.min(lowEnd, highEnd);
  const highest = Math.max(lowEnd, highEnd);

  return sumRange(lowest, highest);
}

console.log(sumAll(1, 4));
console.log(sumAll(4, 1));
console.log(sumAll("1", 4));
console.log(sumAll(1, "4"));
console.log(sumAll(1, -4));
console.log(sumAll(-1, -4));

Total revision with comments:

// Return true if "n" is positive and of type number, else return false
const isValidNum = (n) => typeof n === "number" && n >= 0;

// Formula for adding a range of numbers
const sumRange = (low, high) => ((high - low + 1) * (low + high)) / 2;

function sumAll(lowEnd, highEnd) {
  // Return "ERROR" if arguments are invalid
  if (!isValidNum(lowEnd) || !isValidNum(highEnd)) return "ERROR";

  // Find highest and lowest number
  const lowest = Math.min(lowEnd, highEnd);
  const highest = Math.max(lowEnd, highEnd);

  // Return added numbers
  return sumRange(lowest, highest);
}

console.log(sumAll(1, 4));
console.log(sumAll(4, 1));
console.log(sumAll("1", 4));
console.log(sumAll(1, "4"));
console.log(sumAll(1, -4));
console.log(sumAll(-1, -4));

PS: I really like the way your tests are written. nicely clean and concise.


Java Implementation of linked list add(i, x) method

First: Java-1.5 and a List of Object, not a generic List? But a CS-degree and intermediate level?

Second: Your comment complicates 2 cases: List is empty or not - if not ... - well, if you don't distinguish the cases, from:

// 1. The list is non-empty, but the requested index is out
// of range (it must be from 0 to size (), inclusive)

to:

// it must be from 0 to size (), inclusive.

Now look at condition 2:

// 2. The list itself is empty, which will only work if i = 0

If the size is 0, and i=0, then i is in the range of 0 to 0 inclusive, isn't it? So it is just one condition, and a much shorter condition.

However, the code seems right, and can't be simplified like the condition*), and it isn't that easy, even if it looks easy in the end. Several days seems a lot, but several hours can vanish like nothing, expecially, if you get a wrong start. I remember John Bentley, who wrote, that a simple binary search wasn't correctly implemented by most of the professional developers he interviewed. By none of them, if I remember correctly ('Programming Pearls').

*) This claim isn't proved. Disprove it, friends!

I would expect an IndexOutOfBoundsException if the index is negative or too big. A size-Method would be useful for that.


A much simpler way is:

function convert_to_time(tenths)
  local hh = (tenths // (60 * 60 * 10)) % 24
  local mm = (tenths // (60 * 10)) % 60
  local ss = (tenths // 10) % 60
  local t = tenths % 10

  return string.format("%02d:%02d:%02d.%01d", hh, mm, ss, t)
end


You've got tree paths encoded as integers such as: 10030201. Your code would much easier to write if instead they tuples like: (10, 03, 02, 01). If at all possible, you should change your dictionary to always use tuples. If not possible, have a function to convert the integers to tuples when you need them. If you do that, you'll find its fairly easy to devise a general implementation of your BACKS logic.

On the stylistic front: We typically use ALL_CAPS only for constants. We use lowercase_with_underscores for local variables which all of your stuff appears to be.

My solution:

def calculate_backs(source, destination):
    """
    Return how many "resets" are required to transform source into destination
    """

    def as_tuple(id_number):
        """
        Converts the id_number into a path sequence:
        10010200 becomes (10, 1, 2)
        """
        pieces = []
        while id_number:
          pieces.append(id_number % 100)
          id_number /= 100
        pieces.reverse()

        # position 0 denotes a root node in the tree, so remove any trailing
        # zeros.
        while pieces[-1] == 0:
          pieces.pop()
        return tuple(pieces)

    def calculate(source, destination):
        if source and destination and source[0] == destination[0]:
            # If both source and destination agree for the first piece of the
            # path, drop that piece and determine the number of resets required
            # for the rest.
            return calculate(source[1:], destination[1:])
        else:
            # If the path disagrees on the first piece, we have to reset
            # everything remaining in both paths.
            return len(source) + len(destination)

    return calculate(as_tuple(source), as_tuple(destination))


Truncating an integer from left to right and right to left

I would suggest returning the truncations in order of increasing lengths for truncation from the left (checking the shorter tails for primality is faster, so if the number is not a left-truncatable prime, that should be detected faster on average when the tails are yielded in that order),

IEnumerable<long> LTR (long x)
{
    long powerOfTen = 10;
    while(powerOfTen <= x)
    {
        long tail = x % powerOfTen;
        powerOfTen *= 10;
        yield return tail;
    }
}

is nice and short if you know that the argument x is never so large that the next larger power of 10 exceeds long range. I f x may be that large, you need to guard against overflow, slightly longer:

IEnumerable<long> LTR(long x)
{
    // if (x < 10) return ??;
    long bound = x/10, lastPowerOfTen = 1;
    while(lastPowerOfTen <= bound)
        lastPowerOfTen *= 10;      // doesn't overflow
    }
    long powerOfTen = 1;
    do
    {
        powerOfTen *= 10;
        yield return x % powerOfTen;
    }while(powerOfTen < lastPowerOfTen);
}

If you want to return the truncations in order of decreasing lengths, you can easily modify the last:

IEnumerable<long> LTR(long x)
{
    // if (x < 10) return ??;
    long bound = x/10, powerOfTen = 1;
    while(powerOfTen <= bound)
        powerOfTen *= 10;      // doesn't overflow
    }
    while(powerOfTen > 1)
    {
        x %= powerOfTen;
        powerOfTen /= 10;
        yield return x;
    }
}

Note: If the decimal representation of x contains at least one zero other than the last digit, these would all return the same value more than once. Since no (right or left) truncatable prime can have a zero digit in its decimal expansion, I did not care about that. If you do, in the last (decreasing length) version, you could easily avoid that by replacing

powerOfTen /= 10;

with a loop

do {
    powerOfTen /= 10;
}while(powerOfTen > 1 && powerOfTen > x);

In the increasing-length versions, that would not be as simple.

Further note:

long p = (long)Math.Pow(10, powerten);

Don't use floating point functions for integer arithmetic. In this case, if the called Math.Pow function operates on doubles [I'm not sure how that is in C#], it will not lead to wrong results, but it could produce wrong results if it operates on floats, and also in general (for other bases) even if double is used.


Function for removing forbidden characters

Declare a string containing the illegal characters: "\\/:?"<>|". All you need to do is check if the char is in the array, so use a native function for that, or write a method CharInString(char* needle, string* haystack) which loops through the contents of the provided haystack to check if the needle is inside it.

Your loop should end up looking like this:

string illegalChars = "\\/:?\"<>|"
for (it = s->begin() ; it < s->end() ; ++it){
    bool found = illegalChars.find(*it) != string::npos;
    if(found){
        *it = ' ';
    }
}

It's more maintainable and readable. You can tell if you've duplicated a character quite easily and since you can do it with any target string and any string of illegalChars you've just created for yourself a generic RemoveIllegalChars(string* targetString, string* illegalChars) method usable anywhere in your program.

I may be using those pointers wrong. My C++fu is weak... for now.


Saving and uploading images in a database

Yes, there certainly is. Prepared statements can be reused, over and over again. The way your code works is: it's creating the same prepared statement over and over again, and binds the new parameters right after doing so, why not move the prepare call outside of the loop?

$stmt = $this->dbh->prepare("INSERT INTO adrenaline_junkies_uk_event_images (event_image_name, event_id) VALUES (?,?)");
foreach($_FILES['event-images']['tmp_name'] as $tmp_name)
{
    $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];
    move_uploaded_file($tmp_name, $imgName);
    $stmt->bindParam(1, $imgName, PARAM_STR);
    $stmt->bindValue(2, $event_id, PARAM_INT);
    $stmt->execute();
    //done for now, to re-use a statement, close its cursor first?
    //though this is done implicitly, best do it ASAP
    //especially when using SELECT + PDOStatement::fetch in a loop
    $stmt->closeCursor();
}

For a start, that saves you the trouble of that prepare call in the loop, increasing readability and, if all goes well, it'll also improve performance a bit.

Now, I do have some other niggles with your code, like this statement:

$imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];

Now, I don't know how your $_FILES array is structured, but check some of the contributed notes on the man page there are quite a few snippets that deal with $_FILES arrays recursively.

Another thing, and this is really a detail, is that you don't seem to be using transactions. When you're in the process of inserting images, one by one, and you reach a point where your script fails (either through timeout or another reason), you might end up with partially inserted data. That's not great. Transactions are an easy way to avoid this:

try
{
    $this->dbh->beginTransaction();//start transaction here
    $stmt = $this->dbh->prepare("INSERT INTO adrenaline_junkies_uk_event_images (event_image_name, event_id) VALUES (?,?)");
    foreach($_FILES['event-images']['tmp_name'] as $tmp_name)
    {
        $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];
        move_uploaded_file($tmp_name, $imgName);
        $stmt->bindParam(1, $imgName, PARAM_STR);
        $stmt->bindValue(2, $event_id, PARAM_INT);
        $stmt->execute();
    }
    $this->dbh->commit();//ok, all was well, commit inserted data
}
catch (PDOException $e)
{
    $this->dbh->rollBack();//undo inserts, because not all of them were successful.
    throw $e;//rethrow, let caller deal with the exception
}

Now this is looking better, I do believe. But like I said in the comments, bindParam uses references:

public bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
                                                               ^^ & => reference

, which (in a loop) can lead to unexpected behaviour from time to time, so I'd rather pass my values to PDOStatement::execute, if I were you:

    foreach($_FILES['event-images']['tmp_name'] as $tmp_name)
    {
        $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];
        move_uploaded_file($tmp_name, $imgName);
        $stmt->execute(array($imgName, $event_id));
    }

But for completeness' sake, here's the same thing using bindParam outside of the loop:

$stmt = $this->dbh->prepare("INSERT INTO adrenaline_junkies_uk_event_images (event_image_name, event_id) VALUES (?,?)");
$imgName = null;
$stmt->bindParam(1, $imgName, PARAM_STR);
//$event_id might fail, because this var is argument
$stmt->bindParam(2, $event_id, PARAM_INT);
//if it fails, try:
$eventId = &$event_id;
$stmt->bindParam(2, $eventId, PARAM_INT);
foreach($_FILES['event-images']['tmp_name'] as $tmp_name)
{
    $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];
    move_uploaded_file($tmp_name, $imgName);
    $stmt->execute();
}

Lastly: You're using both bindParam and bindValue as though they both do the same thing. Now at first glance, they do, but be weary of references. read this, to see why references in loops are risky


strstr implementation with python and sets

As someone trying to pivot from physics to Computer Science, I think this solution is good, many CS graduates might not come up with a better solution first up.
Let's get some optimizations unrelated to cyclomatic complexity out of the way.
You added the pattern to a set. The lookup is constant O(1), I don't see a need to do that and you can save on a high constant.
Let's take a closer look at
    for index in range(len_text-len_pattern+1):
        if text[index:index+len_pattern] in lookup:

specifically text[index:index+len_pattern], this creates a copy of the string for the range index:len_pattern.  This is an implementation detail of Python, one can just as easily imagine an optimization that does not create a copy.
This question and its response might help explain this better.
You might be able to optimize away the object creation, again this unrelated to cyclomatic complexity.
premature optimization is evil - the intent above is more of a code review. Addressing you question below.

The runtime complexity of the loop is the equivalent of creating a copy of the pattern times the len of text
if m is len(text) and n is len(pattern) the for loop is O(n*m) in every iteration.
Typically in questions like these, there is an insight that is not always obvious that drives the solution resulting in a lower cyclomatic complexity. In this instance it is that the algorithm can be implemented in a single pass O(n) by keeping track of indexes across both the text and the pattern
def strstr(text, pattern):

    t = 0
    len_text = len(text)
    len_pattern = len(pattern)
    i = 0
    for i in range(len_text + 1):
        if (t == len_pattern or i == len_text):
            break
        if (text[i] == pattern[t]):
            t += 1
        elif (text[i] == pattern[0]):
            t = 1
        else:
            t = 0

    if (t < len_pattern):
        return -1
    else:
        return i - t

def tests():
    """Sample Tests."""
    samples = [("CodesignalIsAwesome", "IA", -1),
               ("CodesignalIsAwesome", "IsA", 10),
               ("a", "a", 0),
               ("a", "A", -1),
               ("sst", "st", 1),
               ("lrnkbldxguzgcseccinlizyogwqzlifxcthdgmanjztlt", "an", 38),
               ("abcd" * 300000 + "abcde", "abcde", 1200000),]
    for text, pattern, answer in samples:
        actual = strstr(text, pattern)
        if actual != answer:
            print(f"FAILED : pattern: {pattern}, actual: {actual}, expected: {answer}")
        else:
            print(f"SUCCESS: pattern: {pattern}, actual: {actual} matched expected")

I added an additional text case to demonstrate the runtime, testing this with time module in python, the clock time of the implementation is a few milli seconds compared to the clock time of the O(n*m) algorithm which on my machine is aboue 21 seconds.