Decided to learn Scala. Here's an attempt at a Cloth simulation

for (row <- grid) {
  for (p <- row) {

//should be written as:

for(row <- grid; p <- row) {

Tuple2("bla", 42)

//should be written as

("bla", 42)

I don't really understand why you use tuples when you have already a class for doing exactly such kind of math, namely Position.

The code could be more functional by using immutable case classes for Positions (but it depends on the problem if this is the right thing to do):

case class Position(x: Float, y: Float) {
    def -(that:Position) = Position(this.x - that.x, this.y - that.y)
    def +(that:Position) = Position(this.x + that.x, this.y + that.y)
}

Then you can write things like pos1 + pos2. Note that you don't need the getter methods, as you can write pos1.x, and no setter methods, as you can write and pos1.copy(x=12). The new isn't required any longer: val p = Position(1, 3).

How to proceed with the refactoring would depend on your decision if you keep Position as it is, or if you want to go with immutable Positions.

[Edit]

Here is how I would refactor it:

Run.scala:

package cloth

object Run {

  def main(args: Array[String]): Unit = {

    import javax.swing.JFrame

    val test = new Screen
    val frame = new JFrame("scalacloth")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setPreferredSize(new java.awt.Dimension(640, 720))
    frame.getContentPane().add(test)
    test.init
    frame.pack
    frame.setVisible(true)
  }

}

import processing.core._

class Screen extends PApplet {

  val cloth = new Cloth(
    rows = 20,
    columns = 20,
    gravity = 0.001f,
    timestep = 0.8f,
    fixedParticles = List(Coordinate(19,0))
  )

  override def setup() {
    cloth.createGrid()
    size(640, 720)
    background(255)
    smooth()
    noStroke()
    fill(0, 102)
  }

  override def draw() {
    background(255)
    fill(255)
    stroke(0)

    def drawLines(particle: Particle):Unit = particle.neighbors.foreach { n =>
      line(particle.currentPos.x * 20 + 20, particle.currentPos.y * 20 + 20,
           cloth.grid(n.x)(n.y).currentPos.x * 20 + 20, cloth.grid(n.x)(n.y).currentPos.y* 20 + 20)
    }

    for(column <- cloth.grid; particle <- column) drawLines(particle)
    cloth.verletIntegration
    cloth.satisfyConstraints
  }
}

Position.scala:

package cloth

case class Position(x: Float, y: Float) {
    def -(that:Position) = Position(this.x - that.x, this.y - that.y)
    def +(that:Position) = Position(this.x + that.x, this.y + that.y)
    def *(scalar:Float) = Position(this.x * scalar, this.y * scalar)
    def length = math.sqrt(x*x + y*y).toFloat
}

Particle.scala:

package cloth

class Particle(
    var currentPos: Position,
    var previousPos: Position,
    val gridIndex: Coordinate,
    val restLength: Float,
    val neighbors: Array[Coordinate],
    var stuck: Boolean
    ) {

  val forces = 0.0f
}

... and Cloth.scala:

package cloth

import scala.collection

case class Coordinate(x: Int, y: Int)

class Cloth(
  val rows: Int,
  val columns: Int,
  var gravity: Float,
  val timestep: Float,
  val fixedParticles: List[Coordinate]
) {

  val grid = new Array[Array[Particle]](rows, columns)

  def createGrid(): Unit = for (x <- 0 until rows; y <- 0 until columns) {
    val coord = Coordinate(x, y)
    val pos = Position(x, y)
    grid(x)(y) = new Particle(pos, pos, coord, 1.0f, findNeighbors(coord),
                              fixedParticles.contains(coord))
  }

  def findNeighbors(coord: Coordinate): Array[Coordinate] = Array(
    coord.copy(x = coord.x - 1),
    coord.copy(y = coord.y - 1),
    coord.copy(x = coord.x + 1),
    coord.copy(y = coord.y + 1)
  ).filter(isOccupied(_))

  def isOccupied(coord: Coordinate): Boolean =
    (0 <= coord.x && coord.x < rows &&
     0 <= coord.y && coord.y < columns)

  def verletIntegration(): Unit = for (row <- grid; p <- row)
    p.currentPos =
      if (p.stuck) p.previousPos else {
        val multiplyByTime = Position(p.forces * timestep * timestep, gravity * timestep * timestep)
        val together = multiplyByTime + p.currentPos - p.previousPos
        p.previousPos = p.currentPos
        p.currentPos + together
    }

  def satisfyConstraints() {

    def calculateConstraint(constraint: Coordinate, p: Particle) {
      val c2 = grid(constraint.x)(constraint.y).currentPos
      val c1 = p.currentPos
      val delta = c2 - c1
      val difference = 0.5f * (1.0f - 1.0f / delta.length)
      val dtemp = delta * difference
      p.currentPos = c1 + dtemp
      grid(constraint.x)(constraint.y).currentPos = c2 - dtemp
    }

    for(row <- grid; p <- row)
      if (p.stuck) p.currentPos = p.previousPos
      else p.neighbors.foreach(calculateConstraint(_, p))
  }

}

Hope that helps...


Return fake jqXHR from custom Ajax method

Looking at the documentation for $.ajax reveals a beforeSend option that would allow you to cancel the request before it's sent by returning false.

$.rpc = function(method, args) {
    var beforeSend = function () {
        return method && 'string' !== typeof method;
    }

    return $.ajax({
        type: 'POST',
        url: '/rpc',
        data: { method: method, params: args },
        beforeSend: beforeSend
    });
};


Doesn't SDL have a function for drawing a circle, or are you just doing that as practise?

#define PI  3.14159

math.h should have M_PI.

struct Circle {
    int radius;
    int h; // The X access of the center of the circle.
    int k; // The Y access of the center of the circle.

Just call them x and y, or center_x and center_y.

int new_x; int new_y; int old_x; int old_y; float step;

These should be in the function that draws the circle, as they're part of the logic of drawing, not the circle as an object.

int main (int argc, char *argv[])
    Circle circle;
    circle.radius = 200;
    circle.h = SCR_CEN_X;

Make a function to initialize the Circle struct, esp. as you have fields that are initialized to as uninteresting a value as zero.

        if ( event.type == SDL_QUIT ) {
            is_running = false;

I would break out of the loop here, since you're going to exit soon anyway.

    for ( float theta = 0; theta < (PI * 2); theta += circle.step ) {
        circle.new_x = circle.h + (circle.radius * cos ( theta ));
        circle.new_y = circle.k - (circle.radius * sin ( theta ));
        SDL_RenderDrawLine ( renderer, circle.old_x, circle.old_y,
                             circle.new_x, circle.new_y );

Put the circle drawing in a function, and make new_x, new_y etc. locals to it. As for step, you might want to scale it based on the circle's radius. Or make it a parameter to the function.

I think you have a sort of an off-by-one error here, as (1) on the first iteration of the loop, you draw starting from (old_x, old_y), but old_x and old_y aren't set yet. And (2) when the loop ends, you probably want to draw a line from the last point (at angle 49/50*2*pi) to the very first point (at angle 0) to complete the circle.

Also, decide if you're writing C or C++. You can't define a struct Circle as just Circle foo in C, and in C++, you should make the class have a proper constructor.


Unfortunately, your algorithm is not correct. It evaluates an expression 1-(1+1)+1 to -2.0, but it is clear that the right answer is zero. It is not an implementation bug. The logic itself is wrong. So what can be done to avoid(or, at least, to minimize the risk of) ending up with an incorrect algorithm?

You shouldn't make arbitrary assumptions. The algorithm you are using is not a well-known one, it is rather complex so it is not obvious whether it is correct or not, but you probably did not prove its correctness. For instance, you made an assumption that we can remove the first opening parenthesis and evaluate the part of the expression which goes after it separately. Is this assumption based on something? Did you try to figure out why it is correct? As you can see, it turned out to be incorrect. Proofs give you confidence in the logic of your solution.
You can use already existing algorithms. Arithmetic expressions evaluation is a well-studied topic. There is an efficient shunting-yard algorithm, which runs in linear time and is proven to be correct. Reinventing a non-trivial algorithm is not a good idea(unless you deliberately decide to do it as an exercise, but in this case you should be able to reason about the correctness of your solution).
Test your code in a systematic manner. Writing unit-tests is a good practice. The counterexample to your algorithm is rather short and simple, so you probably could have spotted that it is not correct if you had tested your code carefully.


System.currentTimeMillis() is the system clock, and can change if someone changes the current date / time.  It's not really a good way to accurately measure elapsed time.  Use System.nanoTime() instead, which is invariant to system clock changes.


Store all entries in a single array from Wufoo api

Just some quick note:

1, I would separate the configuration settings to a distinct php file (and use a WufooConfig class/struct) and include it at the beginning of the code. It makes the configuration easier to change. If you use a WufooConfig class/struct and pass it to the wufoo_entries() function you will be able to use the same function to fetch data from more than one accounts. Furthermore, it would encapsulate configuration, so you just have to pass around one parameter instead of $account, $form, $api_key, etc.

class WufooConfig {
    private $account;
    private $form;
    private $api_key;
    ...

    public function __construct($account, ...) {
        $this->account = $account;
        ...
    }
}

2, Extract the then and else branches of the if in the wufoo_entries() function:

if ($refresh) {
    $results = fetchContent(...);
    saveToCache($results, ...); // write file here
    return $results
} else {
    return getCachedContent();
}

It makes your code easier to read, you'll see the big picture immediately, it won't be distracted with low-level API calls.

For the same reason I'd create some new functions, for example:

functio entryCount(...)
    $count = wufoo_api($api_key, $account, $form, $offset, $limit, $api_uri);
    $counted = $count['EntryCount'];
    return $counted;
}

The name of the function says what you want to get and the body shows how you do it.

3, Change

for ($offset = 0; $offset <= $counted - 1; ...

to

for ($offset = 0; $offset < $counted;

It's more common.

4, In the inner for loop the $result loop variable is a little bit confusing, it's easy to mix up with $results. $resultIndex would be better.

for ($resultIndex = 0; $resultIndex < $limit; $resultIndex++) {
    array_push($all_results, $results['Entries'][$resultIndex]);
}

Finally, I agree with @Yannis Rizos, the whole logic would be better as a class.


I would not rely on assert. If Python is started with the -O option, then assertions will be stripped out and not evaluated. Better to raise an Exception here.


Insert a table row with text in cells when a button is clicked

So you want for example 6 inputs and create a table from it with the input when you click on a button.

(plain javascript):

This way it doesn't matter how many input fields you have. It will get all of them. I added some comments so you can understand what's going on.

<!DOCTYPE html>

Click the button to add a new row at the first position of the table and then add cells and content.

<input type="text">

<input type="text">

<input type="text">

<input type="text">

<input type="text">

<input type="text">

<button onclick="Display_inputs()">Try it</button>


Query of users for some age, gender, and state, using a subselect

Your query doesn't do what you think it does. It discards the original ordering when it re-sorts. It might, depending on the sorting algorithm chosen, happen to come out how you want, but there's no guarantee.

  I am using sub query because i want sort created_on DESC and email ASC

If that's what you want, just write:

ORDER BY created_on DESC, email ASC

Your bigger worry with performance is that combo side table, which appears to be EAV and thus likely to be painful in performance terms. Consider using a hstore or json field instead.


I'm not too familiar with the math side of this, so I'll just focus on the Rust part.

Run rustfmt

Running cargo fmt will autoformat your code to the Rust best practices. For example, it will convert

fn arctan(x:f64) -> f64 {
    let mut sum=0.;
    let epsilon=x/PRECISION;
    let mut i=0.;
    while i<x {
        sum+=epsilon/(1.+i*i);
        i+=epsilon;
    }
    sum*(180./pi())
}

to

fn arctan(x: f64) -> f64 {
    let mut sum = 0.;
    let epsilon = x / PRECISION;
    let mut i = 0.;
    while i < x {
        sum += epsilon / (1. + i * i);
        i += epsilon;
    }
    sum * (180. / pi())
}

Notice the spacing added.

Run clippy

Running cargo clippy will point out a few common mistakes. Let's take a look at them here.

warning: using `print!()` with a format string that ends in a single newline
   --> src/main.rs:136:9
    |
136 |         print!("{:.4}\n",arctan((i as f64)/100.));
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: `#[warn(clippy::print_with_newline)]` on by default
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#print_with_newline
help: use `println!` instead
    |
136 |         println!("{:.4}",arctan((i as f64)/100.));
    |         ^^^^^^^

As it suggests, you should replace that line with println!.

warning: casting integer literal to `f64` is unnecessary
   --> src/main.rs:141:28
    |
141 |     println!("e={:.4}",exp(1 as f64));
    |                            ^^^^^^^^ help: try: `1_f64`
    |
    = note: `#[warn(clippy::unnecessary_cast)]` on by default
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

That, and the line that follows it, can be used as a float like you do everywhere else in your code. You can do 1_f64, 1f64, 1.0, or like elsewhere in your code, 1..

Extract repeated operations

When you print things out, you repeat the calculation a lot, and it actually appears to have a difference in assembly (although not when #[inline(never)] is used on ln?). So instead of

if arccos((i as f64) / 100.) < 90. && arccos((i as f64) / 100.) > 0. {
    print!("{:.4}\t", arccos((i as f64) / 100.));
} else if arccos((i as f64) / 100.) > 0. {
    print!("90\t");
} else {
    print!("0\t");
}

Prefer

let inv_cos = arccos((i as f64) / 100.);
if inv_cos < 90. && inv_cos > 0. {
    print!("{:.4}\t", inv_cos);
} else if inv_cos > 0. {
    print!("90\t");
} else {
    print!("0\t");
}


Here are the major comments:

Ideally functions should do one thing at once. Your function is doing two: (1) asking the user for a password and (2) evaluating the strength of that password.

You should break this code into two functions: (1) ask_user_for_password() and (2) is_password_strong(password).
Regexes are not always the right tool for the job. (I appreciate this is a chapter on regexes, but the point has to be made.)

Python has fairly powerful string  manipulation tools. You should reach for those before opening your regex toolbox – I think the Python constructs are usually much easier to read and debug. Brownie points for writing a version that doesn’t use regexes – I would almost always prefer this version in a “real” codebase.
Be lazy about evaluation. This function is fairly fast, because it doesn’t have many checks. Even so, you can save yourself a little work – as soon as a check fails, you can return False.

(It’s fine to bail out early for a password strength evaluation. Try to avoid doing this when doing real authentication – if your function takes noticeably different time depending on what’s wrong with the function, you’re vulnerable to a timing attack.)
Your function should have a docstring. Docstrings are the preferred way to document functions in Python. For this function, it should be fairly simple -- it evaluates a password, and returns True/False depending on whether it meets certain criteria -- but you should still write it.

And a few nitpicks:

Compare to None with “is”, not “==” and “!=”.

It’s always preferred to check using “is”, which checks identity, not equality – this makes sure the object you’re dealing with really is None, and not a class with a strange equality operator. It’s also faster.
You can tidy up your booleans.

Quite a few of your lines boil down to:

result = True if (check != None) else False

This line reduces to:

result = (check is not None)

That’s more readable and direct.

Then your final boolean can be reduced to:

return (length and case and digit)

which is equivalent.
Put your main code in an if __name__ == '__main__' block. This means that it only runs when the file is called directly – not, for example, when it’s imported as a module.

This makes your code easier to reuse.


Saving search history with many checks and validations inside

It seems dirty and unobvious.

I wouldn't go that far. I think that the code generally looks fine.

Style

The indentation and spacing is generally fine, but sometimes it is inconsistent (2 vs 4 spaces, spaces around +).

validate

I would validate right in the constructor instead of in a public method, because someone might forget to call the method, and then you end up with an invalid object.

And as validate has side-effects (it doesn't just check the string, it actually changes it), I would add a JavaDoc comment.

removeSameWord

Is this method really needed? Your database schema should be able to use a unique constraint to not allow duplicate rows. Or, since you are using merge, you should also be able to just remove it completely, since merge updates existing entries.

Naming

Sometimes, you use word or words and sometimes searchString for what seems to me to be the same thing. This is a bit confusing, you should use variable names consistently.
the query removeOldWords could just be removeByIds, because it doesn't care if words are old or new, it just deletes all words with the given ids.
checkWordsSizeLimit doesn't just check, it also deletes, the name should reflect this (maybe something like enforceWordsSizeLimit; or split the method up in getLastIds and removeByIds).
the query removeSameWord could be renamed to remove (the query doesn't really care if it's the same word as some other word, it just removes the given entry).
removeSameWord could also be remove (the parameters make it clear what will be removed) or removeExisting.


Multiplying an array by a number in C and how can achive vectorize the principal loop in this function?

Review of your Godbolt-fu: https://godbolt.org/z/doD3Ld

You can change the language from "C++" to "C" via the dropdown in the upper right corner of the source-code-editor pane.
You wanted to be using "gcc (trunk)", not "gcc (modules)", anyway.

The biggest contributor to running time must be that uint8_t digit is being provided as a runtime parameter instead of a compile-time parameter. But your benchmark only ever calls LongNumConstMult with 9, 8, 7, and 3. You should benchmark what happens if you write four different versions of the code: one with static const int digit = 9; at the top, one with static const int digit = 8;, and so on. Maybe that won't meet your design requirements, but it will give you a nice bound on what kind of improvement might be possible.

I infer that maybe you only need to handle 10 different digits. In that case, you could implement the runtime-parameterized LongNumConstMult as

void LongNumConstMult(uint8_t *V, size_t N, uint8_t digit)
{
    switch (digit) {
        case 0: return LongNumSetTo0(V, N);
        case 1: return;  // no-op
        case 2: return LongNumConstMult2(V, N);
        case 3: return LongNumConstMult3(V, N);
        [...]
        case 8: return LongNumConstMult8(V, N);
        case 9: return LongNumConstMult9(V, N);
    }
}

I predict that "one branch at the beginning, followed by many constant multiplications in a loop" might well beat "many non-constant multiplications in a loop."

  It's fine for the solution to use intrinsics or other specialized techniques

What about making V an array of uint16_t, uint32_t, uint64_t, or even __uint128_t? Even if V remains uint8_t, could you type-pun it to load 8 or 16 bytes at a time and do the multiplication at that width? (What is the native width of your machine?)

Here's some code that's in C++, so not directly applicable to your case, but you might find it useful: https://quuxplusone.github.io/blog/2020/02/13/wide-integer-proof-of-concept/
The code itself uses some x86 compiler intrinsics that may be relevant to your interests.


Personally, because this function can be simplified, I don't believe the variables are necessary. Since you are using Typescript, an enum would fit well here, but I believe even this is unnecessary. The results of a compare function are well standardized.

enum Result {
  equal = 0,
  greater = 1,
  lesser = -1
}

You are correct that it is more appropriate to apply the function with generics. If somewhere you need the flexibility that any provides, you can simply call the function with compare<any>(a, b) to override the type. I personally have found that any is only useful when first converting a project and will avoid it like the plague if at all possible.

Now, a few comments about the function itself.

I'm not sure how you are compiling this, but it emits three errors in the playground.

nullOrUndefined(s1) ^ nullOrUndefined(s2) - The '^' operator is not allowed for boolean types. Consider using '!==' instead.
s1 = s1.toLowerCase();- Type 'string' is not assignable to type 'T'.
s2 = s2.toLowerCase(); - Property 'toLowerCase' does not exist on type 'T'.

You will have problems if you try to use this function with the built in Array.prototype.sort function because undefined results in the array being treated as a sparse array. See the spec.
To ignore string case, it would be better to use String.prototype.localeCompare.

Here is how I would implement this function. I purposely use == instead of === for comparing null as it also catches undefined.

function compare<T>(a: T, b: T): number {
    if (a == b) return 0;
    if (a == null) return -1;
    if (b == null) return 1;

    // To appease the type system, check both
    // I think it might be a bug that this is required
    if (typeof a === 'string' && typeof b === 'string') {
        return a.localeCompare(b, 'standard', { sensitivity: 'case'});
    }

    return b > a ? -1 : 1;
}


Use unordered_map to maintain account number and balance.
You can use unordered_map(hash table) for checking if an acc_num already exists or not and the membership check in unordered_map is O(1).
You can use int64_t for long long int
You can int64_t for long long int, uint64_t for unsigned long long int and since bank balance can't be less than 0 use uint64_t for balance.
count is unnecessary, use unordered_map::find.
You can eliminate count when you are using unordered_map to check if acc_num exists use unordered_map::find.
Create alias using using.
using account_table not only allows you to give a short name to a complex type, but it puts the type definition in a single place. Then if you change the underlying type you only need to change it in that one place.
Avoid using using namespace std;
Find more details here why using namespace std; is considered bad praactice
I added Account::print_details, it prints acc_num --> balance
Refactored code
#include<iostream>
#include<unordered_map>
#include<string>

class Account{
    using account_table = std::unordered_map<std::string, uint64_t>;
    private:
        account_table table;
    public:
        void add_acc();
        void print_details();
};

void Account::add_acc(){
    std::cout<<"Enter account number : ";
    std::string acc_num;
    std::cin>>acc_num;
    if (table.find(acc_num)==table.end()){
        uint64_t balance;
        std::cout<<"Enter balance : ";
        std::cin>>balance;
        table.insert({acc_num, balance});
    }
    else{
        std::cout<<"Account number already exists\n";
    }
}

void Account::print_details(){
    for(auto& d: table){
        std::cout<<d.first<<"-->"<<d.second<<std::endl;
    }
}

int main(){
    Account A;
    char ch{'Y'};

    while(ch){
        A.add_acc();
        std::cout<<"Want to add another account : ";
        std::cin>>ch;
        if (ch!='Y' && ch!='y'){
            break;
        }
    }
    A.print_details();
    return 0;
}

Example run
Enter account number : 1234
Enter balance : 50
Want to add another account : y
Enter account number : 1234
Account number already exists
Want to add another account : Y
Enter account number : 12345
Enter balance : 12
Want to add another account : n
12345-->12
1234-->50

You can use clang-format-9(code formatting tool)
Example:
clang-format-9 -i -style=Google your_file.cpp


Convert data back-and-forth between CSV files and pretty-print

Names

Follow the Haskell convention of names

The Haskell convention is camelCase.  That is, start names with a
lowercase letter, and join words together by capitalizing them.  So
head_lens would be headLens, or better yet, headerLengths.

Use names with meanings, not just labels

Come to think of it, an even better name would be columnWidths,
as that is not just what the value is, but what it means (and
what it is used for).  lp and erg don't tell me a lot,
either.  For preprocess I would suggest a name like rightPadLines.  That way, I won't be so surprised to find out what it does :)

Don't be afraid of longer names

It is also useful and nice for other readers not to use
abbreviations, unless the scope is very small.  So the a and b
in dissect line are good and clear (very short scope -> very
short names).  add_del, on the other hand, would be more readable
as addDelimiters.  delim is a somewhat more conventional
abbreviation.

Types

Use the type system

Yes, Haskell can find out what types your values and functions
have.  And it will be correct in many, many cases.  But if you
are wrong, Haskell cannot tell you, unless you tell the compiler
what you intend to do.  So always, always write the type signatures
of at least the top-level bindings.  That way, if your function is
not yet finished, or you make a mistake, the compiler will be able
to tell you almost exactly where.

So:

main :: IO ()
main = do -- ..

rpad :: Int -> String -> String
rpad len string = take -- ..

preprocess :: [String] -> [String]
preprocess lines = map -- ..

dissect :: String -> [Int]

compress :: [String] -> [[String]]

inflate :: [String] -> [[String]]

Adding those type signatures alone, makes the function more
readable, because now I can expect what it is going to do.

Use hlint on the code and heed warnings from ghc

Many warnings and suggestions are worthwile.  They can point out
possible mistakes or partial functions, but also show what an
idiomatic Haskell solution could be.  For instance:

Use head instead of (!!0)

readfile (args !! 0) is reminiscent of other languages, where the
command line arguments are in an array, which you'd need to index.
Using the 0th index though, is normally done by using the head
function.  readFile $ head args is the suggested alternative.

elem is more readable as `elem`

Functions that take more than one argument, can be inserted between
the first and second argument (infix) if you write backquotes
around them.  For many functions, such as elem, mod and div,
this makes much sense.  So if elem "inflate" args can be
rewritten as if "inflate" `elem` args.

Redundant parentheses

In that same line, (inflate) and (compress) have parentheses
around them, but they are really not necessary.  Removing them
makes the line more readable (even for LISP programmers).

The same goes for map (length) lines in preprocess, map (shrinkcol) cols in compress and (map length) c in inflate.
And even string++(repeat ' ') can do without the parentheses.

Shadowed bindings

Three functions use the name lines for a parameter, which happens
to be the name of a function, too.  It is best to heed this
warning, for two reasons:

If you happen to want to split some string later on in those
functions, you'll have to change the name anyway.
People who see lines somewhere, will probably think of the
function first, be confused, then remember that it is a
redefined value.

Using ls is not that bad, by the way, especially if you change
the type to be more documentational (see below).

Eta reduction

This mathematical term comes down to "remove the variable name", so
that the focus lies more on what the function does, and less of
what it functions on.  The function shrinkcol has a c on both
ends, and they can both be removed, resulting in:

shrinkcol = map (\el -> reverse $ dropWhile (==' ') $ reverse $ dropWhile (==' ') el)

Which expresses exactly the same, just in less "words".

Avoid lambda

This warning, on the same function as above, suggests about the
same thing, but now for the \el variable.  However, because we
use the $ for application of values, this line should be
rewritten using . for composition.  As f . g means: do f
after g, this comes mostly down to just replacing the $ with
.:

shrinkcol = map (reverse . dropWhile (==' ') . reverse . dropWhile (==' '))

Another composition opportunity

The last warning that ghc and hlint give us, is to use composition
in the mapM_ call.  Instead of saying: "map putStrLn over the
result of mapping concat over the list erg, and combine that
into one IO action", you can say "map (putStrLn after concat)
over the list erg, and combine that into one IO action".  Which
is shorter in English already :)

mapM_ (putStrLn . concat) erg

And now we are warning-free!

Types

Use the type system

What, again?  Yes.  But this time, use it to document the intent of
the functions, not just the functionality.  The easiest way to do
this, is to declare simple type aliases.  For instance,
preprocess works on lists of String, but each String is
actually a Line.  So adding type Line = String, while it does
not give any added compiler safety (Line is just an alias, and
exactly the same as String), it does give a bit of documentation.

type Line = String
type Cell = String

preprocess :: [Line] -> [Line]

compress :: [Line] -> [[Cell]]

inflate :: [Line] -> [[Cell]]

Of course, making stronger types with constructors, using data is
even better, so that the type system helps you check whether the
code works, even before you run it.  Then, you can write functions
as transformations between types, instead of transformations
between "just Strings".


Print strings in order with dynamic arrays

When allocating an array to hold arbitrary numbers of things, consider using calloc and reallocarray (reallocarray is not standard C, but there isn't a standard analog to calloc).

The reason is that calloc will fail if you try to allocate more memory than size_t can hold. If, for example on a 32-bit system, you decide you want to allocate 500 million of some struct, you could do this:

typedef struct { char a; } little_struct_t;
...
ptr = malloc(500000000 * sizeof(little_struct_t));

and it might work. But later, when you decide that your struct actually needs more stuff, you'll end up with something like this:

typedef struct { char a; int b; bool c } little_struct_t;
...
ptr = malloc(500000000 * sizeof(little_struct_t));

and boom, you've just caused a multiplication overflow without thinking about it. If instead you had used calloc, you'd either see the error when you checked that ptr was not NULL (see my next comment) or a happy segfault when you try to dereference ptr. Instead, now you have a 1705032704-byte ((sizeof(little_struct_t) * half a billion) & 0xffffffff)) chunk of memory, and if you're lucky you'll get a segfault when you write off the end of it. If you're not lucky, you'll corrupt a bunch of other memory before your program crashes.

My second comment is that you should always always check the return value of malloc. If it's not NULL, no harm done. If it is, either you want to crash right now or you want to take a different path. Whatever happens, you don't want your program to happily keep chugging along as though nothing's wrong.

Third, and this isn't super relevant to your example (though I would apply it in deallocate_words after the free call inside the loop), but it's good practice to null out your pointers after you free them. I think I've spent too many words already, so I'll just say that it will simplify debugging and get rid of double free issues in the future.


Remove all usages of the keys method. Note, this was already mentioned in the comments to your question, but it seems to have mostly done the trick for your problem.


Removed unnecessary concatenation.

public static IQueryable<T> Sort<T>(this IQueryable<T> query, List<SortationDto> sortations)
    where T : BaseEntity
{
    List<SortationDto> combined = sortations.Where(s => s.Concatenated.Count == 0).Union(sortations.SelectMany(so => so.Concatenated)).ToList();

    combined.ForEach(s =>
    {
        ParameterExpression parameter = Expression.Parameter(query.ElementType, "item");
        Expression value = s.Column.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
        LambdaExpression predicate = Expression.Lambda(value, parameter);

        string methodName = (combined.IndexOf(s) == 0 ? "Order" : "Then") + (s.Direction == "asc" ? "By" : "ByDescending");
        MethodCallExpression orderBy = Expression.Call(typeof(Queryable), methodName, new Type[] { query.ElementType, value.Type }, query.Expression, Expression.Quote(predicate));
        query = query.Provider.CreateQuery<T>(orderBy);
    });

    return query;
}


With your first file, parser.py:

Because the Info class' __init__ method requires the three arguments: a, j, and z, which it then attributes to itself, you can remove the class attributes of the same name, as they become superfluous.
Within the process method, you set several variables before doing anything; retA, retJ, and retZ, which you set to None. If you aren't modifying these objects in place, you can omit these completely and add an else statement.

if infoline:
    # filling some of retA, retJ, retZ
    return Info(retA, retJ, retZ)
else:
    return Info(None, None, None)
In the aforementioned if statement, you can simply use

if get_infoline(line, prov):

Rather than setting the infoline variable. Then, if you need the result, you can define it within the statement.


Using argparse, your script can be greatly simplified:

from argparse import ArgumentParser

def main():
    parser = ArgumentParser(description='TODO')
    parser.add_argument('-f', '--file', metavar='PROXYFILE', required=True)
    parser.add_argument('-u', '--url', required=True)
    parser.add_argument('-t', '--timeout', required=True)
    args = parser.parse_args()

    print("Using proxies in: " + args.file)
    print("Using URL: " + args.url)
    print("Timeout: {0}s".format(args.timeout))

if __name__ == "__main__":
    main()


Find length of non-repeated numbers in array

The correct data structure to use to eliminate duplicates is a Set. The String processing is more expensive, and the Map code is less clear because you don't care at all about the values.
It's nice to provide a vararg parameter so that clients don't need to define an array if they don't want to.
It's a better practice to return your result from the method. If the client wants to print it, that's up to them. But if you print it, and the client changes what they want to do with it, they're out of luck.
You can used the enhanced for loop to make your code a little prettier.
More descriptive names are better than less descriptive names.

If I were to take a stab at writing your code with the above changes in mind, it might look something like:

private static int countUniqueValues(final int... values) {
    final Set<Integer> uniqueValues = new HashSet<>(values.length);
    for (final int value : values) {
        uniqueValues.add(value);
    }
    return uniqueValues.size();
}


split and spread to variables:

$IP, $SubnetBits = $Subnet -split '/'

your user-function invocation with parentheses is incorrect and works only for single parameter (basically it's interpreted as user-function (param1), the correct syntax is user-function param1 param2 param3 e.g. IPv4toBin $IP
to get a power of 2 use a bitwise left shift:

$imax = (1 -shl $HostBits) - 2

use $array = foreach ($i in 1..$imax) { ... } to generate arrays directly instead of overly verbose for loops and += operator, which recreates the entire array each time
ipconfig may list many networks with empty gateways so you need to account for that or use .NET method (C# source):

$gate_ip = [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() |
  where { $_.OperationalStatus -eq 'Up' -and $_.NetworkInterfaceType -ne 'Loopback' }|
  foreach { $_.GetIPProperties().GatewayAddresses } |
  select -expand Address -First 1 |
  select -expand IPAddressToString

Select-String $gate_ip will incorrectly select the header line with no ARP info in case the interface IP address matches the gateway IP e.g. 192.168.1.1 and 192.168.1.176
work with actual numbers instead of binary representation and use bitwise operators:

function Get-IPs($subnet) {
  $IP, $SubnetBits = $Subnet -split '/'
  [uint32]$imax = (1 -shl (32 - $SubnetBits)) - 2
  [uint32]$baseIP = 0
  foreach ($s in ($IP -split '\.')) {
    $baseIP = ($baseIP -shl 8) + $s
  }
  $baseIP = $baseIP -band -bnot ($imax + 1)
  foreach ($i in 1..$imax) {
    $IP = $baseIP + $i
    "$($IP -shr 24).$($IP -shr 16 -band 255).$($IP -shr 8 -band 255).$($IP -band 255)"
  }
}

I'm using implicit output here: a statement that consists only of a value (or an expression) is equal to Write-Output $value_or_expression and the entire collected output is returned from the function without the need for an explicit return


Finding Egyptian fractions with A* search

There's a bug in is_solution:

>>> is_solution((2, 3, 6), 4)
False

even though $$ {1\over2} + {1\over3} + {1\over6} = 1 = {4\over4}. $$

This is because \${1\over3}\$ and \${1\over6}\$ can't be exactly represented as floating-point numbers:

>>> 1/2 + 1/3 + 1/6
0.9999999999999999

The way to solve this is to represent fractions using the fractions.Fraction class:

>>> Fraction(1, 2) + Fraction(1, 3) + Fraction(1, 6) == Fraction(4, 4)
True

The question claims the algorithm is "A*", but that's not true. The A* search algorithm tries to find the least-cost path to an identifiable goal in a directed graph. But here you can't identify the goal (because you're looking for a minimum, you won't know what it is until the search is complete), and you don't care about the cost of the path taken to get there.

It would be better to call the algorithm "best-first search".
You're basically searching over all triples of integers looking for one that happens to add up to your target. This is a waste of time, because after you've picked \$y\$ and \$z\$, say, then you can know that $$ x = {1 \over {4\over n} - {1\over y} - {1\over z}} $$ and all you have to do is compute this and check that it's an integer.

So a (slightly) better strategy looks like this:

from collections import namedtuple
from fractions import Fraction
from itertools import chain, count, takewhile
from math import floor

Triple = namedtuple('Triple', 'x y z')

def egyptian_triples(n):
    """All solutions to 1/x + 1/y + 1/z = 4/n in lexicographic order."""
    tz = Fraction(4, n)
    for z in count(floor(1 / tz) + 1):
        ty = tz - Fraction(1, z)
        for y in range(floor(1 / ty) + 1, z + 1):
            tx = ty - Fraction(1, y)
            if tx.numerator == 1 and tx.denominator <= y:
                yield Triple(tx.denominator, y, z)

def min_egyptian_triple(n):
    """Return the solution to 1/x + 1/y + 1/z = 4/n with minimum x + y + z."""
    triples = egyptian_triples(n)

    # First solution in lexicographic order.
    first = next(triples)
    max_z = sum(first) - 2

    # Return minimum solution.
    return min(chain((first,), takewhile(lambda t: t.z <= max_z, triples)),
               key=sum)

This is substantially faster:

>>> from timeit import timeit
>>> timeit(lambda:main(115), number=1)
(290, (60, 92, 138))
19.941934717004187
>>> timeit(lambda:print(min_egyptian_triple(115)), number=1)
Triple(x=60, y=92, z=138)
0.46365413605235517


Find the total number of emails in a folder (with all of the subfolders)

First, your code doesn't give correnct answers; for (m, 1) the answer should be 120 (30 in ./1, +10 in ./1/2, +20 in ./1/2/3, +60 in ./1/4; you never count more than a single entry in the sub-folder slice).

Also, you should run go fmt (or goimports) on your code (perhaps you did and that was lost when posting). Also, adding a Go Playground link to your original code in posts is helpful.

You mention that you wanted to create a function taking two parameters, the first being []Folder but your code instead converts the slice into a map and uses that as the first argument. Which did you intend? When you have a function or functions that are answering questions based on an argument you could consider making a method. For example, perhaps something like:

type Folders []Folder
// or
type Folders struct {
    list []Folder
    byID map[int]Folder
}

func (f Folders) EMailCount(folder int) int {
    // code that uses f and folder as arguments
}

You use snake_case for some of your identifiers and camelCase for others; idiomatic Go code uses camelCase for all identifiers.

In your InsertIntoMap function:

When you make the map you know how many entries you expect so you should include that number to make as a size hint (e.g. make(map[int]Folder, len(data))). If the size is large this avoids the having to dynamically re-size the map as you add entries.
You name the map retval, I'd instead name it based on what contains (a map of folders by ID) rather than it happens to be the return value. I'd call it just m or byID.
Within the loop you effectively copy the element elem to the variable folder. You can do this with just folder := elem but at that point the entire loop body can just be rewritten as retval[elem.ID] = elem.

In your GetTotalEmailCount function:

Normally in Go instead of:

var foo []int
foo = something[bar].foo

you'll just see:

foo := something[bar].foo

not only is it shorter but it can make future code changes easier. In the latter if the field foo changes type you don't need to edit the type of the variable foo to match. (By the way, shorter isn't always better. Clarity is more important than conciseness).
Idiomatic Go code tends avoid indenting code by using early returns (see https://github.com/golang/go/wiki/CodeReviewComments#indent-error-flow). You return if len(…) == 0 so you should just drop the else clause and remove the indent (golint will suggest this). E.g, instead of:

if someCondition {
    return something
} else {
    // other code
    //     possibly with more conditional/loop indenting
}

it would be:

if someCondition {
    return something
}

// other code
//     possibly with more conditional/loop indenting

In this specific case, you don't even need the conditional since for range loops don't do anything on empty/nil slices the following return total line is sufficient.
It's in this for loop your your bug exists. On the first iteration you stop looping and return the total of this folder and it's first child without iterating to the next child.

return total + GetTotalEmailCount(p_map, child_folders[e])

should be:

total += GetTotalEmailCount(p_map, child_folders[e])

Without changing the basic structure of your code, all the above gives something like this (Go Playground):

package main

import "fmt"

type Folder struct {
    ID             int
    emailCount     int
    childFolderIDs []int
}

func InsertIntoMap(data []Folder) map[int]Folder {
    m := make(map[int]Folder, len(data))
    for _, e := range data {
        m[e.ID] = e
    }
    return m
}

func GetTotalEmailCount(m map[int]Folder, folder int) int {
    children := m[folder].childFolderIDs
    total := m[folder].emailCount

    for e := range children {
        // BUG: doesn't detect infinite loops
        total += GetTotalEmailCount(m, children[e])
    }

    return total
}

func main() {
    var folders = []Folder{
        Folder{1, 30, []int{2, 4}},
        Folder{2, 10, []int{3}},
        Folder{4, 60, []int{}},
        Folder{3, 20, []int{}},
    }

    var m = InsertIntoMap(folders)
    fmt.Println(GetTotalEmailCount(m, 1)) // result is 120, 30+10+20+60
    fmt.Println(GetTotalEmailCount(m, 2)) // result is 30
    fmt.Println(GetTotalEmailCount(m, 3)) // result is 20
    fmt.Println(GetTotalEmailCount(m, 4)) // result is 60
}


Using both setInterval and setTimeout for simple image carousel

How about this: every 3 seconds, you hide the previous image and show the next image. This is simple.

Some changes I made:

I prefer .style.opacity = as opposed to setAttribute("style"). This may be personal preference, but it looks cleaner to me because it uses javascript's object access instead of setting it via a string.
You can use a modulus (%) instead of checking if counter === slides.length.

var carousel = document.getElementById("carousel"),
  slides = carousel.getElementsByTagName('li'),
  counter = 0,
  liList = Array.prototype.slice.call(slides);

setInterval(function() {
  slides[counter].style.opacity = 0; // Hide the previous image
  counter = (counter + 1) % slides.length; // Increment counter
  slides[counter].style.opacity = 1; // Show the next image
}, 3000); // setInterval
#carousel {
  padding: 0;
  margin: 0;
  position: relative;
  width: 315px;
  height: 177px;
}
#carousel li {
  opacity: 0;
  list-style: outside none none;
  width: 315px;
  position: absolute;
  background: #fff;
  transition: opacity 1s;
}


Mini HttpClient json post by Action parameter

Great job. Here are some minor notes though.

In newer versions of C# you can leverage async Main in order not to wait for your test method.

public static async Task Main(string[] args)
{
    await Test();
}

You can speed things up a bit with executing your tests in parallel

public static async Task Test()
{
    var successExecute = Execute("https://jsonplaceholder.typicode.com/posts", new { value = "ITWeiHan" }); //Result : {"value": "ITWeiHan","id": 101}
    var errorExecute = Execute("https://jsonplaceholder.typicode.com/error404", new { value = "ITWeiHan" }); //Result : Error 404
    await Task.WhenAll(successExecute, errorExecute);
}

Also, PostByJsonContentTypeAsync throws couple of more exceptions. Namely InvalidOperationException and ArgumentNullExceptions. Are you intentionally not handling them?


Here are a few comments:

1) There are three different places in the code where you ask the user to enter the next number to guess. This is not very readable and will backfire if and when you want to extend this code. It's better to have something like this:

def getNextGuessFromUser(messageToPrint):
    print messageToPrint + '\n'
    return int(input())

Then remove the tooHigh, tooLow and initial guess calls, and replace them with calls to this function. By the way, I'm not sure how your reading of guesses works with the print call; looks like a defect to me.

2) Unnecessary usage of global variables. guess should be generated for the first time inside guessLoop, and not rely on the outer code to initialize it.

3) Double check of the right guess. First, you do it in guessLoop to print the right message, and then again in the main module. Again, all of this should be happening in guessLoop: something like this

def guessRun(rightAnswer):
   counter=1
   guess=getNextGuessFromUser("Please enter a number within the range: ")

   while guess != rightAnswer:
     if guess>rightAnswer:
        guess = getNextGuessFromUser("<Too high message>")
     elif guess<rightAnswer:
        guess = getNextGuessFromUser("<Too low message>")
     counter+=1

   print("you guessed it!")
   return counter

4) Consider using PEP-8.


The are a number of problems here.

You do a poor job of validating user input before working with it.  I would strongly suggest you look at using PHP's filter_input() or filter_input_array() to provide basic data validation and error handling. You can use these to easily validate URL formats for example, or provide you own custom validation rule. You probably need to further sanitize some of your input against cross-site scripting vectors depending on how you are using the data added to your database in your application.
You should be leveraging prepared statements for inserting your data to help mitigate against sql injection.
You have a lot of conditional nesting complexity.  You should consider adopting a coding style where you look for early exits and design away nested conditionals to whatever extent is possible.

For example:

if (empty($link1) || empty($link2) || empty($flink)) {
    // error and exit
}

// continue with rest of code, now without nesting.

This minimizes your number of code paths making your application less complex, easier to debug, and easier to maintain. Actively try to design away else conditions, as they are usually avoidable.

Note also, in my example above that I reduced conditionals to only use emtpy() instead of isset() and empty().  empty() would fail for same conditions but is also more specific than isset(), so it is redundant to have both.  Just use the more specific criteria.
You repeat yourself unnecessarily.  Look to factor things like you link re-writing logic into a function to minimize repeated code.  By the way, I am not sure exactly why you use preg_match() and concatenation here.  Won't that break your links?  Perhaps preg_replace() instead?
It appears to me that you a falling into classic programming anti-pattern by naming variables like $somename1, $somename2, etc.  Naming like this is a possible code smell that you should be thinking about using arrays or other data structures to describe these logically-grouped values.
Your lines of code are too long.  It makes it hard to read your code.
Variable names seem to be somewhat poorly named (not very meaningful in some cases).
Why are you closing $db, when you are working with $conn?  There is obviously context missing from example, but this seem like an error.
It is unclear from this code example how you are validating that user making the request should be allowed to modify your database in this manner. Perhaps that is in check_user()?  But typically, at a minimum any form-posting like this would have cross-site request forgery (CSRF) mitigation (i.e. session token) if not some form of user authorization.


Telling me what lesson I have tomorrow and emailing me the results

I would change the data organization to be the opposite way, to have a dict mapping to the two week types containing a dict with a mapping from the weekday to the lessons:

timetable = {"A": {"Monday": ["English", "Maths", ...],
                   "Tuesday": ["Maths", "Computing", ...],
                   ...},
             "B": {"Monday": ["History", ...],
                   ...}}

By the way, it is spelled Biology, not Bioligy.

Then you can just use it like this:

import smtplib
import datetime

TIMETABLE = {"A": [["English", "Maths", ...],
                   ["Maths", "Computing", ...],
                   ...],
             "B": [["History", ...],
                   ...]}

SEMESTER_START = datetime.datetime(2016, 9, 1)

def calculate_week_type(date, start_date):
    """Even weeks since start_date are "A" weeks, uneven are "B" weeks"""
    return "A" if ((date-start_date).days / 7) % 2 == 0 else "B"

def lessons(timetable, start_date, date):
    week_type = calculate_week_type(date, start_date)
    return timetable[week_type][date.weekday()]

def mail_lessons(lessons, to_email='*email*'):
    content = "You have {} today.".format(", ".join(lessons))
    mail = smtplib.SMTP('smtp.gmail.com', 587)
    mail.ehlo()
    mail.starttls()
    mail.login('*email*', '*password*')
    mail.sendmail('*email*', to_email, content)
    mail.close()

if __name__ == '__main__':
    today = datetime.datetime.today()
    mail_lessons(lessons(TIMETABLE, SEMESTER_START, today))

I put the different responsibilities into separate functions, got rid of most of the global variables, and fixed some small differences to PEP8, python's official style-guide. I used a format string, because it is in general faster than string addition (it is usually more readable as well).

I also made the mapping now using numerical weekdays as indices into the internal list of lists, because this is what datetime returns. This way there is no need to translate between the two.


Classifying counts of repeat visits per user for a website

MySQL version 8 supports common table expression.  If you want to differentiate between the three sub queries, use a column containing literal:

WITH SESSIONS_THIS_MONTH AS (
SELECT ipaddress,
        COUNT(*) AS sess
   FROM analytics
   WHERE trunc(datecreated) > getdate() - interval '30 days'
   GROUP BY trunc(datecreated), ipaddress
)
SELECT 'MORE THAN 100' AS CATEGORY,
       COUNT(SESSIONS_THIS_MONTH.sess) as acount,
       SUM(SESSIONS_THIS_MONTH.sess) as asum,
       AVG(SESSIONS_THIS_MONTH.sess) as aavg
FROM SESSIONS_THIS_MONTH
WHERE sess >= 100

UNION ALL

SELECT 'BETWEEN 50 AND 100' AS CATEGORY,
       COUNT(SESSIONS_THIS_MONTH.sess) as bcount,
       SUM(SESSIONS_THIS_MONTH.sess) as bsum,
       AVG(SESSIONS_THIS_MONTH.sess) as bavg
FROM SESSIONS_THIS_MONTH
WHERE sess < 100 AND sess >=50

UNION ALL

SELECT 'LESS THAN 50' AS CATEGORY,
       COUNT(SESSIONS_THIS_MONTH.sess) as ccount,
       SUM(SESSIONS_THIS_MONTH.sess) as csum,
       AVG(SESSIONS_THIS_MONTH.sess) as cavg
FROM SESSIONS_THIS_MONTH
WHERE sess < 50


Java class that generates a short URL string for an input string

Unit Tests and Single Responcibility

It's always good to test your code. With random data, this is a bit complicated, but at least your original mistake of the same input generating different urls would have been caught by tests.

Now the question becomes how to test that there will be no duplicates when randomness is involved. And the easy answer would be to remove the randomness from it.

As creating random numbers shouldn't be the responsibility of this class anyways (it's already responsible for managing urls), you could create a Random interface (with int getRandonNumber(int lowLimit, int highLimit) as method) whose instance you can inject into the class (via the getInstance(Random random) method). For unit tests, you can then simply create a dummy random object which returns a static value. Your test would then look something like this:

URLTinyMe url = URLTinyMe.getInstance((x, y) -> 60); // inject dummy random object that always returns 60
List<String> urls = new ArrayList<>();
for (int i = 0; i < 500; i++) {
    urls.add(url.getTinyMeUrl("foo" + i));
}
Assert.assertTrue(!hasDuplicates(urls));

Additional tests would be:

// same url creates same tiny url
Assert.assertEquals(url.getTinyMeUrl("foo"), url.getTinyMeUrl("foo"));

// getOriginalUrl works
String test = "foobar";
Assert.assertEquals(test, url.getOriginalUrl(url.getTinyMeUrl("foobar")));

Misc

Unnecessary assignments just complicate your code. String tinyUrl = inputUrl; isn't needed.
Your getRandonNumber doesn't do what it says it does, as it also filters out numbers in between the limits. Either change how the method works, or change the comment. I would probably get rid of the parameters, and rename the method to something that expresses that only alphnum is generated.
Your spacing and indentation is off (and not even internally consistent), which makes your code harder to read.
I don't think that you will gain any performance increase from using a StringBuilder if you call toString each time you append something.
You should probably throw an exception if the original url could not be found.


C program to find and replace a word in a file

Small suggestions:

Be consistent. What jumps out right away is that you say "This program will perform a find and replace on a single word in a file" but then  your program prompts the user to either write to file or replace a word.  That confuses me as a user of your program as to what it's supposed to do.
Removed. Refer to Difference between int and char in getchar/fgetc and putchar/fputc?

You've declared int c in main(). Why int and not char ?  This also comes up when your case statement reaches the default part. When user enters wrong command, say g, it displays:

Enter 'w' to write to the file, 'r' to replace a word
g
Invalid command:103
Invalid command:10

 So avoid confusing the user and the people who are going to read your code.
In fgets(old_word, sizeof(old_word), stdin); why do you use sizeof(old_word) ? You already have a constant for WORD_SIZE defined, so there's no need to figure out size of your string.
Consider moving the code from case 'r' for getting user's input to replace_word() function or separate function get_user_input().  What was nice about your case statement is that you started out with case 'w' where you executed a specific function for that case. That's good strategy. Use that case statement to direct the program to specific functions that do specific job.
When user selects to replace a word, you give the user instructions to enter old and new string. That's good - user is not left hanging and is guided in what to do. But when user selects to write to file, there's no instruction and user is just dropped into typing stuff.

I only clicked Ctrl+D ( to send EOF character since I'm Linux user, not sure how would that work on Windows) because I know that this is what program expects to receive to indicate that there's no more input, but what about a random user who's absolutely unfamiliar with your program and never read your source code ?
On the same related note, how does user exit your program ? In your case statement you only have two cases for specific action, there's no quit option, and neither does it explain to the user that they could use Ctrl+C or Ctrl+D to quit.
Give the user Enter 'w' to write to the file, 'r' to replace a word  each time an action has been complete. Take for example the example I showed in my first point. User enters wrong command, they see an error and . . . what's next ? The program just sits there waiting for input without explaining to the user what it wants.


Create a two dimensional int array and find the smallest and biggest member along with the indexes

The formulated task leaves a lot of room for interpretation. You chose to simplify several points.

Fill [the array]...now find...

I take this as "create a function that finds...". This forces you to organize the program. Combining both (2D array, function) leads to a subtle problem - I ended up with a #define COLS 10, because that number (from your imagination also) has to be known to the function at compilation.
I also think setting max to 0 and min to INT_MAX is mixing up logic and parameters.
The other problem with a function is: how to return the bunch of results. I took your structs and put them into one.
The call at the center is:
struct minmax mm = minandmaxCOLS(array, nrows);
The function takes an array and number of rows. The caller can choose this value, but the number of cols must always be COLS.
If COLS is variable, then a 2D array is the wrong approach. Array of pointers works.
Instead of
array[10][10]

I have
int nrows = 10;
int array[nrows][COLS];

illustrating that the caller (main) can choose the rows, but not the cols, if it wants to use a function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>

#define COLS 10

/* Result type */
struct minmax {
    int min, minrow, mincol;
    int max, maxrow, maxcol;
};

/* scan for min and max in a 2D array "a[][]" with dims rows and COLS  */
struct minmax
minandmaxCOLS(int a[][COLS], int rows) {

    int r, c;
    struct minmax result;

    /* Initialize result-struct before comparing in loop */
    result.min = result.max = a[0][0];
    result.minrow = result.mincol = 0;
    result.maxrow = result.maxcol = 0;

    for (r = 0; r < rows; r++)
        for (c = 0; c < COLS; c++)
            if (a[r][c] > result.max) {
                result.max = a[r][c];
                result.maxrow = r;
                result.maxcol = c;
            }
            else
                if (a[r][c] < result.min) {
                    result.min = a[r][c];
                    result.minrow = r;
                    result.mincol = c;
                }

    return result;
}

int main (void) {
    int nrows = 10;
    int array[nrows][COLS];

    srand(time(NULL));

    for (int i = 0; i < nrows; i++)
        for (int j = 0; j < COLS; j++)
            array[i][j] = rand();

    /* A kind of test */
    //array[5][5] = -3;
    //array[6][7] = INT_MAX;

    struct minmax mm = minandmaxCOLS(array, nrows);

    printf("Max number: %d, row: %d, column: %d\n", mm.max, mm.maxrow, mm.maxcol);
    printf("Min number: %d, row: %d, column: %d\n", mm.min, mm.minrow, mm.mincol);

    return 0;
}

As a side effect you can now also search for min and max only in certain rows:
struct minmax mm = minandmaxCOLS(array+2, 1);
Output with "test" activated:
Min number: -3, row: 0, column: 5
"row" is now relative to the arg array+2. The "2" means "two rows of 10 (COLS) ints". Same as &array[2].

typedef
The function paramter list can be simplified by using a typedef. After defineing COLS as 10:
typedef int Arrcolsint_t [COLS];
This shows that an array of COLS integers is a basic unit. Now I can forget half (two thirds) of the details of "a":
minandmaxCOLS(Arrcolsint_t a[], int rows)
Same as:
minandmaxCOLS(Arrcolsint_t *a, ....
The advantage is you can use that type in several functions and only change the typedef itself. Without it is int a[][COLS] or int (*a)[COLS].
Row_t might be a better typedef name. Still there always is the compile time value 10 behind it all.


Poor error handling: Throw inside Finally

ClassLoader.getResourceAsStream() throws a NullPointerException if the given name is null, something you can easily check. InputStream.readAllBytes() does not throw a NullPointerException, and neither does instatiating the String.

So basically, the null exception will happen if and only if fileName is null, or if the resource is not found and therefore resource is null; you can easily check both without catching an exception:

private String getResourceContent(String fileName) throws IOException {
    if (fileName == null) {
        // now what?
    }
    try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
        if (resource == null) {
            // now what?
        }
        return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
    }
}

The question now is what you want to do if fileName or resource is null. This depends on how you want your function to be used; in my opinion, you should expect the user to give a file name that is not null, so throw a NullPointerException if that is not the case. In the resource case, you could use your custom exception for that.

Now, what if readAllBytes() throws an exception? You can either let it propagate to the caller (like it's happening now) or use ErrorDescriptorException as a wrapper (but maybe this makes fortify complain again):

private String getResourceContent(String fileName) throws ErrorDescriptorException {
    if (fileName == null) {
        throw new NullPointerException();
    }
    try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
        if (resource == null) {
            throw new ErrorDescriptorException(
                String.format("Error loading Error description data from Resource file [%s].", fileName));
        }
        return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
    }
    catch (IOException | OutOfMemoryException e) {
        throw new ErrorDescriptorException(
                String.format("Error loading Error description data from Resource file [%s].", fileName), e);
    }
}


Add neighboring stones of the same color to form chains, with logging for isolated stones

You don't really need your elses. Move count++ to the if, and change your last if to !count.
Rather than using !=, you should really use < and <=. This means you you can use x + 1 < boardSize rather than (x + 1) != (boardSize).
You should learn operator precedence, == happens before &&. And so you can remove even more parentheses.

And so you can use:

function checkChains(x, y, color, array)
{
    var count = 0;

    if (x + 1 < boardSize && stones[x + 1][y] == color)
    {
        addToChain(x, y, x + 1, y, array);
        count++;
    }

    if (x > 0 && stones[x - 1][y] == color)
    {
        addToChain(x, y, x - 1, y, array);
        count++;
    }

    if (y + 1 < boardSize && stones[x][y + 1] == color)
    {
        addToChain(x, y, x, y + 1, array);
        count++;
    }

    if (y > 0 && stones[x][y - 1] == color)
    {
        addToChain(x, y, x, y - 1, array);
        count++;
    }

    if (!count)
    {
        console.log("none!");
    }
}


PANDAS DataFrame operations to analyze top Server Fault tags

The easiest way to go about this problem is to separate the tags, unstack them then stack them back in a way that doesn't lose creationDate values, this is done through concat, group the data then use pivote_table to rearrange the data where the periods are the columns and the tags are the index

To group the data take one of two approaches;

The first approach is to keep the creation date as a string and extract the year through str.split, then group the data by year and tag

import pandas as pd

# top n tags for each year will be displayed
n = 10
debiandf = pd.read_csv("filename")
debiandf = debiandf.reset_index().set_index(['index', "CreationDate"])
df = debiandf["Tags"].str.extractall(r'\<(.*?)\>').unstack()
df.columns = df.columns.droplevel(0)

# take all columns in df, convert each column to a df with
# columns Year(CreationDate) and tag and stack them on top of eachother
# the resulting x will be a 2 column dataframe
x = pd.concat(
    [pd.DataFrame(df[x], columns=['tag']).reset_index(
    ).rename(columns={'CreationDate': 'Period'}
             ) for x in df.columns.tolist()]).drop('index', axis=1)

# change the value of year from "%Y-%m-%d %H:%M:%S" to "%Y" using split
x['Period'] = x['Period'].apply(lambda x: x.split('-')[0])

# group values of x according to year and tag that will produce a 3 column
# ['Period','tag','count']
x6 = x.groupby(['Period', 'tag'])['tag'].agg({'count': len}).reset_index(
    # use pivote_table to reorganize the data
).pivot_table(index=['tag'], columns='Period').xs(
    # the resulting df will have the tags as index and the years as columns
    'count', axis=1, drop_level=True)

topn = pd.concat([pd.DataFrame(x6[col].nlargest(n)).astype(
    int).reset_index().rename(columns={
        col: 'count'}) for col in x6.columns],
    keys=x6.columns, axis=1)
print(topn[topn.columns[-6:]])

The second approach involves the use of pd.tseries.resample.TimeGrouper, to resample the date creation yearly A while grouping the data by year and tag

import pandas as pd

n = 10
debiandf = pd.read_csv("filename")
debiandf = debiandf.reset_index()
debiandf["CreationDate"] = pd.to_datetime(
    debiandf["CreationDate"], format="%Y-%m-%d %H:%M:%S")
debiandf.set_index(['index', 'CreationDate'], inplace=True)
df = debiandf["Tags"].str.extractall(r'\<(.*?)\>').unstack()
df.columns = df.columns.droplevel(0)

# take all columns in df, convert each column to a df with
# columns Year(CreationDate) and tag and stack them on top of eachother
# the resulting x will be a 2 column dataframe
x = pd.concat(
    [pd.DataFrame(df[x], columns=['tag']).reset_index(
    ).rename(columns={'CreationDate': 'Period'}
             ) for x in df.columns.tolist()]).drop(
    'index', axis=1).set_index('Period')
# group the data by the tags and the creationDate resampled to yearly
x6 = x.groupby([pd.tseries.resample.TimeGrouper('A'), 'tag']
               )['tag'].agg({'count': len}).rename(
    index=lambda x: str(
        x.year) if type(x) != str else x).reset_index().pivot_table(
    index=['tag'], columns='Period').xs('count', axis=1, drop_level=True)
topn = pd.concat([pd.DataFrame(x6[col].nlargest(n)).astype(
    int).reset_index().rename(columns={
        col: 'count'}) for col in x6.columns],
    keys=x6.columns, axis=1)
print(topn[topn.columns[-6:]])

Note that the second approach is more flexible and if you decide to look at a resample rate, i.e. look at quarterly data rather than yearly, all you have to change will be the resample rates and the format of the period columns.

A sample output for both snippets is shown below, the output contains the top 10 tags for each year:

Period                2014                2015                2016
                       tag count           tag count           tag count
0                   ubuntu   957        ubuntu   854        ubuntu  1010
1                    linux   428         linux   419         linux   409
2                   debian   318        debian   343        debian   339
3               apache-2.2   195    apache-2.2   120  ubuntu-14.04    91
4             ubuntu-12.04    70  ubuntu-14.04    50    apache-2.2    76
5                    nginx    59         nginx    41         nginx    67
6                    mysql    38           ssh    38    apache-2.4    46
7               networking    36    networking    37    networking    44
8                      ssh    33         mysql    29         mysql    31
9       domain-name-system    16    apache-2.4    28           ssh    27


Fetching table using mysqli, closing statement before displaying results

As soon as you are finished using your $stmt object, it is practical to close it.

However, I find that I am never calling $stmt->close(); in any of my projects because php is going to trash them as soon as my script is done anyhow.

Technically, you could have called it one line earlier.

Some leisure reading:

$stmt->close() vs $stmt->free_result()
When to close Prepared Statement
PHP - close prepared stmt
When is the right time to close a prepared statement?


How can I make my isSorted function faster?

The problem is simply that your two solutions are not equivalent. For example, you would probably not use Array, but barring that, a direct translation of the Java code to Scala would be:

def isSorted[A](items: Array[A], cond: (A, A) => Boolean): Boolean = {
    for (i <- 1 until items.length if !cond(items(i - 1), items(i))) {
      return false
    }
    return true
}

However, using an Array in Scala is a bit uncommon, and one would rather use Seq instead. Especially, a LinearSeq promises an efficient tail operation but slow indexing, this is reversed for an IndexedSeq.

@tailrec // remind the compiler that the recursion can be eliminated
def isSorted[A](items: LinearSeq[A], cond: (A, A) => Boolean): Boolean = items match {
  case Seq()     => true  // you forgot to handle empty input!
  case Seq(_)    => true
  case x :: tail => cond(x, tail.head) && isSorted(tail, cond)
}

But in this specific case, destructuring is actually silly: The isSorted test should male sense for any iterable (let's hope that it terminates, but that isn't our problem). It doesn't actually matter that much here that we can't do much destructuring for a general trait like Iterable. This here is a fairly elegant solution, but I wouldn't make any bets about performance.

def isSorted[A](items: Iterable[A], cond: (A, A) => Boolean): Boolean =
  items.isEmpty || (items zip items.tail forall (pair => cond(pair._1, pair._2)))

The zip method joins two lists pairwise: items = Seq(1, 2, 3, 4) would then produce ((1, 2), (2, 3), (3, 4)).

I am not sure whether any of these solutions would actually be faster – it's to be expected that Scala is a bit slower than Java, but the difference for a careful implementation should not be as large as in your question.

Style notes:

Always annotate tail recursive functions with @tailrec (from the scala.annotation package). This will either perform a tail call optimization or produce an error if the compiler is unable to do so.
When specifying the type of a variable, put a space after the :, but not before: name: Type. (source)
Invoke methods by using ., except when the method is an operator or takes a function as parameter – items.tail instead of items tail (source)
In general, the spacing around your operators is inconsistent. A comma should always be followed by a space, and binary operators like = or < should have a space on either side. (source)


I would say it is an adequate solution. The product may not feel very useful yet, but it's probably not supposed to be. In some sense, the exercise is formulated ambiguously. Your Node class can be used to construct linked lists and as such is a building block of instantiated linked lists. However, I would not consider that a LinkedList implementation. A LinkedList implementation would consist of a wrapper class that hides this Node from the user and allows you to say thinks like

List list = new LinkedList();
list.add("foo");
list.add("bar");
list.remove("foo");
int index = list.indexOf("bar");
etc.

It may seem somewhat unsatisfactory that you have to construct your test list so clumsily, but ease of use wasn't a goal of the exercise ;)


In Haskell, unsafe can mean various things, but it almost always means that you have to have a very solid understanding of what the unsafe thing is about before you use it if you want to have any hope of staying out of trouble.
unsafeFreeze and unsafeThaw in particular are low-level functions exposed to allow programmers to dig into the internal guts of vectors to build new abstractions offering a safe interface. For example, you might use a pure function to build a new vector, then use unsafeThaw to produce a mutable vector. You'd then have a new function hiding away the unsafety and exposing a plain old "make a new vector like this within ST/IO/PrimMonad". Or you might create a mutable vector, do a bunch of mutation, and then unsafeFreeze it to make a pure one. You'd then have a new function hiding away the unsafety and exposing a plain old "make an immutable vector like this".
What you've written is something you should never see: an action that takes what, to the outside world, is a pure value, and actually changes it. Such a "function" breaks all the usual rules of Haskell; it's as strange as something that changes every 3 in the world into a 4.
What you should do instead, if you want to keep mutating the same vector, is put that whole thing within the monad. Make the vector, do all your mutations (holding on to whatever you need to return) and then produce a result at the end.
Side note: the general rule about unsafe also applies to any function or constructor imported from a module named GHC.*, *.Internal or *.Private, as well as certain functions whose names begin with unchecked or end in Descending or Ascending. The primitive member of the PrimMonad class is also deeply unsafe.

Update
You should read The Genuine Sieve of Eratosthenes by Melissa O'Neill, which shows how to lazily produce a list of primes in an efficient manner. It's a very accessible and interesting article.
I've pasted my own version of a fairly simple vector-based sieve below, with extensive comments. To run the testing code you will need the arithmoi and hspec packages. You can install those (and vector) in a Cabal sandbox if you wish.
module Primes where

import Control.Monad.ST
import qualified Data.Vector.Unboxed as Vec
import qualified Data.Vector.Unboxed.Mutable as MutableVec
import Control.Exception (assert)

-- For testing
import Test.Hspec
import Test.QuickCheck
import qualified Math.NumberTheory.Primes.Sieve as MNPS

-- Approximate square root of an Int. Note that this may not work properly
-- when the Int is too large to be represented precisely as a Double.
intSqrt :: Int -> Int
intSqrt n = ceiling (sqrt $ fromIntegral n)

-- We make a vector indicating which *odd* numbers are prime. An odd number n
-- is prime if (primalityTable n) ! getIndex n is True.
primalityTable :: Int -> Vec.Vector Bool
primalityTable 0 = Vec.empty
primalityTable 1 = Vec.singleton False
primalityTable 2 = Vec.fromList [False, False]
primalityTable upto = runST (do
  let limit = let root = intSqrt upto in root - fromEnum (even root)

  -- Make a mutable vector and fill it with True
  arr <- MutableVec.replicate (getIndex (upto - fromEnum (even upto)) + 1) True

  -- 1 is not prime
  assert (MutableVec.length arr > 1) $ MutableVec.write arr (getIndex 1) False

  -- For each element of the vector up to the limit, check if the element has
  -- been crossed off. If not, use it to cross off other elements.
  flip mapM_ [0 .. getIndex limit] $ \i -> do
    -- Does the index i represent a prime?
    isPrime <- assert (i < MutableVec.length arr) $ MutableVec.read arr i
    if isPrime
      then crossOff i arr
      else return ()
  Vec.freeze arr)

-- Since we're skipping all the even numbers, we use these functions to convert
-- numbers and the vector indices they correspond to. That way, we don't have
-- to try to keep track of the conversions in our poor heads, except where we
-- want to.  Since we're using Control.Exception.assert, we'll get useful
-- information about where in the source the assertion failed, and the
-- assertion will go away when we compile with optimization enabled (unless we
-- use -fno-ignore-asserts).
getIndex :: Int -> Int
getIndex n = assert (odd n) $ n `quot` 2

getValue :: Int -> Int
getValue n = n + n + 1

-- Cross off odd multiples of the prime represented by the index passed in. How
-- do we calculate this efficiently? We are working with the prime p = getValue
-- i = 2 * i + 1. We first cross off the value p*p. Instead of monkeying around
-- with getValue and getIndex in the inner loop, we will use thte fact that
-- moving up in value by 2*p corresponds to moving up in index by p.
crossOff :: Int -> MutableVec.MVector s Bool -> ST s ()
crossOff i arr = mapM_
     (\q -> assert (q < MutableVec.length arr) MutableVec.write arr q False)
     [startingIndex, startingIndex+p .. MutableVec.length arr - 1]
  where p = getValue i
        startingIndex = getIndex (p*p)

-- Note that we can reasonably expect the intermediate vector here to be fused away by
-- the fancy compiler rewrite rules in the vector library.
primesSum :: Int -> Int
primesSum uptoNotEqual
  | uptoNotEqual <= 2 = 0
  | otherwise = 2 + Vec.sum (Vec.imap (\i isPrime -> if isPrime then getValue i else 0)
                                      (primalityTable (uptoNotEqual-1)))

primesSumMNPS :: Int -> Int
primesSumMNPS upto = sum . takeWhile (< upto) . map fromInteger $ MNPS.primes

staticTests = [(0,0),(1,0),(2,0),(3,2),(4,5),(5,5),(6,10),(9,17),(10,17),(11,17),
               (12,28),(29,100),(30,129),
               (100,1060),(1000,76127),(10000,5736396),
               (25000,32405717), (100000,454396537),
               (2000000,142913828922)]

testOnList summer lst =
    flip mapM_ lst $ \(n,s) ->
           it ("works for "++show n) $ summer n `shouldBe` s

main :: IO ()
main = do
  hspec $ do
  -- Since we're using primesMNPS to check primesSum,
  -- we want to be sure it passes the static tests.
  describe "Primes.primesMNPS" $
    testOnList primesSumMNPS staticTests
  describe "Primes.primesSum" $ do
    testOnList primesSum staticTests
    it "works just like primesSumMNPS" $
      property $ \n -> let upto = abs (n `rem` 30000000)
                       in primesSum upto == primesSumMNPS upto


Check if relations exists for a parent node before deleting it so that we don't have any orphan child node

Some thoughts below:

I would encourage you to think about validating parameters more thoroughly on your public methods.  For example, in deletePosts(), you do nothing to validate that you even have an integer value (or whatever) to work with.  You do it in some cases such as type-hinting for array and validating non-empty array on hasRelations(), but it is not consistent.  What if non-array is passed to your exception constructor? What if non-integer (or whatever) is passed to deletePosts()?

You may not think it matters now because you are currently working in this application area and understand where all the calls are made against these methods, but think about in the future when you try to leverage these classes in new ways.  The call patterns may be different.  If, for example, you introduce a buggy use case that passes a non-array to your exception class, you want that class to complain loudly, rather than silently fail so that you can focus your debugging efforts more quickly on the problem code.

$relations = ['tags', 'comments'];

Why is this hard-coded here?  I would think this should, at a minimum, be a property on the class, if not derived from configuration.

$hasRelations = $this->postRepo->hasRelations($post_id, $relations);

Consider placing this code in a try-catch block since hasRelations() can throw. I know that since $relations is hard-coded here that we would never expect to get into a state where that exception is thrown, however I think it best practice to always use try-catch block in such a case so that as someone working in this code, you have quick understanding of how methods you are calling might perform.  Who knows, maybe the implementation of RepositoryTrait changes at some point and throws exceptions for other reasons besides the passed relations parameter.

throw new \Exception('No relation is provided.');

Consider throwing InvalidArgumentException if you want to be more specific here.  I actually find it a bit odd that you use custom exception types in the code calling this but not here.  It might call into question how you are using custom exceptions throughout the application.

Your custom exception seems to have a very limited use case. It really only exists to format the message string from a passed array, functionality that might rightfully live in the code where the exception is thrown not within the logic of the exception.

Is this message even meaningful to caller as is?  You can't tell what kind of relationship exists amongst the types provided, nor the specific ID's of the relationships that exist, so there is questionable value in preparing this specific message string vs. just a simple 'Cannot delete because this post has relations' message in the exception. You could easily provide this message in context of where the exception is thrown totally eliminating the need to override the constructor (or maybe even this class altogether).

Is this class going to be used elsewhere in your application?  If not, should it even exist (vs. using other exception types)? If so, are you always going to want to pass this class an array of relation types as parameter to format into message string?

I actually question whether you should even be throwing an exception here at all if a relationship exists.  Since you are specifically building this functionality, my guess is that you are expecting the application to handle deletion requests against posts that have relationships as part of normal operation of the application.  If so, should this really be an exception or just an alternate code path that needs to be followed to handle this condition?  Only if you truly never expect the application to be put into this state would it make sense to have this code throw an exception.

To your question about how to call model dynamically while avoiding having to set $modelName, you could use something like:

call_user_func($this->model . '::where', 'id', $id);

but I honestly find what you have in place to be easier to read, and I would not be concerned about the cost of having the additional variable in memory (that seems like a micro-optimization type of concern).


Easy-to-use C++ class for asking current time stamp in milli-, micro- and nanoseconds

Since std::chrono::high_resolution_clock::now() is static method you don't need any instance for it.

This is all you need.

#ifndef CURRENT_TIME_H
#define CURRENT_TIME_H

#include <chrono>
#include <cstdint>

inline uint64_t CurrentTime_milliseconds()
{
    return std::chrono::duration_cast<std::chrono::milliseconds>
              (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
}

inline uint64_t CurrentTime_microseconds()
{
    return std::chrono::duration_cast<std::chrono::microseconds>
              (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
}

inline uint64_t CurrentTime_nanoseconds()
{
    return std::chrono::duration_cast<std::chrono::nanoseconds>
              (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
}

#endif  /* CURRENT_TIME_H */


Consider checking src[currentByte] for '\0' and abort when it's true (apparently the passed in string wasn't long enough). Depends on your usage though.
Alternatively to the previous point you could add a source_length parameter to let the caller supply the information of how long the sequence really is.
I would consider changing the interface slightly. Have some methods which manage the object for you:

bits_t *new_bits_t(int nbits)
{
     bits_t *res = malloc(sizeof(bits_t));
     res->data = calloc(nbits);
     res->len = nbits;
     return res;
}

// frees the memory allocated for the structure and sets the reference to NULL
void delete_bits_t(bits_t **bits)
{
     if (bits == NULL || *bits == NULL) return;
     free((*bits)->data);
     free(*bits);
     *bits = NULL;
}

Then your read_bits function could fill in the  structure passed in and also return error code in case the reading failed (i.e. source is too short):

int read_bits(unsigned char *src, bits_t *bits, int bits_offset)
{
    ...
}

bit_position_in_byte = (curr_bit - 1) - (curr_byte * 8); should be equivalent to bit_position_in_byte = (curr_bit - 1) % 8;
Your loop is one based for some reason but inside the loop you have to subtract 1 from current_bit everywhere. You should just make your loop 0 based which would de-clutter the loop a bit.
I would find bit_in_byte just as descriptive a name as bit_position_in_byte.
You could get rid of the remaining_to_read by calculating the position:

for (curr_bit = 0; curr_bit < nbits; ++curr_bit) {
    input_bit = curr_bit + bits_offset - 1;
    input_byte = input_bit / 8;
    bit_in_byte = input_bit % 8;
    bits->data[nbits - curr_bit - 1] = read_bit(src[input_byte], bit_in_byte);
}

The loop apparently fills data from the end which seems little bit unexpected to me (kind of string reversal).


Suppressing warnings

It's hard to defend suppressing warnings at the class level.
The problematic lines in your code are these:

    data = (T[]) new Object[INITIAL_CAPACITY];

Which appears in two places.
I suggest to move the array allocation to one place,
and suppress the warning only for that line, like this:

public ArrayStack() {
    data = newArray(INITIAL_CAPACITY);
}

private final T[] newArray(int capacity) {
    @SuppressWarnings("unchecked")
    T[] tmp = (T[]) new Object[capacity];
    return tmp;
}

private void enlarge() {
    T[] temp = Arrays.copyOf(data, data.length);
    data = newArray(data.length * 2);

    System.arraycopy(temp, 0, data, 0, temp.length);
}

This hits two birds with one stone:

The ugly array creation is now at once place instead of two
Warnings are suppressed for the single problematic line, not for the entire class

In case you were wondering, the local tmp variable is necessary in newArray, otherwise Java doesn't allow suppressing the warning on a return statement or regular assignment. It has to be declaration + assignment.

Another important note here is the private final modifier of newArray.
The private modifier is necessary to prevent sub-classes from overriding the behavior and potentially breaking the constructor.
The final modifier is necessary to prevent sub-classes from shadowing the method by another method with the same name, causing confusion.

Manual array copy

Instead of this:

for (int i = 0; i < temp.length; i++) {
    data[i] = temp[i];
}

It's better to use System.arraycopy instead:

System.arraycopy(temp, 0, data, 0, temp.length);

(Also seen in the previous section.)

Other minor things

In clear, I'm wondering why you manually null out the elements,
rather than simply creating a fresh new array.
You could let the garbage collector take care of the stale array.

Random is unused, so remove the import.


As Slicer wrote in his comment you should create a method/function for the algorithm.
And you could make it as an extension method:

public static class NumberExtensions
{
  public static ulong Factorial(this ulong number)
  {
    if (number < 2) return 1;

    checked
    {
      ulong factorial = number;
      for (ulong i = 2; i < number; i++)
      {
        factorial *= i;
      }
      return factorial;
    }
  }
}

Here I've widened the domain to ulong and I iterate upwards from 2 as it is more intuitive and easier to read. Further I've encapsulated the method in a checked statement in order to throw on overflow, because factorial grows quickly out of even the scope of ulong.

Usage

  while (true)
  {
    Console.Write($"Enter a number: ");
    if (ulong.TryParse(Console.ReadLine(), out ulong number))
    {
      try
      {
        Console.WriteLine($"Factorial of {number} = {number.Factorial()}");
      }
      catch (OverflowException ex)
      {
        Console.WriteLine($"Entered number is too big: {number}");
      }
      catch (Exception ex)
      {
        Console.WriteLine($"An Error occured: {ex.Message}");
      }
    }
    else
    {
      break;
    }
  }


Array-based MinHeap implementation in Java

There are numerous "microstyle" issues; for example:

superfluous blank lines
missing spaces before / after symbols; e.g

  for(int i=0; i< heap.length; i++){

should be

  for (int i = 0; i < heap.length; i++) {

if(found == false) should be if (!found)
redundant (and inconsistent) use of this in the constructor.

And there are no javadocs!

Also, this looks like a bug:

    public int min(){
        return heap[1];   // should this be zero?
    }

Have you >>tested<< the code thoroughly?


Getting images and saving them to localstorage

loadStorage()

Wierd selective use of jQuery.

container is already a jQuery object. Just do container.append(elem); no need to wrap it in jQuery again.
document.getElementById(key); could be shortened to $("#"+key)[0]
$(thisImg).attr('src', source); could just be thisImg.src = source

createThisImage()

Why didn't you declare this function like the other ones?
The conditional if ((name === "" && url === "") || (url === "")) is the exact same thing as if (url === "")

Image.prototype.createImage()

Image is already a JS object, it represents an <img> object. Get rid of your Image constructor and use the native one.

Image.prototype.createImage = function() {
    $(container).append(this);
    saveImages(this.id, this.src);
    window.location.reload(true);
};

This would then be used like this...

img = new Image();
img.id = name;
img.src = url;
img.createImage();


Function to return a string legal for a range name

Using a VBScript.RegExp will greatly help clean your algorithm:

Static reg As Object
If reg Is Nothing Then
    Set reg = CreateObject("VBScript.RegExp")
    reg.Pattern = "(?:^(?=\d)|\W)" 'A Digit at the start or any illegal character
    reg.Global = True 'Replace all matches
End If
Namify = reg.Replace(inputName, "_")

This does the same as your entire function. Read more about RegExps here

If you additionally write a function ContainsName(name As String) As Boolean wich traverses ActiveWorkbook.Names and returns True if name is a valid name, you can add an additional feature to generate a valid new name as Mat suggests:

Static trailingNum As Object
Dim number As String
If trailingNum Is Nothing Then
    Set trailingNumm = CreateObject("VBScript.RegExp")
    trailingNum.Pattern = "\d*$"
End If
While ContainsName(Namify)
    number = trailingNum.Execute(Namify)(0).Value
    If Len(number) = 0 Then number = "0"
    Namify = trailingNum.Replace(Namify, CStr(CInt(number) + 1))
End While


I have some suggestions for your code.

Most of your loops can be replaced with java.lang.String#repeat (Java 11+)

Example
"*".repeat(10) // Will give you "**********"

I suggest that you create a class constant for each of the tree's parts (*, \n, |) to allow the code to be easier to refactor / make changes in the future, if you need to (i.e., change the star by a plus sign, etc.).

For the tree's parts, I suggest that you use character instead of string, since the character will take less memory than the string (very small amount in this case, but still).
" " -> ' '


FirstOfDefault can also take a filtering query, just so you know.

Which means :

db.context.users.AsNoTracking().Where(u => u.userID == userID).FirstOrDefault();

can be :

db.context.users.AsNoTracking().FirstOrDefault(u => u.userID == userID);

If you use C#6, you can use the null propagation operator ?. instead of multiple null checks :

if (usr != null)
{
    var cbs = usr.customBehaviours.ToList();
    if ((cbs != null) && (cbs.Count > 0))
        //...

is now :

if (usr?.customBehaviours != null && cbs.Count > 0)

As pointed @ANeves in the comments, ToList never returns null. It'll return an empty collection or will throw an ArgumentNullException if the enumerable is null.

So, doing .ToList() before checking if usr.customBehavious == null won't save you.

I feel like you should split both your if in different methods, maybe GetUserCustomBehavior and GetOrganizationCustomBehavior. Then, your code woudl be cleaner.

// GET: api/CustomBehaviours
public IEnumerable<CustomBehaviour> Get(int? orgID = null, long? userID = null)
{
    using (PAMDatabase db = new PAMDatabase(WebApiConfig.PAMConnectionString))
    {
        List<CustomBehaviour> output = new List<CustomBehaviour>();

        // Add all custom behaviours for the specified user
        if (userID != null) {
            var userBehaviors = GetUserCustomBehaviors(userID.Value, db);
            output.AddRange(Mapper.Map<List<CustomBehaviour>>(userBehaviors));
        }

        // Add all custom behaviours for the specified organisation
        if (orgID != null)
        {
            var orgBehaviors = GetOrganizationCustomBehavior(orgID.Value, db);
            output.AddRange(Mapper.Map<List<CustomBehaviour>>(orgBehaviors));
        }

        return output;
    }
}

private IEnumerable<???> GetUserCustomBehavior(int? userId, PAMDatabase db)
{
    var usr = db.context.users.AsNoTracking().FirstOrDefault(u => u.userID == userID);

    return usr?.customBehaviours ?? new List<???>();
}

private IEnumerable<???> getOrganizationCustomBehavior(int orgId, PAMDatabase db)
{
    var org = db.context.orgs.AsNoTracking().FirstOrDefault(o => o.orgID == orgID);

    return org?.customBehavior ?? new List<???>();
}

Now, notice something, I wasn't able to see which type was used in your code because of the var keyword. var is cool, but tools like Resharper indicate they should be used only when you can see which type is used ex :

//good
var list = new List<int>();
//not good
var user = FooTheBar();

Also, you don't really need to check for Count > 0, what's the worst that can happen, you'll add an empty range to your list? That's usually not important, and your code has less if, which is good.

I'm no pro with Automapper, but I don't think it's a good practice to map lists, maybe you should define your map per object (Mapper.CreateMap<???,CustomBehaviour>()) but maybe there's a performance gain I'm not aware of.


Retrieving a list of patients that have visited certain hospitals

Using IN tends to have a performance hit in most DBMS, as it typically results in a row by row lookup.  As a rule of thumb, I don't use a subquery if I can express the relationship in a simple join.  I also try to stay away from DISTINCT wherever possible.  When I need to dedup records, I'll typically use a GROUP BY and return the count of records, since it's often useful in my field (reporting) and/or for QA.  For example, the below query should return the patients you are looking for, with the added benefit of how many other hospitals were visited.  You could also do a plus one for total hospitals visited (including "Green").  That may or may not be useful for your needs.

SELECT
    green.PatientID,
    COUNT(1) AS OtherHospitals,
    COUNT(1)+1 AS TotalHospitals
FROM
    Patients green
JOIN
    Patients other ON other.PatientID = green.PatientID
WHERE
    green.Facility = 'Green'
    AND other.Facility <> 'Green'
GROUP BY
    green.PatientID


Don't give into that temptation.

Suppose that the user inputs an invalid number say "45a", and then the default is taken. What happens? In the best case its obvious the user that something went wrong. However, its probably not obvious exactly what went wrong. However, your program knows exactly what went wrong, but chose not to tell the user. You've just made things harder for the user. Even worse, what if the user doesn't notice that something is wrong. The user assumes that his input was read correctly and takes the program's output as accurate and acts on it. Now they have incorrect information, and don't know it!

As far as I'm concerned nothing good can happen from ignoring invalid user input. Tell the user they goofed.

EDIT

Firstly, there is a very large important difference between tinyurl and your function. Tinyurl never overrides the user input with defaults. It doesn't try and guess what you really meant when you give it nonsense. Your function overrides user input and tries to guess what the user really wanted. Its the guessing and overriding that is a really bad idea. The only effect of doing those is to mask bugs.

Secondly, while tinyurl can get away with it as a website, I don't think "suffering fools lightly" is a good idea. We all play the fool occasionally, and when that happens I want my programs to slap me in the face, not play along. When I introduce a bug in my program, I want that bug to manifest itself as close as possible to point where I introduced it. That way I should have the easiest time tracing the problem. What your method does is prevent function from dying because I passed it the wrong types, but then exhibits incorrect behavior later on. As far as I can tell, there are no circumstances in which that will be helpful to me.