Overall the existence of this code does not seem justified. It seems like boiler paste that doesn't offer a whole lot of new functionality, and people are better off calling requests directly.

It also doesn't make sense as a class. There's enough static content that it should be a module, not a class. It's good that you're thinking about factoring the fallback feature into a common module, but you need to take a different approach.

One thing you can do is make a subclass of requests.Session, but even that doesn't really seem necessary. Things to avoid:

Don't add logging for stuff that's already logged by requests.
Pass args and kwargs implicitly instead of explicitly copying stuff.
Explicitly pass is_fallback instead of passing it implicitly in kwargs.
Just return the response. Don't convert it to JSON. It's like seven more characters at the calling side, and simplifies everything.
Don't rename request to invoke. Just call it request.
Don't rename url to endpoint. Just call it url.
Don't rename json to json_data. Don't even pass it explicitly. It's quite simple to pass it as json in the kwargs.
Don't set the content type as you are. When requests sees the json kwarg it will do this for you.

In my opinion, at the absolute most, you should condense this to one utility method:

import logging
import requests

def request(method, url, is_fallback=False, **kwargs):
    response = requests.request(method, url, **kwargs)
    if is_fallback and response.status_code == 405:
        logging.debug('%s action failed, applying fallback strategy', method)
        return requests.request(method, url, **kwargs)
    return response

Anything else is unnecessary boilerplate.


Global variables

one major suggestion - don't (over)use global variables, it's generally not a good practice and it will make more difficult to test the code. For example if you'd like to add a functionality for downloading multiple items at the same time you'll have a hard time with it.

So instead of this:
def av_select():
    global av_switch # this function is setting value for this variable

def Main():
    global av_switch # this function is reading this variable
    av_select()

do this:
def av_select():
    while True:
        av_switch = input('Please enter \'1\' for Video and \'2\' for Audio\n')
        if av_switch not in ('1', '2'):
            print('Please make a valid selection')
            continue
        return av_switch # add return statement with the value

def Main():
    av_switch = av_select() # use the value returned from function
    if av_switch == '1':

same applies to other global variables.
Python coding guidelines

follow PEP 8 guidelines, in this case the name of the function Main is violating it - function names should be lowercase.

recommended way how to do code comments is to use docstrings. Instead of this:

#Define Download location
def download_location():

do this:
def download_location():
   """define download location"""

this way the comment can be accessed as download_location.__doc__ and a lot of tools (eg. for generating documentation) can work with it.
Code flow

the following one is probably a matter of taste, but it feels like you're overusing while True: loops in places where you can rely on other variables you are "waiting" for. For example av_select() - I'd use the aw_switch variable as a condition of the loop this way:

def av_select():
    av_switch = None
    while av_switch not in ('1', '2'):
        av_switch = input('Please enter \'1\' for Video and \'2\' for Audio\n')

    # outside the while loop, av_switch finally matches '1' or '2'
    return av_switch


It looks pretty good to me.

Generally, generator expressions and list comprehensions are preferred to map() in Python.  I'd write sum(values[c] for c in word).  Using c for "character" would be preferable to x, which has a connotation of being a floating-point number.

If you are practicing functional programming, then there is no sense in including "get" in the name, as every function should be a deterministic calculation based on its parameters.  By PEP 8, word_score would be a more appropriate name for the function.  Also, I suggest defaulting n=7, as that is the size of a full Scrabble hand.


Loop through string array with exit if test passed

Join the string to create a jQuery selector

var elementTypes = ['btn', 'textbox', 'ui-jqgrid', 'flexboxdiv', 'headerlabel'];
var selector = '.' + elementTypes.join(', .');

return $('.TestModule').first().find(selector).length > 0;

The variable selector will return the string '.btn, .textbox, .ui-jqgrid, .flexboxdiv, .headerlabel' which can be used in the jQuery selector.

The statement

return $('.TestModule').first().find(selector).length > 0;

is equivalent to

return $('.TestModule').first().find('.btn, .textbox, .ui-jqgrid, .flexboxdiv, .headerlabel').length > 0;

after the string substitution.

To make it more dynamic, store complete selector in the array and join the array by ,-comma.

var elementTypes = ['.btn', '.textbox', '.ui-jqgrid', '.flexboxdiv', '.headerlabel', '#myId', 'input', 'input[name="firstname"]'];
var selector = elementTypes.join(', ');


Let's start with the easy one:

. - hello - You need to understand that hello refers to an address. And that . refers to the "current" address. So . - hello is the distance between the current location and hello; effectively the length of hello.

Just one of those tricks you learn.  While you could manually put the length into len, there's always the chance that someday someone would change the contents of hello, and forget to change len.  Done this way, it's self-maintaining. Being able to compute this at 'assembly time' rather than counting bytes during run time is also a bonus.

As for the code itself, let me start with the main point: Comments.

Assembly can be tricky to code correctly, and sometimes is even harder to maintain.  Especially when you can't figure out what #@%! the guy who was writing it was trying to do.

I realize that this is just a beginner's project.  But you should acquire the habit of commenting early:

Comments at the top of the code telling the purpose of the file.
Comments at the top of routines (and macros) telling what they do.
Comments at the end of individual statements describing the intent.

As an example:

    exit $0 ; Exit the application with return code 0

While to a veteran assembly programmer this comment may seem obvious, to a beginner (and everyone is a beginner at some point), it makes the intent significantly clearer.  Just a few words of text can take a screen full of numbers and symbols and provide clarity.  Maintainers of your code (as well as your future self) will thank you.

Next (in no particular order) I would look at this section of code:

mov $1, %esi
l:
  write $hello, $len
  inc %esi
  cmp $10, %esi
  jle l

As I'm sure you are aware, the purpose of the cmp instruction is to set the flags so that you can use conditional instructions like jle.  However, there are other instructions that adjust those same flags.  For example, dec:

mov $10, %esi
l:
  write $hello, $len
  dec %esi
  jnz l

Nothing magical, but it does save an instruction.

Next we've got

  Wouldn't it be better to use the %rax registers and syscall instead of int $0x80?

It absolutely would be better to use syscall.  IF you were programming for 64bit.  int 0x80 is correct for 32bit.  And when I say 32/64bit, I'm referring to whether the application is 32 bit or 64bit, not the OS you are running on.

Note: The function number (and where each of the arguments go) are different between int 0x80 and syscall.


A command-line utility to solve a system of linear equations

List comprehensions

List comprehensions are a cool feature that could shorten your code, at many places.
For example instead of this:

    values = []
    for item in X:
        values.append(Fraction(item[0, 0]).limit_denominator())

You can write like this:

    values = [Fraction(item[0, 0]).limit_denominator() for item in X]

Another example:

    vars = []
    for i in range(0, len):
        vars.append(raw_input())

Better this way:

    vars = [raw_input() for _ in range(len)]

There are some more tips in there:

range(len) is equivalent to range(0, len)
When you don't use the loop variable in the loop body, the convention is to name the loop variable _

There are other places in your code that you could shorten using list comprehensions, I suggest to rewrite them all.

Magic values

The number 23 is a magic value here:

    # x is the 24th alphabet
    start = 23 if len <= 3 else 0

Although the comment explains it, it would be better to put the value in a constant with a name that describes its purpose.
And instead of the hard-coded number, I suggest to express it in a programmatic way, for example:

POS_X = ord('x') - ord('a')

When written this way, we don't even have to know what the value really is (23), the important thing is its relative position from the letter 'a'.

Code duplication

The solve calls are duplicated here, except for the 3rd parameter:

    if varlist is None:
        answer = solve(A, B, vars(rows))
    else:
        answer = solve(A, B, list(varlist))
    print_answer(answer)

It would be better to reorganize the code to eliminate such duplication:

    if varlist is None:
        varlist = vars(rows)

    answer = solve(A, B, varlist)
    print_answer(answer)

Of course, in your current implementation varlist is not really a list.
It would be better to fix that, and make it a list when you assign it earlier, for example:

elif num == 4:
    script, a, symbols, b = argv
    varlist = list(symbols)


Pivot some rows to new columns in DataFrame

groupby

When iterating over the values in a column, it is bad practice to hardcode the values (for pivot in [1, 2, 3]). A better way would have been for pivot in df["dof"].unique(), but the best way is with DataFrame.groupby

To see what happens in the groupby, I try it first with an iteration, and printing the groups

for pivot, data in df.groupby("dof"):
    print(pivot)
    print(data)

Then I get to work with one of the data to mold it the way I want. In this case, we don't need the column dof any more, since we have it in the pivot variable, and we rename the columns using rename

for pivot, data in df.groupby("dof"):
    print(pivot)
    print(
        data.drop(columns="dof").rename(
            mapper={
                column_name: f"{column_name}{pivot}"
                for column_name in data.columns
            },
            axis=1,
        )
    )

Then we can use pd.concat to stitch it together

pd.concat(
    [
        data.drop(columns="dof").rename(
            mapper={
                column_name: f"{column_name}{pivot}"
                for column_name in data.columns
            },
            axis=1,
        )
        for pivot, data in df.groupby("dof")
    ],
    axis=1,
)

unstack

An alternative is with unstack:

From you description, dof is part of the index, so add it there. Then you can use DataFrame.unstack to bring it to the columns.

df2 = df.set_index("dof", append=True).unstack("dof")

        foo foo foo bar bar bar qux qux qux
dof     1   2   3   1   2   3   1   2   3
idxA idxB
100 101 10  11  12  30  31  32  50  51  52
100 102 13  14  15  33  34  35  53  54  55
200 101 16  17  18  36  37  38  56  57  58
200 102 19  20  21  39  40  41  59  60  61

If you are okay with a MultiIndex, which will be handier then the concatenated strings in most cases, you can leave it at that. If you want it in the form you have it, you can do df2.columns = df2.columns.map(lambda x: f"{x[0]}{x[1]}").


mie isn't a good variable name. usesIE would be better, or well.. something like that!

Why is mouseX and mouseY defined outside your method's scope? They're useless there.

I don't think keeping variable at the root of the script is a good practice. Why don't you wrap it inside a window.onload call?

The only comment in your code seems useless. You do not use document.write anywhere in your code.

Also, when you have the choice, your conditions should be positive. It's just a little easier to read.

I don't see the use of returning true in a case like that. It means nothing.

Finally, I think that it'd be better to pass the usesIE parameter to the mousePos function. By the way, mousePos should be renamed writeMousePosition.

This is what the final code would look like :

function writeMousePosition(args,usesIE) {
    var mouseX = 0;
    var mouseY = 0;

    if(usesIE) {
        mouseX = args.clientX + document.body.scrollLeft;
        mouseY = args.clientY + document.body.scrollRight;
    } else {
        mouseX = args.pageX;
        mouseY = args.pageY;
    }

    document.body.innerHTML += "X: " + mouseX + ";Y: " + mouseY + ";  Time: " + new Date() + "<br>";
}

window.onload = function() {
    var usesIE = (navigator.appName == "Microsoft Internet Explorer") ? true : false;

    if(!usesIE) {
        document.captureEvents(Event.MOUSEMOVE);
    }

    document.onmousemove = function(args) {
        writeMousePosition(args, usesIE);
    };
};


Merge array of hashes, keeping duplicate values as arrays

I think the refactor is barely readable, the first version is better. Anyway, if you use functional abstractions, instead of doing a imperative processing from scratch, algorithms tend to be more clear.

In this case, we can use the abstraction Enumerable#map_by (a group_by variation where you can control both the grouping function and the accumulated values) and write:

require 'facets'

class Array
  def merge_hashes
    flat_map(&:to_a).map_by { |k, v| [k, v] }
  end
end

Note that this snippet always returns an array as a value, instead of the scalar/list you have.


Encryption scripts using the module cryptography

The good news is that as far as I can tell, the cryptography is correct (password-based key derivation function, random salt). The bad news is that your code is hard to read, and so it's hard to make sure that it's correct.

Please read PEP 8. It's good advice. The first thing one sees is 62 lines and not a single blank line. Use blank lines between function definitions. And on a related note, use auxiliary functions with a clearly-defined task. Avoid very long lines (80 columns maximum is a good idea), and break up long chains like Fernet(base64.urlsafe_b64encode(kdf.derive(getpass.getpass("Password to use: ").encode()))).encrypt(script.encode())) into manageable pieces. Because the code is hard to read, don't expect a complete review.

def exitmsg(msg):
    print(msg)
    input("Press ENTER to exit")
    sys.exit()

Don't require the user to press a key to exit the program. And don't print anything when you don't have anything to say. Standard output is for program output and standard error is for useful messages. This function doesn't do anything useful. Replace exitmsg(msg) by sys.exit().

    def input(string):

Don't override standard functions.

    exitmsg("cryptography not installed install it with pip install cryptography via cmd or powershell (On Windows)")

punctuation is important your message is incomprehensible language is not just a bunch of words thrown together

        exitmsg("Wrong password (-:")

Print error messages to standard error, not standard output. And when there's an error, exit with a nonzero status.

loc = input("Script to use: ")

Don't read script arguments from standard input. Read them from sys.argv. That's what it's for.

try:
    exec(…)
except Exception as ex:
    if(type(ex).__name__ == "InvalidToken"):
        exitmsg("Wrong password (-:")
    print(ex)

You're reporting a “wrong password” error for a certain class of errors. It's not clear to me what you're trying to do with InvalidToken. Rather than hope that the wrong key will result in a particular kind of parse error, start the ciphertext with a known value and check that known value. Since you know that the ciphertext is Python code, start the ciphertext wih a Python comment line.

plaintext = fernet.decrypt(ciphertext)
if not ciphertext.startswith('# OfficialNoob PasswordScriptLocker ciphertext version 000000001\n'):
    raise IncorrectPassword

And once again, error messages go on standard error, and the script must exit with a nonzero status on error.

Of course the whole thing is pretty pointless. Entering a password on each use of the script would be annoying. Using gpg to decrypt the script once and for all would be more flexible (you can use keys instead of a password), more convenient, and more secure (less risk of implementation errors).


private def getToken(): Option[Token] = {
  def remoteToken =
    getTokenRemote() map { r => writeTokenToDb(r); r }
  getTokenFromDb orElse remoteToken
}

Please write always the type of a function for outer functions - it makes it far more readable to understand the source code (often it is useful to add the types to inner functions/declarations as well).

Beside from that you can also write case t: Some => t or case t @ Some(_) => t to express that you return the matched type. Your way of case Some(x) => token is hard to understand, because one needs to know what's token.

Furthermore, you don't need braces around a match block, you can simply write

case x =>
  a
  b

And naming a variable in a similar way as a function, like in val token = getToken() is completely unnecessary, when it is only used once, it also doesn't increase readability. In such cases just inline the function call: getToken match { ... }.


I believe you can shorten it to just

function testAsync() {
    var files = ['Statistics_Schema.json', 'seriesData'];
    async.map(files, fs.readFile, function (err, data) {
        for(var i = 0, l = data.length ; i < l ; i++) {
            console.log( data[i].toString() );
        }
    });
}

Right now, you're first calling fs.stat on each file, only so you can create a buffer in your fileread method.

But fs.readFile does not take a buffer argument. It takes an options object (and there's no buffer option).

The Buffer object you're passing is an object, though, so Node doesn't complain. It just doesn't find any relevant fileRead options in that object either, so it's basically ignored.

So you don't need the buffer, which means you don't need fs.stat, which means you can skip almost all of your code.


A scalable way to remove duplicates from Arrays without extensions in Swift 4

Your algorithm is O(n^2) so not very scalable... The immediate improvement I can think of is to use a Set for results (which means making T Hashable).

If you aren't worried about position, then just create a Set from an array and you are done.


Program to convert number from any base to decimal

PEP-8
The Style Guide for Python Code has many recommendations for the formatting of Python code that all developers should (must!) follow.  These include

single blank space around binary operators, eg negative_flag = False, not negative_flag=False
no blanks after ( or before ), eg print(number_holder * -1) not print( number_holder*-1 )

Useless code
int(number) can only ever return an int, or raise an exception.  There are no other possibilities.  So if no exception is raised, the if condition will always be true, making the if statement an unnecessary control structure:
try:
    if type(int(number)) == int:
        ...
except:
    ...

Similarly you only exit this loop if response == 'n' or response == 'y'
while True:
    response = input("Do you want to continue?(y or n) - ")
    if response=='n' or response=='y':
        break
    else:
        print("Wrong input")
        continue

So why test both possibilities?
if response == 'n': # Conditions for only two valid answer.
    break
elif response == 'y':
    continue

From the comment, it seems you have already realized this.  So why elif response == 'y':?  Why not simple else:?
Finally, every last one of the continue statements is used as the last statement in a control structure, in a loop.  Without the continue statement, the loop would be restarting anyway, so these can all be omitted.
Only catch the exceptions you expect
Consider this code:
while True:
    number = input("Enter a number : ")
    try:
        if type(int(number)) == int:
            break
    except:
         print("Wrong input. Only integers are allowed.")
         continue

Try pressing Control-C at the input prompt to quit the program.  Whoops!  Why isn't the program terminating?  Because Control-C raises the KeyboardInterrupt exception, which you catch, display an inappropriate error messages, and then loop back for another try.  How unexpected.
You want to catch ValueError exceptions, only.
while True:
    try:
        number = int(input("Enter a number: "))
        break
    except ValueError:
        print("Wrong input.  Only integers are allowed.")

Note the absence of useless if statements and continue statements.
Any Base?
Your program is supposed to convert from "any base" to decimal.  But really, you only allow base 2 through base 10 input.  You don't allow FF to be converted from base 16 to base 10.
To Base 10
You've got a lot of code to convert a number to base 10.  This functionality is built-in to Python.  If your intention is not reinventing-the-wheel, you should use the int(x, base=10) function.
Reworked Code
while True:

    number = input("Enter a number: ")

    while True:
        try:
            base = int(input("Enter the base the number is in: "))
            if base >= 2:
                break
            print("Base should be greater than or equal to 2")
        except ValueError:
            print("Wrong input.  Only integers are allowed")

    try:
        print(int(number, base))
    except ValueError:
        print(f"Unable to convert {number!r} to base {base}")

    while True:
        response = input("Do you want to continue? (y or n): ")
        if response in {'y', 'n'}:
            break
        print("Wrong input")

    if response == 'n':
        break

Or super condensed:
print("Press Control-C to stop.")
while True:
    try:
        print(int(input("Number: "), int(input("Base: "))))
    except ValueError as err:
        print("Invalid input:", err)
    except KeyboardInterrupt:
        print("Conversions to base-10 complete.")
        break


String formatting for uint64_t that represents a fixed-point decimal

std::string uint64_to_string(uint64_t n) {

Make interfaces easy to use correctly and hard to use incorrectly.

The function name is confusing as it would lead me to believe that if I called uint64_to_string(1ull), I would expect a returned value of "1".

From your problem statement:

  My goal is to take a uint64_t that represents a fixed-point decimal

Instead of using a built-in integer type, leverage the type system by using a fixed-point decimal class.

Ensure you are using <cstdint> and prefix the namespace on the integral type std::uint64_t.

Avoid magic numbers. If 8 is supposed to represent a fixed radix point, you should document that by assigning it to a descriptive variable name.  If you use a fixed-point decimal class, you could just refer to its radix point instead.

  How can I make the following code cleaner and/or faster? Obviously all the character insertions/deletions are very slow, but what's the best way to get rid of those?

If you've measured and multiple allocations are slowing you down, calculate the string length of your result first, then fill it with the characters.  I highly recommend you watch Andrei Alexandrescu's Fastware talk he's been giving for the past few years.  He covers this exact topic of converting integers to strings using specific optimization techniques.


to_day_of_week can be heavily simplified by using match instead of if-else:

fn to_day_of_week(input: &str) -> Option<usize> {
    match input {
        "mon" => Some(0),
        "tues" => Some(1),
        "wed" => Some(2),
        "thurs" => Some(3),
        "fri" => Some(4),
        "sat" => Some(5),
        "sun" => Some(6),
        _ => None,
    }
}

The bulkiness of your code can be somewhat helped if you provide additional functions and use ? instead of unwrap. Using unwrap is discouraged, as far as I know. If you don't want to use ? or additional functions, early returns prevent your code from getting too much indented.


If you are using GCC, we can use the typeof()(C99) keyword to get rid of one of the arguments.  Also, add a do-while so the macro to be used in contexts where it would otherwise be problematic.

#define SWAP(a, b) do { typeof(a) t; t = a; a = b; b = t; } while(0)

You could also use an exclusive-or (^=) to get rid of that temporary variable, but that only works for integers.

#define SWAP(a, b) do { a ^= b; b ^= a; a ^= b; } while(0)


Formatting

Your spacing is inconsistent, which makes the code harder to read. By the original conventions released with the language, =, ==, and < should have a whitespace character on either side. Whatever you choose, make it consistent.

Implementation

Your System.out.println is for debugging and should be removed.

Use Arrays.fill() to populate your array.

Declaring len makes the code harder to read. Just refer to the length in your for loop.

As @Marc-Andre said, prefer a Deque to a Stack. And use generics.

Don't do if (foo == false). Use if (!foo).

I'm in the minority, but I prefer explicit boxing rather than autoboxing for clarity.

Don't use abbreviations for variable names. The extra characters enhance readability and cost nothing.

If it's in your control, for a non-weighted graph the adjacency matrix should probably be a boolean[][], not an int[][]. If this is a weighted graph, checking if the value == 1 is almost certainly a bug.

Correctness

You detect a cycle in this graph: { { 0, 1 }, { 1, 0 } }. Is it really a cycle if any two nodes are adjacent to each other? Is this an unweighted directed graph?

You also detect a cycle in this graph: { { 0, 1 }, { 0, 0 } }. Surely that is not correct. Please test before posting. CodeReview is for reviewing working code, not fixing broken code.


The current code has a bug when the limit is exactly is exactly the length of a word. For example,

trim('Hello World', 5)

will return an empty string, when it should return "Hello", since it is of length 5, therefore it fits in the length limit.

The issue stems from the loop over i going from 0 to limit - 1 (excluded). The variable end represents the index of the last character to keep in the string, (because the method is returning text.substring(0, end + 1)). Therefore, it could be the case that end is equal to limit - 1, this happens when the limit falls right before a space. For example, when the limit is 5, and the string is 'Hello World', the last character to keep is 'o' at index 4. So the loop should go up to limit (excluded).

Then, there are slight adjustements to make:

The early-return testing text.length < limit should be text.length <= limit (because otherwise the next character in the loop over i won't exist for the last character of the string);
The added check if (i === text.length - 1) can safely be removed as a consequence: the only case where i would be equal to text.length - 1 is if limit == text.length (since i goes up to limit - 1 included). But that was already handled with the modified early-return.

There is a simpler and efficient way to tackle this problem, using the built-in lastIndexOf(searchValue, fromIndex). This method starts at the specified fromIndex, and searches backwards the first occurence of the given value. If we tell it to search the first occurence of ' ' searching backwards from limit, we'll exactly have the length of the substring to return.

The only corner case is if limit is greater than the length of the string, in which case the method should simply return the text unchanged (like the current code is doing). It needs to be tested separately; otherwise lastIndexOf would start searching from the end of the string, and the last word would always be cut. This is what it could look like:

function trim(text, limit) {
  if (limit >= text.length) {
    return text;
  }
  return text.substring(0, text.lastIndexOf(' ', limit));
}

[0, 2, 4, 5, 6, 8, 10, 11, 12, 50].forEach((limit) => {
  console.log(limit + ' -> ' + trim('Hello World', limit));
});

Note that, even if the lastIndexOf call returns -1, because there was no space character found before the limit length, it is still safe to call substring since:

  If either argument is less than 0 [...], it is treated as if it were 0.


Getting single element or throwing one of two exceptions

I don't really like the second while condition count++ < 1 because IMO it is to hard to grasp at first glance when this condition really comes true.

I would do it without a loop but with simple if statements like so

public static T Single2<T>(this IEnumerable<T> source)
{
    using (var enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext() == false)
        {
            throw new EmptySequenceException();
        }
        var single = enumerator.Current;
        if (enumerator.MoveNext())
        {
            throw new MoreThanOneElementException();
        }
        return single;
    }
}

Now you don't have a count anymore hence no switch either. I have not used the ! operator on purpose, because having two calls to MoveNext() in two different if condition one checking for false and the other for true harms the readability a little by using that operator.


You are needlessly complicating this a little, checking a single table for multiple records can be done the same way as checking multiple tables for the same record. You want to use a join.

You also use PH1 and PH2 as aliases, but what do they mean. Your aliases should be meaningful. I replaced PH1 with base, as it's the base table of our search, and PH2 with duplicate, as it contains the duplicate records.

Last but by no means least, you should avoid using SELECT * in SQL in general. If the schema of the table changes then the query will happy continue to run, even though the data may now be incorrect or irrelevant. SELECT * also tends to run slower than typing out the column names, although I am not 100% sure this is also the case in Access SQL.

Here is your first query after I finished tinkering:

SELECT
    base.[VendorNameCol] AS [Vendor Name],
    base.[InvoiceNoCol] AS [Invoice #],
    base.[InvoiceDateCol] AS [Invoice Date]
    base.[InvAmountCol] AS [Invoice Amount]
FROM [Payment History] AS base
INNER JOIN [Payment History] AS duplicate
    ON base.[ID] <> duplicate.[ID]
    AND base.[VendorCol] = duplicate.[VendorCol]
    AND base.[InvoiceNoCol] = duplicate.[InvoiceNoCol]
    AND base.[InvoiceDateCol] = duplicate.[InvoiceDateCol]
    AND base.[InvAmountCol] = duplicate.[InvAmountCol])
ORDER BY
    [InvAmountCol] DESC,
    [InvoiceDateCol] DESC;


Make a MySQL SELECT and INNER JOIN faster

Moving your subqueries to the from clause may improve performance.

Additional indexes may help too. Add a clustered index on ID or (ID, ref) for tables mi, jo and cl to speed up the group by and max operations. You may also benefit from a clustered index on each of your order by columns.

SELECT mi.ref, jo.ID, mi.ID AS mID, mt.mi_type, jo.ref, jt.jo_type, cl.cl_name
FROM mi
INNER JOIN mt ON mt.ref = mi.mi_type
INNER JOIN jo ON jo.ID = mi.job
INNER JOIN cl ON cl.ID = jo.cl
INNER JOIN jt ON jt.ref = jo.jo_type
INNER JOIN (SELECT MAX(ref) AS ref FROM mi GROUP BY ID) mi2 ON mi2.ref = mi.ref
INNER JOIN (SELECT MAX(ref) AS ref FROM jo GROUP BY ID) jo2 ON jo2.ref = jo.ref
INNER JOIN (SELECT MAX(ref) AS ref FROM cl GROUP BY ID) cl2 ON cl2.ref = cl.ref
ORDER BY cl.cl_name, jt.jo_type, mt.mi_type


Plotting an input curve and its FFT using gnuplot in C++

Firstly, does the program give correct results?

If so, how do you know?

Without going into extensive unit testing, checking your results against a Matlab prototype/your Python implementation is probably good enough for now.

I can't comment on the Gnuplot functions as I don't have it installed, also but some general C++ tips are...

std::vectors are your friend! Try use them instead of C-style arrays. They 'know' their size and accessing out-of-bounds values are a major problem with C-style arrays and definitely for fiddly calculations like FFT. (You can use my_vector.data() to pass it into C-style functions).
Reduce reliance on a 'global' nPoints constant by using the vectors .size() member. (Unfortunately this outputs an unsigned integer size_t so there are some casts in the code to silence the compiler warnings). This is so that if nPoints goes out of sync with the size of the array/vector, you're not going to access an out-of-bounds value.
Always try to define a variable's value as soon as you declare it. Undefined variables are a major problem as C++ doesn't (usually) auto-define say, a double to zero. (double x; would refer to some garbage value in memory).
Always try to define variables when you need them i.e. as late as possible (see code for examples)
Try get into the habit of spitting out little functions right from the get-go, instead of one big block of code. It will break the problem up and be easier to debug. Also this will limit some variables scope so its easier to see what parts of the program change what variables.
For FFTs probably best to stick to doubles all round for the extra precision (removed the floats)
Use C++11 if you can and turn up the compiler warning level g++ -std=c++11 -Wall ...

Hopefully a bit to get you started!

I whole heartedly recommend this book if you're coming from Python, it's a short in length but really comprehensive and does a much better job than I could at explaining how to write good C++, and by the man himself - Stroustrup's "A Tour Of C++"

//#include "gnuplot-iostream.h"
#include <iostream>
#include <vector>
#include <cmath>
#include <fftw3.h>
#include <complex>
#include <cassert>

using doublePairs = std::vector<std::pair<double, double> >; // using (instead of typedef) for long named vector of pairs

void makeGaussian(std::vector<fftw_complex>& v, double tau) { // pass-by-reference indicates v is going to be altered
    for (size_t idx=0; idx<v.size(); idx++) {   // in.size() so we don't go out of range
        const int halfPoints = v.size() / 2;
        v[idx][0] = exp(-pow((idx-halfPoints)/tau, 2));
        v[idx][1] = 0;
    }
}

void performFft(std::vector<fftw_complex>& in,
                std::vector<fftw_complex>& out) {

    fftw_plan p;

    assert(in.size() == out.size()); // test same sizes
    const int nPoints = static_cast<int> (in.size());

    std::vector<fftw_complex> pArr1 (nPoints);
    std::vector<fftw_complex> pArr2 (nPoints);
    p = fftw_plan_dft_1d(nPoints, pArr1.data(), pArr2.data(), FFTW_FORWARD, FFTW_MEASURE);
    fftw_execute_dft(p, in.data(), out.data()); // access raw pointers to vectors for c-style function call

    fftw_destroy_plan(p);

    for (auto& n : out) {                           // nicer c++11 range based for loop
        n[0] *= (1/static_cast<double> (nPoints));  // static_cast<T> is preferred to c-style casts
        n[1] *= (1/static_cast<double> (nPoints));
    }
}

void makePlotPairArrays(const std::vector<fftw_complex>& in,
                        const std::vector<fftw_complex>& out,
                        doublePairs& inPlot,
                        doublePairs& outPlot) {

    assert(in.size() == out.size()); // test same sizes
    const std::complex<double> i {std::sqrt(-1)}; // typedef not necessary? (it's only used once)
    const int halfPoints = in.size() / 2;

    for (size_t idx=0; idx<in.size(); idx++) {
        // these Temps should be doubles?? since it's a pair of doubles not floats?
        // would lead to less precise FFTs
        double inTemp = std::abs(in[idx][0] + i*in[idx][1]); // keep these local to the loop scope

        // Deal with fftshifts needed for visuals:
        double outTemp {0};

        const int idx_ = static_cast<int> (idx); // for signed/unsigned compiler warnings
        if (idx_ > halfPoints)                              // what about when idx == halfPoints ???
            outTemp = std::abs(out[idx-halfPoints][0] +     // try make this an if/else statement so
                                i*out[idx-halfPoints][1]);  // at least one branch is always touched
        if (idx_ < halfPoints)
            outTemp = std::abs(out[idx+halfPoints][0] +
                                i*out[idx+halfPoints][1]);

        inPlot.push_back(std::make_pair(idx-halfPoints, inTemp));
        outPlot.push_back(std::make_pair(idx-halfPoints, outTemp));
    }
}

int main()
{
    constexpr int gridOrder = 9;
    constexpr int nPoints = std::pow(2, gridOrder);
    constexpr double tau = 18;
    // 'halfPoints' not needed here by declaring in function's scope
    // std::pow(2, gridOrder-1); BTW pow is heavy why not nPoints / 2?

    // our fft arrays
    std::vector<fftw_complex> in (nPoints);
    std::vector<fftw_complex> out (nPoints);

    makeGaussian(in, tau);

    performFft(in, out);

    doublePairs inPlot;
    doublePairs outPlot;
    makePlotPairArrays (in, out, inPlot, outPlot);

    // ... do the GnuPlotting

    return 0;
}


Breaking group of items into rows then ensure consistent height of each row element

Keep it simple
Your algorithm is too complex, with too many iterations and uses too much memory. It can be simplified using only a single outer iteration to get a row, and the row's max height. Then an inner loop to set the new height values. (see rewrite)
Some points

document.querySelectorAll returns an iterable object. There is no need to convert it to an array. You can use for of or any of the iteration features on it. EG document.querySelectorAll("query string").forEach( and [...document.querySelectorAll("query string")]

You only need to use .getAttribute when the attribute is not part of the DOM. const height = element.height is more concise.

You can use the Math function max  to get the maximum of 2 or more values at a time. maxHeight = Math.max(maxHeight, element.height)

Don't pollute the global scope. Use a self invoking function to encapsulate your variables.  ;(()=>{ /* your code in here */ })();

Rewrite
;(() => {
    "use strict";
    const itemsPerRow = 3;
    const query = ".summary-image-wrapper";
    const minHeight = 100; // Maybe a min height just in case

    const row = [];
    var maxHeight = minHeight;

    document.querySelectorAll(query)
        .forEach((imgWrap, i, imgWrappers) => {
            row.push(imgWrap);
            maxHeight = Math.max(imgWrap.firstElementChild.height , maxHeight);

            if (row.length === itemsPerRow || i === imgWrappers.length - 1) {
                row.forEach(imgWrap => imgWrap.style.height = `${maxHeight}px`);
                maxHeight = minHeight;
                row.length = 0;
            }
        });
})();


Refactoring the legacy code which is using '§' char in the code

I don't see you using std::, surely you didn't put using namespace std somewhere in your code right?

I find your parameter names a bit confusing. stringToReplace is actually the replacement. The string you want to replace is stringToFind. Maybe use something like replaceWith or just replacement for the second parameter instead.

There is a type mismatch which your compiler should have caught (no warnings enabled?). The return value of find is size_t.

You can also pass the first argument as a reference and the other two as const reference.


Avoid bare except

Writing except: without specifying a precise exception is asking for trouble, as anything will be caught, silencing all possible  bugs, instead use: except MyExpectedKindOfException.

Reconsider the very long sleeping

The function tor_browser_initialise ends with time.sleep(30).

That is a lot of time to sleep. Are you 100% sure that any call to that function will want to sleep so much?

Much worse, the sleep is not documented, so the caller will see his program hang on for 30 seconds for no apparent reason!

Just remove the call to time.sleep and let the user decide if and how much he wants to sleep after calling the function.


First of all there is a bug in your code, range(0, n, slice+1) should be range(0, n, slice) otherwise you'll miss every (slice+1)th item.
I don't understand why you re-assigned l = file_list to l here, note that simple assignments in Python don't create a copy of the object. Also don't use l as a variable name because it looks like 1(one) in many fonts.
If you're using Python 2 then use xrange() instead of range().
dict(zip(range(1,num_keys+1),vals)) can be replace with a simpler dict(enumerate(vals, start=1))
The parenthesis around (dict) in return statement are unnecessary.
slice is a built-in function, so try not to use it as a variable name. slice_size is one alternative.

Also I don't understand why you need a dict here, you can simply use a list of lists. Then the only difference will be that you'll have to start indexing at 0. Indexing is very faster than dictionary key-lookups and will also make sure the order of items is maintained.


Function that Loads a Random Image from an Array

Try to use array_rand function, code will look cleaner:

<?php
function displayRandomPhotoArea()
{
    $photoAreas = array("imageURL1", "imageURL2", "imageURL3", "imageURL4", "imageURL5");

    $randomNumber = array_rand($photoAreas);
    $randomImage = $photoAreas[$randomNumber];

    echo "<img src=\"$randomImage\" width=\"725\" height=\"194\">";
}

displayRandomPhotoArea();
?>


Class to create HTML heading tags in React

Choosing the heading level at runtime:

According to the official docs, you cannot use expressions within JSX types. However, you can use capitalized variables:

const Heading = "h" + 1;
return <Heading>...</Heading>;

Further suggestions:

Rename TypographyHeader to TypographyHeading to avoid confusion with .
Rename headerType to level.
Rename txt to text in let txt = this.props.text for consistency's sake.
Don't recycle the txt variable by rebinding it to a JSX .
Consider using const variable bindings.
As there are 6 official heading levels, you might want to relax your propTypes constraints:

headerType: PropTypes.oneOf([1, 2, 3, 4, 5, 6]).isRequired

Use destructuring arguments to avoid writing let txt = props.text.
Make the white space following the  element obvious by appending {" "}.
Handle heading texts without spaces by splitting according to this suggestion.

Proposed refactoring:

function TypographyHeading({text, level}) {

    // Split text into leading and remaining words:
    const space = text.indexOf(" ");
    const leading = text.substr(0, space);
    const remaining = text.substr(space + 1);

    // Select heading
 -
:
    const Heading = "h" + level;

    return (

            <Heading className="typography_header">

                    {leading}

                {" "}{remaining}
            </Heading>

    );
}


PHP program to generate random phone number

Use accurate and meaningful names for functions and variable to improve readability.
Condense your numeric loop conditions into a for loop versus while loop.
Avoid declaring single-use variables.
Make functions versatile by passing output-altering arguments with the call.
Write default argument values when possible/reasonable so that, in some cases, no arguments need to be passed for the most common scenario.
Avoid counting a static array in a loop.  If you need to count it, count it once before entering the loop and reference the count variable.
If you prefer mt_rand's randomness, use it in place of my array_rand() call below, but obey #6 about counting.
Obey PSR Coding Standards.  Spacing and tabbing don't improve performance, but they sure make your code easier to read.

Some suggested applications of my generalized advice:

Code: (Demo)

function randomNumberSequence($requiredLength = 7, $highestDigit = 8) {
    $sequence = '';
    for ($i = 0; $i < $requiredLength; ++$i) {
        $sequence .= mt_rand(0, $highestDigit);
    }
    return $sequence;
}

$numberPrefixes = ['0812', '0813', '0814', '0815', '0816', '0817', '0818', '0819', '0909', '0908'];
for ($i = 0; $i < 21; ++$i) {
    echo $numberPrefixes[array_rand($numberPrefixes)] , randomNumberSequence() , "\n";
}

Possible Output:

08161776623
08157676208
08188430651
08187765326
08176077144
09087477073
08127415352
08191681262
08168828747
08195023836
08198008111
09096738254
08162004285
08166810731
08130133373
09093214002
08154125422
08160702315
08143817877
08194806336
08133183466


Rebuilding WAR files in webapps directory

I think your first version looks pretty slick. You could use a let-binding to do a little reordering and naming.

import Data.Monoid

main = shellyFailDir $ verbosely $ do
  escaping False $ rm_rf $ webapps </> "*"
  let sourceName = artifact <> "-" <> version <> ".war"
      source = m2repo </> groupPath </> artifact </> version </> sourceName
      destination = webapps </> finalName <> ".war"
  cp source destination
  echo "done"


Style

Your structure for this program is fine, except one bug highlighted below. However, from first glance, you can make some style adjustments to increase the readability of your program. Coding conventions are extremely important - and although things like "do I put brackets on the same line or  a new line?" are controversial, it is essential that you write clean and readable code. A little spacing never hurt anybody, but it should be consistent and clean.

float num2= input.nextFloat();

Put a space before the equal sign.

String Operation = input.next();

Variable names should typically be lower camel case. Operation is actually a class from the java.rmi.server library, so you should rename this to simply operation.

case "division":
    if (num1 == 0 || num2 == 0) ;
{
    System.out.println("You can not divide by or with a zero!");
}

There should not be a semi-colon after the if-statement. This is causing wrong output! Line up your brackets. Also, why can't you divide 0? 0 / 5 is a perfectly valid operation.

You can clean this up simply by using the following

case "division":
    if (num2 == 0)
        System.out.println("You cannot divide by zero!");
    else
        System.out.println(num1 / num2);
    break;

You could also keep the brackets if you wish. If the statement contains only one inner statement, you don't need brackets, but some people prefer it for the readability. This is a personal style.

    case "division":
        if (num2 == 0) {
            System.out.println("You cannot divide by zero!");
        } else {
            System.out.println(num1 / num2);
        }
        break;

If you really want to trim it down, you can use the ternary operator ?.

    case "division":
        System.out.println(num2 == 0 ? "You cannot divide by zero!" : (num1 / num2));
        break;

Once you've done that, challenge yourself by getting yourself familiar with reading input files, so you don't have to type your input every time! You could try experimenting with a BufferedReader for example.


CSV parsing program that creates distinct header rows with transaction rows underneath

Don't reuse names for multiple purposes

Before this line, reader is a DictReader,
after this line it's a list:

    reader = sorted(reader, key=lambda key: (key['PEOPLE_ID'],
                                             key['DON_DATE']))

This can be confusing. It would be better to name the result something else.
And it gets worse: this new reader reader is passed to create_header_list and mapData as parameter named "dict_obj",
which further adds to the confusion.

Simplify set creation

This function essentially creates a set:

def create_header_list(dict_obj):
    p_id_list = []
    for row in dict_obj:
        if (row['PEOPLE_ID'], row['DON_DATE']) not in p_id_list:
            p_id_list.append((row['PEOPLE_ID'], row['DON_DATE']))
    return p_id_list

The not in check is inefficient, because it's an \$O(n)\$ operation.

It would be simpler and more efficient to use a set:

def create_header_list(dict_obj):
    p_id_set = set()
    for row in dict_obj:
        p_id_set.add((row['PEOPLE_ID'], row['DON_DATE']))
    return p_id_set

Or even:

def create_header_list(dict_obj):
    return set([(row['PEOPLE_ID'], row['DON_DATE']) for row in dict_obj])

If the ordering of the elements is important,
then instead of a set, you can use an OrderedDict,
as suggested by this post.

Running Python scripts

Not all systems have Python at /use/bin/python. The recommended shebang for Python scripts:

#!/usr/bin/env python

Follow PEP8

PEP8 is the coding style guide for Python.
Among other things,
it recommends using snake_case for variable and function names.
Several functions violate that.

Even if you disagree with a specific naming convention,
it's a universal violation of good naming practices to mix two kinds of naming styles in the same program, such as create_header_list and mapData.


Variables, scope, naming

Since you have only one method (main), there's no need to declare trovato and ok outside of it. Move them inside main, and make them local variables.

On the other hand, the variables a, ii, and s are for constant strings, indicating special commands in your command line interface, so it would be good to make them constants, loud and clear at the top of the class, with meaningful names, for example:

public static final String ADD_COMMAND = "a";
public static final String ITEM_COMMAND = "i";
public static final String SEARCH_COMMAND = "s";

The same goes for the <END> marker, which didn't have its own variable and it deserves to have one:

public static final String END_MARKER = "<END>";

Your program becomes instantly more readable. These constants are now also protected from mistakes: you cannot accidentally reassign their values, as they are final.

Furthermore, the variables trovato, cont and ok are actually only used when you're processing ADD_COMMAND. You should declare and initialize them there. This will also make it clear and easy to see that you don't need to reset their values at the end of the loop.

Good coding practices

Use interface types when declaring variables (and function parameters). Instead of this:

HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
// ...
map = new HashMap<String, HashSet<String>>();
// ...
HashSet<String> hs = new HashSet<String>();

Do like this:

Map<String, Set<String>> map = new HashMap<String, Set<String>>();
// ...
map = new HashMap<String, Set<String>>();
// ...
Set<String> hs = new HashSet<String>();

And try to think of better names for your maps and sets instead of map and hs. For example cars and tags.

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

Calling this BufferedReader as stdin is confusing and it invites mistakes. stdin is really System.in itself. A better name would be reader, or bufferedReader.

Always use braces with if statements. Instead of:

if (cont == 2)
    ok = true;

Do like this:

if (cont == 2) {
    ok = true;
}

Simplify

Notice the duplicated line in this code:

stringa += letteraPerLettera[i];
if (map.containsKey(stringa)) {
    map.get(stringa).add(elemento);
} else {
    Set<String> hs = new HashSet<String>();
    map.put(stringa, hs);
    map.get(stringa).add(elemento);
}

You can simplify:

stringa += letteraPerLettera[i];
if (!map.containsKey(stringa)) {
    Set<String> hs = new HashSet<String>();
    map.put(stringa, hs);
}
map.get(stringa).add(elemento);

This is not very efficient though, because you search for stringa twice: first with containsKey and then again with get. This is equivalent and more efficient:

Set<String> hs = map.get(stringa);
if (hs == null) {
    hs = new HashSet<String>();
    map.put(stringa, hs);
}
hs.add(elemento);

Last words...

Even with the above improvements, I find this code almost unreadable. They way you process the lines, it's just far more complicated than it needs to be. For example, instead of processing the ADD_COMMAND letter by letter, it would make more sense, and more readable to process word by word, like this:

String[] parts = line.split(" ");

// 0: the command, 1: the car name, 2, ...: tags, length-1: -1 (???)
for (int i = 2; i < parts.length - 1; ++i) {
    String car = parts[1];
    String tag = parts[i];
    for (int j = 1; j <= parts[i].length(); ++j) {
        String tagPrefix = tag.substring(0, j);
        Set<String> cars = map.get(tagPrefix);
        if (cars == null) {
            cars = new HashSet<String>();
            map.put(tagPrefix, cars);
        }
        cars.add(car);
    }
}

This is almost the same as the original program, except it also fixes a bug: the original program drops the last letter of car names (resulting in "Dun", and "Nissa"), this one doesn't.

On a related note, do you really need the -1 at the end of lines? It would be easy to make it work without them.

Instead of using a BufferedInputReader, a Scanner can be easier to work with. I recommend to take a look at it (hint: Scanner scanner = new Scanner(System.in))


The way you dissected the problem was a good way to get a handle on it but once you had, it reveals some refactoring opportunities.  Once you have the individual methods, you can begin to see how to build them back together

Let's begin by focusing on your two Matrix#<xxx>_segment methods.  Both have the same method signature and differ only by the use of width and height. So those could be combined to just be

def segment(index, length)   # maybe name it segment_enumerator just to be clear?
  (length - (2 * index) - 1).times
end

For top(index) then, you get

def top(index)
  segment(index, width)
    .map { |w| [index, w + index] }
end

which has the advantage of keeping width in the same function, making it slightly more readable and DRY.

Your side functions (top, right, et al.) really only differ by the block they use.  So you could write a single map_side method that just passes a block in the map.  However, because of the refactor we just did in the new #segment, a lambda helps pull it together:

def map_side(index, length, &block)
  lambda{ segment(index, length).map &block }
end

You might want to name that map_side something that means more to you in the problem domain (I know it returns an array of arrays, but didn't come up with a better name than map_side).

With that, we just use the new method to set up a quick hash of lambdas for each side, passing each the specific block you wanted:

def sides(index)
  _sides = {}
  _sides[:top] =    map_side(index, width)  { |w| [index, w + index] }
  _sides[:bottom] = map_side(index, width)  { |w| [height - index - 1, width - index - w - 1] }
  _sides[:left] =   map_side(index, height) { |h| [height - 1 - index - h, index] }
  _sides[:right] =  map_side(index, height) { |h| [h + index, width - index - 1] }
  _sides
end

Note, this is a hash of lambdas now, not the arrays you're looking for yet.  But with it, we can now write this for layers in whatever order you need:

def layers
  number_of_layers.times.map do |index|
    _sides = sides(index)
    [:top, :right, :bottom, :left].inject([]) do |array, side|
      array += _sides[side].call
    end
  end
end

A key thing to look at when you have tiny methods is whether you ended up using those methods more than once.  I like labeling things too to keep them straight (and that's always a Good Thing), but when it's just a single use, a variable name is as good as a method name.  So, we can just get rid of number_of_layers as a method.  I called it count below, but whatever works for you.

def layers
  count = [height, width].min / 2
  count.times.map do |index|
    _sides = sides(index)
    [:top, :right, :bottom, :left].inject([]) do |array, side|
      array += _sides[side].call
    end
  end
end

Now the following methods can be safely removed: horizontal_segment, vertical_segment, top, bottom, left, right, and number_of_layers.

The code is now DRYer, the width and height references are near each other for their specific uses, and you can quickly see how they stack up (in other words, your naming of elements was retained).  The one part that might throw you if you're not used to it is how I used the lambda closures to pull this off, but it's not an uncommon approach in Ruby and as you can see, a handy one.

I tested this refactor with your test suite and it ran fine.  I didn't benchmark, but it certainly didn't seem any slower and might be a little faster.


You can do something like this:

Masthead

Section 2

Section 3

and js:

$( 'a[data-bg-color]' ).click(function() {
  $('#sidebar').css('background-color', $(this).attr("data-bg-color"));
});

or if you cannot change html:

$( '.main-nav a' ).click(function() {

    var color = "blue"; //default;

    switch($(this).attr("href")) {
        case '#masthead' : color = "blue"; break;
        case '#section2' : color = "pink"; break;
        case '#section3' : color = "orange"; break;
    }
    $('#sidebar').css('background-color', color);
});

Improved solution

If you can do the first option but if you don't like to write in HTML the color of background (according to best practice, the style should be inside css), then you can use the same approach but using the class to add on sidebar.

For example:

Masthead

Section 2

Section 3

and js:

$( 'a[data-sidebar-class]' ).click(function() {

    // http://stackoverflow.com/questions/2644299/jquery-removeclass-wildcard
    $('#sidebar').removeClass(function (index, css) {
        return (css.match (/(^|\s)sidebar-\S+/g) || []).join(' ');
    }).addClass("sidebar-"+$(this).attr("data-sidebar-class"));

});

and css:

.sidebar-master { background-color: blue }
.sidebar-section2 { background-color: pink }
.sidebar-section3 { background-color: orange }

demo: http://jsfiddle.net/9vtxutth/1/


Find mobile phone contact according to number typed

Here's a few suggestions:

I would model the contacts list as an array of objects, like this:

const contacts = [
  { name: 'kostas', number: '6986100100' },
  { name: 'maria', number: '6986100200' },
  { name: 'george', number: '6986300300' },
  { name: 'sofia', number: '6986300400' },
  { name: 'chris', number: '6987500500' },
  { name: 'marine', number: '6944600600' }
];

If you use your contacts' first name as object keys, you can't have two contacts with the same name. Moreover, if each contact is represented by an object, you can add additional information to the contact in the future. I would also write the phone numbers as a string, not a number, since phone numbers can contain non-digit characters (like '+') or leading zeros.

The search returns a list of corresponding contacts, so you might as well replace the results div with a list, a

 for example.

Searching for and displaying the matches becomes easy now:

function handleKeyUp(e) {
  const inputValue = e.target.value.trim();

  if (inputValue) {
    found.innerHTML = contacts
      .filter(contact => contact.number.startsWith(inputValue))
      .map(
        contact =>
          `
${contact.name}: ${contact.number.replace(
            inputValue,
            `<span>${inputValue}</span>`
          )}
`
      )
      .join('');
  } else {
    found.innerHTML = '';
  }
}

No need to convert the input value to a string, it's a string already. Notice how there's only one call to found.innerHTML. Your code updated the dom once for each found match, but dom operations are expensive and should be minimized.


If you have performance issues, then I believe you should first try and profile your script, to identify which function(s) run slowly. There are profilers embedded in most scripting consoles.

Regarding your question: since your code should not trigger any repaint, I believe that method 1 would be fine. Unfortunately, I have not been able to reproduce the issue on my machine, so cannot confirm this answer.

To improve performance, I suppose you could try the following:

Rather than using setInterval, consider chaining setTimeout calls, so that the browser remains responsive.
Try and remove your library, to use native Javascript. It looks like you do not need anything more than getElementById, getElementsByTagName, getAttribute and setAttribute - so should be able to safely eliminate any library overhead.
Possibly cache the retrieval of all the div, as you only need to perform it once.

So basically, try and run the following (untested) on window.onload:

function update() {
    var delay = 100;
    var container = document.getElementById("container");
    var divs = container.getElementsByTagName("div");

    function updateDivs() {
        for (var ii = 0; ii < divs.length; ii++) {
            var div = divs[ii];
            if (randNum(0, 10) == 1) {
                var value = randString();
                if (div.getAttribute("alt") != value) {
                    div.setAttribute("alt", value);
                }
            }
        }
        setTimeout(arguments.callee, delay);
    }

    updateDivs();
}


Checking if an array can be rotated to equal another in JavaScript

I have not looked too deeply into the problem and I am guessing that there may be some function that produces a unique hash based on the sequence and independent of starting position. That would then only require that you iterate each array to create the hash and then compare to see if they match. That would give you a O(2n) solution where n is the size of one of the arrays.

If such hashing function does not exist, the brute force approch can easily be divided up and done in parallel. In javascript you would use webWorkers

There is also the approch that can use the GPU and the basic canvas 2D API but that has some limits on the size of the input arrays and the integer size of the values. Or via WebGL which is a little more flexible, but again the bottle neck is converting the arrays to an appropriate data format that the GPU can handle. The are some libraries out there that simplify the process, but you would only start to see any gains for very large arrays.

So to make some minor changes to your solution. To remove the pop and unshift  you can use the % operator to cycle past the end back to the start (see inner loop)

And the using continue to jump out of the loops is hacky to say the least. A little smarter logic and you don't need the goto in disguise.

So the function below is not an improvement in complexity, but rather a improvement of efficiency.

function canRotate(a, b) {
    var pos, count;
    const len = a.length;
    if (len === b.length) {
        pos = 0;
        while (pos < len) {
            count = 0;
            while (count < len && a[count] === b[(pos + count) % len]) {
                count ++;
            }
            if (count === len) { return true }
            pos ++;
        }
    }
    return false;
}

You could also use a regExp to do the search but again its not an improvement in complexity, just less code, and may be a lot faster in many situations (however the joins may need a separator to work on all cases)

Just join the second array and double it by add to its self, then join the first and convert to a regExp (or use String.API ) to test if the first array has a match in the second.

function canRotate(a,b){
    if(a.length === b.length) {
        const strB = b.join("");
        return new RegExp(a.join(""),"").test(strB+strB);
    }
    return false;
}

Or using a asymmetrical separator ie has two different characters.

function canRotate(a,b){
    if(a.length === b.length) {
        const jStr = "=>";
        const strB = b.join(jStr);
        return new RegExp(a.join(jStr),"").test(strB + jStr + strB);
    }
    return false;
}

Update
This answer assumes that the arrays contains positive values of the JS 32bit signed int.

Obliviously you should take care with the regExp solutions and only use it if array content can be joined without breaking the sequence uniqueness, and does not contain regExp tokens.


From the top:

Imports

Since you're only using one thing from random, you might as well only import that one thing:

from random import randint

As PEP8 recommends, whenever the time comes order your imports by standard imports, then third-party imports, then lastly local imports.

Use of Parentheses

In Python 2, your print statements do not require parentheses. If you're on Python 3, print function calls require them. Other areas (such as your while loop and return statement for collections) do not require parentheses around them.

As a later note: You can use commas within print statements to have spaces between things or you can concatenate two strings with the + operator, e.g.

>>> print "Hello", "World!"
Hello World!
>>> print "Hello" + "World!"
HelloWorld!

I wouldn't mix the two though (might make things look messy), and this is just a helpful note on the difference.

Unnecessary Comments

A lot of your code is self-documenting already and do not require comments (which is a good thing).

You should only comment areas that you believe might be hard to understand, e.g. calculation for the game result.

If you end up using functions, you might want to add some helpful docstrings to describe what's going on, or rename the function e.g.

def calculate_winner(x, y):
    """<Explain how calculate_winner works here>."""
    #...etc...

Code Organization

A lot of your code doesn't seem to need to be in functions, e.g. translate_choices and compare. You only ever use them once, and its all related to your game.

This is a bit of personal preference, but it might be nicer to move all your code into a function and avoid having global variables. This way, if others end up importing your code they won't encounter conflicts.

def play_rps():
    # ... rest of your code here ...

Also, it might be good to make sure your code only runs if it's called as main, e.g.

if __name__ == '__main__':
    play_rps()

and being called via python rps_name.py or however the file name hosting your code may be.

More info on __main__ here.

Handling User Choice

Instead of making a list every time, why not use the keys from the dictionary you already made?

while user_choice not in options:
    # do user_choice stuff here

Also, to make the logic a bit simpler in the while loop, you can remove the break statement by only checking for invalid inputs:

while user_choice not in options:
    #...print prompt for user choice here...
    user_choice = raw_input()

    if user_choice not in options:
        print '\nPlease pick either 1, 2, or 3!\n'

Lastly, you can also merge the later conversion of raw_input into an integer into your while loop:

try:
    user_choice = int(raw_input())
except ValueError:
    # input was not a valid integer
    user_choice = None

if user_choice not in options:
    print '\nPlease pick either 1, 2, or 3!\n'

Unnecessary Semicolons

Do you come from a C++/Java background? Reason I ask is because you seem to have a lot of semicolons in your code (which aren't required for python).

End Product

With the suggestions I listed above (and a few small things such as splitting up your option prompt), here's the code I came up with:

from random import randint

def play_rps():
    print "Hello! Let\'s play Rock-Paper-Scissors!\n"

    options = {1:"rock", 2:"paper", 3:"scissors"}
    player_result = ["tie", "win", "lose"]

    user_choice = None

    # get user choice
    while user_choice not in options:
        print "Game options:"
        print "-------------"
        print "1) Rock"
        print "2) Scissors"
        print "3) Paper"

        try:
            user_choice = int(raw_input("Your choice: "))
        except ValueError:
            # input was not a valid integer
            user_choice = None

        if user_choice not in options:
            print "\nPlease pick either 1, 2, or 3!\n"

    # calculate computer choice
    computer_choice = randint(1, 3)

    print "\nYou chose: " + options[user_choice] + "!"
    print 'Computer chose: ' + options[computer_choice] + "!"

    # calculate winner
    result = player_result[ (user_choice-computer_choice) % 3]
    print 'You ' + result + '!'

if __name__ == '__main__':
    run_game = play_rps()

NOTE: With the above format, it also makes creating a loop (if you choose to have a replay option) much easier.


Method for formatting a decimal number in Python using the given maximum number of digits and decimal places

Your code looks quite good to me. Good structure, consistent naming, appropriate documentation.

There are just some small ideas I would like to offer to you. Since your question is specifically tagged for Python 3, you might make use of the new f-string synthax instead of format. So your error messages would become something like

raise TypeError(
    f"The value '{value}' is not a valid decimal number."
)

which I think looks even nicer. I also replaced the outer ' with " so one does not have to escape the inner ' with backslashes.

The last error message could use the same tricks and could also utilize implicit line continuation in function parenthesis instead of manual line continuation triggered by \. This would ultimately lead to the following snippet:

raise ValueError(
    f"After formatting, the number of digits in the value '{rounded_down}' "
    f"is {rounded_down_digits_length}, which exceeds the maximum number of "
    f"digits of {max_digits}."
)

I was thinking about to address the idea of adding doctests to your code, but you have added this feature in an edit that took place while is was writing this up. So consider this to be done.


Find common substring that starts a set of strings

You should read PEP 8 and get a linter; pycodestyle, pylint, flake8, prospector, coala. It doesn't matter which one, just get one and use it.

Indenting with 3 spaces is awful, no-one can easily interact with your code.
I've never in my life seen 3 spaces for indentation, it makes me think your post is a joke.
Variables like s, l and  ii are useless.
It's really bad to put statements on the same line as other statements.

  if l == 0: return None

The amount of times I've just not seen the return None with lines like this isn't funny. It's nearly 100%.

Change your if, elif, else to guard statements and you can dedent your code.
There's no need for while else, you've not broken from the loop.
Returning None is just odd at best, change it to an empty string.
Taking a set as input is really strange, it causes you to have to do next(iter(s)). And you're not even exploiting the benefits of it.
Using iterators is clever, but not smart. You can just make a new list to contain all but the first value.

Additionally it doesn't really matter if you check against the first value because it's always going to be a subset of itself. Just seems like adding complexity for the sake of complexity.
You can remove the if l == 1 check.

def common_start(values):
    if len(values) != 0:
        start = values[0]
        while start:
            if all(value.startswith(start) for value in values):
                return start
            start = start[:-1]
    return ""

However this isn't the best. If there are \$s\$ values, and each have a length \$l\$ then your code runs in \$O(sl^2)\$ time.

Instead I'd suggest checking the first value against everything once - running in \$s\$ time. Since you do this \$l\$ times it runs in \$O(sl)\$ time.

To do so you can use zip to iterate through all the first characters, then second characters at the same time. From this you can check if they are the same and append them to a temporary list. Finally you return the contents of the list converted to one single string. In the end you would end up with something like salparadise created.

Again I would still make an empty list or set as input return an empty string.

def common(values):
    start = []
    for characters in zip(*values):
        if len(set(characters)) != 1:
            break
        start.append(characters[0])
    return ''.join(start)


Performance here won't be a problem. The splits you have are relatively trivial, and presumably there is a human component in here too (someone entering the roll-specs), so the parse time will essentially be negligible compared to that.

The code itself though has some neat features, and also some concerns.

Random

First up, the getRandomInt method is good. It follows the classic definition for retrieving a random value from a specified closed range [low,high]. I would prefer for there to be spaces on the operators though. Your code:

return Math.floor(Math.random()*(max-min+1)+min);

should be:

return Math.floor(Math.random() * (max - min + 1) + min);

Numbers

Your code makes some lucky guesses about numbers, and although it works, it is also easy to break. For example, if I take your random function again:

return Math.floor(Math.random()*(max-min+1)+min);

and instead make it:

return Math.floor(Math.random()*(1+max-min)+min);

it should work fine, right? Except, it won't, because you give the max value to the function as string:

var diceParts = diceRoll.split('d');

.....
    totalScore += getRandomInt(1,diceParts[1]);
.....

So, since you pass in diceParts[1] as a string, the 1+max-min will become 1 + "4" - 1 which in turn becomes 14 - 1 instead of 5 - 1.... so, your code works, but is it an accident? Well, not really, because you figured this out in the other side of the situation - where there is no d in the spec. For that, you have:

totalScore += parseInt(diceRoll);

You should be more defensive about number-handling in your code. You will run into mysterious bugs at some time in the future if you don't control them now.

parseInt(...)

You should always give parseInt a radix to work with. The documentation says:

  Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

(note: the bold emphasis is from the documentation, it is not my addition)

Since parseInt() ignores leading whitespace, and stops parsing on the first non-digit, it is OK to give parseInt(...) padded values - you don't need to trim them first.

Map->Reduce

I would have liked to have seen a map-reduce process happening here:

you have a + separated sequence of inputs
each part has a roll/limit
each result should be summed.

I would be tempted to build the process as:

this.rollDices = function(spec) {
    return spec.split(/\+/)
          .map(parseRoll)
          .reduce(function(a,b){return a + b;});
};

The above code describes the process quite well:

split on the +
convert parts to values
sum each part.

The implementation details for parseRoll is:

var getRandomInt = function(min, max){
    return Math.floor(Math.random() * (max - min + 1) + min);
};

var parseValue = function(val) {
    return parseInt(val || "1", 10);
}

var parseRoll = function(roll) {
    var parts = roll.split(/d/);
    var sum = 0;
    var limit = parseValue(parts[1]);
    for (var i = parseValue(parts[0]) - 1; i >= 0; i--) {
        var got = getRandomInt(1, limit);
        sum += got;
        // console.log("From roll " + roll + " part " + i + " got " + got + " sum " + sum);
    }
    return sum;
};

I have put the above in to a snippet here:

var getRandomInt = function(min, max){
    return Math.floor(Math.random() * (max - min + 1) + min);
};

var parseValue = function(val) {
    return parseInt(val || "1");
}

var parseRoll = function(roll) {

    // only here for the snippet
    debug("Parsing " + roll);

    var parts = roll.split(/d/);
    var sum = 0;
    var limit = parseValue(parts[1]);
    for (var i = parseValue(parts[0]) - 1; i >= 0; i--) {
        var got = getRandomInt(1, limit);
        sum += got;

        // only here for the snippet
        debug("  From roll " + roll + " part " + i + " got " + got + " sum " + sum);

    }
    return sum;
};

var rollDices = function(spec) {
    // only here for the snippet
    debugarea.value = "";

    return spec.replace(/[^+0-9d]+/g, "")
          .split(/\+/)
          .map(parseRoll)
          .reduce(function(a,b){return a + b;});
};

// *************************
// only here for the snippet
// *************************

var results = document.getElementById("result");

var debugarea = document.getElementById("debug");

var debug = function(txt) {
    debugarea.value = debugarea.value + txt + "\n";
}

function updated(input) {
    results.value = rollDices(input.value);
}
#spec {
  background-color: lightgreen;
}

#result, #debug: {
  background-color: lightgray;
}
Dice Spec :

<input id="spec" type="text" size="20"  oninput="updated(this)" />

Dice Value:

<input id="result" type="text" size="5" readonly="true">

Debug:

<textarea id="debug" rows="20" cols="40"></textarea>


Avoid calling system()
If possible, avoid calling system(). There are almost always issues doing this:

It is slow: system() will spawn another shell, which has to parse the command line you give it, and then it will spawn the actual commands you want to run).
Constructing a command line itself has all kinds of issues. For example, are you sure openssl is in your $PATH? And what if the search path finds a different version of openssl than the one you expected (/usr/bin/openssl)?
There is no easy way to send and receive data to the commands you start, so you have to redirect the input/output to files.

Especially the latter issue is important: what if someone reads /opt/PW/test.txt between the two calls to system()?
It would be much better to use a crypto library. OpenSSL is not just a program, it's also a library that you can call directly from C. However, I would say it is not the easiest to work with. There are other libraries out there that make encrypting and decrypting files easier and safer, for example NaCL.
Cryptography is hard to get right
Trying to learn about cryptography is great! However, be aware that it is not easy to get cryptography right. You are using AES-256 in ECB mode, which is bad. Furthermore, you are not using any form of message authentication, so if someone tampers with the encrypted file, then even if they cannot decrypt it properly, when you try to decrypt it you will not get the same data back as you put it. Sometimes it will be obviously garbage, but it sometimes is possible to change the data in more subtle ways (especially with ECB mode, but other modes also have issues if not combined with a MAC).
Go ahead and try to improve your program, learn more about cryptography, but I strongly suggest you do not use your cryptographic code for anything serious until you get a much better understanding of cryptography.


Directory that lists employee information - follow-up

in your while statement you are listing all sorts of information inside of one list item tag, I am not so sure this is intentional,  it looks like it is going to be really messy. I think you should look into creating sub-lists there especially for the multiple Department names and Job Names.  you want something like an XML Date File here,  maybe I am overstepping my reviewer line and telling you to change the structure, but this is going to look really messy on a website I think.

something like this would be more convenient.

       $firstName $lastName

Department1

Department1

Job1

Job2

I don't know exactly what you want your finished product to look like, but this structure is far more solid than what your PHP is going to output,  you should look into making it output something like this,  because this is going a lot easier to work with for Styling and manipulating with PHP.

all of your image tags () need to be closed(), so does your break tags (
,
)

From what you are saying it sounds like you want something more like this

            $firstName $lastName

Department1, Department1

Job1, Job2

I removed the Div tag and some of the other stuff just so we could visualize this better.  this is a little more organized than what you are going to get with your current code.  it will still be easier to deal with.

As Far as whether or not to do another list for the Department Names and Job Titles,  I would go with yes, even if they only have a single item, it will be easier to navigate the ones that do have them, and easier to manipulate the data,  it is more maintainable I think.

I mentioned still using nested lists for the Department Names and Job Names,  you should still have a title for the list item that is holding them, so you know what they are, but I will leave that up to you

            $firstName $lastName

Department1

Department1

Job1

Job2

so here is what that would look like with out the titles for the sub lists


It looks like you are sending almost the same message multiple times. I see at least two possible speed improvements.

The most likely bottleneck is the actual email sending process, which is outside of your program, an overhead for every single message sent. You could reduce that overhead by putting multiple recipients in BCC, if possible. As you noted in comments, ISPs might consider messages with a large number of recipients. If you stay within reasonable limits, and you're not in fact spamming, you can hopefully convince them to allow it. (This did happen to me once, and my ISP was reasonable.)
Another minor improvement can be, instead of creating a new message from scratch for each recipient, you could create a single message object once, and replace the recipient and other variable parts in it.

The code is too compactly written. I suggest to use your IDE to reformat it nicely.

The try block covers a lot of code. It seems you could move some code of it. That would be better, to clarify the sensitive parts where something might go wrong.

Catching Exception is not recommended. It's recommended to catch the most specific exception that might be thrown.

It's a bit strange to catch OutOfMemoryError. This is not something a program can recover from gracefully. You don't share the piece of code handling the exception, but I doubt it would be much different from not handling that at all.


Kattis "Hitting the Targets" utilizing a polymorphic relashionship

Virtual destructor

As a simple rule of thumb, if a base class contains any virtual functions, its destructor should also be virtual. The primary reason for it to declare a virtual function is so a derived class can override that virtual function. If you have public derivation, you nearly always want the destructor to be virtual--without that, destroying a derived object via a pointer to the base class gives undefined behavior.

Defining empty functions

As another simple rule of thumb, if you don't have a specific idea of what a function is supposed to do, it's probably better not to define it at all. In your case, the base class' constructor isn't doing anything, so it probably isn't needed at all. The destructor isn't currently doing anything either, but it should be defined as virtual (see previous point).

If the derived classes don't have anything to do in their destructors, you probably don't need to define their destructors.

Factory

You might want to consider moving all the code for reading data from the file and creating an object from that data into a class (or possibly just a function) by itself. This sort of thing is usually called a factory.

Error handling

Right now, if you encounter bad input (neither the "Circle" nor "Rectangle" pattern is matched by a line of input) you simply ignore that line of input and proceed to the next. This is fine for a site like you're dealing with here, but it's rarely good behavior in the real world, where bad input should normally produce some message to the user letting them know what happened.

Standard algorithm

You mentioned using std::count_if to do the counting. You could use it something like this:

std::cout << std::count_if(shapes.begin(), shapes.end(),
        [=](std::unique_ptr<Shape> &s) { return s->contains(x, y); }) << "\n";

Note that in this case, the unique_ptr doesn't really work particularly well, so we end up passing it by reference. Otherwise, the pointer would be moved (transferred) to the algorithm, so the pointer in the vector would have released it; on the second iteration, the vector would only contain null pointers.

This could be handled by using shared_ptrs instead. Another (probably preferable) solution would be to look up (and use) Boost ptr_vector instead.

Adding a Point class

It's probably at least worth considering adding a Point class (or maybe struct) to encapsulate an X/Y coordinate pair.

Prefer member initializer lists over assignment

When you have a constructor that initializes members from arguments, it's usually preferable to do the initialization in a member initializer list. For example, your Circle constructor could look like this:

Circle(const int _x1, const int _y1, const int _r) : x1(_x1), y1(_y1), r(_r) {
}

Note that a ctor with an empty body like this is quite common and expected.

Prefer make_unique over unique_ptr<T>(new T(arguments))

There's rarely much (if any) reason to use an unadorned new to allocate your object(s), and doing so can introduce exception safety issues (which don't arise in this exact code, but I'd advise normally using make_unique as it eliminates the possibility).

Putting most of those together, we could end up with code something like this:

#include <iostream>
#include <memory>
#include <regex>
#include <string>
#include <vector>

class Shape {
public:
    virtual ~Shape() { }
    virtual bool contains(int, int) = 0;
};

class Circle : public Shape {
    int x1, y1, r;
public:
    Circle(const int _x1, const int _y1, const int _r)
        : x1(_x1), y1(_y1), r(_r)
    { }

    bool contains(const int x, const int y) override {
        int x_dist = std::abs(x - x1);
        int y_dist = std::abs(y - y1);
        return x_dist * x_dist + y_dist * y_dist <= r * r;
    }
};

class Rectangle : public Shape {
    int x1, x2, y1, y2;
public:
    Rectangle(const int _x1, const int _y1, const int _x2, const int _y2)
        : x1(_x1), y1(_y1), x2(_x2), y2(_y2)
    { }

    bool contains(const int x, const int y) override {
        return x >= x1 && x <= x2 && y >= y1 && y <= y2;
    }
};

struct Factory {
    std::unique_ptr<Shape> build(std::string const &line) {
        static const std::regex rect_pat{ R"(rectangle (-?\d+) (-?\d+) (-?\d+) (-?\d+))" };
        static const std::regex circ_pat{ R"(circle (-?\d+) (-?\d+) (-?\d+))" };

        std::smatch matches;
        if (std::regex_search(line, matches, rect_pat)) {
            return std::make_unique<Rectangle>(std::stoi(matches[1]), std::stoi(matches[2]), std::stoi(matches[3]), std::stoi(matches[4]));
        }
        else if (std::regex_search(line, matches, circ_pat)) {
            return std::make_unique<Circle>(std::stoi(matches[1]), std::stoi(matches[2]), std::stoi(matches[3]));
        }
        // Probably want to add something here to deal with bad data (e.g., throw an exception).
    }

};

int main(void)
{
    std::string line;
    std::getline(std::cin, line);
    int num_shapes = std::stoi(line);
    std::vector<std::unique_ptr<Shape> > shapes;

    Factory f;

    for (int a = 0; a < num_shapes; a++) {
        std::getline(std::cin, line);
        shapes.push_back(f.build(line));
    }
    std::getline(std::cin, line);

    int num_points = std::stoi(line);
    for (int a = 0; a < num_points; a++) {
        int x, y;
        std::cin >> x >> y;

        std::cout << std::count_if(shapes.begin(), shapes.end(),
            [=](std::unique_ptr<Shape> &s) { return s->contains(x, y); }) << "\n";
    }
}


What might be another way to test if int is 32 bits wide at compile time?

In C++, sizeof returns the size of a number relative to the size of char.

So, sizeof(int) should give you how many chars each int takes.

Next, we need to know how many bits each char has. CHAR_BIT has that information.

So try this:

constexpr size_t bits_per_int = sizeof(int) * CHAR_BIT;
constexpr bool intbitwidthcheck = (bits_per_int == 32);

Frankly, I believe this way is more readable.

Not to mention, can one reasonably expect a 32-bits signed int to contain values up to 2^32 - 1? Shouldn't that be the UINT_MAX? INT_MAX should be up to 2^31 - 1.


Python compare every line in file with itself

On reading the file twice

Constructing data structures is costly. You do it once for each line in the file (\$n\$ times) and then do it again \$n^2\$ times. There is absolutely no need as you could only use one list to do so:

>>> a = [[1], [2], [3]]
>>> for i in a:
...     for j in a:
...         print(i, j)
...
[1] [1]
[1] [2]
[1] [3]
[2] [1]
[2] [2]
[2] [3]
[3] [1]
[3] [2]
[3] [3]

That way, with only one list, you avoid spending time converting strings to datastructure and can focus on your algorithm.

So just build the list once and use it any time you want.

Use functions

It lets you reuse your work more easily, by changing parameters. You can also more easily add code to handle command-line arguments and not need to change your code each time you change your input/output file.

A simple layout could look like:

def parse_input(filename):
    ...

def compute_output(output_file, data, filter_value):
    ...

def filter_file(path, filter_value=3, in_name='file', out_name='filteredSets'):
    data = parse_input('{}/{}'.format(path, in_name))
    with open('{}/{}{}'.format(path, out_name, filter_value), 'w') as out_file:
        if len(data) > 1:
            compute_output(out_file, data, filter_value)
        else:
            for datum in data:
                print(datum, file=out_file)

if __name__ == '__main__':
    filter_file(arg2 + arg1)

I’m assuming Python 3 here for the print(datum, file=out_file) line. Change it accordingly if you are using Python 2. It, however, will change your output a bit, but more on that later. I'm also using a for loop in the else just in case there is no rows in data.

Separating concerns with functions let you focus on being efficient for simple tasks. And, if later you want to improve your code thanks to multiprocessing, it will be easier to process it in parallel (using map_async for instance).

Iterate directly over items

Rather than iterating over indices and using these indices to retrieve items. Instead of:

for i in range(0, len(list1)):
    ...
    set2 = list1[i]

You should use:

for set2 in list1:

It's both easier to read and faster. If you truly need the index, you can still use enumerate:

for i, set2 in enumerate(list1):

But as far as eliminating tests against the same line in our product you can test if the object is the same:

for set1 in list1:
    for set2 in list1:
        if set1 is not set2:
            # Do something

Note that I used is instead of == to be sure that we are performing tests on the same line and not on lines with identical values:

>>> a = [[1], [1], [1]]
>>> for i in a:
...     for j in a:
...         print(i, j, i==j, i is j)
...
[1] [1] True True
[1] [1] True False
[1] [1] True False
[1] [1] True False
[1] [1] True True
[1] [1] True False
[1] [1] True False
[1] [1] True False
[1] [1] True True

Managing "stop-early" in loops

Python allows loops (for and while) an optional else clause. This clause executes only if the loop executed entirely without reaching a break (or a return, for what it's worth).

In your case, you could use that at your advantage in the inner for loop: instead of waiting to reach the end of the file for each line, you can break as soon as you find that two lines shares more than 3 items. If you handle writing lines in the else clause of the inner for loop, you can rely on that break to not print a line that has too many items in common with an other one.

Miscellaneous

You can use os.path.join to concatenate folders and filenames.
You can use set1 & set2 as a shorthand to set1.intersection(set2).
You should write each import statement on its own line.

Proposed improvements

import os
from ast import literal_eval

def parse_input(filename):
    with open(filename) as f:
        data = [set(literal_eval(line)) for line in f]
    return data

def compute_output(output_file, data, filter_value):
    for set1 in data:
        for set2 in data:
            if set1 is set2:
                # Do not try to compare a row with itself
                continue
            if len(set1 & set2) >= filter_value:
                # Do not keep lines that have more than a few items
                # in common with any other line
                break
        else:
            # If the second for loop did not break, then keep the line
            print(set1, file=output_file)

def filter_file(path, filter_value=3, in_name='file', out_name='filteredSets'):
    data = parse_input(os.path.join(path, in_name))
    output_filename = os.path.join(path, '{}{}'.format(out_name, filter_value))
    with open(output_filename, 'w') as out_file:
        compute_output(out_file, data, filter_value)

if __name__ == '__main__':
    filter_file(arg2 + arg1)

You should have noticed that I changed the output format a bit. Now each line is a set instead of a list. It's easy to change that by calling print(list(set1), file=output_file) instead. It may change the order, but wont change the content. You could even use sorted(set1).

Beyond ast.literal_eval

I don't know if you can manage the input files of if you have to build around their limitations. But in case you can change them, I suggest you have a look at the pickle module.

Basicaly, when creating your input file, you can pickle.dump a list of all rows (possibly already a list of sets) and then, load them in this script using a simple data = pickle.load(os.path.join(arg2 + arg1, 'file')).