Improving logic for pulling and passing data();

squished and optimized, the code looks like this:

function getData() {
  var guestData = $('.guest-data'),
    knownFors = $('.known-for li', guestData),
    data = $($this).data();
  $('.guest-image').html('');
  $.each(data.knowns, function (i, entry) {
    knownFors.eq(i).html('')
  });
  $('.title', guestData).text(data.name);
  $('.desc', guestData).text(data.desc);
  $('.link', guestData).text(data.link).attr('href', data.link)
}

and here's the explanation

//named functions are better in debugging
function getData() {

  //cache frequently used elements
  var guestData = $('.guest-data'),

  //providing a query context limits jQuery to locate a selector only under the context
  //so in this code, we find .known-for li only under guestData which we already cached
  //instead of traversing the DOM again for each find
    knownFors = $('.known-for li', guestData),

    //jQuery data can be fetched as a JS object by a parameter-less .data()
    data = $($this).data();

    //by informal convention, variables prefixed by $ usually means it
    //references a jQuery object. You may not need wrap it again with
    //a $() call if you are sure it's already a jQuery object

  //there are two ways to build elements in jQuery

  //for performance, string assembly would be faster
  $('.guest-image').html('');

  //for readability, but slow, the jQuery element builder method
  $('.guest-image').html($('', {
    'src': data.image
  }));

  //I also have to note as to why .guest-image was not cached
  //it's simply because it is only used once in the function

  //for your "knowns", I suggest placing them in an array and in order
  //so that you can easily iterate through and attach to your html

  //example of the structure
  /*
  data.knowns = [
    {
      known : 'known here',
      title : 'title here'
    },{
      known : 'known here',
      title : 'title here'
    }
  ];
  */

  //looping through the structure
  $.each(data.knowns, function (i, entry) {

    //string assembly method
    knownFors.eq(i).html('')

    //builder method
    knownFors.eq(i).html($('', {
      'src': entry.known,
      'data-title': entry.title
    }));

  });

  $('.title', guestData).text(data.name);
  $('.desc', guestData).text(data.desc);

  //lastly, some jQuery functions return the element they operated on
  //this makes chaining possible.
  $('.link', guestData).text(data.link).attr('href', data.link);
}

Here's a JS perf performance test. Compared to your code, the builder method is more readable, verbose but 23% slower. The string assembly method is 7% faster than your code.

Seems like it was faster only on my Firefox 18 and Firefox 21 Android (Nightly) and was too eager to conclude.


Crawling pages to obtain .htm and .txt files from sec.gov

Since you never use getLinks without a call to getFullLink afterwards, I would merge these two functions. I would also make it a generator:

def get_links(soup, pattern):
    for link in soup.select(pattern):
        yield urljoin(base, link.get("href"))

Then your main part can become this nested for loop:

if __name__ == "__main__":
    pattern1 = "#seriesDiv [href*='&CIK']"
    pattern2 = "[id=documentsbutton]"
    pattern3 = "[summary='Document Format Files'] td:nth-of-type(3) [href$='.htm'],td:nth-of-type(3) [href$='.txt']"

    final_links = []
    for first_link in get_links(make_soup(start_urls[0]), pattern1):
        for second_link in get_links(make_soup(first_link), pattern2):
            final_links.extend(get_links(make_soup(second_link), pattern3))
    print(final_links)

I also renamed your functions according to Python's official style-guide, PEP8 and added a if __name__ == "__main__": guard.

One way to make this a bit faster (this sounds like it could be a lot of requests) is to use requests.Session to re-use the connection to the server:

session = requests.Session()

def make_soup(url):
    res = session.get(url)
    res.raise_for_status()
    return BeautifulSoup(res.content, "lxml")

Here I also added a guard so that the program stops if any site does not exists (i.e. returns 404 or similar).


JavaScript responsive menu (dropdown/dropup)

General feedback
Overall it seems somewhat simple and works fine except for the issue I saw you mentioned in a comment on the accepted answer to the related Stack Overflow post, about having to click the menu button twice after resizing it that is caused by a conflict with page builder as explained in question update above.
One thing to consider is getting rid of the variable isMenuVisible - just check the value of menu.style.display when updating the visibility of the menu.
Suggestions
const vs let
I would use const for any value that should not get re-assigned - e.g. menu, burger. That way if you inadvertently re-assign a value to those, an error will be thrown.
Identifying the element used to open the menu
If there really is only one element for opening the menu, why not use an id attribute to find that instead of a class name.
Querying DOM for elements
Using document.getElementById() to access those DOM elements will be quicker1 than using document.querySelector().
Variable clicks
The variable clicks doesn't appear to be used - just set to 0 initially and then updated during the resize event callback. Is that leftover from other code? Or does it control something else in your code?
simpler and shorter patterns
As far as shortcuts using ecmascript-6 features, the only things I could think of would be to remove the block on mobileBehavior (to make it a single line) and using a single argument with only one character (e.g. named something like _) for the arrow functions instead of an empty set of parentheses (though that only saves character for each function).
Method mobileBehavior() and the resize event callback
Since mobileBehavior() is only called once, that functionality could just be moved to the place it is called... Then it doesn't really make sense to have that function. Perhaps it would be suitable to define a function like setDisplayBasedOnWidth, which contains most of the functionality of the resize callback (except setting the display to none when the width is less than the threshold). Then that function can be called initially, as well as after a resize event.
See the updated code below for slight improvements adapted.

document.addEventListener('DOMContentLoaded', _ => {
  const menu = document.getElementById('menu-primary');
  const burger = document.getElementById('burger');

  burger.addEventListener('click', _ => {
    const currentDisplay = menu.style.display;
    menu.style.display = currentDisplay == 'none' ? 'block' : 'none';
  });
  const setDisplayBasedOnWidth = _ => menu.style.display = window.innerWidth <= 959 ? 'none' : 'block';

  window.addEventListener('resize', setDisplayBasedOnWidth);
  setDisplayBasedOnWidth();
});
:root {
  --w: #00ff00;
}

#burger {
  display: block;
  text-align: center;
  color: var(--w);
  margin-bottom: 0 !important;
  font-weight: bold
}

#menu-primary {
  display: none
}

@media screen and (min-width: 796px) {
  .burger {
    display: none
  }
  #menu-primary {
    display: block
  }
}

BARS

Homepage

Contact_us


Welcome to Code Review. I think the simpler way of expressing your code would look like this:

def compute_pay(hours: int, rate: float) -> float:
    return (min(hours, 40) + (max(0, hours - 40) * 1.5)) * rate

hrs = int(input('Hours: '))
hrs_rate = float(input('Rate: '))

print('Pay:', compute_pay(hrs, hrs_rate))


Optimization of a "Sieve of Eratosthenes" in Java

Alright, a few notes:

Your for loop strikes one as odd.

 for (int i = 0; i < 1000; i++) {
                primes.add(i + 1);
            }

Why not start iteration at 1 and have your conditional be  <= 1000, and you could just call primes.add(i) Note that this is just an example to be equivalent to yours, just removing unnecessary bloat, it actually makes the most sense to start with 2 for a sieve, since it's the first prime. These changes would more clearly communicate your intention.

Courtesy of this answer I learned that a sieve is best implemented through a simple boolean array.

  boolean[] sieve = new boolean[1000];
    Arrays.fill(sieve, true);

 for (int prime = 2; prime < sieve.length; prime++) {
        if (sieve[prime]) {
            // this is a prime number
          for (int notPrime = prime * 2; notPrime < sieve.length; notPrime += prime) {
              sieve[notPrime] = false;
          }
        }
    }

As this answer notes there may be ways to improve it, but I like this implementation for being light on memory (booleans are 1 bit) and the performance and convenience of simply using the indexes as the prime or not prime values.

Edit: Although booleans actually take up 1 bit in memory, the actual number of bits allocated is JVM dependent and typically a byte is reserved for each boolean used. Although the performance would be intangible using a Bitset would be the target route to achieve 1 bit per boolean.

*If any of this was useful, please give the linked answer up-vote priority.


To use or not to use public variables in javascript?

None of this code needs to create any global variables. The pattern you have here is known as namespace creation.

It often follows the pattern:

var myNamespace = (function () {
    //private stuff
    var public = {}; //or function () ...
    //build up public object
    return public;
}());

But sometimes the public object can be inlined like it can be in your case:

var geoLocateAddress = (function () {
    function init() {
        //...
    }
    return { init: init };//unnecessary to expose the other functions as public
}());

In this case, all you are doing with this namespaced global object is calling the init function. So instead of creating a global (generally considered bad taste in most languages) you can simply initialize the object:

(function () {
    function init() {
        //...
    }

    init();//unnecessary to expose the other functions as public
}());

(this pattern of having the function surrounding your code like this is commonly referred to as an IIFE)

Aside: for declaring a namespace I prefer the following form:

(function ($, window) {
    'use strict';

    ...
    window['geoLocateAddress'] = window['geoLocateAddress'] || {};
    window['geoLocateAddress'] = $.extend({}, window['geoLocateAddress'], {
        'init': init
    };
}(jQuery, window));

Back on topic:

In my opinion, it is a bad practice to force the Javascript engine to go looking for your globals when you are not in global scope due to leaving off the window qualifier. Thus everywhere you reference console without calling it window.console (and the same goes for Navigator) or caching it in a local variable is wrong. In the event where you run this script outside of a browser that implements console you will get an exception. Navigator is slightly less of an issue because it is a reasonably safe assumption that you will not run this from a browser that doesn't supply a Navigator global namespace. For this reason I always pass the globals that I am going to use into my IIFE:

(function ($, geolocation, console) {
    ...
}(jQuery, Navigator.geolocation, window.console));

I would modify the rest of the code as follows; please comment if you want me to explain any of it in more detail and I'll try to get to it. Comments dictionary:

pref: personal preference (the opinions of others may vary)
rule: avoids possible issues with the code
possibility: potential source for further enhancement, outside of the scope of this question.
consideration: something I haven't decided one way or the other on yet

//pref: don't create global variables that are unnecessary
(function ($, geolocation, console) {//pref: pass in globals for munging purposes
    'use strict'; //pref: 100% on JsLint

    //pref: instead of defining one object variable and methods on it
    //we could define the methods and export an object at the end
    //this saves us from needing to do some sort of static object call syntax
    var updateAddressFields = function (data) { //pref: remove unused parameters
            console.log('Zip: ' + data.address.postalCode);
            //pref: renaming variable provides very little benefit;
            //outweighed by ability to simplify syntax by inlining to success
            //function and then replacing the success function here
            console.dir(data); //pref: make above a constant string and use this instead of just logging zipcode
            $(function () {  //rule: don't update DOM until after the ready event
                $('#zip').text(data.address.postalCode);
            });
            //pref: further logging beyond start of function adds nothing but cruft to your log
        },
        loadAddressByLocation = function (position) { //pref: renamed function for readability
            console.log('loadAddressByLocation:');
            console.dir(position); //pref: inlined function to simplify code
            var data = { //possibility: abstract this as a jQuery helper if it has uses outside of setting zipcode (outside of this question scope)
                    lat : position.coords.latitude,
                    lng : position.coords.longitude
                },
                url = "http://ws.geonames.org/findNearestAddressJSON"; //consideration: variable unnecessary?
            $.ajax({ //consideration: ajax vs getJSON?
                url: url,
                dataType: 'jsonp', //consideration: specify datatype or put callback in the url?
                data: data, //consideration: inline data definition?
                success: updateAddressFields, //pref: extra function wrapping unnecessary
                error: function (xhr, textStatus) {//perf: remove unused parameters
                    console.log(textStatus);//consideration: necessity of error function?
                }
            });
            //pref: return false did nothing here; removed
        };

    console = console || { //rule: safe to remove shim if you know you're browser compat
        log: function () {}, //otherwise console may not exist under certain browsers
        dir: function () {}
    };
    //perf: removed and inlined "return { init: init };" to not create globals
    console.log("Using your browser's GeoLocation API");//pref: inlined init and initEventHandlers for readability
    if (geolocation && geolocation.getCurrentPosition) { //rule: more behavior detection, also safe to remove if browser compat
        //assume correct api if this passes
        geolocation.getCurrentPosition(loadAddressByLocation);
    }
}(jQuery, navigator.geolocation, window.console));
//pref: passing in navigator.geolocation will allow better minification (though I wouldn't minify this version anyway)
//rule: more behavior detection, referring to console as window.console to not trigger possible error referencing global that doesn't exist

Simplified for minification, I don't really see anything "wrong" with this version:

(function ($, geolocation) { //console removed
    if (geolocation) { //possibly unsafe if future browser implements geolocation but not getCurrentPosition, perhaps leave this as it was above
        geolocation.getCurrentPosition(function (position) {
            $.getJSON( //using this helper instead of ajax lets us not define an object and property names
                "http://ws.geonames.org/findNearestAddressJSON?callback=?",
                //dataType: 'jsonp', unnecessary with callback in url
                { //inlined data to remove var, IMO readability is not affected too much
                    lat : position.coords.latitude,
                    lng : position.coords.longitude
                },
                function (data) { //unused params dropped from success callback
                    $(function () {
                        //don't update until after the ready event
                        $('#zip').text(data.address.postalcode);
                    });
                }
            );
        });
    }
}(jQuery, navigator.geolocation));

which shrinks down to 266 chars (via uglifyjs):

(function(e,t){t&&t.getCurrentPosition(function(t){e.getJSON(
"http://ws.geonames.org/findNearestAddressJSON?callback=?",{lat:
t.coords.latitude,lng:t.coords.longitude},function(t){e(function(){
e("#zip").text(t.address.postalcode)})})})})(jQuery,navigator.geolocation)


URL selection function that is designed to randomly assign users to different surveys until full

You seem to have a fair bit of hard-coding there. I would suggest instead something like:

PATH_MAX = 10
WIZARD_COUNTER = {'/surveyone/': 0,
                  '/surveytwo/': 0,
                  '/surveythree/': 0,
                  ...}

def start(request):
    if WIZARD_COUNTER:
        survey_url = random.choice(WIZARD_COUNTER)
        WIZARD_COUNTER[survey_url] += 1
        if WIZARD_COUNTER[survey_url] == PATH_MAX:
            del WIZARD_COUNTER[survey_url]
        return render(request, 'start.html', {'survey_url': survey_url})
    else:
        return render(request, 'surveyfull.html')

This makes it much easier to alter the number of surveys in the future, you just need a dictionary mapping {url: count}. If you want to have different counts, the simplest way is to set the PATH_MAX to whichever you want the most of, then preset individual counts to PATH_MAX - count_for_that_survey.


What if fill were a comma?  Does that remind you of a common string-handling idiom?

>>> ','.join('abcde')
'a,b,c,d,e'

The only remaining task is to convert that result into a list.

Therefore, the solution would be better written as:

list(fill.join(l1))


return returns the value, in this case the dictionary birthdays, whereas print just prints the value to the terminal. Your printing might be improved by using f-strings. This is usually a bit easier than having to use "+" inside your print statements. So for example, instead of

print(new_name + "'s birthday has been added as " + new_birthday)

You could write:

print(f"{new_name}'s birthday has been added as {new_birthday}")

This combined with a generator could also make your dictionary printing a little neater:

print("\n".join([f"{name}'s birthday is {bday}" for name,bday in birthdays.items()]))

The generator creates a list of strings for each item in the birthdays dictionary, so in this case, it would generate the list ["Jon's birthday is July 17","Shauna's birthday is Jan 27", "Lynette's birthday is July 10"]. The join() function is used to combine each element of this list into a new string, separated by the newline character \n. So the final result would produce:

Jon's birthday is July 17
Shauna's birthday is Jan 27
Lynette's birthday is July 10

If you want to further extend this code, I'd recommend representing the birthday as a date object, from the Python built-in library datetime. Then you could also add the functionality of easily telling how many days until someone's birthday and other features like that.


A good rule of thumb is that you should only ever use foldr when you're really sure that your fold is not an instance of something simpler. In your case, the fold is doing pretty much exactly two things while traversing the pattern list:

Keeping track of the "case index"
Accumulating the result list

The second should be easily recognisable as a map - maybe less obvious is that the first can just be written as a zip with an enumeration:

getResult :: [String] -> (Int, String) -> String
getResult w (count, pattern) =
  "Case #" ++ show count ++ ": " ++ show (numberOfMatches pattern w)

main :: IO ()
main = do
  [...]
  let results = map (getResult knownWords) $ zip [1..n] patterns

Which is much easier to understand than trying to bend the fold to do the right thing.

Also, just as a suggestion, here's main implemented in a more "imperative" (read: monadic) style. After all, Haskell is said to be the best imperative language ever invented, so we can do that proudly:

main :: IO ()
main = do
  [_, d, n] <- fmap (map read . words) getLine
  knownWords <- replicateM d getLine
  forM_ [1..n] $ \count -> do
    pattern <- getLine
    let matches = numberOfMatches pattern knownWords
    putStrLn $ concat ["Case #", show count, ": ", show matches]


A couple of conceptual errors:

Pass by value

You can remove the temporary copy of head in your functions. In C, all arguments are passed by value. This means you can operate directly on the head parameter exposed to your function without worrying about the argument in the calling code. Although both point to the same location, each is a different pointer variable with its own address.

Pointer declarations

struct pid_node* temp, other_part_of_list, delete_node;

Remember that the * is not part of the type, but part of the declarator. A clearer way to write declarations involving pointers is to move the * directly in front of the identifier. This follows the C convention that "declaration mimics use." So, the line changes to

struct pid_node *temp, other_part_of_list, delete_node;

Now the error (and fix) is obvious. If there is no * before a variable, its a variable of the type instead of a pointer to the type.

struct pid_node *temp, *other_part_of_list, *delete_node;

Edit: remove head special case

In order to modify the head argument itself, which is a pointer-to-struct, you need to pass a pointer-to-pointer-to-struct or return the new head. For example (pointer-to-pointer-to-struct):

void remove_pid_node(struct pid_node **head, struct pid_node *dead) {
...
    if (*head == dead) {
         temp = *head;
         *head = temp->next;
         kfree(temp);
         return;
    }

Then you would call the code like this:

remove_pid_node(&head, head);

Note: don't forget to check for NULL arguments.


With a bit of knowledge of modular math then you can know that for numbers > 0 getDigitalRoot(n)== n%9 except when dividable by 9 then it is 9.

This simplifies the algorithm a bit.

public static int getDigitalRoot(int n) {
    if(n==0)
        return 0;
    if(n%9 == 0)
        return 9;
    return n%9;
}

If you still want the looped version you can do a variation; instead of using another variable to hold the result and retrying until smaller than 10 just do this:

while (num >= 10) {
    num = num/10 +num % 10;
}

It works for roughly the same reason as the first modulo operation.


Extracting ids out of arguments of different types

You should expect
Starting a couple of years back, rspec is moving to a new expectation syntax, you should consider porting to it:

shared_examples 'it requests ids' do |resource|
  it 'sends the ids to Foo::Client' do
    allow(Foo).to receive(:parse)

    expect(Foo::Client).to receive(resource).once.with(expected)

    Foo.send(resource, *args)
  end
end

Be more transparent
Your code hides pretty well the fact that clients and services is different from accounts and contacts - both in your code and in your tests.
It makes your code quite obfuscated (in the name of DRYness?) - you should make it clear that you have two different behaviors - and spell them out:

shared_examples 'resources have numeric ids only' do |resource|
  it_behaves_like 'it requests ids', resource do
    let(:args) { [1, 2] }
    let(:expected) { [1, 2] }
  end

  it_behaves_like 'it requests ids', resource do
    let(:args) { [3, 'jesse-pinkman', 5, {'links' => {resource.to_s => [98, 99]}}] }
    let(:expected) { [98, 99, 3, 5] }
  end
end

shared_examples 'resources have numeric and string ids' do |resource|
  it_behaves_like 'it requests ids', resource do
    let(:args) { [2,'saul-goodman', 6] }
    let(:expected) { [2, 6, 'saul-goodman'] }
  end

  it_behaves_like 'it requests ids', resource do
    let(:args) { [3, 'saul-goodman', 5, {'links' => {resource.to_s => [202, 234]}}] }
    let(:expected) { [202, 234, 3, 5, 'saul-goodman'] }
  end
end

it_behaves_like 'resources have numeric ids only', :accounts
it_behaves_like 'resources have numeric ids only', :contacts
it_behaves_like 'resources have numeric and string ids', :clients
it_behaves_like 'resources have numeric and string ids', :services

And in your code, I would rather use simple method delegation than meta-coding:

class << self
  def accounts(*args)
    parse(client.accounts(hash_ids(args, :accounts) + numeric_ids(args))
  end

  def contacts(*args)
    parse(client.accounts(hash_ids(args, :contacts) + numeric_ids(args))
  end

  def clients(*args)
    parse(client.accounts(hash_ids(args, :clients) + numeric_ids(args) + text_ids(args))
  end

  def services(*args)
    parse(client.accounts(hash_ids(args, :services) + numeric_ids(args) + text_ids(args))
  end
end

It might be less DRY, but it is a lot clearer what your class actually does.


Suggestions on Python code to update/insert data in PRODUCTION system

A couple thoughts.

When opening database or other resources, try to use a context manager (the with statement). At the end of your code you are closing a bunch of connections/cursors:

## Closing cursors'
## Closing cursors'
cur_msql.close()
cur_psql.close()
cur_psql_1.close()
cur_msql_1.close()
cur_msql_2.close()

## Closing database connections
cnx_msql.close()

But your code could crash while processing, all it takes is a network error. There is no guarantee this code will be executed.

One thing you can do is wrap the code in a try/finally block, and move those lines to the finally section. You don't have to have an except section. So I think it would be a good idea to use the finally for cleanup tasks.

Some lines (the SQL statements) are way too long and require scrolling eg:

insert_sql_base="""select gr.email,c.customer_id,'',3,'',CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP),'','',CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)
                   from unsubscribed gr
                   LEFT JOIN nl_subscriber sn on sn.email=gr.email
                   LEFT JOIN customers c on c.customer_email=gr.email
                   WHERE sn.email IS NULL"""

You can reflow the text like this for example:

insert_sql_base = """SELECT gr.email,c.customer_id, '', 3, '',
CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP), '', '',
CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)
FROM unsubscribed gr
LEFT JOIN nl_subscriber sn ON sn.email = gr.email
LEFT JOIN customers c ON c.customer_email = gr.email
WHERE sn.email IS NULL"""

Added some more spacing too. Have a look at PEP guidelines, for instance PEP8.

Also, one thing I like to do is add aliases to the expressions in SQL queries. You have some blanks ('') or hardcoded values (3) but it's not immediately apparent what they represent.

I think that you could reduce the number of variables. Too many similar-looking variables increases the risk of confusion.
Consider this code:

msql_update_1="""UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'"""

msql_update_2="""UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';"""

cur_psql.execute(update_sql_base)

for row in cur_psql:
    email=row[0]
    cur_msql.execute(msql_update_1 %email)
    cur_msql_2.execute(msql_update_2 %email)
cnx_msql.commit()

You could have one cursor and reuse it eg:

for row in cur_psql:
    email=row[0]
    msql_update = """UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'"""
    cur_msql.execute(msql_update %email)

    msql_update = """UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';"""
    cur_msql.execute(msql_update %email)
cnx_msql.commit()

Although I am not sure why you have two statements instead of just one. Again, use context managers whenever possible to limit scope as much as possible.

There are very few comments in the code, and the flow is not that straightforward because there is overlap. For example:

update_sql_base="""select gr.email from unsubscribed gr
                   INNER JOIN nl_subscriber sn on sn.email=gr.email"""

msql_update_1="""UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'"""

msql_update_2="""UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';"""

cur_psql.execute(update_sql_base)

for row in cur_psql:
    email=row[0]
    cur_msql.execute(msql_update_1 %email)
    cur_msql_2.execute(msql_update_2 %email)
cnx_msql.commit()

Note that between the definition of update_sql_base and its execution, you define msql_update_1, msql_update_2. Move these two lines, try to keep related code together.

A very modest change to better separate the two (includes proposed changes above):

update_sql_base = """SELECT gr.email FROM unsubscribed gr
INNER JOIN nl_subscriber sn ON sn.email = gr.email"""
cur_psql.execute(update_sql_base)

for row in cur_psql:
    email=row[0]
    msql_update = """UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'"""
    cur_msql.execute(msql_update %email)

    msql_update = """UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';"""
    cur_msql.execute(msql_update %email)
cnx_msql.commit()

But I find that the name update_sql_base is misleading. This is not an UPDATE statement but a SELECT statement. The names are not very helpful overall.

You can declutter the code by moving blocks of code to small functions then call them in sequence eg:

open_mysql_db()
open_postgress_db()
update_mysql_db()
update_postgress_db()
close_postgress_db()
close_mysql_db()

That would make the whole more readable and easier to follow.

Example:

def copy_subscribers(cnx_msql, cnx_psql):
    """Copy subscribers from MySQL to Postgress
    """

    try:
        cur_psql = cnx_psql.cursor()
        cur_msql = cnx_msql.cursor()

        # get subscriber list from MySQL
        insert_sql_base = """SELECT gr.email,c.customer_id, '', 3, '',
        CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP), '', '',
        CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)
        FROM unsubscribed gr
        LEFT JOIN nl_subscriber sn ON sn.email = gr.email
        LEFT JOIN customers c ON c.customer_email = gr.email
        WHERE sn.email IS NULL"""
        cur_psql.execute(insert_sql_base)

        # insert susbcriber to Postgress
        msql_insert = """INSERT INTO `nl_subscriber`(`email`,  `customer_id`,
        `options`,  `status`,  `confirm_code`,
        `timestamp`,  `ip`,  `store_id`,`confirmed_at`)
        SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s"""
        for row in cur_psql:
            print(msql_insert)
            cur_msql.execute(msql_insert, row)

    finally:
        cnx_msql.commit()
        cur_psql.close()
        cur_msql.close()

I don't know if the function description is accurate but this is an idea. Note that I am passing connection instances cnx_msql and cnx_psql as arguments to the function (I prefer to avoid global variables). The idea is to better isolate the blocks, also avoid the proliferation of variables and at the same time limit their scope.


Code does not handle "wrap-around" correctly.

2 ^ 32 is the exclusive-or of 32 and 2.  That has the value of 34.  Instead, as unsigned math is defined to wrap-around, just subtract.

//if (endtime > starttime) {
//    deltatime = endtime - starttime;
//} else {
//    deltatime = ((2 ^ 32) - starttime) + endtime;
//}

deltatime = endtime - starttime;

Missing objects

event, appisrunning, renderer, window are not obviously declared before use in SDL_PollEvent(&event);.  Perhaps an SDL thing?

Unnecessary use of global variables

Uint32 starttime, endtime, deltatime; belongs in main().  Or even better, within the loop.

Use an auto formatter

The below code hints at manual formatting.  Use an auto formatter and save time.

 // render stuff here
 endtime = GetTickCount();
    if (endtime > starttime)

An auto formatter would have the below and constant indent amount per level (rather than 2 and sometimes 4 spaces).

Example re-format

#include <stdio.h>
#include <stdbool.h>
#include "SDL.h"
#include "Windows.h"

#define WIN32_LEAN_AND_MEAN
#define FPS 30

int main(void) {
  timeBeginPeriod(1);
  while (appisrunning) {
    Uint32 starttime = GetTickCount();
    SDL_PollEvent(&event);

    if (event.type == SDL_QUIT) {
      SDL_DestroyRenderer(renderer);
      SDL_DestroyWindow(window);
      SDL_Quit();
      appisrunning = false;
      break;
    }

    Uint32 endtime = GetTickCount();
    Uint32 deltatime = endtime - starttime;

    if (deltatime > (1000 / FPS)) {
    } else {
      Sleep((1000 / FPS) - deltatime);
    }
  }
  timeEndPeriod(1);
  return 0;
}


Calculate permutation from Factorial representation of the K-th iteration of the N-th permutation

The loop

for(int i = 0; i < N; i++)
    s.push_back(i);

is idiomatically expressed as std::iota(s.begin(), s.end(), 0) (you'd need to #include <numeric>).
A no naked loops principle demands giving a name to the

    for (int i = 0; i < N; i++) {
        e.push_back(s[c[i]]);
        s.erase(s.begin() + c[i]);
    }

loop. It surely represents an important algorithm. What exactly does it do?

In any case, the s and e vectors shall not be exposed to the client.
Computing factorials restricts the utility of the code to N < 21 (21! = 0x2_c507_7d36_b8c4_0000 doesn't fit in 64 bits). Unfortunately you cannot even express K within uint64_t limits for larger N. Consider BigInteger.
It is possible to avoid factorials (as well as ancillary vectors) by working other way around. Consider a pseudocode:

    while N > 0:
        index = K % N
        swap a[N-1] with a[index]
        K /= N
        N -= 1

While correct, it doesn't produce the same K'th permutation as your code does. May I suggest changing it to produce the correct sequence as an exercise?

PS: a mandatory warning on using namespace std


Algorithm optimization on date calculation

In my experience, Moment.js is somewhat too heavy for this simple task. Did some profiling not too long ago and the library does too much movement for this task. Maybe it's for robustness/scalability/compatibility purposes, but nevertheless, still heavy.

Straight to the point, check out this blog post which demonstrates his method of getting the ISO week. It appends an additional getWeek method to the native Date object. I have used this in one of my projects as substitute for Moment.js's ISO week function.

Date.prototype.getWeek = function () {
    // Create a copy of this date object
    var target  = new Date(this.valueOf());

    // ISO week date weeks start on monday so correct the day number
    var dayNr   = (this.getDay() + 6) % 7;

    // ISO 8601 states that week 1 is the week with the first thursday of that year.
    // Set the target date to the thursday in the target week
    target.setDate(target.getDate() - dayNr + 3);

    // Store the millisecond value of the target date
    var firstThursday = target.valueOf();

    // Set the target to the first thursday of the year
    // First set the target to january first
    target.setMonth(0, 1);
    // Not a thursday? Correct the date to the next thursday
    if (target.getDay() != 4) target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);

    // The weeknumber is the number of weeks between the
    // first thursday of the year and the thursday in the target week
    return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
}

As for your code:

I suggest putting it in plain English as much as you can. Readability will be an issue for reviewers who prefer verbose, purposeful naming.
Compared to the proposed code I have put up, your version creates way more Date objects (3 at my count). This could be a significant bottleneck if you are calling this function over a set of tabulated data. This is going to eat memory and CPU time.
"Cloning" a Date is as simple as var clone  = new Date(original.valueOf());. No need to individually call months, dates, etc. to setup the clone.


Move your code into functions
Functions are easier to test, and make it easier to modify your code over time.
For example, I think the first block requests information from a server and creates a list of links. I think the second block processes that list of links and generates some other sort of list. I think the third block iterates over the list from the second block and generates yet another list.
If these blocks were in functions, then the main logic would be self explanatory. For example, your code could look like:
...
ilmot = get_students(link)
parsittu = some_other_function(ilmot)
parsilmot = another_function(parsittu)
quote = create_quote(parsilmot)
...

If those functions all had reasonable names, the code would be very easy to understand, and it would be easy to test each function in isolation.
Not only that, but you can more easily move all of that code into a function so that you can implement a "refresh" feature into the UI so that you don't have to restart the script every time you want to update the data.


First of all, you should encapsulate your functionality in a function, unless you really want to use your code only once. At the moment you would have to duplicate your code somewhat just to check a second credit card. So instead let us write a function with a doc string:

def is_valid_card_number(sequence):
    """Returns `True' if the sequence is a valid credit card number.

    A valid credit card number
    - must contain exactly 16 digits,
    - must start with a 4, 5 or 6
    - must only consist of digits (0-9) or hyphens '-',
    - may have digits in groups of 4, separated by one hyphen "-".
    - must NOT use any other separator like ' ' , '_',
    - must NOT have 4 or more consecutive repeated digits.
    """

    #  do your stuff here

However, credit card numbers follow a fixed pattern, and therefore are a perfect candidate for regular expressions:

import re

PATTERN='^([456][0-9]{3})-?([0-9]{4})-?([0-9]{4})-?([0-9]{4})$'

This might seem arcane, so let us have a look at that pattern. Anything inside parentheses is considered a group. So we have four groups: ([456][0-9]{3}) and three times ([0-9]{4}). The hyphens in between have ? and are therefore optional. If they exist, they must occur once, so -- is not allowed.

The […] indicates are character class. Only characters inside that class are allowed at that point. The ^ indicates that we're describing the start of our string, not some point in the middle. So we have to start with 456. That requriement is now met. We're followed by 3 ({3}) digits. Our first group therefore consists of four digits, and so do the others. The $ makes sure that there is nothing left: our string has to stop there.

The re documentation provides more information.

We now have met most of our conditions:

we have 16 digits
we have groups of four
we only have digits or hyphens
we start with a 4, 5 or 6

We're missing the four consecutive digits. This is now tricky, since it's not clear whether the hyphens are part of the run. If they are only invalid four 4 character groups, we can simply check whether the current character * 4 is the complete group:

import re

PATTERN='^([456][0-9]{3})-?([0-9]{4})-?([0-9]{4})-?([0-9]{4})$'

def is_valid_card_number(sequence):
    """Returns `True' if the sequence is a valid credit card number.

    A valid credit card number
    - must contain exactly 16 digits,
    - must start with a 4, 5 or 6
    - must only consist of digits (0-9) or hyphens '-',
    - may have digits in groups of 4, separated by one hyphen "-".
    - must NOT use any other separator like ' ' , '_',
    - must NOT have 4 or more consecutive repeated digits.
    """

    match = re.match(PATTERN,sequence)

    if match == None:
        return False

    for group in match.groups:
        if group[0] * 4 == group:
            return False
    return True

If the repeated digits may also not span hyphens/groups it gets a little bit more complicated, but not too much. This is left as an exercise, though.

That being said: make sure to handle multiple numbers, not a single one. That way you will be able to check your code easier. But that depends. If it's a single use script, you probably don't have a need for a function.


Your class will be difficult to test since you don't implement Inversion of Control. In particular due to this line in the constructor:

_nsoWebService = new NSO { Credentials = GetCredentials() };

But the same applies to Logger _logger = LogManager.GetCurrentClassLogger();: what if you want to write a unit test to check whether the correct message is logged?

There are several instances of this:

if (errorCode != 0)
   HandleErrors(errorCode);
else
   _logger.Trace(/* message */);

I'd rather see this reversed, because testing for a negative makes things more complicated than they should be IMHO (I've also added brackets, something that you should always do):

if (errorCode == 0)
{
   _logger.Trace(/* message */);
}
else
{
   HandleErrors(errorCode);
}

Considering that this log action is the only thing that happens, you could even do this:

if (errorCode == 0)
{
   _logger.Trace(/* message */);
   return;
}

HandleErrors(errorCode);

Your errorCode shouldn't be an int, but an enum with a description.

Isn't there an overload for _logger.Trace() and _logger.Error() that functions the same as string.Format()? Seems there is if you're using NLog.

NSO doesn't follow Microsoft's rules: capitalize only the first character of acronyms with three or more characters. But it is also a class name that doesn't tell me anything.

I also don't think _user and _pass should be in the WebServiceAccess class, nor GetCredentials(). These things belong to NSO.

You do not take into account that an exception may have an inner exception:

_logger.Error("Error updating a technician in Navision. Error: " + ex.Message);

HandleErrors doesn't really do any error handling, now does it? It merely logs the error.


Naming

plAveragedPoints
paNearbyPoints

this variables would be more obvious if you wouldn't use this strange kind of hungarian notation. I figured out the pl means point list and pa point array, but if you need to read this fast you just can't because your brain will try to decypher what pl and pa means.

Does it really matter wether it is a List or an Array ?

       if (!plAveragedPoints.Any(p => p.X == nX && p.Y == nY))
        {
            plAveragedPoints.Add(new Point(nX, nY));
        }

and

       if (!plAveragedPoints.Any(p => p.X == points[pi].X && p.Y == points[pi].Y))
        {
            plAveragedPoints.Add(points[pi]);
        }

made me think that maybe a HashSet<Point> would be the better datastructure instead of a List<Point. You could simply call the Add() method and forget about the result of it.

Instead of using the tenary expression, @Caridoc had shown a different implementation which was a good start.

I would suggest to add another method which takes two Func<double,double> which are determined before calling that overloaded method like so

    private Func<double, double> CreateDesiredFunc(bool useFloor)
    {
        if (useFloor)
        {
            return Math.Floor;
        }
        return Math.Ceiling;
    }

Edit: Like @RickDavin pointed out in the comments this can be cleaned a little bit more by using more idiomatic names for the looping index variable and for the coordinate variables. In addition you should/could use the var type where it is clear from the right hand side of an assignment what type it is.

This boils down to the following

    private Point[] AverageNearbyPoints(Point[] points, bool averageLeft, bool averageHigh)
    {
        return AverageNearbyPoints(points, CreateDesiredFunc(averageLeft), CreateDesiredFunc(averageHigh));
    }

    private Point[] AverageNearbyPoints(Point[] points, Func<double, double> averageLeft, Func<double, double> averageHigh)
    {
        var averagedPoints = new HashSet<Point>();
        int numberOfPoints = points.Length;
        for (int i = 0; i < numberOfPoints ; ++i)
        {
            var nearbyPoints = points.Where(p => (Math.Abs(p.X - points[i].X) <= _nCornerTolerance)
                                              && (Math.Abs(p.Y - points[i].Y) <= _nCornerTolerance))
                                            .ToArray();
            var point = points[pi];

            if (nearbyPoints.Length > 1)
            {
                int x = (int)averageLeft(nearbyPoints.Sum(p => p.X) / (float)nearbyPoints.Length);

                int y = (int)averageHigh(nearbyPoints.Sum(p => p.Y) / (float)nearbyPoints.Length);

                point = new Point(x, y);

            }

            averagedPoints.Add(point);
        }

        return averagedPoints.ToArray();
    }


Improving the speed of creation for three Perlin Noise Maps in Python?

Losing your Loops

Austin Hastings' comment gives you a good hint where to look at. The main takeaway for you should be:

(Most) loops are damn slow in Python. Especially multiple nested loops.

NumPy can help to vectorize your code, i.e. in this case that more of the looping is done in the C backend instead of in the Python interpreter. I  would highly recommend to have a listen to the talk Losing your Loops: Fast Numerical Computing with NumPy by Jake VanderPlas. Although primarily tailored towards data science, it gives a good overview on the topic.

I did some slight modifications to your original script to include some of the vectorization ideas while still using your chosen Perlin noise library. (Sidenote: I changed the __ prefix to a single _, because that is the convention most Python programmers use for internal functions. See PEP8 style guide.)

# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
import noise
import timeit

class ST(object):
    MAP_HEIGHT = 1800
    MAP_WIDTH = 6400

def _noise(noise_x, noise_y, octaves=1, persistence=0.5, lacunarity=2.0):
    """
    Generates and returns a noise value.

    :param noise_x: The noise value of x
    :param noise_y: The noise value of y
    :return: numpy.float32
    """
    if isinstance(noise_x, np.ndarray):
        #rand_seed = np.random.randint(1, 9999, noise_x.size)
        rand_seed = np.ones((noise_x.size, ))   # just for comparison
        value = np.array([noise.pnoise2(x, y, octaves, persistence, lacunarity, r)
                          for x, y, r in zip(noise_x.flat, noise_y.flat, rand_seed)])
        return value.reshape(noise_x.shape)
    else:
        value = noise.pnoise2(noise_x, noise_y,
                              octaves, persistence, lacunarity,
                              1.0)   # just for comparison
                              #np.random.randint(1, 9999))
        return np.float32(value)

def _elevation_mapper(noise_x, noise_y):
    """
    Finds and returns the elevation noise for the given noise_x and
    noise_y parameters.

    :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
    :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
    :return: float
    """
    return _noise(noise_x, noise_y, 8, 0.9)

def _climate_mapper(y, noise_x, noise_y):
    """
    Finds and returns the climate noise for the given noise_x and
    noise_y parameters.

    :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
    :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
    :return: float
    """
    # find distance from bottom of map and normalize to range [0, 1]
    distance = np.sqrt((y - (ST.MAP_HEIGHT >> 1))**2) / ST.MAP_HEIGHT

    value = _noise(noise_x, noise_y, 8, 0.7)

    return (1.0 + value - distance) / 2.0

def _rainfall_mapper(noise_x, noise_y):
    """
    Finds and returns the rainfall noise for the given noise_x and
    noise_y parameters.

    :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
    :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
    :return: float
    """
    return _noise(noise_x, noise_y, 4, 0.65, 2.5)

def create_map_arr():
    """
    This function creates the elevation, climate, and rainfall noise maps,
    normalizes them to the range [0, 1], and then assigns them to their
    appropriate attributes in the singleton ST.
    """
    # assign noise map values
    randomizer = np.random.uniform(0.0001, 0.9999)

    start_arr = timeit.default_timer()

    X, Y = np.mgrid[0:ST.MAP_WIDTH, 0:ST.MAP_HEIGHT]
    noise_x = X / ST.MAP_WIDTH - randomizer
    noise_y = Y / ST.MAP_HEIGHT - randomizer
    elevation_arr_np = _elevation_mapper(noise_x, noise_y)
    climate_arr_np = _climate_mapper(Y, noise_x, noise_y)
    rainfall_arr_np = _rainfall_mapper(noise_x, noise_y)

    duration_arr = timeit.default_timer() - start_arr

    start_loop = timeit.default_timer()

    elevation_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
    climate_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
    rainfall_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
    for y in range(ST.MAP_HEIGHT):
        for x in range(ST.MAP_WIDTH):
            noise_x = x / ST.MAP_WIDTH - randomizer
            noise_y = y / ST.MAP_HEIGHT - randomizer

            elevation_arr[y, x] = _elevation_mapper(noise_x, noise_y)
            climate_arr[y, x] = _climate_mapper(y, noise_x, noise_y)
            rainfall_arr[y, x] = _rainfall_mapper(noise_x, noise_y)

    duration_loop = timeit.default_timer() - start_loop

    print(np.allclose(elevation_arr, elevation_arr_np.T))
    print(np.allclose(climate_arr, climate_arr_np.T))
    print(np.allclose(rainfall_arr, rainfall_arr_np.T))

    print("GENERATION TIME: loop: {:.6f}, array: {:.6f}".format(duration_loop, duration_arr))

if __name__ == "__main__":
    create_map_arr()

The bottleneck is still in

value = np.array([noise.pnoise2(x, y, octaves, persistence, lacunarity, r)
                  for x, y, r in zip(noise_x.flat, noise_y.flat, rand_seed)])

and it would be highly favorable to use an implementation which supports 2D input, preferably from NumPy, directly (see further reading below).

Nevertheless, the modifications bring the execution time down to a third of the original time on my machine (which is not that powerful):

True
True
True
GENERATION TIME: loop: 338.094228, array: 101.549388

Those three Trues are from a little test I added to check if the generated maps are the same within reasonable accuracy. For this purpose the additional random value in _noise was disabled.

Further reading

There have also already been similar questions on Code Review (see, e.g. here), where a reviewer created a Perlin noise implementation purely in Numpy. There also seems to be a GitHub project also doing Perlin noise with Numpy. So maybe have a look at them if your not forced to stick with noise.


Your code is \$O(n^2)\$. You can improve it to \$O(n)\$ by precomputing a sum array.

int solution(vector<int> &A) {
    int n = A.size();
    int i, j, rsum, lsum, difference;
    int currentmindifference = 1000;

    std::vector<int> pre(n);
    pre[0] = A[0];
    for (i = 1; i < n; i++)
        pre[i] = pre[i - 1] + A[i];

    for(i = 0; i < n; i++)
    {
        lsum = pre[i];
        rsum = pre[A.size() - 1] - lsum;
        difference = abs (lsum - rsum);
        if (difference < currentmindifference) currentmindifference = difference;
    }

    return currentmindifference;
}

Reasoning. By calculating a sum array, we save the need to calculate lsum on each iteration. Furthermore, we notice that we can find rsum by finding the total sum less lsum.

We can simplify this further by noting that lsum and rsum are now superfluous. We will also replace 1000 with std::numeric_limits<int>::max() to ensure we get a true minimum instead of capping it, and check if A is empty before using it.

#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>

int solution(std::vector<int> &A) {
    if (A.empty())
        return -1; // or some other meaningful error value

    int n = A.size();
    int minDifference = std::numeric_limits<int>::max();

    std::vector<int> pre(n);
    pre[0] = A[0];
    for (int i = 1; i < n; i++)
        pre[i] = pre[i - 1] + A[i];

    for (int i = 0; i < n; i++)
        minDifference = std::min(minDifference, std::abs(2 * pre[i] - pre[n - 1]));

    return minDifference;
}

Further reading: Prefix sum array and difference array. Disclosure: I am an administrator on this site. Excuse the formatting.


Return a string without the first two characters

Yes, some of the things you are doing is redundant and quite messy. As this seems to be a homework assignment I will only provide hints for you here.

What you can do is:

If the string is empty, return an empty string immediately
Store the first character in a variable
Store the second character in a variable, if it exists
Store the rest of the string in a variable, if it exists
Check if the second character is 'b', if it is then add it to the beginning of the string
Check if the first character is 'a', if it is then add it to the beginning of the string
Return the string

A problem of your existing code is that it will fail for strings of length 1. So it is important to only use the first and second characters if they exist at all.


Your first step is to wind your thinking back a few steps and re-approach your code with a fresh line of thinking. Looking at your code, you say "to detect the real file type of a given file" but you have written code to detect a JPEG(*) file.

There is a subtlety here, but once you have mastered that you can approach complex problems with more confidence. The subtlety is you want a generic approach, but your thinking at the moment is constrained to and focussed on a particular example - your solution is tailored to that example. More specifically, your current code answers the question "Is this a JPEG file?", you want your solution to answer the question "What is the file type of this file?".

Signatures

You define your signatures early. This is a good approach because it lends itself to a future implementation where you can import a tailored list of signatures.

However, you are currently using separate arrays to store the signature data. The use of multiple arrays is going to be inefficient for any improvements or even for checking multiple files/filetypes.

The use of static arrays implies looping through all arrays. In a small implementation this is not that noticeable, but if you have a hundred arrays with a size ranging from 3 to 15 bytes, you will start to notice a performance hit. Basically, you will be continuing to check arrays that you have already eliminated as being relevant to your quest.

A suggested way to improve the performance initially is to put the signatures in a collection (e.g. List(Of OrderedList(Of Byte))). This way, once you eliminate a signature you can remove it from the collection, thus quickly removing the unnecessary checks with a commensurate improvement in performance.

The use of the inner collection removes the need to check array lengths, but having a List(Of Array) could also work.

Looping

You manually loop through your array. This is always a simple first approach and reflects the basic solution to identifying a signature. Your code is set up to first loop through the first signature and I assume you were thinking of duplicating this kind of loop for the other signatures.

Sitting here, I can think of two simple approaches:

Looping through the file bytes individually, removing signatures from the collection as they fail
Looping through the signatures and doing an array check against the first x bytes of each file

Intuitively, I think the second option will be less efficient but I could be wrong.
Some example code (not guaranteed to be compilable):

For Each file As String In files
    file_data = IO.File.ReadAllBytes(file)
    For signatureIterator = MasterSignatureList.Count - 1 to 0 Step -1
    ' Declare and implement as required
    ' Used a For loop going backwards because in this example we are going to remove elements from the collection
        signature = MasterSignatureList(signatureIterator) ' the shorter text makes my example easier to read.
        If file_data.Length < signature.Length then
            MasterSignatureList.Remove signatureIterator
        Else
            If Not CheckArrayIsSame(file_data.Resize(signature.length), signature) then
            ' Some function to check arrays are the same will be required
            ' The native .Resize actually changes the original array, so you should make a copy before running .Resize. I was being lazy.
                MasterSignatureList.Remove signatureIterator
            End If
        End if
    Next signatureIterator
' **** do something here with the remaining signatures as these are the valid ones for that particular file!
Next file

And an example for the first option

For Each file As String In files
    file_data = IO.File.ReadAllBytes(file)
    For each signature in MasterSignatureList
        if filedata.Length < signature.Length Then MasterSignatureList.Remove signature ' Obviously wrong
    Next signature
    For signatureIterator = 0 to file_data.Length ' we should exit the loop before getting to the end of most files!
        signatureCheck = false
        For each signature in MasterSignatureList
            If signatureIterator <  signature.Length Then ' retains signatures that have already passed
                signatureCheck = true ' still some signatures to check
                If file_data(signatureIterator) <> signature(signatureIterator) Then
                    MasterSignatureList.Remove signature ' signature does not match
                End if
            End if
        Next signature
        If MasterSignatureList.Empty or Not signatureCheck then Exit For ' exit if nothing left to check
    Next signatureIterator
' **** do something here with the remaining signatures as these are the valid ones for that particular file!
Next file

In both of those examples, the signatures remaining in the signature list are the potential file types. In these examples, the possibility of multiple signatures passing is allowed - how you handle that is up to your programming logic.

As already noted - I have not tested the above code, so also check for the dreaded Jedi array error condition (off-by-1) in my iterations.

(*) The correct nomenclature is JPEG, the file extension in traditional 8.3 style is ".jpg". Why this is so, I leave up to your own research.


You're using the right approach with the log - you're saving it in a variable so you don't have to select the element again. Do the same thing with the newly appended
.

const log = $('#log')

function logMessage(message, type) {
    const newDiv = $('

')
      .addClass(type)
      .appendTo(log);
    for (let charIndex = 0; charIndex < message.length; charIndex++) {
        setTimeout(() => {
            newDiv.append(message[charIndex])
        }, charIndex * 10)
    }
}

logMessage('something with lots and lots and lots and lots of characters', 'sometype');

A tiny issue with iterating over the indicies of the string manually is that characters composed of surrogate pairs (like ) will take twice as long to print as others, and if you were to slow down the animation, you'd get a broken character before the second part gets fully rendered:

const log = $('#log')

function logMessage(message, type) {
    const newDiv = $('

')
      .addClass(type)
      .appendTo(log);
    for (let charIndex = 0; charIndex < message.length; charIndex++) {
        setTimeout(() => {
            newDiv.append(message[charIndex])
        }, charIndex * 500)
    }
}

logMessage('something with lots and lots and lots and lots of characters', 'sometype');

It also might be useful to return a Promise indicating that the message has been fully logged, instead of a number indicating how long to wait before the message is finished.
To tweak this, and to avoid having to touch the string indicies at all (since you only really care about the characters, not the indicies of characters) would be to invoke the string's iterator and await a Promise inside the loop:

const log = $('#log');
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function logMessage(message, type) {
    const newDiv = $('

')
      .addClass(type)
      .appendTo(log);
    for (const char of message) {
        newDiv.append(char);
        await delay(500);
    }
}

logMessage('something', 'sometype')
  .then(() => {
      console.log('message fully printed');
  });

I'm a bit worried about the log ID - you have both a global identifier log which refers to the HTMLElement and exists on the window. Then the code shadows the global identifier and creates a log which refers to the jQuery collection. It's an unlikely source of bugs, but I'd use a class instead of an ID.
I notice you're not using semicolons. If this is a deliberate style choice and you consider yourself an expert who can avoid the pitfalls of Automatic Semicolon Insertion, that's just fine. Otherwise, you may occasionally run into very confusing bugs due to a statement unexpectedly crossing a linebreak, and I'd recommend using them.


requests is third-party, so (per the style guide) there should be a blank line in the imports:

import os

import requests

api_repo is constant, so should be API_REPO. There should also be spaces around the = in assignments:

API_REPO = 'https://api.github.com/user/repos'

Explicit line continuation isn't very Pythonic, especially when the line is short enough anyway:

url = '%s?access_token=%s' % \
(api_repo,API_TOKEN,)

Also, there should be spaces after commas (and I wouldn't bother with the trailing one). This would be better written as:

url = '%s?access_token=%s' % (API_REPO, API_TOKEN)

r and i aren't very good variable names. I would use req_json and git_url.

You are mixing % string formatting with + concatenation. You should at least be consistent, and I would use the more modern str.format:

os.system("git clone {}".format(git_url))

You should also be consistent with string literal quotes. Per the style guide:

  In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

In all, I would probably have written it as:

import os

import requests

API_TOKEN = "..."
API_URL = "https://api.github.com/user/repos"

url = "{}?access_token={}".format(API_URL, API_TOKEN)
req_json = requests.get(url).json()

for repo in req_json:
    os.system("git clone {}".format(repo["git_url"]))


First thing I notice is that this...
nxt = input('Welcome, press enter to continue \n')
if nxt == '':
    break

...could just be:
input('Welcome, press enter to continue')

It doesn't seem like you're using nxt for anything else so there's no need to store a value for it, especially if you just want the user to hit enter.

Next, you never do f_n.close() which can cause some issues with the file (e.g., it doesn't save or something weird happens with the garbage collector system, etc.).
You might want to replace...
elif name.lower() == "exit":
    exit()

...with:
elif name.lower() == "exit":
    f_n.close()
    exit()

The same should be done with the file in the first elif. Something I also noticed about this is that f_n is the same file as f. You shouldn't need to keep opening it; just use the f_n variable.

Instead of...
if name.lower() == "add":
    n_input = input("Name:")
    with open('names.txt', 'a') as f:
        f.write(n_input + '\n')
        f.close()
    continue

...with:
if name.lower() == "add":
    n_input = input("Name:")
    with open('names.txt', 'a') as f:
        f.write(n_input + '\n')
        f.close()

You don't need to say continue because the rest of the while loop is just elifs.

In terms of overall code style, mostly good, but there are a few things you might want to keep in mind:

Put spaces around equals signs for readability (e.g., use n = 10 instead of n=10).
It's spelled "log" not "logg."
I don't see a usage of snames, so is it really necessary?
The first comment in your code looks rather odd. Maybe just say # USER LOGIN , use a simple block comment, or, if you have to:

##############
# USER LOGIN #
##############

Hope this helps! If I think of something else, I'll edit it in.


Hook to switch the linter binaries in Emacs Lisp according to virtual environment

It would be a good idea to write a docstring for the defvar'd variables like linter-execs. The explanations in the post would make an excellent start, for example:

(defvar linter-execs '((flycheck-python-flake8-executable "bin/flake8")
                       (flycheck-python-pylint-executable "bin/pylint")
                       (flycheck-python-pycompile-executable "bin/python"))
  "The linter executables, as list of two-element lists. The
first element of an entry is the flycheck variable that contains
the path of a linter executable. The second element is the
relative path of the executable from within the venv.")

Writing (nth 0 exec) and (nth 1 exec) makes it hard to understand the meaning of these items of data. In Python you'd use tuple unpacking to give meaningful names to each element of the exec data structure, like this:

flycheck_var, path = exec

In Emacs Lisp you can use cl-destructuring-bind in a similar way:

(dolist (exec linter-execs)
  (cl-destructuring-bind (flycheck-var path) exec
    (let ((venv-linter-bin    (concat pyvenv-virtual-env path))
      ;; etc

But exec comes from a list that you are looping over, so you could use the cl-loop macro instead of dolist, and cl-loop has destructuring built in:

(cl-loop for (flycheck-var path) in linter-execs do
  (let ((venv-linter-bin    (concat pyvenv-virtual-env path))
    ;; etc

You'll need (require 'cl-macs) to use cl-destructuring-bind or cl-loop.
The two directories pyvenv-virtual-env and default-linter-venv-path are treated in exactly the same way: first we do (let ((Y (concat X path)) and then (file-exists-p Y) and finally (set flycheck-var Y). This repetition could be factored out into a loop:

(defun switch-linters ()
  "Switch linter executables to those in the current venv.

If the venv does not have any linter packages, then they will be
set to those in the `default-linter-venv-path` venv.  If these do
not exist, then the linter will be set to nil."
  (cl-loop with dirs = (list pyvenv-virtual-env default-linter-venv-path)
           for (flycheck-var path) in linter-execs
           do (set flycheck-var
                   (cl-loop for directory in dirs
                            for executable = (concat directory path)
                            if (file-exists-p executable) return executable)))

Instead of file-exists-p, you probably want to use file-executable-p.
Looking for a file in a list of directories is built into Emacs as the function locate-file. Using this, we get:

(defun switch-linters ()
  "Switch linter executables to those in the current venv.

If the venv does not have any linter packages, then they will be
set to those in the `default-linter-venv-path` venv.  If these do
not exist, then the linter will be set to nil."
  (cl-loop with dirs = (list pyvenv-virtual-env default-linter-venv-path)
           for (flycheck-var path) in linter-execs
           do (set flycheck-var (locate-file path dirs nil 'file-executable-p))))


For convenience, even though the challenge doesn't specify it, I suggest optionally taking input from System.in.  It's more reasonable behaviour than crashing with an ArrayIndexOutOfBoundsException.

Scanner input = (args.length > 0) ? new Scanner(new File(args[0]))
                                  : new Scanner(System.in);

In printCashChange(), avoid two calls to split().

String[] fields = line.split(";", 2);
float pp = Float.parseFloat(fields[0]);
float ch = Float.parseFloat(fields[1]);

The loop in getCashChange() should be data-driven, like this:

for (Denomination d : Denomination.values()) {
    while (cashBack >= d.getValue()) {
        cashBack -= d.getValue();
        change.append(d).append(',');
    }
}

Here's an enum to support that:

public enum Denomination {
    ONE_HUNDRED(100.00f),
          FIFTY( 50.00f),
         TWENTY( 20.00f),
            TEN( 10.00f),
           FIVE(  5.00f),
            TWO(  2.00f),
            ONE(  1.00f),
    HALF_DOLLAR(  0.50f),
        QUARTER(  0.25f),
           DIME(  0.10f),
         NICKEL(  0.05f),
          PENNY(  0.01f);

    private final float value;
    private final String description;

    Denomination(float value) {
        this.value = value;
        this.description = this.name().replace("_", " ");
    }

    public float getValue() {
        return this.value;
    }

    @Override
    public String toString() {
        return this.description;
    }
}

The performance of your program will be fine.  You aren't doing anything particularly inefficient, and the bottleneck will be I/O rather than processing.


Your filter isn't actually producing any benefit if the resulting collection isn't saved for further processing.

dataMapStorage.keys
  .foreach { key =>
    val value = dataMapStorage.get(key)
    if (currentTime.getMillis - value.getMillis > timeout) {
      // ... do some work with "value"
      dataMapStorage.remove(key)
    }
  }

Also, if dataMapStorage is just a key->value Map then couldn't you simplify it?

dataMapStorage.foreach { case (key, value) =>
    if (currentTime.getMillis - value.getMillis > timeout) {
      // ... do some work with "value"
      dataMapStorage.remove(key)
    }
  }

You could use collect() here but since the procedure results in a side-effect I think foreach() is more explanatory.

Of course the real Scala FP approach is to avoid mutable data structures.

val newDataMapStorage = oldDataMapStorage.filter { case (key, value) =>
    if (currentTime.getMillis - value.getMillis > timeout) {
      // ... do some work with "value"
      false
    } else true
  }


Find the number of elements larger than a given element in BST

Answering my own question, I made these improvements to the code which allowed me to solve the HR problem:

Instead of representing duplicate values as separate nodes use a counter of occurrences of the value.
Since we need to get the rank of a value immediately after inserting it, we can combine the insert() and get_rank() methods.
Turn recursion into iteration.

The final code:

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
        self.num_right_children = 0
        self.occurrences = 1

    def insert(self, data):
        current_node = self
        rank = 0

        while True:
            if data < current_node.data:
                rank += current_node.num_right_children + current_node.occurrences
                if current_node.left is None:
                    current_node.left = Node(data)
                    break
                current_node = current_node.left
            elif data > current_node.data:
                current_node.num_right_children += 1
                if current_node.right is None:
                    current_node.right = Node(data)
                    break
                current_node = current_node.right
            else:
                current_node.occurrences += 1
                rank += current_node.num_right_children
                break
        return rank


From what it looks like, you are correctly checking the submission form for a valid CSRF token before processing, therefore a separate, malicious website [EDIT: without access to the hidden CSRF token on the submission form] would be unable to execute CSRF.

From here: Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user's web browser to perform an unwanted action on a trusted site for which the user is currently authenticated


Loading and displaying JSON quickly in PhoneGap app

Although I doubt it will make a big difference and help you much,
but it would be more efficient to move operations out of the function whose input and output never change. Such as these:

var path = window.location.href.replace('index.html', '');
path + "data/heb-text/"

No need to execute these every time a tap is fired.
You could execute these once, save the result in a variable,
and use those variables inside the tap handler.

If the document structure doesn't change,
then you could save processing time by caching these dom lookups too:

$('.date')
$('.title')
$('ol')
$("html, body")

Again, this might not make a big difference, but perhaps worth a shot anyway.


Cyclomatic complexity
is a measure of the number of possible paths thorough some code. For example an if statement with one clause eg if (foo) {} has two paths, One if foo is true and one if false. Any point where the code can branch, the branches are counted as part of the cyclomatic complexity.
Unfortunately how the complexity is summed differs so without knowing how the metric was calculated there is no easy way to give an answer. The best you can do is reduce the number of possible branches in the code.
Improving the code
Looking at your code and there is plenty of room to reduce the number of branches.
The function shortestCostNode is not needed as the shortest link in a node has no influence on the final result. The shortest link may well move you to the longest path. Searching for the shortest link is no improvement on picking nodes sequentially.
shortestCostNode is the major source of complexity in your solution, it effectively randomizes your search. Because of this you must track which path you have traveled so you don't end up repeating the same path, this adds a lot of baggage.
If you systematically search all possible paths in order (keeping track of where you have not been) you eliminate the need to track where you have been and can thus remove a lot of code.
Use a stack to search a tree
As the search for the shortest path involves traveling along paths and then backtracking to the nearest untraveled branch a stack is the best way to keep track of your progress.
You start at a node, push all paths and the cost so far to a stack, then pop one path and move along that path to the next node adding the cost as you do. Then do the same for the next node.
When you reach an end node you then check the distance and if it is the shortest so far you save that distance and the path traveled. Then pop the next path step from the stack until all paths have been checked.
A Recursive stack
The simplest (but not the quickest) way to implement a stack is via recursion.
Thus you end up with a function something like
function shortestPath(graph) {
    const result = {distance: Infinity}, endName = "end";
    function followPath(node, totalDist = 0, path = ["start"]) {
        for (const [name, length] of Object.entries(node)) {
            const distance = totalDist + length;
            if (distance < result.distance) {
                if (name === endName) {
                    Object.assign(result, {distance, path: [...path, endName]});
                } else {
                    path.push(name);
                    followPath(graph[name], distance, path);
                    path.pop();
                }
            }
        }
    }
    followPath(graph.start);
    return result;
}

The function has a Cyclomatic complexity of about 5.
Note that the function only follows paths while the distance traveled is less than the shortest path found already found. This means that you may not need to check all paths to the end.
There is also plenty of room for improvement (in terms of complexity and performance), but as you have not defined much about the graphs possible structure there is no point going any further,.


The code provided might fulfill the functionality however the API is hard to use.

Passwords are usually strings and not binary (byte[]). It would also be nice that the salt could be generated automatically when you hash the password. That way you would call a single method to hash a password instead of calling two methods, in this case that would be GenerateSalt followed by HashPassword.

According to my argument I would suggest you to implement the following API:

// returns hashed password + salt
Tuple<byte[], byte[]> HashPassword(string password, int iterations)
bool ComparePassword(string attempt, byte[] hashedPassword, byte[] salt)

You can always replace the Tuple type by another class that would have the properties byte[] HashedPassword and byte[] Salt. Also often, but not always, the salt and the password are usually base64 encoded. That usually allows you to have a slightly nicer view of the data that is stored while also avoiding storing binary data in your persistence mechanism.

Additionally Rfc2898DeriveBytes outputs 20 bytes. So return rfc2898.GetBytes(32); should be return rfc2898.GetBytes(20);

Answering your additional question about the iteration count, there is nothing wrong with that. You can even use that as a pepper, different users can have slightly different iteration counts. Which makes the job of a hacker harder. In some scenarios people also store the actually algorithm that was used to hash the password. That might allow you to switch between algorithms in a easier fashion.


Handling multiple optional parameters in Spring

Although it works, the major issue with this approach is its extreme complexity and concreteness. If a new parameter d enters the game, it will became hellish to maintain!
What can be done to improve the current implementation, without changing the approach?

there are many repetitions of .containsKey(arg) calls. They can be extracted to respective booleans like hasA, hasB -> the code will be more readable.

there are many redundant casts. (String) query.get("a") and the others can be extracted into respective local var a = (String) query.get("a") -> it will also become shorter and more readable.

I think that the result variable might be avoided, if myDao.get* methods already return Sets.

How the design can be improved?
For the solution below, I suppose that the interface of the myDao object cannot be changed. If it could, there might be ways to play with method overloads, attempting to apply a pattern.
The current API of myDao looks very concrete and clear. The names of the methods mention each expected parameter and the order and the number of the arguments is predictable for each case. So the solution that I suggest below is based on the calculation of the method to invoke by reflection.
The name of the method to invoke on myDao can be calculated as follows:
private String calculateDaoMethodToInvoke(boolean hasA, boolean hasB, boolean hasC) {
  var builder = new StringBuilder("getBy");
  if (hasA) {
    builder.append("A");
  }
  if (hasB) {
    builder.append("B");
  }
  if (hasC) {
    builder.append("C");
  }
  return builder.toString();
}

We can also calculate the arguments to invoke this method with:
private Object[] calculateDaoMethodArgs(String a, String b, Map<String, String> c) {
  return Stream.of(a, b, c)
               .filter(Objects::nonNull)
               .toArray();
}

Now, since we know the name of the target method and the parameters to use, the Java reflection features can be used to produce the results.
We can define a wrapper around the Class.getMethod call, in order to retrieve the reference to the method of myDao to be invoked:
private Method extractDaoMethod(String daoMethodName, Object[] params) {
  try {
    var paramTypes = Arrays.stream(params)
                           .map(Object::getClass)
                           .toArray(Class[]::new);
    return Dao.class.getMethod(daoMethodName, paramTypes);
  } catch (NoSuchMethodException ex) {
    throw new IllegalStateException(ex);
  }
}

And its invocation can also be wrapped:
private Collection<ResultEntry> getByParams(String daoMethodName, Object[] params) {
  var method = extractDaoMethod(daoMethodName, params);
  try {
    return (Collection<ResultEntry>) method.invoke(myDao, params);
  } catch (IllegalAccessException | InvocationTargetException ex) {
    throw new IllegalStateException(ex);
  }
}

Finally, the getByParameters method is reduced to the following:
public Set<ResultEntry> getByParameters(Map<String, Object> query) {
  var a = (String) query.get("a");
  var b = (String) query.get("b");
  var c = (Map<String, String>) query.get("c");

  var daoMethodName = calculateDaoMethodToInvoke(a != null, b != null, c != null);
  var daoArgs = calculateDaoMethodArgs(a, b, c);
  return new HashSet<>(getByParams(daoMethodName, daoArgs));
}

Please note that there are no more rigid if - else if chaining, the algo became flat.
This approach allows to easily introduce new parameters, provided that the myDao API continues to respect the same convention for its method names.
There can be further improvements. For example, the signatures of calculateDaoMethodToInvoke and calculateDaoMethodArgs can be changed in order to accept varargs (and corresponding changes in the implementation). It will make the introduction of new parameters even easier.


Time of day based timer - run function at certain time, daily

Without knowing what you're trying to do, I'd say this is the wrong approach. I would create an executable and set it up as a scheduled task to run every 24 hours.

Not sure what OS you are using, but assuming it's windows its fairly easy http://windows.microsoft.com/en-au/windows7/schedule-a-task


Your variable names are quite hard to make sense of. I had to read your explanatory text to figure out what vali was supposed to do; I still have no idea what obs means. Judging by the line print O+'[+]'+W+' Got first packet! Many more to go...\n', it also looks like you might have a variable called "O" (capital letter oh), which most style guides advise against because it's hard to distinguish it from 0 (the number zero). I would use longer, more descriptive names. Write out validation or valid_pairs instead of using vali. Write packet and packet_counter instead of p and pc. I could have written my first sentence as "ur vrbl nms r q hd 2 mk sns of", and you might have been able to understand it, but ovssly ts mch mr dfclt 2 ndrstnd if i wrt lk ths. Apply the same principle to your code.

Spaces between your string concatenation operators also make code easier to read: print O + '[+]' + W + ' Got first packet! Many more to go...\n' is easier to read than the version with everything all scrunched up. In this case, though, I would prefer format strings to using concatenation: print "{} [+] {} Got first packet!".format(O, W). (Or the percent-sign version, if you're stuck on a version of Python before 2.6.)

Your code is rather deeply nested, which makes it harder to read and understand overall. The Zen of Python says flat is better than nested, and while I don't always agree with the Zen, in this case I think it's right. To relieve this problem, I would make some functions. Pick out some nested blocks and drop them into their own functions, passing in whatever arguments they need, so your code is flatter and easier to read and understand. At the very least, your entire block under if p.haslayer(Dot11Elt) could be its own function.

There are improvements both big and small that could be made to your for loop. It looks like you could do the same thing you currently do in a lot less code, like this:

if (p.addr2, ssid) not in obs:
    obs.append((p.addr2,ssid))
    checkmac(p.addr2)
    checknet(ssid)
    count +=1
    get_oui(p.addr2)
    print str(count)+'>',p.addr2+' ('+G+macf+W+') <--Probing--> '+O+ssid+W
    wr_log(p.addr2,ssid,macf)

This does a linear search of obs for the tuple (p.addr2, ssid); it checks every element in obs to see if it's equal to (p.addr2, ssid) as your current code does.

But there are faster ways to do this. I would probably rethink the way obs is stored. Right now, you're storing the valid pairs of MAC addresses and SSIDs as a list, so in order to find duplicates, you have to do a list search. You could speed this up by sorting the list and using a binary search, but you can speed it up even more by bringing a set into the equation.

It wasn't clear to me from your explanation whether you need obs to be in order or not. If you don't need it in order, you can just switch from a list to a set:

if (p.addr2, ssid) not in obs_set:
    obs_set.add((p.addr2, ssid))
    # other stuff

If you do need it in order, you can still use a set to speed this particular operation up, but unfortunately, there's no ordered set in Python. The Stack Overflow question Does Python have an ordered set? gives several ways you can mimic one. Another option: you could just keep your current list, but also add everything to a set. Maybe even wrap it in a class so you don't have to remember to do both. It's sort of hacky, and it takes more memory, but it's simple, quick to implement, avoids adding more dependencies, and is much easier than implementing your own red-black tree. (I consider an OrderedDict with all the values as True to be kind of hacky and a waste of memory too.)


Implementation of Newton's method of finding root of a function

Math.Abs(y) >= EPSILON

I think this condition is only satisfied for roots around zero on the x-axis. Maybe you confuse yourself by naming the next x as y? A better name would be x1.

The actual continue condition should be Math.Abs(x - x1) >= EPSILON and you then can skip the test if (x == y) break;

Your rather large value of EPSILON may result in imprecise roots now and then.

You can clean up the main algorithm to something like:

public static double Newton(MyFunction func, double init)
{
  double x;
  double x1 = init;

  do
  {
    x = x1;
    x1 = NextNewton(func, x);

    Console.WriteLine("Root = {0}", x1);
  } while (Math.Abs(x - x1) >= EPSILON);

  return x1;
}


Summarizing the score of a personality quiz

Let me review your code first and then provide an alternative:

The naming for the reduce-function is a little confusing, since you're just using x. Generally the lambda parameters are problematically named. Only fixing the naming should already give huge boosts to maintainability:

const res = _.zip(questions, answers)
    .filter(qa => qa[1])
    .map(qa => qa[0].quadrant)
    .reduce(
        (res, quadrant) => {
        [...]
    );

that was the simple part. Along the way we kind of made the comments in the code superfluous. I'll not review the assignment of the return quadrants though it seems like there could be some simplifications if you didn't try to directly return a hardcoded array.

Let's reexamine your approach. You already stated that you're basically trying to accumulate increments and decrements along two axes. Let's consider the following then:

.filter(qa => qa[1])
.map(qa => {
  switch (qa[0].quadrant) {
     case 1:
       return { dominance: 1, warmth: -1 };
     case 2:
       return { dominance: -1, warmth: -1 };
     case 3:
       return { dominance: -1, warmth: 1 };
     case 4:
       return { dominance: 1, warmth: 1 };
     default:
       return { dominance: 0, warmth: 0 };
  }
}).reduce(
  (res, assessment) => {
    return { dominance: res.dominance + assessment.dominance,
             warmth: res.warmth + assessment.warmth }
  },
  { dominance: 0, warmth: 0 }
);

This clarifies your logic tremendously and makes obvious to the reader which quadrant entails which change in assessment


A couple of issues I found:

GetConnection method:

var connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
_connection = new MySqlConnection(connectionString);
_connection.Open();

Here you're creating a new connection object and storing it in _connection. This is not defined anywhere in the code, but seems like a private field. This shouldn't be necessary, as you're simply returning it and leaving it to the caller to handle it. Just use a normal variable and get rid of the field:

MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
return connection;

    catch (MySqlException ex) {

        switch (ex.Number)
        {
            //0: Cannot connect to server.
            case 0:
                MessageBox.Show("Cannot connect to server.  Contact administrator");
                break;
            //1045: Invalid user name and/or password.
            case 1045:
                MessageBox.Show("Invalid username/password, please try again");
                break;
        }

    }

This seems like a bad idea to me. For one, you're using MessageBox.Show to display errors, which ties it to the presentation layer. This breaks Separation of concerns, as the class should only do one thing. Leave it to the caller to display errors the way it likes.

Another issue is that any further detail about the error is lost, like the stack trace, message or any inner exceptions. A second, major issue is that any error with a number other than 0 or 1045 is simply shallowed and the caller has no idea it failed, leaving it with a closed, failed connection. My suggestion is to simply remove the try-catch althogether and make the caller handle errors as it finds appropriate.

AuthenticateUser method:

string query = "SELECT * FROM users WHERE user_name = @userName LIMIT 1";

A small issue with the LIMIT 1 is that it implies that there could be more than one user in the DB with the same username. That can be an indication of an issue on the DB design, lacking an UNIQUE key in the user_name column, it shouldn't be needed. Another problem is the use of SELECT * which brings more data than needed. Specify those columns you actually use and leave the rest out.

Console.Write("connection");

This is odd to put here. For one, other pieces of code refer to MessageBox to display errors and messages, while this uses the console. Why this inconsistency? Either use one display technology or the other, but clearly not both. As before, this creates a poor user experience in seeing random debug messages out of nothing. Most likely, this could be replaced by some kind of log to a file or similar, but remember to add more context to it, so you can extract some useful information out of the file.

cmd.Parameters.AddWithValue("@userName", this.UserName);

It's always nice to see properly parametrized queries. But remember that AddWithValue is a bad practice, declare the exact data type for the parameter and make sure it matches the server side declaration exactly.

while (reader.Read())

There is no need to loop here. As before, the query will return at most only 1 row, or nothing is the user name is wrong, so just replace it by a single call. if (!reader.Read()) return false; will do, and will exit early is no user exist.

password = BCrypt.Net.BCrypt.Verify(this._password + reader["salt"].ToString(), reader["password"].ToString());

Great to see a properly stored password and a nice validation! There is a small thing though. Keep the scope of the password variable as small as possible, possibly with a return at this point to avoid having to read until the end of the method. Also, "password" don't seems like a proper name for this one, something like "validPassword" would better describe what's going on.

this._user_id = int.Parse(reader["id"].ToString());

This is possibly the gravest problem. The method uses class fields all other the place (to input the username and password and to return the user id), which seems odd to me, because that ties the result of this method to the state of the class, which can be used elsewhere (although we don't have that much context here). Why not use method parameters and return values instead? So you can get rid of all private class-level variables. I find a method declaration like this to be much better:

public int? AuthenticateUser(string userName, string password)

The username and password are passed as parameters instead of class fields, and the return value is the id of the logged user or null if nothing is found. This clearly expresses what's going on and what the method expects and return. Also, this allows to simplify the body by doing something like this:

//Check if the password matches, and exit if not
if(!BCrypt.Net.BCrypt.Verify(this._password + reader["salt"].ToString(), reader["password"].ToString())) return null;
//We've got a valid user and password, return its id
return int.Parse(reader["id"].ToString());

   catch (MySqlException ex)
    {
        throw new ArgumentException(ex.Message);
    }

Once again the same problem. The exception is caught and a new one is thrown. But here the problem is that it's misleading. For one, the type ArgumentException is wrong, you didn't make a mistake in the arguments, something blew up while contacting the DB. Moreover, you keep only the message, but you discard the stacktrace, any inner exception and DB-specific exception information which can help debugging. This is will likely give you problems later on. My suggestion is to simply remove the try-catch and leave it to the caller to handle the exception and log, display something or retry. At most, throw a specific exception adding some context, but keep all of the original exception as an inner exception.


Custom function extending jQuery.Deferred

Tips:

1)

Returning this from a function of an object instance allows for the method to become chainable.

Example:

var File = function(){
    this.readCallCount = 0;
    return this;
};
File.prototype.readLine = function(){
    this.readCallCount++;
    console.log( "read line: " + this.readCallCount );
    return this;
};
var fileA = new File();
fileA.readLine().readLine().readLine();
/*
output:
read line: 1
read line: 2
read line: 3
*/

2)

The passed arguments from deferred.resolve() are saved until deferred.resolve() is invoked again.
Therefore the callbacks stored from deferred.done() will be passed the same values from the last call from deferred.resolve().

Example:

var arr = [];
function log(str){
    return arr.push( str );
}
function fn1(time) {
  return log( "fn1 called at " + time );
}
function fn2(time) {
  return log( "fn2 called at " + time );
}
var dfd = $.Deferred();
dfd.done(fn1);
dfd.resolve( +(new Date()) );

setTimeout(function(){
    dfd.done(fn2);
    console.log( arr.join( ", " ) );
}, 2000);
/*
 outputs after 2 seconds
 fn1 called at 1348177948625, fn2 called at 1348177948625
*/

Different results can be produced if a function or object is passed to deferred.resolve().

Example:

var arr = [];
function log(str){
    return arr.push( str );
}
function fn1(getTimeFunc) {
  return log( "fn1 called at " + getTimeFunc() );
}
function fn2( getTimeFunc ) {
  return log( "fn2 called at " +  getTimeFunc() );
}
var dfd = $.Deferred();
dfd.done(fn1);
dfd.resolve(function(){
    return +(new Date())
});

setTimeout(function(){
    dfd.done(fn2);
    console.log( arr.join( ", " ) );
}, 2000);
/*
output after 2 seconds
fn1 called at 1348178107859, fn2 called at 1348178109860
*/

3)

The callbacks passed to deferred.done() are saved in a callback queue called $.Callbacks().
The queue is set like so, jQuery.Callbacks("once memory"). This means that all the callbacks stored in the queue will only fired once and that every callback receieves the same arguments.
Also notes that the callbacks are fired in order of First in First out.

Final Code:

This might work. Instead of extending the deferred object to include a read method, I opted to return an plain object.

Note: My code is assuming that libraryCall() and fileEntry.getText() return a deferred.promise() or deferred object.

Code:

var FileEntryObj = function(){
    this.libraryCallObj = libraryCall();
};
FileEntryObj.prototype.read = function(fn){
    this.libraryCallObj.done( function( fileEntry ){
        return fileEntry.getText().done( fn );
    });
    return this;
};
var getFileEntry = function(){
    return new FileEntryObj();
};

Usage:

getFileEntry().read(function (text) {
    console.log("reading content:" + text);
}).read(function (text) {
    console.log("reading content again: " + text);
});


Jquery Max character with character count for input and textarea

There are a few things I would suggest:
1. Replace you numbers with constants and revert the condition to get rid of 'else':

var minTextLength = 0;
var maxTextLength = 5000;
if (maxCharLength >= minTextLength || maxCharLength <= maxTextLength){
      //Your code...
    }

2. Move the block of code:

$(this).next("span").html('<strong> Maximum of ' + maxCharLength + ' characters used.</strong>');
            $(this).next("span").addClass("red");
        } else { $(this).next("span").removeClass("red"); }

To a separate function.

And there are a couple of things that confuse me:
1. In 'Max Length textarea' you have:

$('textarea[maxlength]').keyup()

Is it correct? Becasue it means that you'll add a lot of handlers to all your textarea[maxlength].

2
. In your 'Max Length Input' you have:

if(charLength == maxCharLength )

Maybe it could be replaced with:

if(charLength > maxCharLength )

Depending on the answers to these questions, maybe it'll be possible to move the keyup  handler to a separate function. And maybe even the whole code from both 'Max Length textarea' and 'Max Length Input'.


As far as I remember, the game isn't strictly pairs. It's everyone's names in a hat, and everyone gets to draw a random name, redraw if it's your own name. This means you don't need an even number of names.

var pairsUL = document.getElementById('pairs'),
      pairsLI,
      textLI;

newList.forEach(function(currentValue, index){
  pairsLI = document.createElement('li'); // the LI element
  textLI = newList[index].person1 + ' and ' + newList[index].person2; // the text for the LI
  pairsLI.appendChild(document.createTextNode(textLI)); // add text to the LI
  pairsUL.appendChild(pairsLI); // append the LI to the UL
});

DOM manipulation is slow. Instead of appending to a live element on each iteration, use a fragment. It's something like an in-memory, not-in-DOM element-like container. Use document.createDocumentFragment() to create one, and append your lis to it. After the loop, append the fragment to your list.

function getRandomInteger(min, max) {
  return Math.round(Math.random() * (max - min)) + min;
}

Instead of Math.round, use Math.floor or append | 0 to the operation. Arrays are zero-indexed. Math.random values range from 0 to 1, excluding 1 itself. This means you'll never get length * 1 and floor will always round down down to the integer before length * 1, the last index in the array.

Readable code is good enough to explain what it's doing. Comments should not explain what the code already does. Instead, it should explain why it was done in that manner. Additionally, you're overloading the lines with long comments. Put them before the code described and limit them to something like 80 characters or 120 characters per line.


Filtering a Vec of structs and creating new vector of Strings or strs in Rust

The [..] slicing operation isn't going to cost anything, but isn't very descriptive either. I'd want to call s.style.as_str() instead.
As for the return type, I'd agree that &str is more appropriate, since it is the more general type. The functionality of a String is a superset of what you can do with a str, so it's irrelevant when that extra functionality isn't useful to the caller