Get count of positive numbers and sum of negative numbers

The count of positive numbers can be better written as:

sum(n > 0 for n in data)

This will take a lot less memory (which is important if data becomes large), because it uses a generator expression.

Also, are all the checks of isinstance really needed? Is data sometimes not an iterable? And does it sometimes not contain integers? Because if not, then those checks will cost some time.

At the same time, it is usually better to ask for forgiveness than permission, so just use:

try:
    print len(data)
except AttributeError:  # will trigger if `data` has no `len` function
    pass

to be more inclusive and allow any custom iterable.


Prevent Variable Overflow from InputBox user error

I think you over engineered this function a bit, which is easy to do. Simply store your value in a variant to check if it will fit in an integer.

 Private Function IsInteger(ByVal prompt As String) As Integer
    Dim longHolder As Variant
    longHolder = InputBox(prompt)
    If IsNumeric(longHolder) Then
        If Int(longHolder) = CDbl(longHolder) Then
            If Abs(longHolder) < 32768 Then
                IsInteger = longHolder
            Else
                MsgBox "Too Big"
                IsInteger = 0
            End If
        Else
            MsgBox "Decimals!"
            IsInteger = 0
        End If
    Else
        MsgBox "Not a number"
        IsInteger = 0
    End If
End Function

You would use it like this

Sub test()
    Dim x As Integer
    x = IsInteger("give me an integer")
End Sub

That being said, integers are obsolete. According to msdn VBA silently converts all integers to long. So, just use Long to begin with.


Some comments:

There is no need to store the results in memory, so don't. Simply output them as they are computed.
It's been many years since C has allowed variables to be declared where they're used instead of being lumped together at the top. Do this for legibility.
Don't loop through to get q. Powers of 2 are easily found via << .
Don't loop through to reset the array contents to 0. Simply set the elements to their desired value.
Don't populate an array forward and then loop back through it in reverse to do an output. Simply populate a string that is ready to be output.
f doesn't mean anything to the program user, so don't use it in the output; use something like "decimal" instead.

An alternative implementation is:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    scanf("%d", &n);

    char *output = malloc(n+1);
    output[n] = '\0';

    for (int number = 0; number < (1 << n); number++)
    {
        int temp_num = number;
        for (int idx = n-1; idx >= 0; idx--)
        {
            output[idx] = '0' + (temp_num & 1);
            temp_num >>= 1;
        }
        printf("dec: %d bin: %s\n", number, output);
    }
    return 0;
}


Start, stop and restart script for a MongoDB server

Bug

Can you spot the bug on this line?

    PID=$(ps -ef | grep "[m]ongodb" | awk {'print $2'})

The awk script here should be {print $2},
with the curly braces included,
so that needs to be within the single-quotes:

    PID=$(ps -ef | grep "[m]ongodb" | awk '{print $2}')

Quoting path variables

It's good to make it a habit to always double-quote path variables in command statements, to protect from globbing and word splitting. Instead of:

SCRIPTNAME=$(basename $0)

Write like this:

SCRIPTNAME=$(basename "$0")

The same goes for this line:

    sudo $MONGOD --dbpath $MONGODBPATH --config $MONGODBCONFIG

Useless variable and echo

PID is not used anywhere else inside the script but here:

function isRunning {
    PID=$(ps -ef | grep "[m]ongodb" | awk '{print $2}')
    echo $PID
}

You could simplify as:

pid() {
    ps -ef | awk '/[m]ongodb/ {print $2}'
}

I also renamed the function, because pid() reflects better its purpose.

User experience

Something's odd in this condition:

rc=$(isRunning)
echo "... stopping mongodb-server with pid: $rc"
if [ ! -z "$rc" ]; then
sudo kill $rc
fi

If the process is not running $rc will be empty, and users may think the output is weird and the script is buggy.
You might want to rearrange this part,
for example if the server is not running, then say so.

Make the most of awk

Very often a grep ... | awk ... combo can be simplified,
because awk can filter all by itself. Instead of:

PID=$(ps -ef | grep "[m]ongodb" | awk '{print $2}')

You can write:

PID=$(ps -ef | awk '/[m]ongodb/ {print $2}')

Style

This is fine:

function isRunning {
    # ...
}

But the recommended style for function declarations is like this:

isRunning() {
    # ...
}

Variable initialization

This is fine:

MONGOHOME=""
MONGOBIN="$MONGOHOME/bin"
MONGOD="$MONGOBIN/mongod"
MONGODBPATH=""
MONGODBCONFIG=""

But you could write simpler as:

MONGOHOME=
MONGOBIN=$MONGOHOME/bin
MONGOD=$MONGOBIN/mongod
MONGODBPATH=
MONGODBCONFIG=

Redundant semicolon

The semicolon at the end of exit; is redundant, I suggest to remove it:

if [ $# != 1 ]
then
    echo "Usage: $SCRIPTNAME [start|stop|restart]"
    exit;
fi


Conditionally copying cells from other worksheets

There are two different ways you could go about DRYing this up.
1) Create a subroutine that takes some parameters.
I want to show you this first, because it's very important to learn this concept. Anytime you see patterns like below, you should be extracting out new subroutines or functions.

For i = 2 To lastRow
For r = 2 To lastRow2
    If ws.Cells(i, 18) = ws2.Cells(r, 17) Then
       ws.Cells(i, 20) = ws2.Cells(r, 19)
    Exit For
   End If
Next r
Next i

For i = 2 To lastRow
For s = 2 To lastRow3

    If ws.Cells(i, 18) = ws3.Cells(s, 17) Then
       ws.Cells(i, 21) = ws3.Cells(s, 19)
    Exit For
    End If
Next s

If you look carefully at this, you'll notice that the only difference between these loops is the source column, the destination sheet, and the destination column.
Sub CopyData(souceWs As Worksheet, sourceCol As Long, destWs as Worksheet, destCol As Long)
    Dim lastRow As Long, destLastRow As Long
    lastRow = sourceWs.Range("Q" & Rows.Count).End(xlUp).Row
    destLastRow = destWs.Range("Q" & Rows.Count).End(xlUp).Row

    Dim i As Long, j As Long
    For i = 2 To lastRow
        For j = 2 To destLastRow
            If destWs.Cells(i, 18) = sourceWs.Cells(r, 17) Then
                destWs.Cells(i, destCol) = sourceWs.Cells(r, sourceCol)
                Exit For
            End If
        Next j
    Next i
End Sub

And then call this subroutine from your main routine once for each sheet that needs to be processed.
CopyData Worksheets("To"), 19, ws, 20
CopyData Worksheets("Copy"), 19, ws, 21
'etc

However, this would be terribly slow if there is a large amount of data to process. It would loop through the entire destination once for every call to CopyData.
2) Move everything inside of the outer loop.
There's no sense in looping from 2 To destLastRow over and over again. The code gets DRYed up a good bit and sees a performance boost by moving the logic inside.
For i = 2 To destLastRow

    sourceWs = Worksheets("To")
    lastRow = sourceWs.Range("Q" & Rows.Count).End(xlUp).Row

    For j = lastRow
        'do stuff
    Next j

    sourceWs = Worksheets("Blah")
    lastRow = sourceWs.Range("Q" & Rows.Count).End(xlUp).Row

    For j = lastRow
        'do stuff
    Next j

    'etc

Next i

At this point there's still some duplication, so you could use the concepts from #1 to extract the inner loop to its own subroutine.
Some other things you could do better:

The inside of each For block should be one indentation level (1 tab or four spaces) deeper. It's easier to follow.

I know a lot of people innocently recommend not reusing variable names, but sometimes it's cleaner to do so. Your inner loop counter was way up past r in the alphabet. Note how I reused j above once I was done with the previous loop. It just makes for less to remember. Just make sure that you're actually done with these generic variables before reusing them.

Don't number variables. If you catch yourself numbering variables, do exactly what you did =;)- Stop and look for a way to clean it up with a loop, subroutine, function, etc. If you just can't avoid it, give them meaningful names like sourceSheet and destSheet.


At most one LocalDate per month in a list

Bit late but there is Guava built-in method for that - Maps.uniqueIndex - given:

List<LocalDate> dates = Arrays.asList(
     new LocalDate(2012,3,25), new LocalDate(2012,4,30), new LocalDate(2013,3,26);

with JDK 8:

Maps.uniqueIndex(dates, LocalDate::getMonthOfYear);

or with JDK <7:

Maps.uniqueIndex(dates, new Function<LocalDate, Integer>() {
    @Override
    public Integer apply(final LocalDate date) {
      return date.getMonthOfYear();
    }
});

It will throw

java.lang.IllegalArgumentException: duplicate key: 3

in this example.


Check whether two JavaScript arrays are equal, using basic library only

Your function should be dedicated to its functionality. Have all the printing done externally. You don't need testName as a parameter.
Have your function return true or false. It's much more useful and reusable that way. Having it return also allows you to exit the function early if you know the arrays are not equal. For example:

function assertArraysEqual(actual, expected) {
    if (actual.length !== expected.length) {
        return false;
    }
    ...

If this is for something like unit testing, you should use a unit test library to like Mocha or Qunit to validate the behavior of the function.
What data types are you dealing with? Are you only concerned with numbers? Do you want strict type checking and/or null checking?

If you're only concerned with validating arrays of numbers and you know the bounds of the input, you can easily rewrite your function like so:

    function assertArraysEqual(actual, expected) {
        if (actual.length !== expected.length) {
            return false;
        }
        for (var i = 0; i < actual.length; ++i) {
            if (actual[i] !== expected[i]) {
                return false;
            }
        }
        return true;
    }


Function fputs always return zero on success

Although your observations show that you happen to always get 0 as a (success-case) return value, implementations are permitted to return any value of 0 or more.  For example, a different implementation of the standard library may find it convenient to return the number of characters that have been printed.

You cannot assume that rets == 0 will be as good as rets >= 0, because:

You might want to run your code on a different system, with a different standard library.  This might happen if you share your code with somebody else (perhaps for them to help you fix a bug).
The different system might be your current system in a year's time, when you've upgraded your libraries.

If your assumption is no longer true, then you suddenly have a huge number of hard-to-find bugs that all need fixing at once.  That is not what we call a Good Thing.  By depending only on what the standard guarantees, you maximise your likelihood of full portability, including to future versions of your current environment.


Locating child of a nearby ancestor with jQuery

I would make the link between the 2 implicit.

Then the code is

$(".dpicon").click(function(){
  $( this.href ).focus()
}

It is a creative (ab)use of href, but it still follows the spirit in my mind.

If you have the luxury of going HTML5, you can go with a data attribute.

Then the code is

$(".dpicon").click(function(){
  $( this.getAttribute( "data-dpicker" ) ).focus()
}


Simple program to insert values in a linked list

I want to know if this part where I insert the values stored in each node can be done in an shorter way

Definitely it can be done in a shorter way!

the problem is that in your code you are taking the pain to do the same thing twice while inserting. in the for loop :

for (i=0;i<N;i++)
{
    if (i<N-1)
    {

        //here
        int temp;
        printf("Insert value stored into the node %d:\n",i+1);
        scanf("%d",&temp);
        Node_c->value=temp;
        // to here

        Node_c->link=malloc(sizeof(Node));
        Node_c=Node_c->link;

    }
    else if (i==N-1) //Note: it must be == operator not =
    {

        //the same thing again from here
        int temp;
        printf("Insert value stored into the node %d:\n",i+1);
        scanf("%d",&temp);
        Node_c->value=temp;
        //to here

        Node_c->link=NULL;

}

The below part appears twice in your insertion logic :

    int temp;
    printf("Insert value stored into the node %d:\n",i+1);
    scanf("%d",&temp);
    Node_c->value=temp;

Now can we avoid writing twice the same thing?

... Definetely you can write that logic only once and change your insertion logic to :

int i;
Node * Node_c=head;
for(i=0;i<N;i++)
{
    if(i!=0) //not required once again for head
    {
        Node_c->link=malloc(sizeof(Node));
        Node_c=Node_c->link;
    }

    //you don't require temp as you can directly access Node_c->value
    printf("Insert value stored into the node %d:\n",i+1);
    scanf("%d",&Node_c->value);

    Node_c->link=NULL;

}

the logic is quite simple to understand :

first we create a memory for a node and save it's  address to the link of previous node(we don't if its a head node as it's already allocated with memory in the before part of the code and it has no previous nodes to be linked with)
then we take in the value and store in the value member of structure Node_c
then we point the link member of the structure Node_c to NULL... this goes on for N number of times


Is it fine to use my domain model as DTO (Entity Framework Core)?

I was reading about anemic data models and rich domain models in DDD. I don't want to follow DDD completely but take rather pragmatic approach and just take some concepts out of it because clean ddd seems like an overkill.
I don't want to maintain separate DTOs just for serializing and deserializing my models.

I'm similarly pragmatic as you, and I agree with you in this situation.
KISS (keep it simple & stupid) applies here. If your application is not sufficiently large, a DTO layer abstraction is not necessary.
I have several colleagues who would disagree with this, this is an open discussion topic. Personally, I disagree with blindly implementing things just because it was needed in other projects. Before I implement something, I need to justify its existence in the current project.

I'm not planning to use any other ORM other than EF Core.

It's not so much about what you plan to use, but rather the chance of this changing in the future, and how prepared you want to be when it turns out you have to change it.

Is it fine if I will design my models like this and at the same time use them as my DTOs for serialization and deserialization?

Yes, as long as you're okay with the tighter coupling and don't start violating SRP by loading everything into your entity classes.
However, that is a separate discussion from whether or not you should use DTOs. You could just as well violate SRP on your DTO class.


You should not be manually counting references. Instead, you should be letting the garbage collector do the reference management for you, and then hook in to the garbage collection framework when the reference is cleared in Java.
The right tool for the job is the finalize() method. This often-misused method, is actually purpose-designed for this exact case:

the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

public class Texture {
    ....
    @Override
    protected void finalize() {
        // clear resources kept in external areas to Java....
        .....
    }
}

Note:

The Following 'Old' answer is based on the first version of the question that made no reference to non-Java memory....

I believe you have a basic misunderstanding of Java memory management. What you say you are doing, you are not actually doing, and this statement 'This works and is OK' is not what you think is happening.
You cannot possibly tell java to release the memory for an object. What you can do though, is remove all references to an object, and, at some point Java GC will scan through and identify that memory as no longer used, and available for reuse.
In your class, you have the 'pixel data', perhaps an array of private byte[] pixels = ..., and in your dispose() method you call pixels = null, which removes the reference to the byte[] array. When the Garbage collector sweeps the heap, it will identify that the byte[] array is no longer referenced, and it will release that space.
This is what you are seeing, and you think 'it works'. But, that is not the solution you should be using.
What you should be doing, is not referencing the texture when it is no longer needed!
In other words, there's a bigger picture here... there is somewhere in you code where you have done:
Texture mytexture = new Texture(pixeldata);

and then, you have a reference to mytexture that you are not releasing.
If you say mytexture = null, then the garbage collector will release the pixel data as well as the texture object.
Instead of finding all the places in your code that use the texture, and calling retain() and release() they should just set their Texture variable to null, and move on if they no longer need the Texture.
If you are not releasing your pixels after doing that, it means you have some place in your code where you are still holding references to the Texture, perhaps some value in a HashMap, an array, or somewhere else where you are holding a reference. Remove those entries, and you will be fine.
Note: it is possible that your program is part of a very, very, tiny, small proportion of programs that may need finer memory control, and need to keep a Texture cached even though no-one is using it at a particular moment in time. Java has Soft-References that may help, but that is not likely to be your solution, and is more complicated than this post warrants....


Your class names are a little generic, so it is hard for me to get a feel for your intent here. Create seems like an odd name for a class.  Maybe UserFactory, UserProvider or similar.  If Create is ultimately intended to be a more generic factory type of class that could create any sort of entity depending on what endpoint is used, then perhaps a name like EntityFactory or similar would be more appropriate. Try to name classes, methods, etc. to clearly indicate their purpose.
If you are getting advanced enough in your coding to start considering using traits, then you are advanced enough to write proper Doc blocks. Sorry, not trying to shame here, but this is generally well thought out code compared to many samples on this site. I want to see you take it to the next level in terms of being closer to production-ready code in a professional environment.
Consider implementing concrete methods (which could be overridden) in your abstract class. You are repeating yourself a lot in extending classes with implementing your getters.
So do you have a second use case where you are going to use that trait?  It probably doesn't make sense to make a trait unless you have other use cases where you need to consume it.   For this single use case you show here, I don't know why this functionality would not just be part of base class.
From a coding style standpoint, you are doing a few thiings that are generally frowned upon.  You are putting comments out to the right of code instead of above the code they are applicable to, and you have several lines the go beyond the typical "best practice" of keeping lines of code to an 80 character limit.  These make code harder to read.

Some more specific comments follow:

const API_DOMAIN = 'https://test-api.com/v1/';

Why is this a constant on this class? If you want to make this class more flexible, perhaps it is passed on constructor or set via setter.  If this is very narrow use class, perhaps at least consider moving this to app configuration.

public function __construct(array $credentials)
{
    $this->client = new Client(); //This is GuzzleHttp/Client.
    $this->credentials = $credentials; // An array
}

Can these credentials be passed in an object that can be better type hinted? You should take appropriate steps to validate this $credentials parameter as a valid dependency (and throw Exception if it is not) before working with at and setting it on the object. Perhaps throw InvalidArgumentException upon validation failure.

Consider passing the Guzzle client to constructor as dependency (dependency injection). Why should this class need to know how to instantiate its own dependencies and the potential error/exception handling around them (which is absent here) in order to work with the dependency?  It should just get a valid dependency this is properly set up for it to begin working with.

Get in good habit of namespacing.  Wherever you instantiate the guzzle client you should do it like  new \GuzzleHttp\Client(). This is much clearer (eliminates the need for your comment).  Similarly if passing as a dependency, you should type hint as \GuzzleHttp\Client $guzzle_client.

protected function getUrl()
{
    //This has to be fixed to accept an array of parameters: [key => value] format
    return implode('/', array_filter([self::API_DOMAIN, $this->getEndpoint(), $this->getParameter()]));
}

Do you really need to go through this exercise every time or should Url just be set on object?

if (empty($this->credentials))
    throw new InvalidCredentialsException();

As mentioned previously, this should have been validated in the constructor and failed long before the point where a client would ever call this method.

         return $this->parseResponse(json_decode($response->getBody()->getContents()));

Odd to see a return within a try block. Does this code even potentially throw?
There really is too much going on in a single line of code and REALLY assumes a happy path operation of all 4 underlying operations.  There might be need to better handling of edge cases here (what if JSON doesn't decode? what if "parsing" doesn't work?).

    } catch (\Exception $e) {
        throw new ErrorResponseException($e->getMessage(), $e->getCode());
    }

This is kind of a meaningless try-catch block. It takes a more generic exception type and turns it into a more specific exception (an odd pattern in and of itself), but doesn't really do anything meaningful here like log the failure or add additional context to the underlying exception to the caller.  How is this any better than the caller just getting the underlying Exception directly?

    $collection = new Collection();
    foreach ($result as $item) {
        $collection->push(new Server($item));

Namespaces?

protected function getEndpoint()
{
    return 'users';
}

protected function getHttpMethod()
{
    return 'POST';
}

Endpoint, HttpMethod, headers, content, etc. are acting here as de facto class constants or properties when you do something like return 'some hard coded value';.

These should be actual class properties or constants.  This probably also removes the need to override these methods in every implementing class (if you put concrete methods in base class) as well as need to define some subset of these as traits.


Displaying user-defined functions and their docstrings

Use for name, value in globals().items(): then you don't need to use eval


The name could be more meaningful. It's usually a good idea to name a function after its result, which in this case is the multiplier \$k\$, so something like digit_power_multiplier is needed.
The docstring doesn't explain the arguments to the function, or what it returns. Write it from the point of view of a user who is trying to figure out how to call it.
Only the first string in a function definition becomes the docstring: the others are ignored. So make them comments instead.
Returning exceptional values to indicate failure (here, -1 when no \$k\$ is found) is risky: the caller might forget to check for the exceptional value. It's more reliable to raise an exception.
Python has an exponentiation operator ** so there is no need to use math.pow.
When splitting n into its digits you use len(str(n)) to find the number of digits. But if you're going to call str(n) you may as well extract the digits from the result, as suggested by vertere in another answer.
The division operator / changed its meaning in Python 3: it's now floating-point division. To make your code portable to Python 3, use the floor division operator // when you want the integer part of the quotient.
When simultaneously iterating over a sequence and an index, use enumerate. So instead of:

Tsum = 0
for i in digits:
    Tsum = Tsum + math.pow(i,p)
    p = p + 1

write:

Tsum = 0
for q, d in enumerate(digits, p):
    Tsum = Tsum + d ** q

[Thanks to Josay in comments for improving this.]
Take advantage of the sum function and write:

Tsum = sum(d ** q for q, d in enumerate(digits, p))

Putting all this together:

def digit_power_multiplier(n,p):
    """Given a positive integer n with decimal digits a, b, c, d, ..., and
    a positive integer p, return k such that:

        a ** p + b ** (p+1) + c ** (p+2) + d ** (p+3) + ... = n * k

    If there is no such k, raise ValueError. For example:

        >>> digit_power_multiplier(695, 2)
        2

    since 6**2 + 9**3 + 5**4 = 1390 = 695 * 2.

    """
    lhs = sum(int(d) ** q for q, d in enumerate(str(n), p))
    if lhs % n == 0:
        return lhs // n
    else:
        raise ValueError("no k such that {} = {}*k".format(lhs, n))


Creating two dictionaries to lookup values into an array

This is pretty sound, although I never like just creating objects. I normally import the library I want to reference right off the bat. Dictionary and most of those scripting objects are (I believe) in the Microsoft Scripting Runtime library. So just add that reference and you can change

Dim firstTable As Object
Set firstTable = CreateObject("Scripting.Dictionary")
Dim secondTable As Object
Set secondTable = CreateObject("Scripting.Dictionary")

to:

Dim firstTable as Dictionary
Dim secondTable as Dictionary
Set firstTable = new Dictionary
Set secondTable = new Dictionary

The only other critique I would have is to split up those If Statements, but that's all a matter of taste in my opinion (There are some that would have gripes about the formatting of If and Then on the same line)

Overall it's pretty solid code. Kudos!


D3.js interpolating line on circumference of circle

I'd suggest using nested group elements (<g>s) with transform attributes.

I.e. draw the circle (just as a <circle> element) and the line inside a group, and then draw a nested group with a circle and line within that, and so on. When you rotate the outermost group, the nested ones will follow. Rotate each of them, and you'll get the effect from the demo.

This way, you only need to animate one thing: rotation. For instance:

var width = 200;
var height = 200;
var body = d3.select("body");
var svg = body.append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("fill", "blue");

function addCircle(container, radius, x, y) {
    // Note the hardcoded rotation; it's just an example
    var group = container.append("g")
        .attr("class", "circle-container")
        .attr("transform", "translate(" + x + ", " + y + ")");

    function rotate() {
        group.transition()
        .duration(10000)
        .ease("linear")
        .attrTween("transform", function (d, i, a) {
            return function (t) {
                var rotation = t * 360;
                return "translate(" + x + ", " + y + ") rotate(" + String(rotation) + ")";
            };
        })
        .each("end", rotate);
    };
    rotate();

    group.append("circle")
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", radius)
        .style("fill", "none")
        .style("stroke", "steelblue");

    group.append("line")
        .attr("x1", 0)
        .attr("y1", 0)
        .attr("x2", radius)
        .attr("y2", 0)
        .style("stroke", "steelblue");

    return group;
}

var c1 = addCircle(svg, 30, width/2, height/2); // centered
var c2 = addCircle(c1, 20, 30, 0); // offset by 1st circle's radius
var c3 = addCircle(c2, 15, 20, 0); // offset by 2nd circle's radius
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Heck, you can do this in pure SVG (added extra groups to isolate rotation):

<svg width="200" height="200">
  <!-- root transform to center everything -->
  <g transform="translate(100, 100)">

    <!-- draw the outermost group and animate it -->
    <g>
      <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="10s" repeatCount="indefinite" />
      <circle cx="0" cy="0" r="40" fill="none" stroke="steelblue" />
      <line x1="0" y1="0" x2="0" y2="40" stroke="steelblue" />

      <!-- offset the children -->
      <g transform="translate(0, 40)">

        <!-- now repeat, only smaller -->
        <g>
          <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="10s" repeatCount="indefinite" />
          <circle cx="0" cy="0" r="30" fill="none" stroke="steelblue" />
          <line x1="0" y1="0" x2="0" y2="30" stroke="steelblue" />

          <g transform="translate(0, 30)">

            <!-- and again -->
            <g>
              <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="10s" repeatCount="indefinite" />
              <circle cx="0" cy="0" r="20" fill="none" stroke="steelblue" />
              <line x1="0" y1="0" x2="0" y2="20" stroke="steelblue" />
            </g>

          </g>
        </g>
      </g>
    </g>
  </g>
</svg>

At any rate, you can simply skip all the getPointAtLength calls. Your path is a circle, so a) you can use a <circle> element, and b) any point on its circumference can be described using some simple math:

var x = Math.cos(t) * radius + centerX;
var y = Math.sin(t) * radius + centerY;

where t is something between 0 and 2π (or beyond that; it'll just loop around). So your animation needs only change the value of t to find a point on the circle.


I'm a bit worried about file structures and putting every concrete class in its own file, as that results in from Foo.Bar.Baz import Baz; is that acceptable, or is the common wisdom to include more classes in a single module?

There's absolutely nothing wrong with putting multiple classes in the same file, especially if it makes the code more readable. That said, there's nothing saying you can't re-export your classes from another file if you would like the code and the module structure to be somewhat orthogonalized.

  I'm also using a lot of type hinting; while I'm aware that it doesn't actually do anything in Python, it does help me keep the ducks straight in my head while typing and helps my IDE help me. Any concerns here?

No concerns; this is a good thing to do from a documentation perspective and it's even better with IDE support.

I would be hesitant with core.abstract_base_classes; the standard name is the shortened ABC, so ABCs it would be. Even so, it seems strange to put all the ABCs in one place; why not put them with the classes that implement them?

In Operator, you do

if not attributes:
    attributes = AttributeBag()

This should be the explicit

if attributes is not None:
    attributes = AttributeBag()

since you're checking against a sentinel.

You also call super().__init__(); this seems pretty superfluous. You don't need to call super() and I'd avoid it unless it serves a purpose.

I can kind'a get why you'd want a property for id - to keep it read only. However, there's no reason to have status or attributes as a property. Don't, it doesn't buy you anything (and does have costs).

But this puts into question why you have the ABCs at all... why do you? If you had multiple classes, sure. You might want something to guide it. But as it stands, you're using it once and it's just overhead. Don't, it doesn't buy you anything significant (and does have costs).

Similar applies to Pool... but why not just use set? Not only does set do everything that Pool can do, it's better tested and supports more functionality. Further, everyone knows how to use set (I hope).

Don't build abstractions for the sake of abstractions. Build abstractions in order to simplify common functionality or allow extensibility where you plan to extend things. Abstractions are meant to make code simpler to understand, but if you build too many layers you drown out the intent that you're trying to express.


Pulling a subset of elements from a Dictionary

I would write it the obvious straight-forward LINQ way, which gives you good readability as well as lazy evaluation:

public IEnumerable<Resource> GetResources(IEnumerable<string> resourceNames)
{
    return resourceNames
        .Where(name => resources.ContainsKey(name))
        .Select(name => resources[name]);
}


Property to compare in Linq is different by criteria.

You could do something like this, but I don't know, whether it's a good idea:

Func<ViewBooking,DateTime> getDate = null;
switch(...)
{
    case ...:
    getDate = (ViewBooking item) => item.BookingDate;
    break;
}

pObjListBooking = pObjListBooking.Where(item => getDate(item) >= startDate && getDate(item) < endDate);


Shortest distance from point to line segment in 3D

Here is the implementation of the solution provided by Wolfram Alpha, as was suggested in the comments of the OP.

The implemented equation is:

$$ d=\frac{|(\mathbf{x}_2-\mathbf{x}_1)\times(\mathbf{x}_2-\mathbf{x}_1)|}{|\mathbf{x}_1-\mathbf{x}_0|} $$

where

$$x_1=(x_1,y_1,z_1)$$
$$x_2=(x_2,y_2,z_2)$$

are two points on the line and \$x_0\$ is a third point.

function d = point_seg_dist(x0, x1, x2)

    % Make sure we are in 3D
    if length(x0) == 2
        x1(3) = 0;
        x2(3) = 0;
        x0(3) = 0;
    end

    % We want column arrays
    if size(x0,1) < size(x0,2)
         x0 = P';
         x1 = x1';
         x2 = x2';
    end

    d = norm(cross(x2-x1 , x1-x0)) / norm(x2-x1);

Apart from a couple of checks on the input, the calculation is on one line and it does not need projections or checks on the projected point's position.


Yes, it can be shortened by using defstruct. An example from the docs:

      (cl-defstruct person name age sex)
      (setq dave (make-person :name "Dave" :sex 'male))
           ⇒ [cl-struct-person "Dave" nil male]
      (setq other (copy-person dave))
           ⇒ [cl-struct-person "Dave" nil male]
      (eq dave other)
           ⇒ nil
      (eq (person-name dave) (person-name other))
           ⇒ t
      (person-p dave)
           ⇒ t
      (person-p [1 2 3 4])
           ⇒ nil
      (person-p "Bogus")
           ⇒ nil
      (person-p '[cl-struct-person counterfeit person object])
           ⇒ t

Alternatively, if you want something more heavy weight, there is a CLOS-like object system.


Automatic creation of python conda packages

Quoting

It's recommended to quote variables in command arguments that might contain spaces, for example here:

tmp=$(dirname "$(conda-build --output .)")
system=$(basename "$tmp")
root_dir=$(dirname "$tmp")

The version numbers here don't contain characters that the shell would interpret, so you could drop all the single quotes. But you don't have to.

for py_version in '2.7' '3.5' '3.6'

Here again:

package_name=$(basename $(conda-build --python ${py_version} --output .))

It would be better to quote the command arguments:

package_name=$(basename "$(conda-build --python ${py_version} --output .)")

I wouldn't double-quote ${py_version} though,
because we have established earlier that it cannot possibly contain special characters.

This is fine:

package_path="${root_dir}/${py_version}/${system}/${package_name}"

But you could write simpler as:

package_path=$root_dir/$py_version/$system/$package_name

That is, the double-quoting is not necessary in variable assignments,
only in command line arguments.

This is fine:

for platform in 'osx-64' 'linux-32' 'linux-64' 'win-32' 'win-64'

But you could write more concisely as:

for platform in osx-64 linux-{32,64} win-{32,64}


PHP function to extract numbers from the list whose squares are exceed some threshold

Hints?  Ok.

Don’t square the values, O(n), instead square-root the boundary.  You’ll need an or in your test, though.
Don’t unset values in the list.  That requires shifting values in memory.  Make a new list of same size, fill in values, without gaps, and then resize result.


Rob Pike's Golang presentation excercise of day 1

This seems like a good solution except for one thing:

func power(a, b int) int {
    return a ^ b
}

The ^ operator doesn't do what you think it does. It's a bitwise xor operator. There is no power operator in Go, there's only math.Pow for float64s.

On a side note, I personally would create a type for operators:

type Op func(int, int) int

It's easier to type in function definitions and allows you to extend it with methods like String().


Don't load the same resource repeatedly

I don't have much time to give a full review but I can point out one big thing that I saw while looking through the code.

                public void paintComponent(Graphics g) {
                    try {
                        super.paintComponent(g);
                        final Image backgroundImage = javax.imageio.ImageIO
                                .read(new File(
                                        "/Users/langer/Desktop/7923.jpg"));
                        g.drawImage(backgroundImage, 0, 0, FRAME_WIDTH,
                                FRAME_HEIGHT, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

You shouldn't load and parse the background image in the paint method. This method can be called frequently even though your background image doesn't change. If you try to resize your window you'll see how you reload the background several times per second slowing down your application.

Prefer to create a program instance

Doing so allows you to encapsulate variables to the class instead of keeping them in main or as inline. Also makes your code more readable.

public class RectangleMover {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                final JFrame frame = new JFrame();

                frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new JPanel(new BorderLayout()) {
                    /**
                     *
                     */
                    private static final long serialVersionUID = 1L;

should be something like this:

public class RectangleMover {

    private final Image background;

    public RectangleMover(){
        background = loadimage();
        final JFrame frame = new JFrame();
        ...
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RectangleMover();
            }});
    }


I'll review this code with keeping in mind that you want to leave Apache Spark intact, as you intend to use it in the future for purposes it is intended to do.
I strongly believe that your current code can be written in pure Java 8, though that is not the point of the question.

Use lambdas wherever you can!

This will greatly enhance readability of your code.

As an example:

JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            public Iterable<String> call(String s) {
                return Arrays.asList(s.split(" "));
                }
            });

could be rewritten as the following (I checked and FlatMapFunction is indeed an interface that qualifies to be a functional interface):

JavaRDD<String> words = lines.flatMap(str -> Arrays.asList(s.split(" ")));

Similarly it holds that:

JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String s) {
                return new Tuple2<String, Integer>(s, 1);
            }
        });

can be rewritten as:

JavaPairRDD<String, Integer> pairs = words.mapToPair(str -> new Tuple2<>(s, 1));

If type inference is not strong enough, then you need to write: new Tuple2<String, Integer>(s, 1).

Lastly it also holds for:

    JavaPairRDD<String, Integer> counts = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer a, Integer b) {
                return a + b;
            }
        });

can be written as:

JavaPairRDD<String, Integer> counts = pairs.reduceByKey((a, b) -> a + b);

or even better:

JavaPairRDD<String, Integer> counts = pairs.reduceByKey(Integer::sum);

Use the new way to write comparators

You can much much easier write comparators in Java 8, it works via key extraction, you can turn this code:

private class TupleComparator implements Comparator<Tuple2<Integer, String>>, Serializable {
    @Override
    public int compare(Tuple2<Integer, String> tuple1, Tuple2<Integer, String> tuple2) {
        return tuple1._1 < tuple2._1 ? 0 : 1;
    }
}

into this code:

Comparator<Tuple2<Integer, String>> tupleComparator = Comparator.comparing(tuple2 -> tuple2._1);

This will automatically and automagically create a working comparator that works by comparator the _1 field of tuple2, which is inferred to be Tuple2<Integer, String>.

Now this line:

List<Tuple2<Tuple2<Integer, String>, Integer>> wordSortedByCount = countInKey.sortByKey(new TupleComparator(), false).collect();

can become:

List<Tuple2<Tuple2<Integer, String>, Integer>> wordSortedByCount =
countInKey.sortByKey(Comparator.comparing(tuple2 -> tuple2._1, false).collect();

Normally one would use method references in case of Comparator.comparing, if Tuple2 had a get1() method, then you would write it as Comparator.comparing(Tuple2::get1).

Upon further inspecting your code I see that you possibly intentionally have made your comparator serializable, if you need that for Apache Spark, then you can do that as well, though the solution does get a fair bit uglier then:

List<Tuple2<Tuple2<Integer, String>, Integer>> wordSortedByCount =
countInKey.sortByKey((Comparator<Tuple2<Integer, String>> & Serializable)Comparator.comparing(tuple2 -> tuple2._1, false).collect();

Via this mechanism it is possible to make a type implement a wrapper interface without writing boilerplate. It is more common in the form of (Runnable & Serializable)someRunnable than in this form though.

Final words

Lastly your code formatting is in need for some improvements with respect to indenting the anonymous classes, but it may be an oversight and the rest of the code looks great.

When I have some time I'd be eager to show you a pure Java 8 solution as I strongly believe that Apache Spark is making a mess of your code currently. I do understand however that you need to operate with Apache Spark at some point and for that you may be forced to use Apache Spark's classes.

My method using Java 8

As addendum I'll show how I would identify your problem in question and show you how I would do it.

Input: An input file, consisting of words.
Output: A list of the words sorted by frequency in which they occur.

Map<String, Long> occurenceMap = Files.readAllLines(Paths.get("myFile.txt"))
        .stream()
        .flatMap(line -> Arrays.stream(line.split(" ")))
        .collect(Collectors.groupingBy(i -> i, Collectors.counting()));
List<String> sortedWords = occurenceMap.entrySet()
        .stream()
        .sorted(Comparator.comparing((Map.Entry<String, Long> entry) -> entry.getValue()).reversed())
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

This will do the following steps:

Read all lines into a List<String> (care with large files!)
Turn it into a Stream<String>.
Turn that into a Stream<String> by flat mapping every String to a Stream<String> splitting on the blanks.
Collect all elements into a Map<String, Long> grouping by the identity (i -> i) and using as downstream Collectors.counting() such that the map-value will be its count.
Get a Set<Map.Entry<String, Long>> from the map.
Turn it into a Stream<Map.Entry<String, Long>>.
Sort by the reverse order of the value of the entry.
Map the results to a Stream<String>, you lose the frequency information here.
Collect the stream into a List<String>.

Beware that the line .sorted(Comparator.comparing((Map.Entry<String, Long> entry) -> entry.getValue()).reversed()) should really be .sorted(Comparator.comparing(Map.Entry::getValue).reversed(), but type inference is having issues with that and for some reason it will not compile.

I hope the Java 8 way can give you interesting insights.


Accessing time series development data from World Bank API

I would turn your mappings mapping countries and indicators around. Then you can simply do:

COUNTRIES = {"EST": "Baltic States", "LVA": "Baltic States", "LTU": "Baltic States", ...}

df["region"] = df["iso3"].map(COUNTRIES)
df["category"] = df["id"].map(INDICATORS)

If you are too lazy to manually invert the dictionary, or like the current structure more but still want to have the easier usage, just use this one-line function:

def invert(d):
    return {v: k for k, values in d.items() for v in values}

Instead of

ISO3_PARAM = ';'.join(chain(*COUNTRIES.values()))

Use

ISO3_PARAM = ';'.join(chain.from_iterable(COUNTRIES.values()))

This does not have any memory problems (not that that is a problem here, but it is good practice in general).

And if you follow the previous recommendation, replace values with keys.

I would slightly simplify your page_level function by inlining meta["pages"] and using the params argument of requests.get to pass the parameters

def page_level(indicator: str) -> Iterator:
    """ Iterate over all pages related to specific indicator. """
    url = f"{URL}{ISO3_PARAM}/indicator/{indicator}"
    page = 1
    while True:
        meta, data = requests.get(url, params={"format": "json", "page": page}).json()
        yield from item_level(data)
        page += 1
        if page > meta["pages"]:
            break
        sleep(1)

I must say that while I like that you separated things into their own function, I am not so sure about their names (I know, names are hard!). They convey only at which level a function operates, but not what it does.

My suggestions for names:

indicator_level -> get_dataframe (and directly return the dataframe) or get_data
page_level -> get_indicator_data
item_level -> extract_items


Emulating the pipe operator in javascript in a readable way

It works by using the output of each of the functions as the first argument to the next function. The given args are bound to the second argument and up.

Just running by this description, one could easily create a piping operation with 2 helper functions:

const bind = (fn, ...boundArgs) => callArg => fn(callArg, ...boundArgs)
const pipe = (...fns) => initialArg => fns.reduce((r, fn) => fn(r), initialArg)

pipe(
  bind(put_session, current_user, user),
  bind(put_resp_header, location, '/'),
  bind(put_resp_content_type, 'text/html'),
  bind(send_resp, 302, 'You are being redirected')
)(conn)

bind accepts a function and bound arguments and returns a function that accepts a single argument. When this returned function is called, it calls the bound function with the call argument first, followed by the rest of the bound arguments.

pipe accepts a list of bound functions, and calls them one by one. The first function gets the call argument, while the remaining functions gets the return value of the previously called functions.

This approach effectively copies over the lodash signature, but does not require lodash. It also doesn't deal with this. You get the conciseness of your second example, and less of the bloat on your third example.


Shift one value of array values to the beginning

Is there a shorter and more beautiful way of doing that?

shorter: yes
more beautiful: well, that sounds subjective... you can be the judge of the approaches below.

One approach would be to take off the value using $index with array_splice() and then put it (the first element from that spliced array) at the beginning using array_unshift():

$array = [1, 2, 3];
array_unshift($array, array_splice($array, $value - 1, 1)[0]);

See it demonstrated in this playground example.

Another approach would be to merge the spliced array and the original array using array_merge():

$array = [1, 2, 3];
$array = array_merge(array_splice($array, $value - 1, 1), $array);

See it demonstrated in this playground example.


Map square coordinates in matrix to flat array indices without hurting performance

I see nothing wrong with the concept.
Code looks reasonable to me.

Iterator

You implementation of iterator does not meet the requirements for a standard iterator so you may have issues using it with some of the standard algorithms.

See: http://en.cppreference.com/w/cpp/iterator/iterator

You are missing some standard types in the iterator:

Member type Definition
iterator_category   Category
value_type  T
difference_type Distance
pointer Pointer
reference   Reference

Currently your iterator can only be considered an Input Iterator but given its simplicity it really should be Random Access Iterator.

http://en.cppreference.com/w/cpp/iterator/iterator_tags

Which means it needs to support the following:

http://en.cppreference.com/w/cpp/concept/RandomAccessIterator

Accesses

Currently you only have const accesses:

int operator[] (int index) const {

Normally you would expect to see non const access as well

int& operator[] (int index) {

And maybe a version that validates its parameters.

int  at(int index) const {
int& at(int index) {

Also since you currently don't allow write access through operator[] your iterator is actually const_iterator. There are several version of iterator that you can implement.

iterator       begin();
const_iterator begin() const;
const_iterator cbegin() const;

Might also be worth adding the reverse versions of the iterator but that might also be overkill.


How to write efficient javascript/jQuery code involving loops and string concat?

I found out solution to my problem. so basically this is what I learnt

use filter to reduce the set of similar items instead of explicit if condition
use cached variables i.e. var $this = $(this);
use methods chaining
and if same methods are to be used multiple times, try using it like:

.prop({ disabled: true, title: 'Readonly.' });

instead of call .prop (or any other) multiple times.
try to scope restrict the context of your selector as far as you can, i.e.

jQuery("tr[data-uid='" + v.uid + "'] .k-button", e.sender.wrapper)

so here's my final query:

jQuery(e.sender.dataSource._data).each(function (i, v) {
   if (v.IsReadonly) {
      jQuery("tr[data-uid='" + v.uid + "'] .k-button", e.sender.wrapper)
       .filter(function (i) {
          var $this = jQuery(this);
          return !($this.hasClass('k-grid-edit') || $this.hasClass('k-grid-Desc'));
        })
        .addClass('k-state-disabled')
        .prop({ disabled: true, title: 'Readonly.' });
   }
});

and this query took 267ms - 296ms (for 10 iterations)

-- I hope there can still be something even more faster like getting rid of that parent .each loop


Ruby: Remove middle node from Linked List

document/comment your code. In the code.
re-checking .next in the second loop is unusually defensive
do not have a comment repeat what a statement "does" (reset node to point to head):
have it illuminate what is achieved/what-for/why something is done (the way it is)
the ruby way to have a statement executed, say, middle times may be

middle.times do
    node = node.next

(Eyeballing remove_middle_node, it uses O(1) additional space and Θ(n) time.)


HTML 5 form validation and form handling

Validating HTML5 Code

It seems that you are new to HTML5, so it's a good idea to validate your code. You have 14 errors and 5 warnings in your code:

autofocus="on" should be autofocus
Your email regex is invalid (because of the - which needs to be escaped).
You can't have a placeholder for date, month, week, time (it doesn't make that much sense)
You can't use required with color or range (it's automatically set to some value, so requiring it doesn't make sense)
Options must have a value or a label

Problem Statement vs Your Code

range is probably not ideal for age, but as it's in the spec, there's nothing you can do about it. But: For me, it doesn't show the age in firefox or chrome. You probably need JavaScript to do that.
Your password pattern is quite restrictive. The spec says to set a minimum of 6 characters, which makes sense. But restricting what those characters might be, or the length of the password are not good ideas.
Your email pattern is too strict. There are TLDs that are more than 3 characters. The local part of an email can contain more than alphanum + _-., and the domain can also contain a lot more than a-z. Also, {3, 4} matches {3, 4} literally, which doesn't make that much sense. Just use the html5 email validation like the spec says.

Other

autocomplete="off" is a very good idea for passwords. But for many other inputs (generally generic inputs that a user uses often on different websites/forms, such as emails), it reduces usability.
Try to use standard names to increase readability and so that autocomplete will work (what even is an email_id? email would fit better).
autocomplete="on" is the default, so you don't really need to specify it (it clutters up your code and makes it harder to read).
Your indentation is inconsistent (2 vs 4 vs 8 spaces, and datalist is indented even more).
You should not use linebreaks to change the look of the page. That's what CSS is for (I know it's easier to just place

, and I do it too sometimes, but it would be cleaner to do it via CSS).

  Can regex patterns be avoided?

Not for the password, but for the email, it can be avoided. As the problem statements says, use HTML5 email validation (it works automatically for type email, no need for a pattern; and your pattern is way too strict, disallowing a lot of valid email addresses).


Optimizing a search for list of artists in iTunes library

Is it actually necessary to add just the artist to the array?  We could simply do this:

NSMutableArray *artists = artistsQuery.collections;

Now we don't have to iterate through an entire array.  And later, when we need to access the artist at a particular array index, we can still get to that value as such:

[[artists[someIndex] representativeItem] valueForProperty:artistKey];

Also, this SO answer seems to suggest that valueForProperty: is just slow in general.  Despite only needing the artist, it might be better to enumerate through all the properties:

[artistsQuery.collections enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    MPMediaItem *item = (MPMediaItem *)obj;
    [item enumerateValuesForProperties:properties usingBlock:^(NSString *property, id value, BOOL *stop) {
        if ([property isEqualToString:artistKey]) {
            [artists addObject:value];
        }
    }];
}];

At first glance it may seem like this will automatically be slower since you're iterating through every property instead of just accessing the one you need, and in this case, since you only need a single property, this may actually be slower.  But if you need multiple properties, this should definitely be faster--enumerations like this (as well as forin loops) are handled in batches so they run quite fast.


The following is my opinion on how to improve your code.

You don't need write flex-flow: row-wrap because flex by default set row, then you can use another property of css flex-wrap: wrap.
If you want to use flex in the whole of your code, you can set flex properties for .row class.
Care about responsiveness, because flex is very good for making your page responsive. Due to this, we use flex-wrap and min-width to our input.

.stacked-inputs,.stacked-inputs .row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;

}
.stacked-inputs .row {
    display: flex;
    flex-grow: 1;
    flex-shrink: 1;
    flex-basis: 100%;
    margin-bottom: 10px;
}
.stacked-inputs > input,
.stacked-inputs .row > input {
    -ms-flex: 1 1 0%;
    flex: 1 1 0%;
    min-width: 200px;
}


Converting Confluence markup to a simpler XML format

You are using the wrong tool for the job, as explained here:

https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

Use XSLT for this job.


Count words that are longer than a set Length

Signature:

public static int LongerThanStingCompair(string s, int n)

Compair is misspelled, as is Sting - they should be Compare and String, respectively. Although, a better name might be CountLinesLongerThan.

s and n aren't great names for parameters.

On to your code:

// splits based on nextLine break
var sCount = s.Split('\n');

The comment is unnecessary and slightly wrong. The code splits on all new line characters.

// Cast to list
sCount.ToList();

This comment is also incorrect - that doesn't simply cast it creates a new list from an array. It's unnecessary because you only need to enumerate the lines - you don't need the functionality of the list.

Here's a Linq based alternate for you:

public static int CountLinesLongerThan(string source, int characterLimit)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    return source.Split('\n')
        .Count(line => line.Length > characterLimit);
}


Reversing the order of the tests is probably your best option here. In your current code:

function find_coin() {
    var roll = Math.random() * 100;

    if (roll < 0.01)
        currency['platinum']++;
    else if (roll < 0.1)
        currency['gold']++;
    else if (roll < 1)
        currency['silver']++;
    else if (roll < 10)
        currency['bronze']++;
};

90% of your random values will be >= 10, additionally, 9 % will be between 1 and 10 %, so, 99% of your tests will have to check.... 4 roll conditions (< 0.01, < 0.1, < 1, and < 10). So, 99% of all your rolls will check 100% of your conditions.

If you reverse the logic, and do:

function find_coin() {
    var roll = Math.random() * 100;

    if (roll >= 10) {
        return
    }

    if (roll >= 1) {
        currency['bronze']++;
    } else if (roll >= 0.1) {
        currency['silver']++;
    } else if (roll >= 0.01) {
        currency['gold']++;
    } else {
        currency['platinum']++;
    }

};

With the above code, 90% of your rolls will do just one test, 9% will do 2 tests, 0.9 will do 3 tests, and so on.

Note, also, that I have used braces even for the 1-liner blocks in the conditions. This is a good practice and it avoids bugs when maintaining your code, later.


How to optimize these nested loops for better performance?

it looks like you are doing a lot with making all sorts of variables that are really confusing to look at, maybe I am simple minded and that is why I can't figure it all out.

not really sure what you are doing with the t  but I changed it to i

 XmlNodelist ClientNodes;
ClientNodes = Clientes[0].ChildNodes;
XmlNode ChildNode;

int i = 0;

foreach ChildNode in ClienteNodes
{
    i++
    XmlNodeList ClientChildNodes;
    XmlNode ClientChildNodeChild;  //don't keep my name scheme
    foreach ClientChildNodeChild in ClientChildNodes
    {
        string clientZeroItemTchildIname;
        clientZeroItemTchildIname = (ClientChildNodeChild.Item.Name).ToUpper();
        if ( ClientZeroItemTchildIname.Contains("SERVICE"))
        {
            int a = 0;
            int.TryParse(ClientZeroItemTchildIname.Replace("SERVICE",""),out a);

            if (a.Equals(Type))
            {
                try
                {
                    Queues[i].Send(QueueMessage)
                }
                catch (MessageQueueException mqe)
                {
                    //log Error about mqe
                }
            }
        }
    }
}

not sure that I made it any faster, but this is way more readable.

there is one less Variable in my code than there is in your 'optimized' code.

Which is faster,  foreach or a for loop?

Here is an answer to that question, where someone actually went through testing for loops against foreach loops.  and it looks like the foreach is faster in some instances.

Answer to Performance difference for control structures 'for' and 'foreach' in C# (2009)

I also found a page where someone claims that a foreach loop takes longer and is generally good for collections, but then he recommends against it anyway.

Code Project Article "FOREACH Vs. FOR (C#)" (2004)

Threw that one in there in case you thought that I was biased.  I still think the foreach would be better for readability, but I don't know what your code is doing so I don't know what is going to be more efficient for you.  Readable/maintainable vs. faster?  maybe.  not sure though.

Something else to think about

Take the Send out of the Loop.

keep track of which Queues that you want to send in a variable outside of the loop and then once you are finished looping then send them all at the same time, outside of the loop.


Optimizing location updates when adding a new object

The method GetMachinesByOrderNoAndSection returns an IEnumerable<Machine>. Depending on how the method is implemented, iterating the enumeration may query the database. In HandleLocationCount you are iterating it and also calling .Count() on it several times. The LINQ Count extension method might also iterate the enumeration.
Make sure to iterate it only once, e.g. by working on a list crated with var list = AmountOfMachines.ToList();, if something like this is not already done in GetMachinesByOrderNoAndSection.
Also, you could use two distinct variables for storing newLocation and AmountOfMachines.Count() + 1 and call the latter only once.

I am not sure to understand the logic right. But you seem to assign the same AmountOfMachines.Count() + 1 to all the Keep_Last machines. If this is the case, you could simply assign them a constant number like Int32.MaxValue. They would be kept last once and for all.
Another possible approach is to partition the number range into two ranges:

[1 .. Int32.MaxValue / 2] for Blank.
[Int32.MaxValue / 2 + 1 .. Int32.MaxValue] for Keep_Last.

Adavantages:

The machines stay in their respective group.
They are ordered.
Adding a machine at the end of a group does not require the LocationInSection of others to be updated.

Instead of getting the count, you would get the maximium value in the two groups.
int nextBlank = machineList
    .Where(m => m.ForcedLocation == ForcedLocation.Blank)
    .DefaultIfEmpty(0)
    .Max() + 1;
int nextKeepLast = machineList
    .Where(m => m.ForcedLocation == ForcedLocation.Keep_Last)
    .DefaultIfEmpty(Int32.MaxValue / 2)
    .Max() + 1;


Find if some words in array value are in same array php

I have a bias toward regex because I'm generally comfortable with most techniques, so I'll recommend condensing your array of delimiters into a single regex pattern and employ preg_split() to execute the explosion.

After splitting the search string into its separate artists, I am flipping the values & keys to optimize the lookup for later use in the nested loop.

Then as you iterate the haystack of artist times, you can re-use the splitting pattern, then iterate each individual artist and store the desired data for qualifying rows.

Code: (Demo)

$fullArtistTimes = [
    ['time' => '18:31:00', 'artist' => 'LUIS RODRIGUEZ & DEN HARROW'],
    ['time' => '18:32:00', 'artist' => 'J BALVIN'],
    ['time' => '18:33:00', 'artist' => 'THE BLACK EYED PEAS FT J BALVIN'],
    ['time' => '18:34:00', 'artist' => 'THE BLACK EYED PEAS FT J BALVIN'],
    ['time' => '18:35:00', 'artist' => 'J BALVIN']
];

$fullArtist = 'THE BLACK EYED PEAS FT J BALVIN';

$artistDelimiters = '~ (?:[+e,&]|and|f(?:ea)?t\.?|vs\.?) ~i';

$artists = array_flip(preg_split($artistDelimiters, $fullArtist));

$result = [];
foreach ($fullArtistTimes as $row) {
    foreach (preg_split($artistDelimiters, $row['artist']) as $artist) {
        if (isset($artists[$artist])) {
            $result[] = "{$artist} is at {$row['time']}";
        }
    }
}

var_export($result);

Output:

array (
  0 => 'J BALVIN is at 18:32:00',
  1 => 'THE BLACK EYED PEAS is at 18:33:00',
  2 => 'J BALVIN is at 18:33:00',
  3 => 'THE BLACK EYED PEAS is at 18:34:00',
  4 => 'J BALVIN is at 18:34:00',
  5 => 'J BALVIN is at 18:35:00',
)

If this does not work for all of your cases, then I would need to see more test cases and your desired result before I could properly adjust my snippet.


Find the largest continuous descending sum in a 2d matrix

get_largest_neighbour is a big confusing function. Let's try strip it down to avoid rewriting code.

First I would create a loop to run on each of the four directions. To loop, you want to make a list of the four positions and loop over each. To do that, you can just build a simple tuple of co-ordinates were you add and subtract one from i and j in turn:

coordinates = ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1))
for x, y in coordinates:

Now you need to fold all your tests to make sure they're in the right range into one, which is simple enough and more readable in my opinion:

    if not 0 <= x < len(nums) or not 0 <= y < len(nums[0]):
        continue

To break it down a bit, the range we want is for x and y to be 0 or greater, and less than the length of the lists. Rather than hardcode 3, it's better to use len of the matrix. If you're concerned about performance for larger matrices, you could precalculate these values. If either of these values isn't valid for their range, then continue is called, with will skip onto the next co-ordinate and not run the rest of the loop.

Now all you need is your actual test and re-setting the max values. For convenience, I'd grab the value of nums[x][y] before the test:

    num = nums[x][y]
    if previous > num > max_neighbour and not visited[x][y]:
        max_neighbour = num
        max_location = x, y

You notice I also changed your if test, to make a single range test and to replace == False with not. Both make it easier to see what you're actually testing.

Now your code is much simpler, easier to adjust and easier to read:

def get_largest_neighbour(i, j, previous, visited):
    max_location = -1, -1
    max_neighbour = -1
    coordinates = ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1))

    for x, y in coordinates:
        if not 0 <= x < len(nums) or not 0 <= y < len(nums[0]):
            continue

        num = nums[x][y]
        if previous > num > max_neighbour and not visited[x][y]:
            max_neighbour = num
            max_location = x, y

    return max_location


It's a bad practice to reuse a variable for multiple purposes, especially so when the types are different too: selector is first an array and then becomes a string.

Avoid duplication logic in both branches of a conditional like here:

if (flag)
     $('.' + class_id + 'l').filter('[data-id="' + button_id + '"]').hide();
else
     $('.' + class_id + 'l').filter('[data-id="' + button_id + '"]').show();

Extract the dom selector with the filter, store the result in a variable, and in the branches of the if-else do the hide and show.

It's also recommended to use braces always, even with single statement if-else.

It seems to me that some operations could be joined together and done in a single .each, for example here:

$.each(groups, function(k, id) {
  $('#' + id + 'l').children().hide();
});

$.each(groups, function(k, id) {
  $('#' + id + 'l').hide();
});


Your code was better in Rev 1.  I don't know why you changed it.  Whenever you can get away without special cases, it's probably better to do so.

This code is a pure function of the input array and nothing else.  Therefore, it would probably be better as a static function.

Renaming the function from NumberOf… to …Count would make it less verbose.  You should also respect Java naming conventions, in which method names start with a lowercase letter.  The parameter name A also has unconventional capitalization.

As others have said, your algorithm, using TreeSet, is O(n log n).  You would need a HashSet for O(n).  When constructing a HashSet, it's a good idea to provide an estimate of the collection size, since a wrong guess would hurt performance.

public static int distinctItemCount(int[] array) {
    Set<Integer> set = new HashSet<Integer>(array.length);
    for (int i : array) {
        set.add(i);
    }
    return set.size();
}


Extract Duplication

You could extract parts of the duplication to their own method:

private Float someResonableName(Float productPrice, List<RangeValue> values) {
    for (RangeValue value : values) {
        if (productPrice < value.getMinValue()) {
            return value.getMinValue();
        }
        if (value.getRange().contains(productPrice)) {
            return value.getReferPercentFee() / 100 * productPrice;
        }
    }
    return -1;
}

And use it like this:

        if (name.contains(entry.getKey())) {
            Float result = someResonableName(productPrice, entry.getValue());
            if (result != -1) {
                return result;
            }
        }

Use Interface

You could also use an interface:

interface NameKeyRelation {
    boolean isRelation(String name, RangeValue key);
}

Float getPriceContainsCategoryName(BrowseNode node, Float productPrice) {
    return getPriceContainsCategoryName(node, productPrice, (String name, RangeValue key) ->  name.contains(key)));
}

Float getPriceEqualsCategoryName(BrowseNode node, Float productPrice) {
    return getPriceContainsCategoryName(node, productPrice, (String name, RangeValue key) ->  name.equals(key)));
}

Float getPriceCategoryName(BrowseNode node, Float productPrice, NameKeyRelation relation) {
    String name = node.getName();
    for (Entry<String, List<RangeValue>> entry : categoryToFee.entrySet()) {
        if (relation.isRelation(name, entry.getKey())) {
            Float result = someResonableName(productPrice, entry.getValue());
            if (result != -1) {
                return result;
            }
        }
    }
    if (node.getAncestors() == null)
        return 0f;
    return getPriceCategoryName(node.getAncestors().getBrowseNode().get(0), productPrice);
}

Restructure

It seems that your method currently does two things: It finds a category by name, and it calculate/finds some kind of price for a category. I would write two completely separate methods for each tasks, and then try to reduce duplication.


Get module entry by name from external program via WinAPI

Unfortunately, I'm not sure of any way of being more concise.

There are a few changes you could make, but they're mostly optional.

Check the return value of CreateToolhelp32Snapshot(). The documentation says the following:

  Includes all modules of the process specified in th32ProcessID in the
  snapshot. To enumerate the modules, see Module32First. If the function
  fails with ERROR_BAD_LENGTH, retry the function until it succeeds.

I use CreateToolhelp32Snapshot() in an application that runs 24/7 and I know for a fact that I get the ERROR_BAD_LENGTH error here and there. In my case, I cannot afford false negatives, so I have to put this function in a loop. If you are okay with having false-negatives occasionally, then I wouldn't worry too much about it.
I don't know if you're showing us the full code for this function, but you have a memory leak here:

ModuleNameChar = new WCHAR[Chars];

I don't see where you are deleting this buffer. I personally would use an std::vector<WCHAR> as a buffer, give it the correct size, and pass the address of the first element to MultiByteToWideChar().
If you use HANDLEs a lot, consider wrapping them in an RAII container. That way, you don't have to worry about closing them manually. This will also make your code exception-safe if you ever add any functions that can throw (you actually already have one that can throw, the new call).
I noticed you're not calling ::Module32First(). You probably don't need it, but I always have it anyway.
This is a personal preference, but I think your upper-case variable names look absolutely horrendous. Please use snake-case or camel-case for variable names.

There's really nothing helpful to say unfortunately, the Windows API can be quite cumbersome.


It reads file by 4096 chars in hope to find EOL,

local $/ = seteol($fh) // $/;

sub seteol {
    my $fh = shift;

    local $/ = \4096;
    my $line = "";

    while (my $b = <$fh>) {
      $line .= $b;
      last if $line =~ /(\R)/;
    }
    seek($fh,0,0);
    return $1 if $1;

    warn "Unknown EOL";
    return;
}


Length of the longest common sub sequence bottom up

x and y are terrible variable names.  length1 and length2 would be better.

matrix = [[-1]*(x) for val in range (0,y)]

You are not using val in this list comprehension.  Convention is to use _ for throw-away, variables needed for syntax reasons, but not actually used.

0 is the default minimum in range() statements.  If you loop from 0 to some limit, you don't need to mention the 0; you can just use range(y).

You are never reading the -1 value anywhere.  The value is always overwritten by another value before it is read.  To make this clearer, store None instead of -1 in the matrix you are creating.

matrix = [ [None] * x  for _ in range(y) ]

Using i-1 < 0 is an awkward way of writing i == 0.  Similarly, i-1 >= 0 can be written simply as i > 0, or perhaps even i, since non-zero values are "Truthy".

The following is awkward and hard to understand.  6 statements, 4 assignments, two conditionals.  What does it do?  What does it mean?

    val1 = 0
    val2 = 0
    if i-1 >= 0:
      val1 = matrix[i-1][j]
    if j-1 >= 0:
      val2 = matrix[i][j-1]

Python has a x if cond else y trinary operator, which may help simplify and clarify the code.

    val1 = matrix[i-1][j] if i > 0 else 0
    val2 = matrix[i][j-1] if j > 0 else 0

That a lot more concise.  Two statements which look the similar; the differences should be clear, and it should be easier to understand what those differences mean.

  for i in range(y):
    for j in range(x):

      if word1[j] == word2[i]:
        matrix[i][j] = 1
        if i > 0 and j > 0:
          maxtrix[i][j] += matrix[i-1][j-1]

      else:
        val1 = matrix[i-1][j] if i > 0 else 0
        val2 = matrix[i][j-1] if j > 0 else 0
        matrix[i][j] = max(val1, val2)

The statement return matrix[y-1][x-1] returns the last column of the last row.  You don't actually need to know the dimensions of the matrix for this.  Simply return matrix[-1][-1].

After you generate row 1, you no longer need row 0 of the matrix.  After you generate row 2, you no longer need row 1 of the matrix.  After you generate row 3, you no longer need row 2 of the matrix.  This means you could solve the problem in \$O(m)\$ memory, instead of \$O(m*v)\$ memory, by simply maintaining a prev_row and next_row, instead of an entire matrix.


@David Harkness sent my search in the right direction. As it is, the insertion sort portion is only going through one round for each gap, rather than walking up each round, so it's not actually going for more than one round, and most of the sorting isn't done until the gap is 1. When I start fixing problem, it just started getting more convoluted, so I ditched my original approach and followed the pseudocode on wikidepia. Now, it's quite snappy:

var shellSort = function( list ) {
    var gap = Math.floor( list.length / 2 );

    while( gap > 0 ) {
      for( i = gap; i < list.length; i++ ) {
        temp = list[i];
        for( j = i; j >= gap && list[j - gap] > temp; j -= gap ) {
          list[j] = list[j - gap];
        }
        list[j] = temp;
      }

      gap = Math.floor( gap / 2 );
    }

    return list;
  };


Calculate the Fibonacci sequence using bash

What does "Term" mean? I'd prefer to see 5 numbers if the user entered 5.

#!/bin/bash

echo -n 'Term: '
read term

i=0
j=1
for (( c=0; c<term; c++ )) ; do
    (( n=i+j ))
    (( i=j ))
    (( j=n ))
    echo $i
done


I ran through your code, and agree that the output is pretty. I like the idea, and it is a good use-case for a number of exercises. Your code suffers though from a few issues that are awkward.

First up, you have just one real method. Why? You should isolate discrete logic elements in to their own methods. That's the most apparent issue, but we'll get there, but other things get in the way first.

Constants

While we are isolating things, why do you redeclare constant values each time you call paint? Let's take the first chunk of your code:

public class ChasePolygon extends Applet {

    public void paint(Graphics g) {
        final int radius = 200;
        final float velocity = 0.001f;
        final int sides = 6;
        final float theta = (float) (2 * Math.PI / sides);
        final int centerX = 200, centerY = 200;

That should be:

public class ChasePolygon extends Applet {

    private final int radius = 200;
    private final float velocity = 0.001f;
    private final int sides = 6;
    private final float theta = (float) (2 * Math.PI / sides);
    private final int centerX = 200;
    private final int centerY = 200;

    public void paint(Graphics g) {

That's making a bunch of your constants... constants.

Floats

Floats are an awkward value type in Java. You have to keep casting them as floats because the 'natural' floating-point number is a double. I recommend tossing floats out unless you are space-constrained. You are not space constrained, so all your floats should just be doubles. This makes your code a bunch easier to read... for example, lines like:

final float pX = (float) (centerX + radius * Math.cos(i * theta));

become just:

final double pX = centerX + radius * Math.cos(i * theta);

vertices_loc

This ArrayList is a decent concept, but, your code would become a lot easier, and all the 1's and 0's that are scattered though your code would be redundant if you just created two double[] arrays. Consider:

double[] verticesX = new double[sides];
double[] verticesY = new double[sides];

Now you lose your [0] and [1] subscripts for X and Y instead. It is shorter, and even has more meaning. Double-win.

Function Extraction

Right, now it is time for function extraction. First up, extract the polygon draw. We have a trick we can do there too...

Your current polygon draw code is:

GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, sides);
polyline.moveTo(vertices_loc.get(0)[0], vertices_loc.get(0)[1]);
for (int i = 0; i < sides; i++) {
    polyline.lineTo(vertices_loc.get(i)[0], vertices_loc.get(i)[1]);
}
polyline.lineTo(vertices_loc.get(0)[0], vertices_loc.get(0)[1]);
g2.draw(polyline);

Note how you start at (moveTo) vertix 0, and your first line draws to (lineTo) vertix 0? You essentially start with a 0-length line, and then you have to fix that with a post-loop line-to vertix 0.

A neater solution would be to just start at the last vertex, and then go from there to the first.... But, put that in a function too. Using my suggestion for the verticesX and verticesY, it becomes (note the sides - 1 moveTo):

private void paintPolygon(Graphics2D g2, double[] verticesX, double[] verticesY) {
    GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, sides);
    polyline.moveTo(verticesX[sides - 1], verticesY[sides - 1]);
    for (int i = 0; i < sides; i++) {
        polyline.lineTo(verticesX[i], verticesY[i]);
    }
    g2.draw(polyline);
}

Spirals

The final functional extraction comes from the spiral paths. These should be extracted. Again, using an actual array makes it easier than using an ArrayList. Additionally, the final print loop would be better as a for-each loop. That final method becomes:

private void paintCurves(Graphics2D g2, double[] verticesX, double[] verticesY) {
    GeneralPath[] g_p = new GeneralPath[sides];
    for (int i = 0; i < sides; i++) {
        g_p[i] = new GeneralPath(GeneralPath.WIND_EVEN_ODD, delta_T);
        g_p[i].moveTo(verticesX[i], verticesY[i]);
    }
    for (int i = 0; i < delta_T; i++) {

        for (int j = 0; j < sides; j++) {
            double dX = verticesX[(j + 1) % sides] - verticesX[j];
            double dY = verticesY[(j + 1) % sides] - verticesY[j];
            verticesX[j] += dX * velocity;
            verticesY[j] += dY * velocity;
            g_p[j].lineTo(verticesX[j], verticesY[j]);
        }
    }
    for (GeneralPath gp : g_p) {
        g2.draw(gp);
    }
}

Constant vertices.

Finally, after simplifying things, it became apparent that the initial vertices are constant, and you then overwrite them as you spiral in. This makes it simpler to calculate the vertices once, use those for the polygon, and then use a copy for the spirals. The final paint method is just:

public void paint(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;
    paintPolygon(g2);
    paintCurves(g2, Arrays.copyOf(verticesX, sides), Arrays.copyOf(verticesY, sides));

}

Clean version

All told, I would go with the following:

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;
import java.util.Arrays;

public class ChasePolygon extends Applet {

    private final int radius = 200;
    private final double velocity = 0.001;
    private final int sides = 7;
    private final double theta = 2.0 * Math.PI / sides;
    private final int centerX = 200;
    private final int centerY = 200;
    private final int delta_T;
    private final double[] verticesX = new double[sides];
    private final double[] verticesY = new double[sides];

    public ChasePolygon() {
        delta_T = (int) Math.floor(radius * Math.sin(theta / 2) / velocity);
        for (int i = 0; i < sides; i++) {
            verticesX[i] = centerX + radius * Math.cos(i * theta);
            verticesY[i] = centerY + radius * Math.sin(i * theta);
        }

    }

    public void paint(Graphics g) {

        Graphics2D g2 = (Graphics2D) g;
        paintPolygon(g2);
        paintCurves(g2, Arrays.copyOf(verticesX, sides), Arrays.copyOf(verticesY, sides));

    }

    private void paintCurves(Graphics2D g2, double[] vertX, double[] vertY) {
        GeneralPath[] g_p = new GeneralPath[sides];
        for (int i = 0; i < sides; i++) {
            g_p[i] = new GeneralPath(GeneralPath.WIND_EVEN_ODD, delta_T);
            g_p[i].moveTo(vertX[i], vertY[i]);
        }
        for (int i = 0; i < delta_T; i++) {

            for (int j = 0; j < sides; j++) {
                double dX = vertX[(j + 1) % sides] - vertX[j];
                double dY = vertY[(j + 1) % sides] - vertY[j];
                vertX[j] += dX * velocity;
                vertY[j] += dY * velocity;
                g_p[j].lineTo(vertX[j], vertY[j]);
            }
        }
        for (GeneralPath gp : g_p) {
            g2.draw(gp);
        }
    }

    private void paintPolygon(Graphics2D g2) {
        GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, sides);
        polyline.moveTo(verticesX[sides - 1], verticesY[sides - 1]);
        for (int i = 0; i < sides; i++) {
            polyline.lineTo(verticesX[i], verticesY[i]);
        }
        g2.draw(polyline);
    }

}


It is very confusing to set a property just to discover that it returns something else just after you set it. Properties are supposed to keep the value you give them. (At least logically)

And since your SkipSomeStuff property is public, you have no guarantee you won't access that property by accident before the intended recipient accesses it, and the stuff isn't skipped after all.

How about keeping the skipSomeStuff member, but set it using a method called SkipStuffNextTime() or something like that? Nobody will misunderstand the intent of your code that way, and only the code it's relevant for will access and reset it.

private bool skipSomeStuff = false;

public void SkipStuffNextTime() {
    skipSomeStuff = true;
}

public void DoSomeStuff() {
    if (skipSomeStuff) {
        skipSomeStuff = false;
        return;
    }
    // do the stuff
}


An Awk program to find all primes till N

Bug: when I run the program with argument 1, it prints 2 even though 2 > 1.

The code is not optimized at all. It computes ceil and sqrt way too often, in a way that is obvious to optimize. All other prime programs on this site already do that, have a look at them.

The code is not optimized enough. It contains i = i + 2, which should have been i += 2 from the beginning. A third of these calls can be omitted using the standard prime searching technique that has been mentioned more than enough on this site.

The variable name flag is terrible. It should be is_prime instead.

Having the most interesting code in the BEGIN block is bad design. You should define a function is_prime and another function print_primes_up_to. This allows you to declare i and j as local variables.

In the function ceil, the parameter name n is confusing since this name implies to the human reader that it is a natural number. In reality it is a floating point number though. A better name for this variable is x.

The code is missing some documentation. It should clearly state up to which number it reports correct results. It should also state the first number for which a wrong result is printed. Internally, many AWK implementations use 64-bit floating point numbers, therefore I guess this number is somewhere around \$2^{53}\$.


Random item generation system to be used in a roguelike

This isn't bad code for someone learning the language, but there are a few things I'd change:

At the top you have:

i_quality = ["Good", "Bad"]
i_quality = random.choice(i_quality)

And other such lines. The main problem here is you're overwriting i_quality. What if you wanted to generate a second quality later? You overwrote your master list of qualities. Have them as separate variables:

all_qualities = ["Good", "Bad"]
all_bases = ["Sword", "Gun"]
all_elements = ["Fire", "Water"]

i_quality = random.choice(all_qualities)
i_base = random.choice(all_bases)
i_element = random.choice(all_elements)

Be careful how you name things and what the responsibilities of functions are. create_Item does create an Item, but it also prints it out then discards it. Such a function isn't very useful. The caller could have just called the Item constructor themselves and then printed the object if they wanted to. Your function does some formatting, but that would be better off in the __str__ method of Item.

What would make for a useful factory function though would be a create_random_item function that returns a random Item. Taking all that together, I'd change this code to something closer to:

import random

all_qualities = ["Good", "Bad"]
all_bases = ["Sword", "Gun"]
all_elements = ["Fire", "Water"]

class Item(object):
    def __init__ (self, quality, base, element):
        self.quality = quality
        self.base = base
        self.element = element

    # What Python will call when you ask it to
    #  display an Item using str
    def __str__(self):
        return self.quality + " " + self.base + " of " + self.element

def create_random_item():
    quality = random.choice(all_qualities)
    base = random.choice(all_bases)
    element = random.choice(all_elements)

    return Item(quality, base, element)

for _ in range(10): # We'll create 10 random weapons and print them out
    item = create_random_item()
    print(str(item)) # str calls item's __str__

Good Gun of Fire
Good Sword of Fire
Bad Sword of Water
Good Sword of Fire
Good Sword of Water
Good Sword of Fire
Bad Gun of Water
Bad Sword of Water
Bad Gun of Water
Bad Sword of Water

This could be further improved though. Any time you have a closed set of members of a set (like how "fire" and "water" are members of the "elements" set), you should likely being using an Enum. They help avoid errors in many cases, and allow IDEs to assist you in auto-completing names.
In __str__, you could also make use of f-strings to avoid needing to manually concat using +. It would be neater to write:

def __str__(self):
    return f"{self.quality} {self.base} of {self.element}"

That allows for much less noise and allows you to focus more on what you what printed, and less on dealing with opening and closing quotes and +s.
For the sake of context, create_random_item may make more sense as a static method. It makes it clearer what class it's associated with, since then you'd call the method as:

Item.create_random_item()


Write a wrapper to REST API with asyncio

Calling aiohttp.ClientSession in _post and _get is really bad. Don't do this.
There is no main function, this just makes the code harder to convert into a setuptools application.
All these functools.partial only hinder readability rather than enhance it.

Just make a class.
The code isn't very functional. And I can only imagine what a purist would have to say about _send_weather. There are so many side effects in one little, hard to read, function.
There is no separation of concerns, _find_city and _city_weather are solely around getting a forecast, whilst _notify is sending a notification. You've mangled them into one _send_weather function. Not great.
Since the code isn't functional, and this is possibly the worst project to learn functional programming on. Let's just make it so that the code is easy to read.

Make a WeatherForecast class.

At instantiation, it only takes a session.
This is so we can remove all those partials with self.get.
Include get into this class, however without the session creation part.
Include find_city as find_cities, and don't mutate the output.
Include city_weather.
Change send_weather to get_weather and delegate calls to find_city and city_weather.

It is not allowed to print here. All it does is get the weather for the wanted city.

This is a helper function and so mutates the values to get the two other functions to work and to get the output as we desire. Nothing else.

Remove the session creation part from post.
Make a function notify_user that notifies the user of city's weather.

This is as simple as using two f-strings, to build the URL and the message.
Change _send_weather so that it takes a session, city, and user.

To make the function easy to read, we are limited to three things in the function.

Calling another function.
Performing a simple if else to control data flow.
Formatting output to the user - basic f-strings.

Here's how I performed the above. Which is as functional as your code. And you could argue that my functions are more pure than yours, as get_weather only gets weather. notify_user notifies the user. And send_weather only prints and delegates to other impure functions. None of them are pure and can't be because they all have side effects. Which pretty much makes implementing this in 'pure FP' a joke.

import asyncio
from functools import partial

import aiohttp

SUCCESSFUL_PUSH = {'deleted': True}  # Value specific to fake push service

class WeatherForecast:
    def __init__(self, session):
        self.session = session

    async def get(self, headers, url):
        async with self.session.get(url, verify_ssl=False) as response:
            return await response.json()

    async def find_cities(self, city):
        return await self.get(f"https://www.metaweather.com/api/location/search?query={city}")

    async def city_weather(self, city_id):
        return await self.get(f"https://www.metaweather.com/api/location/{city_id}")

    async def get_weather(self, city_name):
        cities = await self.find_city(city_name)
        if not cities:
            return None
        forecast = await self.city_weather(cities[0]["woeid"])
        return forecast["consolidated_weather"][0]["weather_state_name"]

async def post(session, url, data):
    async with session.post(url, json=data, verify_ssl=False) as response:
        return await response.json()

def notify_user(session, city, weather, user):
    return await post(
        session,
        f"https://api.keen.io/dev/null?user={user}",
        {"message": f"Current weather in {city}: {weather}"},
    )

def send_weather(session, city, user):
    weather = await WeatherForecast(session).get_weather(city)
    if weather is None:
        print("Could not get forecast")
    else:
        reply = notify_user(session, city, weather, user)
        if reply == SUCCESSFUL_PUSH:
            print(f"Current weather in {city}: {weather}")
        else:
            print(f"Push notification to {user} failed: {reply}")

async def main():
    headers = {"Content-Type": "application/json"}
    async with aiohttp.ClientSession(headers=headers) as session:
        send_weather(session, "Glasgow", "Bob")

if __name__ == "__main__":
    asyncio.run(main())


Split a string and write the i-th element into a buffer with C

Before we talk about improving the efficiency of your function, lets talk about safety:

You never check the validity of your function parameters.
You have no way of knowing how big buff is.

For the first issue, if str or delim is null, passing them directly in to strstr will cause a segfault and crash your program.
The second issue is worse: if buff is smaller then str, your function may end up clobbering memory when it tries to copy from str to buff.
This is undefined behavior, and the results are unpredictable.
Now for some efficiency suggestions:

Calculate string length only once.
Since strlen works by running over the string looking for '\0' terminator, it is more efficient to call it only once at the beginning of your function and store the result in a variable.
This can also allow you to implement a simple shortcut for edge cases such as where str or delimiter are empty strings, or delimiter is longer then str.

You don't need your own while loop at the end and the buff_i variable.
You can simply use memcpy or strncpy to copy the element in to the buffer.
memcpy would be slightly more efficient, since it does not check for '\0', while strncpy does.

Since your logic is that if delimiter is never found, but the requested element is 0 the result is "success", you don't need to handle this as a separate edge case.
That means you can get rid of the first if block, and handle everything in one loop.
You can also get rid of the special checks in the if loop and just focus on the search.

The following code example does not include the suggested validity checks:
int i;
char *start = str;
char *end = start;
size_t delim_len = strlen(delim);
size_t copy_len;

for (i = 0; i <= index && end != NULL; i++) {
    end = strstr(start, delim);
    if (end != NULL && i != index) start = end + delim_len;
}

/* element not found */
if (i != index) return index;

if (end == NULL) {
    copy_len = strlen(start);
} else {
    copy_len = (ssize_t)(end - start);
}

memcpy(buff, start, copy_len);
buff[copy_len] = '\0';

return 0;


Your data needs to be more

ATOMIC AND HOMOGENEOUS

This table

create table StudentGradeReport
(
    StudentGradeReportId int primary key identity(1,1),
    StudentInstanceId int foreign key references StudentInstance(StudentInstanceId),
    SubjectId int foreign key references Subject(SubjectId),
    FirstTrimester int,
    SecondTrimester int,
    ThirdTrimester int,
    FinalGrade int
)

doesn't look right to me.

I think that you want something more like this

CREATE TABLE StudentGradeReport
(
    TableID INT PRIMARY KEY IDENTITY(1,1),
    StudentInstanceID INT FOREIGN KEY REFERENCES, StudentInstance(StudentInstanceID),
    SubjectID INT FOREIGN KEY REFERENCES Subject(SubjectID)
    Term NVARCH(2), -- this will tell us T1, T2, T3 or F
    SchoolYear INT,
    UpdateDate DATETIME,
    UserChangeID INT NOT NULL
)
-- the UserChangeID would be a foreign key to the Staff table(or User Table),
-- assuming they are the only people that can change these things.
-- this way you can keep track of who is changing things.

This seems like the right way to create this table.

You want your data to be atomic in all of your tables, but not redundant.

In your version of this table you had redundant data, you would fill in FirstTrimester with a 1 (true) and then the other 3 with a 0 (false) that is very redundant.

The data that would go into that table would have to be updated or overwritten if they wanted to change something or there was a mistake.  This isn't good for keeping track of changes.  In the table that I gave you have the ability to add a new row of data and then keeping track of who made the change, this way you can keep track of who changed what and when.

Having your data in the table that I provided it is going to be a whole lot easier to pull reports from. you can pull data from

a specific student
a specific subject
a Specific school year
a range of school years
all changes made by a specific user

I hope that looking at my answer helps you to see how the rest of your tables need to be more ATOMIC.