Function for comparing floating point numbers

Is there something I forgot to consider

Overflow

fabs(x) + fabs(y) is prone to  overflow, even if mathematically epsilon() * (fabs(x) + fabs(y)) * pow(10, doia + 1) is representable as a T, resulting in incorrect results.

I'd expect cmp(T x, T y, unsigned int doia = 0) to work over the entire range of x,y.

// alternative
(fabs(x)/2 + fabs(y)/2) * (epsilon() * pow(10, doia + 1) * 2)

Not-a-number

The generation of gtoeq, ltoeq are 0 when either/both x or y are a not-a-number.  Thus code returns 0, incorrectly implying near equality.  Perhaps return something to indicate more that 3 conditions like a 4-bit (==,>,<,not comparable) or a double -1,0,1,NAN.

Precision

The + 1 in doia + 1 does not well allow code to just use epsilon, but minimally must use 10 * epsilon.  Consider dropping the + 1.

Rather than an integer indicating some power-of-ten * epsilon, consider simply using the desired precision or n * epsilon().  For me I'd rather use a power-of-2.


Counter object in Python with public and private methods

The private objects and attributes are easily accessed using inspect.getclosurevars:

>>> c = CounterController()
>>> import inspect
>>> inspect.getclosurevars(c.add_one_endpoint)
ClosureVars(nonlocals={'counter_controller': <__main__.CounterController.<locals>.CounterControllerPrivate object at 0x10a047cf8>}, globals={}, builtins={}, unbound={'add_one'})
>>> _.nonlocals['counter_controller']
<__main__.CounterController.<locals>.CounterControllerPrivate object at 0x10a047cf8>
>>> _.counter
0

So you might consider whether it's worth spending a lot of effort on this approach. Personally I would spend the effort on API documentation instead.


Combine Medical Response Files Prior To Table Load

The Perl approach can be shorter and faster than it already is:

perl -ple"BEGIN { @ARGV=glob shift } s,$,|$ARGV," *.csv > Consolidated_Magic_File.not_an_input
ren *.not_an_input *.csv

The best PowerShell approach is not so different from the fast Perl approach.  Feed a list of filenames, use Get-Content (or gc) to read them, let PS figure out where the line breaks are, loop through those results and collect all the outputs in one place.

ls \\unc\folder -Filter *.txt | %{ $fn=$_.Basename; gc $_.PSPath | %{ $_ + "|$fn" } } | sc out.csv

$_.Basename is the name without path or extension.  You can use $_.Name to get the original name with extension, or $_.Basename + ".csv" to label the output with CSV-filenames even though your input was TXT files.


Finding unimplemented tasks on Rosetta Code using Requests

LGTM. Ship it!

There were two minor nits that seemed slightly off:

The use of * in the signature to force kw args is maybe overused, as it covers args that are pretty mandatory.
The print(*tasks, sep='\n') would more naturally be handled by this idiom, which is reusable outside of print(): print('\n'.join(tasks))


You want member:

(member val lst)

For example

(if (member 3 '(1 2 3)) t nil) ; t
(if (member 4 '(1 2 3)) t nil) ; nil


Checking a MySQL connection and refreshing it

As per this SO question you need to be aware that calling Close will not necessarily actually close the connection but only put it back into the connection pool.
There is no reason to do mySqlConnection = null;. You assign a new value to mySqlConnection in the next statement so setting it to null achieves nothing.
These docs might be somewhat out-dated but they state that you can call Close multiple times and that no exception is generated so you can probably skip the check and just call Close unconditionally.


Find the shortest whole repetitive substring (part 3)

You currently write:

for i in range(len(original_string)):

Consider using enumerate:

for i, char in enumerate(original_string):
    if char == current_candidate[j]:

enumerate allows you to reference the current object in a nice manner, while also giving you the index that the item belongs to.


I understand semicolons in JavaScript are optional, however I believe you should always use them. It's easy to have something break later on because you neglected a semi-colon and it lost the whitespace which saved it before in a compression/generation/eval parse.

You could declare the timePerShot as a variable, to ensure the amount is not being calculated on every call (Although I'm pretty sure the parser or cache already solves this).

Use exceptions / errors in exceptional cases only. An example being making an HTTP call; The target could not exist, the internet could be down, or other cases that are out of your control.

Catching exceptions is also going to be very slow. You can return a value such as false instead. And/or you could do the check outside of the function.


How to check minimize or make if-condition on object loop more correct?

You could merge the last three ifs. (I assume there are no other states.)

if(data.hasOwnProperty("status")){
        currentStatus =  parseInt(data["status"]);
        switch(currentStatus ) {
             case 0:
                  var object1 = {"status" : data["status"] , "userLocales": data["userLocales"]}
                  userLocalesProcess(object1);
                  break;
             case 1:
                  userChangeProcess({"changeLocales" : data["changeLocales"],"userLocales" : data["userLocales"] });
                  popupMaker({"message":data["message"],"status":data["status"]});
                  break;
             default:
                  break;
        }

}

I think there is nothing else you can do here. All other ifs are totally different. Maybe you could extract method or variables do communicate the meaning of every branch, but beside that I thing we are done.

Of course, if is also suitable

...
if (currentStatus ==0) {
    var object1 = {"status" : data["status"] , "userLocales": data["userLocales"]}
    userLocalesProcess(object1);
} else if (currentStatus ==1){
    userChangeProcess({"changeLocales" : data["changeLocales"],"userLocales" : data["userLocales"] });
    popupMaker({"message":data["message"],"status":data["status"]});
}
...

Maybe you should just stay with obj.property == null. According to the link above it seems to be faster, but at least it is easier to read.


The only suggestion I would make is to extract each culture's tests to it's own unit tests. Each unit test should be testing one aspect of your code, whereas yours are each testing at least two.

Point 1: the only two overloads you need are .ToString(string) and .ToString(string, IFormatProvider). Everything else is just noise.

Point 2: you should not be adding composites like that, at all. It's just noise. If you really need that info to be passable to the .ToString call, then you should consider a third and fourth overload: .ToString(string format, string unit), and .ToString(string format, string unit, IFormatProvider formatProvider).

Point 3: I don't know enough about C# to be able to answer that exactly, but I would assume you should be using the literal space everywhere, or the \u00A0 everywhere. Pick one or the other, but don't mix-and-match.

Your unit tests have good content, but they need better names:

public void FormatSpeed_1p2_Invariant()
public void FormatSpeed_1p2_Sv_Se()
public void FormatAngle_1p2_Invariant()
public void FormatAngle_1p2_Sv_Se()

This makes it a little more clear as to what the tests are doing by name, so that when you look at the test explorer you can see you already have tests that cover certain aspects.


Function to filter comments and ratings, with pagination support

If one of your filters is undefined, just set it to always succeed.

If one of your parameters is undefined, set it to something so that you don't have to check it over and over.

Truncate output to pagesize at the end.

filterFeedback(items) {
    const pagination = { offset: 0, limit: 10, totalCount: items.length };
    const filtRatings=new Set(
        ( this.filterBy.rating && this.filterBy.rating.length ) ?
          this.filterBy.rating : items.map( item => item.rating )
    );
    const filtComment=this.filterBy.comment || '';

    return items.filter( item =>
        ( item.comment || '' ).includes(filtComment)
        &&
        filtRatings.has(item.rating)
    )
    .slice(0,pagination.limit);

}


Let’s try to apply SRP, and get rid of mutable state to increase code maintainability. It inflates C# code a little bit, but usually makes sense.

Demo:

  IEnumerable<Member> members = new Member[] { new Member("n","e") };
  await members
      .SubscribeAsync()
      .LogAsync(Console.Out);

Where Member could be immutable:

public class Member
{
    public Member(string n, string e)
    {
        N = n.Trim();
        E = e.Trim();
    }

    public string N { get; }
    public string E { get; }
    public override string ToString() => $"N={N}, E={E}";
}

We will use this universal helper class to log task exceptions:

static class Logging
{
    public static async Task LogAsync(this Task task, TextWriter writer)
    {
        try
        {
            await task;
        }
        catch (AggregateException ex)
        {
            foreach (var exx in ex.Flatten().InnerExceptions)
                await writer.WriteLineAsync(exx.Message);
        }
        catch(Exception ex)
        {
            await writer.WriteLineAsync(ex.Message);
        }
    }
}

Now subscription helpers:

static class Subscription
{
    public static Task SubscribeAsync(this IEnumerable<Member> members) =>
        Task.WhenAll(from member in members
                     select member.SubscribeAsync());

    public static Task<SubscriptionResponse> SubscribeAsync(this Member member) =>
        new SubscriptionRequest(member).ExecuteAsync();
}

Subscription request:

public class SubscriptionRequest
{
    const string RequestUrl = "";

    public SubscriptionRequest(Member member)
    {
        Member = member;
    }

    public async Task<SubscriptionResponse> ExecuteAsync()
    {
        using (var client = new HttpClient())
            try
            {
                var response = await client.PostAsync(RequestUrl, Content);
                var responseBody = await response.Content.ReadAsStringAsync();
                return new SubscriptionResponse(responseBody);
            }
            catch(Exception ex)
            {
                throw new SubscriptionException(Member, ex);
            }
    }

    FormUrlEncodedContent Content => new FormUrlEncodedContent(Kvps);
    IEnumerable<KeyValuePair<string, string>> Kvps => new[]
    {
        new KeyValuePair<string, string>("e", Member.E),
        new KeyValuePair<string, string>("n", Member.N),
        new KeyValuePair<string, string>("boolean", "true")
    };

    Member Member { get; }
}

And response:

public class SubscriptionResponse
{
    public SubscriptionResponse(string body)
    {
        Body = body;
        if (!Success)
            throw new InvalidOperationException(body);
    }

    public bool Subscribed => Body == "1";
    public bool AlreadySubscribed => Body == "Member present";
    bool Success => Subscribed || AlreadySubscribed;
    string Body { get; }
}

The only missing part:

public class SubscriptionException : Exception
{
    public SubscriptionException(Member member, Exception error) :
        base($"{member} subscription failed, error: {error.Message}", error)
    {
    }
}

P.S. Generally speaking, C# is a pretty verbose language, so it is often punishing good programming practices…


Fetching lists and finding one with the right name, with fallback on error or no match

There's a couple of reasons if err != nil is usually preferred in Go.

It's idiomatic

If you take a look at the source code of Go's standard library you can find it plenty of times, like in bufio's source, for example.

It's more readable in the long run

In your function, the difference between the two is not that big, but the point is valid if you're writing longer functions, where you make multiple calls to other functions that might return errors.

Suppose your function had to call 3 other "failable" functions, handling errors like in the first snippet would look like this:

func getList() (sendgrid.RecipientList, bool, agerr.E) {
    lists, err := client.GetRecipientLists()
    if err == nil {
        // let's call it again, just for fun
        lists, err = client.GetRecipientLists()
        if err == nil {
            // once more!
            lists, err = client.GetRecipientLists()
            if err == nil {
                 // function logic goes here
            }
        }
    }

    return sg.RecipientList{}, false, err
}

You can probably see that lines get much longer, and in this case there's even no actual logic in the snippet I wrote. IMO this reduces readability by a lot, it's harder to separate an error check from function logic at a glance.

Let's try with the other style:

func getList() (sendgrid.RecipientList, bool, agerr.E) {
    lists, err := client.GetRecipientLists()
    if err != nil {
        return sg.RecipientList{}, false, err
    }

    // let's call it again, just for fun
    lists, err = client.GetRecipientLists()
    if err != nil {
        return sg.RecipientList{}, false, err
    }

    // once more!
    lists, err = client.GetRecipientLists()
    if err != nil {
        return sg.RecipientList{}, false, err
    }

    // function logic goes here

    return sg.RecipientList{}, false, err
}

Of course, inverting the condition means that you have to type more returns and you're not really saved from writing all that error handling boilerplate.

At the same time, you can probably notice it's much easier to mentally filter out the actual function logic from the boilerplate. Every check is stand-alone and always looks similar.

As a side note, if you don't like all that boilerplate there's an interesting article on the Go blog that discusses of possible ways to reduce it.


Depth-first traversal implementation in Java (by recursion)

To answer your question exactly and with very little value: no. All those println's and traversal modes add unnecessary length to your code.

But lets get down to business... shortness is not always he most desirable feature of source code. Your choice of providing accessors for value but not for the left and right subtrees is questionable. Be consistent with how you expose and manipulate your fields.

You left out the context of dtfRecursion. Defining the traversal mode outside the traversal algorithm is odd. You could implment the traversal modes as separate classes. This would free you from the need to check the correctness of the tMode. Also you wouldn't need to worry about someone changing tMode during traversal (not that you do it now, eh).

It seems that you're just doing this for the sake of writing the algorithm but to make this review more useful, I'll point out that instead of hardcoding the println's you could pass a Consumer<Integer> to the traversal method and implement whatever you want to do with the values in that. And you could implement Node as a parameterized class to allow storage of types other than just integers.

Node is also a bit generic name for a class that is highly specific in it's implementation. BinaryTreeNode might be better.


Late reply,

this code is good, I can only find 2 faults:

Your code should have error handling for the JSON call, things can go wrong
Too much horizontal stretching, I would introduce some sugar for this:

for (var i = 0; i < response.responseData.feed.entries.length; i++) {
    content = content + response.responseData.feed.entries[i].content; //Join all the feed entries
}

could be

var entries = response.responseData.feed.entries;
for (var i = 0; i < entries.length; i++) {
    content = content + entries[i].content; //Join all the feed entries
}

Also, I find

$element.find(".content").html(content)
                         .addClass($element.find("embed").length? "withVideo" : "");

more readable.

As for find("*"), it seems to be cleanest way to access all children.


Animation of adding / removing nodes from VBox

So I divided it into two methods. This made the conditions considerably easier.

Still, it doesn't seem perfect to me. Plus, I found a mistake. If I run a new animation, an error occurs if the old animation has not been completed yet.

But I don't know how to treat it.

Do you have any idea how, please?

Thank you

public FadeTransition hide_old(ArrayList<Text> nodes) {
    var transition = new FadeTransition();
    var size = getChildren().size();
    if (size > 0) {
        transition = new FadeTransition(Duration.millis(200), getChildren().get(size - 1));
        transition.setFromValue(1);
        transition.setToValue(0);
        transition.setOnFinished((event) -> {
            getChildren().remove(size - 1);
            hide_old(nodes);
        });
        transition.play();
    } else {
        show_new(nodes);
    }
    return transition;
}

private void show_new(ArrayList<Text> nodes) {
    FadeTransition transition;
    var size = getChildren().size();
    if (size < nodes.size()) {
        getChildren().add(nodes.get(size));
        getChildren().get(size).setOpacity(0);
        transition = new FadeTransition(Duration.millis(200), getChildren().get(size));
        transition.setFromValue(0);
        transition.setToValue(1);
        transition.setOnFinished((event) -> {
            show_new(nodes);
        });
        transition.play();
    }
}


Use mustache.js!  It's a js templating engine which will point you in the right direction :)


Implementing data sync from multiple source using OOP concepts

Use __init__ to handle bunch of arguments, then your self will take of passing arguments to your respective definition - that's the good way to use OOP in python.

class Foo:
    def __init__(self, value_a, value_b):
        self.a = value_a
        self.b = value_b

    def func(self):
        pass

To avoid multiple if else you can have list or dict and from there you can access.
Hope this helps !!


Typescript design pattern for rendering different objects with similarities

So I know there gotta be a better way but I found a satisfying one:
interface IBlock {
  getProperty() : string;
  render() : Object;
}

class ColorBlock {
  color: string;
  constructor(color: string) {
    this.color = color;
  }
  getProperty() : string {
    return this.color;
  }
  render(isFirstBlock: boolean) : Object/*Well it's an HTML dom object*/ {
    const tag = document.createElement('div');
    isFirstBlock? tag.classList.add('block-first') : tag.classList.add('block-lasts');
    tag.setAttribute('style', `background: ${this.color};`);
    return tag;
  }
}

class ImageBlock {
  url: string;
  constructor(url: string) {
    this.url = url;
  }
  getProperty() : string {
    return this.url;
  }
  render(isFirstBlock: boolean) : Object/*Well it's an HTML dom object*/ {
    const tag = document.createElement('div');
    isFirstBlock? tag.classList.add('block-first') : tag.classList.add('block-lasts');
    const image_tag = document.createElement('img');
    image_tag.src = this.url;
    image_tag.classList.add('image-block');
    tag.appendChild(image_tag);
    return tag;
  }
}

const global_x = 10;
const global_y = 10;

const world = new Array<Array<IBlock>>(global_x);

const default_ColorBlock = new ColorBlock('#ff00ff');

for(let i=0; i<global_x; i++) {
  world[i] = new Array<IBlock>(global_y);
  world[i].fill(default_ColorBlock);
}

function render(world: Array<Array<IBlock>>) {
  const html_container = document.createElement('div');
  for(let i=0; i<global_x; i++) {
    html_container.appendChild(world[i][0].render(true));
    for(let j=0; j<global_y; j++) {
      html_container.appendChild(world[i][j].render(false));
    }
  }
  document.body.innerHTML = '';
  document.body.appendChild(html_container);
}

render(world);

CSS being:
:root {
  --global-width: 20px;
  --global-height: 20px;
}

.block-first, .block-lasts {
  width: var(--global-width);
  height: var(--global-height);
  border-radius: 50%;
  float: left;
}

.block-first {
  clear: both;
}

.image-block {
  width: var(--global-width);
  height: var(--global-height);
}

And no HTML outside of javascript (typescript) .


Judging by this bit:

if (getIntent().hasExtra(FILE)) {
    webview.loadUrl(getIntent().getStringExtra(FILE));
} else {
    webview.loadUrl(getIntent().getStringExtra(URL));
}

It looks like the loadUrl method doesn't care whether the parameter you pass to it is a file path out a web address. Actually the term "url" has a general meaning that can encompass both file paths and web addresses. So I don't see the point of distinguishing these two in the intents: just use "URL", it doesn't matter if it's a path out web address. Again, this suggestion is based on the posted code.

If you really want to have two separate static method for some reason, then extract the common logic in these methods to a helper method.

private static Intent createIntent(Context context, int titleId, String key, String url) {
    Intent intent = new Intent(context, WebViewActivity.class);
    intent.putExtra(TITLE_ID, titleId);
    intent.putExtra(key, url);
    return intent;
}

public static Intent createURLIntent(Context context, int titleId, String url) {
    return createIntent(context, titleId, URL, url);
}

public static Intent createFileIntent(Context context, int titleId, String path {
    return createIntent(context, titleId, FILE, path);
}


Replace multiple occurrences of a character

Maybe I am wrong but I prefers to use the regex for this kind of text manipulation.
Here is my code,

System.out.println("hhiii!!!  hooowww   aaareee   yyyooou???"
                      .replaceAll("(.)\\1+","$1"));


Two things:

The function may fail for a tree with an incomplete last layer.  For example:

is_symmetric([1, 2, 2, 3, 4, 3])  returns True, but it should be False.

This can be fixed by checking if layers have the expected length.

if len(layer) != (end - start) or layer != list(reversed(layer)):
        return False

The for loop iterates more times than needed.  The loop only needs to run for each layer in the tree, not for each node.  A tree with n layers has 2**n - 1 nodes. It may not matter for small trees, but a tree with 20 layers has over a million nodes.  Replace the for loop with a while loop:

while start < len(tree):
...

Okay, three things.  interval isn't needed.  Use:

end = 2 * end + 1

The revised routine:

def is_symmetric(tree: list) -> bool:
    """
    Returns if the passed tree is symmetric

    :param tree: A list representing a binary tree
    """

    start = 0
    end = 1

    while start < len(tree):
        # Find next layer
        layer = tree[start:end]

        # Determine if layer isn't mirror
        if len(layer) != (end - start) or layer != list(reversed(layer)):
            return False

        # Setup for next layer
        start = end
        end = 2 * end  + 1

    return True

if __name__ == '__main__':
    tests = [
        ([1], True),
        ([1, 2, 2, 3, 4, 4, 3], True),
        ([1, 2, 2, None, 3, None, 3], False),
        ([1, 2, 2, 3, 4, 3], False)
        ]

    for n, (test, answer) in enumerate(tests):
        result = is_symmetric(test)
        print(f"Test {n} {'Pass' if answer==result else 'FAIL'}: is_symetric({test})")


Round-tripping from LinkedHashMaps to Clojure collections

I think automatically creating keywords from string keys and string keys from keywords is not a good idea, for three reasons.

It would be surprising to a user to have values change classes when theoretically just pouring the contents of one map into another.
In the space of possible key transformations, keyword<-->string is just one point. As a user, I might want to do many other kinds of transformations while converting. For a more general approach, think about how transducers can be supplied to the four-argument form of into.
Keywords are interned. This may be a source of your memory trouble. Every new keyword gets stored permanently in the heap. That's how Clojure does fast keyword comparison by just checking object references. That means a property-based test that generates huge numbers of unique keywords is going to consume a lot of memory.


None of the above. Rewrite the first option in readable form. For example,

package main

import (
    "fmt"
    "strings"
)

type Cfg struct{ A, B string }

func getShCfg(c Cfg) string {
    var out []string

    msg := "l_sh_dit conf_data "
    if len(c.A) > 0 {
        msg += c.A
    } else {
        msg += "7MB"
    }
    out = append(out, msg)

    msg = "l_sh_dit cert_data "
    if len(c.B) > 0 {
        msg += c.B
    } else {
        msg += "3MB"
    }
    out = append(out, msg)

    return strings.Join(out, ";\n\r") + ";"
}

func main() {
    sep := "\n================"
    for _, cfg := range []Cfg{
        {},
        {"8MB", "4MB"},
        {"8MB", ""},
        {"", "4MB"},
    } {
        fmt.Println(getShCfg(cfg), sep)
    }
}

Output:

l_sh_dit conf_data 7MB;
l_sh_dit cert_data 3MB;
================
l_sh_dit conf_data 8MB;
l_sh_dit cert_data 4MB;
================
l_sh_dit conf_data 8MB;
l_sh_dit cert_data 3MB;
================
l_sh_dit conf_data 7MB;
l_sh_dit cert_data 4MB;
================

Factoring out common code and data simplifies and highlights the structure of the problem.

To generalize we typically need three to seven cases. We have two. Configuration parameters usually contain a wide range of information and data types and structures. Idle speculation is not useful.

We have safely encapsulated the problem. As we learn more, we can easily revise the code.


tokland is right (on both counts), you should push all that logic into a helper. You can also add a bit of OpenStruct into the mix to make the helper nicer:

# in app/helpers/application_helper.rb or another helper
def user_image_info(user)
    info = OpenStruct.new(:has_image? => false)
    return info if(!user.image?)

    # There might be better ways to do this but I don't know paperclip.
    u = user.image.url
    %w[jpeg gif png jpg csv].find do |ext|
        # A small abuse of `find` but reasonable in this case.
        info.is = "is#{ext.upcase}" if(u.include?(".#{ext}"))
    end
    if(info.is == 'isCSV')
        info.preview_link = '
Your file was a csv file and has no preview
'.html_safe
    else
        info.preview_link = (image_tag(user.image.url) + '
').html_safe
    end
    info
end

Then in your ERB, you could do something like this:

<% info = user_image_info(@user) %>
<% if info.has_image? %>
    <%= info.is %>
    <%= info.preview_link %>
    <%= link_to @user.image.url, @user.image.url  %>
<% end %>


To be honest, this is a bad way to solve the problem - recursion with strlen() is not a good idea. There was a recent discovery that Rockstar Games had their loading screens in GTA5 extended by several minutes due to their JSON parser calling strlen() on a string repeatedly.
Instead, when handling strings in a recursive manner that requires knowledge of the length of the string, one should pass that length alongside the pointer.
On the topic of length, you're storing the length of the string in a variable with type int rather than the size_t that strlen() returns. There are two problems with this - the first is that int is signed and size_t is unsigned, and the second is that size_t is often larger than int, especially with modern 64-bit systems defining the former as uint64_t and the latter as int32_t.
Lastly, you could avoid a lot of mental overhead by using two pointers instead - one to the beginning of the string, and one to the end of the string. You would then stop the recursion when the beginning is no longer before the end.


Code Review
Your code is a little hard to read.
You should have a blank line after the solution body, to separate it from the mainline code.
This code is hard to describe, document, and debug:
l = map(int, input().split(' '))
print(solution(*l))

What is l?  How many arguments are there?  If the wrong number of arguments are given as input, the problem doesn't occur immediately in the first statement but rather when attempting to execute the second.
It would be significantly clearer to write:
a, n = map(int, input().split())
print(solution(a, n))

Now we can see we expect two arguments to be given, and we have names for the arguments.  If too many or too few arguments are given, the first line will raise the exception, which should mean it will be easier to debug.
Note: I'm using .split() instead of .split(' ') so that it will split the string on any white space character, including tabs, and multiple white-space characters will be considered a single delimiter.  It is slightly friendlier.
Adding type hints and a docstring would be useful.  Also, a main guard should be used.
Improved code:
import math

def solution(a: int, n: int) -> int:
    """
    Jedi Challenge:

    Return the smallest positive integer such that
        a^i = 1 (mod n)
    Returns 0 if there is no such number

    Constraints:
        2 <= a < n <= 10^9
    """

    if math.gcd(a, n) > 1:
        return 0

    z = 1
    i = 1
    while True:
        z = z * a % n
        if z == 1:
            return i
        i += 1

if __name__ == '__main__':
    a, n = map(int, input().split())
    print(solution(a, n))

Performance
This is not really a programming challenge; it is a math challenge.
First, due to the modulo operation, z = z * a % n will only ever produce a value between 0 and n-1.  This means there are only n possible results at each iteration step.  However, if 0 is produced, each iteration step afterwards will only ever produce 0, leaving n-1 non-trivial results.
If the k-th iteration produces 1, the code yields the result k.  But if iteration continued, since it has reached its initial starting point, it would produce the same sequence of values in a never ending cycle.
If you chose a different starting value, that did not appear in the above cycle, it would must have one of 3 fates.  It would either terminate at zero, create its own loop of unique values, or possibly merge into the existing sequence.
You have already determined that if gcd(a, n) != 1 then the iteration sequence would eventually reach zero, without finding a solution.
In fact, if n is prime, then \$a^{n-1} \equiv 1 \mod n\$, and therefore the iteration will produce the 1 after n-1 iterations, and must have produced all of the possible values between 1 and n-1.
So, as one optimization, if you can determine n is prime, you could immediately output the answer n-1.  If not, then you could revert to doing the iterative calculations.
If n is not prime, you might want to look at the prime factorization of n, and see if you can determine a relation between it and the result.  (Hint: there is.)


Creating a generic function for objects of different classes

def self.dispatches_for(object)
  klass = object.class.to_s.downcase.to_sym
  raise "unacceptable class" unless klass.in? [:habit, :coach, :content]
  scope = Dispatch.asc(:days)
  scope.where(klass=>object).map{|d|d}
end


Welcome to code review community. Few initial thoughts, when writing python code; following PEP-8 style guide makes your code more maintainable. Which would amount to (but not limited to):

Functions and variables named in lower_snake_case.
Avoiding whitespaces in function parameters/arguments.

Moving on, you can put your websocket handling code in its own submodule. For eg.
class WebSocket:
    def __init__(self, url):
        self._url = url

    def close(self, ws):
        # handle closed connection callback
        pass

    def connect(self):
        self.ws = websocket.WebSocketApp(self._url, on_close=self.close)
        self.ws.on_open = self.open  # for eg.
        self.ws.run_forever()
    .
    .
    .

If you want it to support threading, you can extend this class with threading.Thread sub-classing (you may also choose to subclass multiprocessing.Process later):
class ThreadedWebSocket(WebSocket, threading.Thread):
    def run(self):
        # This simply calls `self.connect()`

this way, if you want to initialise threads:
url1_thread = ThreadedWebSocket(url=url1)
url1_thread.start()
url1_thread.join()

The subclassing is mostly a matter of preference.

In the on_open callback, you are dumping a dict to json and then inserting it to a string template. The following achieves the same result, and is more intuitive (imo):
def on_open(ws):
    def run(*args):
        subs = []
        trade =  {
            "method": "SUBSCRIBE",
            "params": subs,
            "id": 1
        }
        ws.send(json.dumps(trade))

Coming to your question about library alternates, and performance, network I/O is generally a blocking call. This was one of the major reason I suggested going with the websockets package. The other being; we've been using websockets at our organisation for over an year in production. And it has been working really impressively for us, handling a throughput of few GB data everyday with a single low-tier machine.


Good code! Just a few points:

super();

This line of code is automatically put in by the compiler and is unnecessary to write it yourself. If it is a habit that you have a hard time breaking, you may leave it, as it does not compromise speed, but I would leave it out, as it does clutter code slightly.
Over-spacing

Though spacing is good, too much space makes code hard to read as well. Your spacing is good, with one thing: you have a space between each line. Maybe it helps you, but I find it difficult to read.

Compare:

public final class Pulse {

    private final Object Lock = new Object();

    private volatile int count;

    public Pulse() {

        super();

        count = 0;
    }

    public void pulse() {

        synchronized (Lock) {

            count++;

            Lock.notifyAll();
        }
    }

    public void waitForPulse() throws InterruptedException {

        synchronized (Lock) {

            while (count == 0) {

                Lock.wait();
            }

            count--;
        }
    }
}

and:

public final class Pulse {

    private final Object Lock = new Object();
    private volatile int count;

    public Pulse() {
        super();
        count = 0;
    }

    public void pulse() {
        synchronized (Lock) {
            count++;
            Lock.notifyAll();
        }
    }

    public void waitForPulse() throws InterruptedException {
        synchronized (Lock) {
            while (count == 0) {
                Lock.wait();
            }
            count--;
        }
    }

}

Note that I've kept some spaces.
private final Object Lock = new Object();

Java conventions state that variable names are camelCase, not PascalCase. Change Lock to lock.


Overall, its not too bad, but I do have some suggestions for readability. What I like to do is add white-space to make elements line up with each other. For example, for this line:

BCD_add_a_i, BCD_add_b_i : in STD_LOGIC_VECTOR(4*BCD_ADD_DEC_SIZE-1 downto 0);
BCD_add_sum_o : out STD_LOGIC_VECTOR(4*BCD_ADD_DEC_SIZE-1 downto 0);
BCD_add_clk_i, BCD_add_cin_i : in STD_LOGIC;
BCD_add_cout_o : out STD_LOGIC

I'd do something like this:

BCD_add_a_i    : in  STD_LOGIC_VECTOR(4*BCD_ADD_DEC_SIZE-1 downto 0);
BCD_add_b_i    : in  STD_LOGIC_VECTOR(4*BCD_ADD_DEC_SIZE-1 downto 0);
BCD_add_sum_o  : out STD_LOGIC_VECTOR(4*BCD_ADD_DEC_SIZE-1 downto 0);
BCD_add_clk_i  : in  STD_LOGIC;
BCD_add_cin_i  : in  STD_LOGIC;
BCD_add_cout_o : out STD_LOGIC

I think it makes large blocks of text like that a smidge easier to read.

For the increment/decrement functions, I'd split up the big or/and/nand statements with variables. It ultimately doesn't affect much synthesis-wise, but again makes a bit easier to read. I'd also be consistent on whether you use the '&' operator or 'and' operator, rather than switching throughout the statement.

For this statement:

b(4*i+3 downto 4*i) := unsigned(increment6(STD_LOGIC_VECTOR(b(4*i+3 downto 4*i))));

I'd find a way to make that a little less ugly, but I'm not strictly sure how. It might have to be one of those necessary evil type of things, but cleaning that up would be really nice. Maybe do the SLV/unsigned typecasting within the increment/decrement functions.

I'm not too fond of the sorta-Hungarian notation thing for ports and signals, but that's more a personal thing than a readability thing.


You should never do this:

for OS in OS:

Your loop variable "OS" is the same name as the iterator you're looping over.  That is very likely to cause you problems.  In some simple cases it will work, but makes for very unreadable code.

Secondly, for every line in the first file you are reading the ENTIRE second file!  So you read the second file as many times as there are lines in the first.  You need to separate the loops, read the first file (I like using input_fileVms.readlines() to put everything in a list of strings) and then read the second file.  Once you have the contents of the two files in data structures, then you can merge them.  Unless your files are in the 1GB range, this is what I would recommend.  If you are just concatenating the files, you don't need csv.reader() because there is no reason to split out the strings and get the individual fields.


Calculating the distance between one point, and many others

Your existing algorithm is a bit perplexing to me.  In particular, the returnBlobIndicesOfRelevantBlobs doesn't really do much except cause the answer to occasionally be wrong.  For example here's what I'm using to drive your code:

from timeit import default_timer as timer
# your code goes here

blobs = np.array([
    [ [0,0],  [0,0], [0,0] ],
    [ [12,2], [9,0], [0,0] ],
    [ [-1,1], [0,0], [0,3] ]
])

start = timer()
r = 2
ans = returnBlobVertexIndicesOfRelevantBlobs(r, blobs, 0, 0)
elapsed_time = (timer() - start)
print "Found {0} in {1} s.".format(len(ans), elapsed_time)

For efficiency, you can eliminate the use the np.sqrt by simply using the square of minimumDistanceFromFocusVertex (my those are long names!) which you would only need to calculate once.

Your use of 4*minimumDistanceFromFocusVertex seems a bit arbitrary and probably incorrect.  For this particular example, for instance, it causes the second blob (with first coordinate [12,2]) to be removed from further consideration even though its third coordinate is within the target range.

If you're using Python 2.7 (as I am) you should use xrange instead of range.  The difference is that range actually allocates memory and populates an array while range does not.  (In Python 3.3, range now does what xrange did in Python 2.7, and xrange is deprecated.)

Finally, while there may be good reason for your application, it's not at all clear to me why one would create an array of indices as the desired final answer.  If that's really what you wanted, then that's fine, but if you find that you're having to do some additional transformation before using it, consider ways in which that this code could deliver the results is a more directly usable form.

As a final check, and speed test you can use this:

# first create a pseudo-random population of blobs
np.random.seed(7)
r=10000
n=4000000
blobs = np.random.random_integers(-r, r, (n,3,2))
# set the first vertex at the origin
blobs[0,0] = [0,0]

start = timer()
ans = returnBlobVertexIndicesOfRelevantBlobs(r, blobs, 0, 0)
elapsed_time = (timer() - start)
print "Found {0} in {1} s.".format(len(ans), elapsed_time)
print "The value of pi is approximately {}".format((4.0*len(ans))/(3.0*n))

As a bonus, you can use this to calculate an approximate value of \$\pi\$ which serves as a useful sanity check.  That works because the code above places 3 random points per \$n\$ blobs in a square that measures \$2r\$ on each side for an area of \$4r^2\$.  The code then counts the number of points that are within \$r\$ units of the center, which of course describes an inscribed circle with area \$\pi r^2\$.  Since all of the points are placed with uniform distribution, if \$a\$ is the number of points within the circle, we know that
$$\displaystyle \frac{a}{3n} \approx \frac{\pi r^2}{4 r^2} $$
or in other words, that the odds that each point lands in the circle within the square is proportional to the areas of the circle and square.  So,
$$\displaystyle \frac{4a}{3n} \approx \pi$$

When I run the program on my machine with the values shown above, I get:

Found 9424443 in 41.8755390644 s.
The value of pi is approximately 3.141481

I'm sure there are ways to speed up these calculations, which I may have time to pursue later.


In general, Python's tuple assignment and unpacking allows you to rewrite:

temp = foo
foo = bar
bar = temp

as:

foo, bar = bar, foo

which saves you two lines in both versions! This gets you to:

s[index], s[(length - 1) - index] = s[(length - 1) - index], s[index]

Rather than indexing by (length - 1) - index, note that e.g. s[-1] is the last item in the list, s[-2] the penultimate item, and so on. So you can rewrite:

s[(length - 1) - index]

as:

s[-index - 1]

and we're now down to:

s[index], s[-index - 1] = s[-index - 1], s[index]

and there's no need to calculate length.

For the iterative version I would factor out median, too, going from:

median = len(s)//2
for index in range(median):
    ...

to simply:

for index in range(len(s) // 2):  # note whitespace
    ...

Although it's now factored out, note that:

median = len(s)//2
length = len(s)

could be rearranged to:

length = len(s)
median = length // 2  # and here

len(s) is O(1), but why duplicate it? DRY!

As I've previously shown, adding an extra parameter with a default value (def reverse_list_recur(s, index=0):) can simplify recursive approaches, removing the need for a nested function.

I would also remove the closure on median and explicit return/else and just test if index < len(s) // 2: before the swap:

def reverse_list_recur(s, index=0):
    """Reverse the contents of the list s and return None.

    >>> digits = [6, 2, 9, 5, 1, 4, 1, 3]
    >>> reverse_list_recur(digits)
    >>> digits
    [3, 1, 4, 1, 5, 9, 2, 6]
    >>> d = digits
    >>> reverse_list_recur(d)
    >>> digits
    [6, 2, 9, 5, 1, 4, 1, 3]
    """
    if index < len(s) // 2:
        s[index], s[-index - 1] = s[-index - 1], s[index]
        reverse_list_recur(s, index+1)

Depending on how you interpret "built-in list methods", the following may be OK:

def reverse_list(s):
    s[:] = s[::-1]


Merge sort Java implementation for an interview

Here are some thoughts on things you might improve:

Always use curly braces, even when they're optional. This is a common source of errors when existing code is modified.

int i == 0; //For left array should be int leftArrayIndex = 0. Don’t use a comment to label a variable .. use the variable’s name to do that. Same thing for j and k.

mid should be midpoint, perhaps? originalArray instead of a? Variable names should be clear and descriptive. Avoid abbreviations where possible.

Almost all Java style guides put a space between if, for, or while and their opening paren. This easily differentiates them from method calls.

Variables that don’t change should be declared final.

Learn and use the libraries. In particular, System.arraycopy() is preferable to looping to manually copy array entries.

merge should be private, not public.


The two parts to the UNION have too much in common.  I believe this query is equivalent to yours.

SELECT ID, XAxis, YAxis, Player, Castle, Alliance
    FROM SC75
    WHERE
        Snap = (SELECT MAX(SavedSnap) FROM DataSnap WHERE Server = 75)
            AND
        (
            (hex(Player) IN (hex('Vandiel'))
                OR
            Player IN
            (
                SELECT AF.Alts
                    FROM AltFiller AS AF
                    WHERE hex(AF.Player) IN (hex('Vandiel'))
            )
        )
    ORDER BY Player, Castle;


Newton's method to solve cubic equations

Handling of complex roots

When there are complex roots, you have two cases, for a1 > 0 and a1 < 0.  You could just collapse the two cases by using abs(a1) when defining imagg.

Better yet, Python has built-in support for a complex type.  Why not use it instead of building a string?  Then you don't even have to worry about the sign of the imaginary part for the sake of a pretty printout.

Separation of concerns

Your solvedeg3equation() function performs input, calculation, and output.  That may do the job for you, but it ensures that your code will never be reusable, other than by copying and pasting — or by piping the input to you and attempting to parse the output!  Furthermore, it makes your code just as difficult to unit test.  What you want is a function that accepts a polynomial (more on that shortly) and returns a 3-tuple of solutions.  The caller would be responsible for input and output.

Notation

Representing a third-degree polynomial as variables a, b, c, and d is unwieldy.  You can't pass it around easily as one entity.  The proliferation of variables imposes a mental load.  Most importantly, I think that it leads to poor notation in your code.

I propose the following notation:

x0, x1, x2: The first, second, and third roots (better than g, g2, g3)
Polynomial(a, b, c, d): An object representing the polynomial a x3 + b x2 + c x + d
f: The polynomial to be solved (better than a, b, c, d)
df_dx: The derivative of f (better than 3*a*g**2+2*b*g+c)
q: The quadratic polynomial remaining after x0 has been found (better than c1=-d/g; a1=a; b1=(c1-c)/g)
q.discriminant(): Shorthand for b1**2-4*a1*c1
tolerance: better than e (which unfortunately looks like it's related to a, b, c, d)

Furthermore, you shouldn't hard-code a 100-iteration limit, especially twice as a magic number in the code.

Polynomial class

As noted above, having a class for polynomials is extremely useful for your problem.  In addition to the polynomial to be solved, you need its derivative, and you also have a quadratic equation to solve.  A polynomial class lets you

pass the polynomial into the solver function conveniently
collapse several variables into one
evaluate the value of the polynomial easily
take its derivative

Here is an implementation:

class Polynomial(object):
    def __init__(self, *coeffs):
        """
        Polynomial(3, 5, 0, -2) represents f(x) = 3x^3 + 5x^2 - 2.
        """
        self.coeffs = list(coeffs)[::-1]
        while self.coeffs[-1] == 0:
            self.coeffs.pop()

    def __call__(self, x):
        """
        >>> f = Polynomial(3, 5, 0, -2)
        >>> f(2)
        42
        """
        return sum([self[n] * x ** n for n in range(len(self.coeffs))])

    def __getitem__(self, n):
        """
        Gets the coefficient for x^n
        >>> f = Polynomial(3, 5, 0, -2)
        >>> f[2]
        5
        """
        return self.coeffs[n] if n < len(self.coeffs) else 0

    def __str__(self):
        """
        >>> f = Polynomial(3, 5, 0, -2)
        >>> str(f)
        3 x^3 + 5 x^2 + 0 x^1 + -2
        """
        return ' + '.join(["%d x^%d" % (self[n], n) for n in range(len(self.coeffs))][::-1])

    def degree(self):
        """
        >>> f = Polynomial(3, 5, 0, -2)
        >>> f.degree()
        3
        """
        return len(self.coeffs) - 1

    def derivative(self):
        """
        >>> f = Polynomial(3, 5, 0, -2)
        >>> f.derivative()
        9 x^2 + 5 x^1 + 0 x^0
        """
        deriv = [n * self[n] for n in range(len(self.coeffs) - 1, 0, -1)]
        return Polynomial(*deriv)

    def discriminant(self):
        """
        For quadratic polynomial a x^2 + b x + c, returns b^2 - 4 * a * c

        >>> f = Polynomial(4, -1, 2)
        >>> f.discriminant()
        -31
        """
        if self.degree() != 2:
            raise ValueError, "Discriminant of polynomial of degree %d not supported" % (self.degree())
        return self[1] ** 2 - 4 * self[2] * self[0]

Error handling

If something goes wrong, don't just print something.  Raise an exception, which ensures that the caller will notice the problem!

class SolutionNotFound(ValueError):
    """
    Raised when a root of a polynomial cannot be found.
    """

Iteration limit

Python has a language feature for executing an else clause when a loop terminates naturally through exhaustion (i.e., when its condition becomes false, rather than by an early break).  You can use it like this:

for _ in range(max_iterations):
    if abs(f(x0)) <= tolerance:
        break
    # TODO: refine x0 here
else:
    # Loop exhaustion, i.e. max_iterations reached
    # TODO: raise an error
# TODO: Calculate x1 and x2 here

Pretty!

All of that setup lets your code look like mathematics, not like a C program.  Now you can clear your head of the minutiae and focus on things that matter, like your mathematical technique.

I've made a few remarks in the code comments as well.

from math import sqrt

def solve_degree_3_polynomial(f, tolerance=0.00000001, initial_guess=0.01, max_iterations=100):
    if f.degree() != 3:
        raise ValueError, "Input must be a polynomial of degree 3"

    # If 0 is a root, make x0 exactly 0 to trigger a special case for
    # the quadratic equation below.
    x0 = 0 if f(0) == 0 else initial_guess
    df_dx = f.derivative()
    for _ in range(max_iterations):
        if abs(f(x0)) <= tolerance:
            break
        if df_dx(x0) == 0:
            x0 += 0.001
        x0 = x0 - f(x0) / df_dx(x0)
    else:
        raise SolutionNotFound, "Exceeded %d iterations.  Current guess: f(%d) = %d" % (max_iterations, x0, f(x0))

    # q = Quadratic
    q = Polynomial(f[3], f[2], f[1]) if x0 == 0 else \
        Polynomial(f[3], (-f[0] / x0 - f[1]) / x0, -f[0] / x0)

    # These three cases are mutually exclusive, right?  Then write them that way.
    if abs(q.discriminant()) < tolerance:
        # I think that returning a double root is better than returning
        # None for one of the roots.  It's mathematically more correct,
        # and less likely to cause bugs involving NoneType.
        x1 = x2 = -q[1] / (2 * q[2])

    elif q.discriminant() < 0:
        # You could just let cmath.sqrt() take care of this for you instead,
        # in which case all three cases collapse down to one!
        x1 = complex(-q[1] / (2 * q[2]), +sqrt(-q.discriminant()) / (2 * q[2]))
        x2 = complex(-q[1] / (2 * q[2]), -sqrt(-q.discriminant()) / (2 * q[2]))

    else:
        # If you change
        #     from math import sqrt
        # to
        #     from cmath import sqrt
        # then the two lines below handle all three cases, regardless of
        # whether the discriminant is negative, 0, or positive.
        x1 = (-q[1] + sqrt(q.discriminant())) / (2 * q[2])
        x2 = (-q[1] - sqrt(q.discriminant())) / (2 * q[2])

    return x0, x1, x2

Example usage

f = Polynomial(3, -1, 6, -2)
(x0, x1, x2) = solve_degree_3_polynomial(f)

print "f(x) = %s" % (f)
print "f(%s) = %s" % (x0, f(x0))
print "f(%s) = %s" % (x1, f(x1))
print "f(%s) = %s" % (x2, f(x2))

… prints

f(x) = 3 x^3 + -1 x^2 + 6 x^1 + -2 x^0
f(0.333333333333) = 2.423339307e-13
f((3.44613226844e-13+1.41421356237j)) = (-4.36495284361e-12-1.7763568394e-15j)
f((3.44613226844e-13-1.41421356237j)) = (-4.36495284361e-12+1.7763568394e-15j)

Next steps

As noted in the comments, I would recommend using cmath.sqrt() to collapse the three cases for the discriminant into one.

It would also be a good idea to decompose the cubic equation solver into a generic Newton's method solver for any polynomial, followed by a quadratic equation solver.

def solve_degree_3_polynomial(f, ...):
   if f.degree() != 3:
       raise ValueError
   x0 = solve_polynomial_by_newton(f, ...)
   q = Polynomial(f[3], (-f[0] / x0 - f[1]) / x0, -f[0] / x0)
   x1, x2 = solve_degree_2_polynomial(q)
   return x0, x1, x2


First of all, let's not beat around the bush. Clearly your filenames should be Brainfuck.hpp and Brainfuck.cpp. Let's not be shy. Now for the real reviews:

Input

std::string currentLine = " "; // do not start empty

while (currentLine.length() != 0) // escape input by an empty line
{
    std::getline(std::cin, currentLine);
    userInput.push_back(currentLine);
}

This is bad. getline() could fail - and you'd expect it to fail when the input runs out. But you're not checking the result of getline(), so you end up writing an extra string onto your vector. The correct approach would be:

for (std::string currentLine; std::getline(std::cin, currentLine); ) {
    userInput.push_back(currentLine);
}

This ensures that you get the correct strings in your userInput.

Looping

Since this is tagged C++11, you definitely want to use a range-for expression to do your loop. It's less code and clearer:

for (const std::string& str : userInput) {
    std::cout << modifyString(str) << std::endl << std::endl;
}

Know what's in the standard

Your modifyChar() function's job is to pick some character (either + or -) and return a string with that character next times, followed by a period. You do not need a loop for this. There is a constructor for std::string that takes a count and a character and constructs a string with that character that many times.

Thus:

std::string modifyChar(char input, int carry)
{
    int next = input - carry;
    std::string output = (next > 0) ? std::string(next, '+')
                                    : std::string(-next, '-');
    return output + '.';
}

And same comment about looping again for modifyString. Though additionally you should take input by reference-to-const, to avoid a completely unnecessary copy:

std::string modifyString(std::string const& input)
{
    std::string output;
    int traveller = 0;
    for (char c : input)
    {
        output += modifyChar(c, traveller);
        traveller = c;
    }
    return output;
}


use replicate a ' ' instead of concat $ take a $ repeat " "
use pattern matching in main to check that there are exactly two arguments and use it also for read to check that the width is exactly a number. With [(width,_)] you accept also strings that only start with a number, such as "1O" where probably you made a mistake and you wrote it instead of "10"
lead and end can be specific to format to avoid exposing them. Actually you can also remove them and just write "    [" ++ xs ++ "]"
scroll can be simplified and both the helper and the format function can should be only visible to it
don't concat the output together before writing it: just write each line in output. UseforM_ for multiple IO operations over a list of values.

So, my rewrite of your code is

import Control.Monad (forM_)
import System.Environment
import System.Exit
import System.IO

scroll :: Int -> [Char] -> [[Char]]
scroll a = reverse . scrollHelp [] . addSpaces
  where
    addSpaces xs = replicate a ' ' ++ xs ++ replicate a ' '
    scrollHelp acc str
      | length str < a = acc
      | otherwise      = let group = take a str
                         in scrollHelp (format group:acc) (tail str)
    format xs = "    [" ++ xs ++ "]"

main = do
  args <- getArgs
  case args of
    (widthString:text:[]) ->
       case reads widthString of
         [(width,"")] -> forM_ (scroll width text) putStrLn
         _ -> hPutStrLn stderr $ "width must be an integer, got '" ++ widthString ++ "'"
    _ -> do
      name <- getProgName
      hPutStrLn stderr $ "usage: " ++ name ++ " <marquee width> <text to marquee>"
      exitFailure


Generic methods for serializing and deserialzing xml files using streams followup

So my question, is this good code? is this a proper work around?

I would ask different questions:

Does the code work?
Could you avoid editing the csproj file?

If both answers are yes, the I'd say it's a good workaround... but not a perfect one.

stream.Close();

This line shouldn't be there. The caller should take care of disposing the stream. Every method should keep track only of its own resources. The ones that come from the outside world should be taken care of by their respective owner.

I'd be really surprised if I called this method and wanted to work with the stream later but get an exception that it has already been closed.


Given concern for performance, the obvious change would be to allocate a buffer large enough for all the output data. As you compute each result, just write the results to the output buffer. Then, when you've accumulated it all in the buffer, write the entire buffer to the output in one big chunk.


Reading a user credentials from file concurrently

When a variable is volatile, then the code that access that variable is forced to read/write the value of variable from/to the memory. Without volatile, the value of variable can be (temporarily) stored to place (like register/cache) where changes are not immediately visible to other threads, or changes by other threads are not immediately visible.
synchronized is used in the code for avoiding concurrent and duplicate initialization of maintenanceUserCred. Without the synchronized block, two or more threads can enter to maintenanceUserCred = getMaintenanceUserCredentials(); line at the same time. The synchronized will pass only one thread at a time to the block, so maintenanceUserCred = getMaintenanceUserCredentials(); will be done only once.

Both synchronized and volatile will create memory barriers, that ensures that loads and stores are really from/to the main memory (not only local cache of current CPU core).

For example without volatile and synchronized the generated code could effectively work like the following code:

ConfigUserCredentails tmp = maintenanceUserCred;

if (tmp != null) {
    return tmp;
}
tmp = getMaintenanceUserCredentials();
maintenanceUserCred = tmp;
return tmp;

That will allow several threads to call getMaintenanceUserCredentials() at the same time and threads may obtain different ConfigUserCredentails objects.


Here is what it looks like you're trying to do:

loop through set, loop through each individual word in set, until you find toMerge.
When you find that, you then restart the loop through set, and each word in set until you find fromMerge.

This is producing a redundancy in the case that your initial loop iterates over fromMerge, but continues the loop because it is only looking for toMerge. The approach I would take to improve it would be to search for both in the same loop, thereby eliminating the redundant second loop.

public void find(ArrayList<String> operations, ArrayList<String> set) {
    String toMerge = operations.get(1);
    String fromMerge = operations.get(2);
    int toMergeIndex = -1, fromMergeIndex = -1; //add search indexes
    for (int i = 0; i < set.size(); i++) {
        if (set.get(i).indexOf(toMerge) > -1)
            toMergeIndex = i;
        if (set.get(i).indexOf(fromMerge) > -1)
            fromMergeIndex = i;
        if (toMergeIndex != -1 && fromMergeIndex != -1)
            break;
    if (toMergeIndex == -1 || fromMergeIndex == -1){
        throw new Exception();//Failed, didn't find. Deal with as you wish
    }
    else{
        set.get(fromMergeIndex) += " " + set.get(toMergeIndex);
        set.get(toMergeIndex) = " ";
    }

This is the only efficiency improvement that I can think of. Hope it helps!


Implement jquery like functions addClass, removeClass and delay in Javascript

Mutating built-in prototypes is not a good idea. It's not only inelegant, it can also lead to conflicts when other scripts on the page expect the prototypes to be unmutated. (It can even damage future attempts to integrate functionality officially, if enough sites use the bad code.)

Instead of using Element.prototype, create your own class, and put methods onto its prototype.

If you want to emulate jQuery, you should probably select all elements that match the selector, not just the first one. (Using a collection of elements will also avoid errors if the collection is empty - jQuery doesn't error when methods are called on an empty collection)

The active flag would be more informative if it was named more precisely, perhaps call it methodInProgress.

that = this is an antipattern in modern Javascript. If you need to use the calling context from the outer scope, use arrow functions instead. (You're already using ES2015 in multiple places)

callback is a single word, not two, so the proper way to camelCase it would be to keep it as-is. Calling the arguments callBack instead could result in bugs later when other readers/writers of the code expect it to be formatted conventionally.

Promises should be reserved for asynchronous actions. If you're going to run something that's completely synchronous, using a Promise adds unnecessary and confusing noise. Consider having your functions return Promises only if they're asynchronous, and while processing the queue, if a callback returns a Promise, wait for the Promise to resolve before moving onto the next callback. If the callback doesn't return a Promise, you can still await it without errors, and the next queue callback will run immediately.

Since you have multiple methods which add callback to the queue and return this, consider passing those methods through a helper function to make the code a bit more DRY.

Refactored:

const $ = selector => new PsuedoJquery(selector);
class PsuedoJquery {
  constructor(selector) {
    this.elements = [...document.querySelectorAll(selector)];
    this.queue = [];
  }
  async runNext() {
    await this.queue.shift()();
    if (this.queue.length) {
      await this.runNext();
    } else {
      this.methodInProgress = false;
    }
  }
  register(callback) {
    this.queue.push(callback);
    // If errors are a possibility, catch them here
    if (!this.methodInProgress) {
      this.methodInProgress = true;
      this.runNext();
    }
  }
  makeChainable(callback) {
    this.register(callback);
    return this;
  }
  addClass(className) {
    return this.makeChainable(() => {
      for (const elm of this.elements) {
        elm.classList.add(className);
      }
    });
  }
  removeClass(className) {
    return this.makeChainable(() => {
      for (const elm of this.elements) {
        elm.classList.remove(className);
      }
    });
  }
  delay(ms) {
    return this.makeChainable(() => new Promise((resolve) => {
      setTimeout(resolve, ms);
    }));
  }
}

$('#test')
  .removeClass("red").delay(500)
  .addClass("blue").delay(500).delay(500).removeClass("blue")
  .delay(500).addClass("red").delay(500).removeClass("red")
  .delay(500).addClass("blue").delay(500).removeClass("blue")
  .delay(500).addClass("red").delay(500).removeClass("red")
.blue {
  background-color: blue;
}

.red {
  background-color: red;
}


I wouldn't say, your major concern should be performance. I find the method rather error prone and it has a very limited use:

1) All columns have to be of type string - except the first which must be of type Guid

2) The order of the columns in the table must match the order of the properties of the object type. If they don't, a column could easily be mapped with a wrong property without no warning because they must all be strings. You definitely need some type checking.

3) A data table usually has a (unique) Id column, which the instances of the class should be instantiated with, but it seems, that you create a new object Id for every new instance/row. Is that Id saved to the database? And what about the next time the Row/Item are mapped - is a new Id again created for that item? It seems not logical to have a new id for an item every time it is fetched from a database?

I would say that the method is so aimed at a special situation where you need to map a data table with a certain class that it is not a candidate as an extension method - but just as a private method in a class. An extension method should be generic as much as possible and should handle all possible errors in a consistent way.

What about private vs. public members?

I personally don't like the use of an indexed iteration here: I would go along these lines:

  PropertyInfo[] pis = typeof(T).GetProperties();

  foreach (DataRow row in dt.Rows)
  {
    T item = new T();

    foreach (DataColumn column in dt.Columns)
    {
      PropertyInfo pi = pis.FirstOrDefault(p => p.Name == column.ColumnName);
      if (pi != null)
      {
        pi.SetValue(item, row[column]);
      }
    }
  }

or

  PropertyInfo[] pis = typeof(T).GetProperties();

  foreach (DataRow row in dt.Rows)
  {
    T item = new T();

    foreach (PropertyInfo pi in pis)
    {
        pi.SetValue(item, row[dt.Columns[pi.Name]]);
    }
  }

Notice, that the call to typeof(T).GetProperties() is outside the loops, because there is no need to call it for every row/item. In this way you are half the way to a nearly completely generic extension method.

In order to make it more generic, you'll have to consider the mapping strategy:

1) Should the column names match the property names of the class or should you consider to be able to provide a mapping table?:

public static List<T> DataTableToList<T>(this DataTable dt, Dictionary<string, string> mappings) where T : class, new()

or:

public static List<T> DataTableToList<T>(this DataTable dt, (string column, string property)[] mappings) where T : class, new()

You'll also have have to consider conversion of certain types: for instance is DateTime often stored in a data table as SqlDateTime which can not implicitly cast to a DateTime structure, so you should maybe be able to provide some converters:

public static List<T> DataTableToList<T>(this DataTable dt, (string column, string property)[] mappings, Dictionary<string, Func<object, object>> converters) where T : class, new()

called like:

    Dictionary<string, Func<object, object>> converters = new Dictionary<string, Func<object, object>>
    {
      { "BirthDay", (sqlDate) => ((SqlDateTime)sqlDate).Value }
    };

    List<MyItem> items = table.DataTableToList<MyItem>(null, converters);

Both the mapping and converter strategy can probably be more elegant or sophisticated - the above is merely some quick suggestions.


Ensuring array of worksheets are present

There are no risks because you are trapping the errors.

A better way to write the code would be to pass the target Workbook and the array of Sheets into the function for testing.  In the Function itself use On Error Resume Next to turn off the Error notification, Err.Number <> 0 to test if an Error was thrown, and On Error Goto 0 to reset any Errors.  I would also log the missing Sheets to the Immediate Window.

If you need to this pattern often, consider saving it in your Personal Macro Workbook.

Private Sub Test()
    Dim SheetsArr As Variant
    SheetsArr = Array("Response Times", "Incidents", "Calls", "Resources", "NoC, CPR")
    If AllSheetsPresent(ThisWorkbook, SheetsArr) Then MsgBox "Doing something"
End Sub

Private Function AllSheetsPresent(WB As Workbook, SheetsArr As Variant) As Boolean
    Dim msg As String, sh As Variant
    For Each sh In SheetsArr
        On Error Resume Next
        Set sh = WB.Sheets(sh)
        If Err.Number <> 0 Then msg = msg & sh & vbCrLf
        On Error GoTo 0
    Next

    If Len(msg) > 0 Then
        msg = Left(msg, Len(msg) - 1) 'Remove the last line return vbCrLf
        Debug.Print "These Sheets are not in " & WB.Name & ": " & Replace(msg, vbCrLf, ", "); ""

        msg = "These Sheets are not in " & WB.Name & vbCrLf & msg
        MsgBox msg, vbCritical, "Missing Sheets"
    Else
        AllSheetsPresent = True
    End If
End Function


Why is the function named allCombinations?  The "all" seems superfluous.  Also, it's actually returning permutations rather than combinations, so the second half isn't really accurate either.  I suggest naming it something else entirely, though: product, based on the function in Python's itertools module that does something similar.  As for the first parameter, I find dims (or dimensions) to be more descriptive than n.

Why limit yourself to two possible values?  Why not also support a tri-state, for example?  You could make values variadic.  As a bonus, you wouldn't have to manually toggle between value and alternativeValue; you could just use normal iteration tools like .map.

def product[T](dims: Int, values: T*): Seq[Seq[T]] = {
  dims match {
    case 0 => Seq()
    case 1 => values.map(Seq(_))
    case _ => {
      val lesserProduct = product(dims - 1, values:_*)
      values.flatMap(v => lesserProduct.map(_.+:(v)))
    }
  }
}

Note that the ordering convention is different from yours; i.e. product(4, false, true) is equivalent to allCombinations(4, true, false).  I don't consider that to be a drawback.


I will use this method inside my tests class

Your plan is to generate random data to test your thing. Suppose a test fails.  How are you planning on debugging it with the data that caused it to fail?

Don't randomize tests.  Generate the random test data once, and save it, and then use it over and over again.


Targeting string to wrap with HTML element to italicize

First of all, I would highly recommend NOT doing this in JS for the following reasons:

You'd have JS scan through words, which may be slow.
FOUC, where the word is not italic until the JS runs.
jquery.text() captures newlines and whitespace. If the word is split with unexpected newlines in between, the script breaks.
jquery.html replaces HTML using innerHTML. This means:

Existing event handlers, especially those created by frameworks, are not cleaned up properly.
Existing event handlers will not be re-attached to your new HTML.

In addition to that, I suggest not hardcoding the replacement string. Use capture groups to have RegExp capture the match. Then convert the matched string to upper case and wrap it with the element afterwards. That way, you don't have hard-coded replacements, only the searches.

What I highly suggest is to do this on the PHP side instead. You can take the same logic, except just to it there. I believe preg_replace is what you need for this. If you cannot access the server-side code, then request access.

JS might be the quick and easy way to do this, but stuff like this over time leads to fragmented, highly unmaintainable, and hard-to-find code. A normal developer would think "Hey, it's probably italicized in the source." until they find out days later (yes, days) it was never in PHP. Thenthey'll have to hunt it down in JS, except they won't know where to start.


Note: this is not exactly the RSA problem. For it to be the RSA problem, the modulus would have to be composite. Turns out, in this case, the modulus is prime.

Note also: this is not the discrete log problem, as in the discrete log problem we are trying to find the exponent, not the base.

That said, you can find the answer using the method that CodesInChaos recommended.

Factor mod, easy, mod is already prime, so it is factored.
Compute phi(mod). This is the euler totient function. For primes, phi(mod)=mod-1. So in your case, phi(mod)=9691572.
Compute d such that power*d=1 modulo phi(mod). Use the extended euclidean algorithm to do this. You will get d=7868405. There are python libraries that will do it for you (pycrypto Crypto.Util.number.inverse)
Compute 8765^d modulo mod. In python you want to do this using pow. pow takes a third argument (a modulus) which is way optimized when compared to ** followed by %. It does the square-and-multiply method. In this case, pow(8765, 7868405, 9691573) returns 680457.

You can check the answer by doing pow(680457, 101, 9691573) and make sure it return 8765.

If the modulus were not prime, you'd have to factor it to compute phi(mod). After that, everything else is the same.


I'm confused as to why you treat the results of isNaN and typeof as separate things, since failing either test would invalidate the argument.

So you could simplify validateArgAsNumber a lot if you just gave it one argument and let it return a simple boolean. Its name actually already implies only one argument, since it's called "validate arg", not "validate args". However, I'd rather call it isValidNumber - why care if it's an argument for something else?

function isValidNumber(value) {
    return typeof value === 'number' && !Number.isNaN(value);
}

If typeof value isn't 'number', we immediately know something's wrong. The isNaN check is only necessary because JavaScript has this funny thing about NaN itself being a number (it's a long story and has to do with IEEE-754 64-bit floating point numbers).

From there, the rest of the code becomes a lot simpler, since you don't have to worry about checking two separate booleans each time you want to check one argument.

I'd also be tempted to simply make the validation function an inner function in getRelationship, since its purpose is somewhat specific to that task.

Of course, the function is now so simple that it almost doesn't need to be a function, but let's roll with it. It avoids a trivial bit of repetition.

With the above you might get something like this:

function getRelationship(x, y) {
  function isValidNumber(value) {
    return typeof value === 'number' && !Number.isNaN(value);
  }

  var xValid = isValidNumber(x),
      yValid = isValidNumber(y);

  if(!xValid && !yValid) {
    return "Can't compare relationships because " + x + " and " + y + " are not numbers";
  }

  if(!xValid || !yValid) {
    return "Can't compare relationships because " + (xValid ? y : x) + " is not a number";
  }

  if(x === y) {
    return '=';
  }

  return x < y ? '<' : '>';
}

Note that I've combined the check for "x or y is invalid" into a single return. That way, I don't have to repeat a line of mostly-hardcoded text.

The last bit - after checking the arguments - can be handled in many ways. I chose the above, because it puts an explicit return on the last line, which I think reads well. It only returns early from inside a branch if it has to. But you could of course also use if..else if..else, or even a switch:

switch(true) {
  case x > y: return '>';
  case x < y: return '<';
  default: return '=';
}

But that's a little too tricky.


Design considerations
There are a few higher level design considerations that will make your life a lot easier if you decide to make a more complicated game or go to a GUI approach.
Input/output
One thing I see is that you don't have a clear separation of the input/output and the game logic. This will make it considerably harder to move to say a GUI approach in the future.
For example:
class Character(object):
    def battle(self,exp):
        self.exp = self.exp + exp
        self.lvl = self.exp/100
        print ("Successful battle! {} experienced gained!".format(exp))
        self.stats()

You have 2 things going on here that really should be separate. You have the battle aspect that updates information about the character and you have some output handling. As it currently stands there is an implicit assumption in parts of your code that the game is a terminal based game because of where the input/output occurs.
These types of situations are much more nicely handled if you split the input/output out from the game logic.
So in this case:
new_character.battle(100)

Might become
old_exp, old_lvl = new_character.exp, new_character.exp
new_character.battle(100)
print ("Successful battle! {} experienced gained!".format(new_character.exp - old_exp))

Now if you move to a GUI approach you just change the print here to something else. This is a lot easier than having to track down the print statements scattered throughout the code.
Lack of functions
There's a noticeable lack of functions here. An especially good example is the menu handler, with the large change of else-if statements:
if menu_choice == "new":
    chardata = ["Foo", 300]
    new_character = Character(*chardata)
    print ("New character created!")
    new_character.stats()

I would start breaking out things like this into functions:
def create_new_character(character_data):
    """Create a new character"""
    new_character = Character(*chardata)
    new_character.stats()
    return new_character

if menu_choice = "new":
    new_character = create_new_character(["Foo", 300])
    print ("New character created!")

Again notice how I am separating out the input/output here from the other functionality. Step 1: create the character then step 2: deal with the output. I would do a similar refactoring with other cases in this chain of else-if's.
Mutable global state
This can turn into a particularly nasty maintenance burden as your codebase grows in size. It makes the flow of the code harder to follow and reason about. This is because having global state that can be change from anywhere makes it much harder to track down which parts of the code can change other parts of the code.
I would strongly recommend creating a class that manages the state of the game which contains the main game loop. This will pay off whenever you have issues you have to debug.
Python usage
In some places you are comparing against None and other "truthiness" values. This is not a recommend practice.
For example
while loop_menu == True:

if menu_display == "new" and menu_error == None:

can be written as:
while loop_menu:

if menu_display == "new" and not menu_error:

I notice you quit the program by breaking out of the main game loop. If there is code after the thread loop you might not immediately quit here. If your intent is to quite immediately you can use something like:
elif menu_choice == "quit":
    print ("Quitting program...")
    import sys
    sys.exit()

This guarantees your code exits here.


Show() is probably slowing it down. It transforms your implementation into \$O(n^3)\$ and even worse increases the algorithm's time by (n*[time taken to access and write to console stream]) in the last loop. Preparing your string and printing once to the console would increase the speed, even better, printing when the list is sorted. Requesting and using resources (e.g. streams) during an expensive operation will increase execution time. You are using Console.Write <-- probably accessing the raw stream would be even faster if needs be.


Which one of the two enum implementation is better?

Why not use the order you are setting up in the enum declaration? I played with this a while ago and came up with something like this (modified to fit your implementation above):

private enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE;
   public Planet getNext() {
       return this.ordinal() < Planet.values().length - 1
           ? Planet.values()[this.ordinal() + 1]
           : this;
   }
   public Planet getPrevious() {
       return this.ordinal() > 0
           ? Planet.values()[this.ordinal() - 1]
           : this;
 }


Ensure every element in array passes asynchronous test

First of all, it appears that Item.findOne already returns a promise. You don't need to wrap it again in a promise. Simply use that same promise as the return value for your array.every.

Now as far as I understand your problem, you just need to hit the db for every element in item and resolve the promise belongTo returns if every element belongs to user. I don't think your code will work that way. What will happen is that belongTo return a promise will resolve immediately with the value returned by array.every.

Next, you don't need to pass true or false as promise resolution. The fact that it resolved/rejected is enough to tell you that. Also, you don't need to wrap an operation with a promise to create a promise. There's Promise.resolve() and Promise.reject() that create already resolved/rejected promises.

function belongTo (user, items) {
  const pingPromises = items.map(item => Item.findOne({ owner: user,
    assetID: item.assetid,
    appid: item.appid,
    contextid: item.contextid,
    marketHashName: item.marketHashName
  }).then((item) => {
    // Validate result if we should resolve/reject this promise.
    return Object.keys(item).length ? Promise.resolve() : Promise.reject();
  }));

  // Do not catch. If Item.findOne rejects, let's reuse that rejection.

  // Accepts an array of promises. Returns a promsie that resolves when all
  // promises resolve, rejects when at least one rejects.
  return Promise.all(pingPromises);
}

Now even with that code, the operation itself is very inefficient. You might want to consider creating some form of compound query instead and only hit the DB once. Not very familiar with MongoDB, but in MySQL this can easily be done by using multiple conditions.


Replace

try (FileInputStream fis = new FileInputStream(file)) {

with

try (InputStream fis = new BufferedInputStream(new FileInputStream(file))) {

See also Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream?


Testing if numbers in the array can be added up to equal the largest number in the array

First, let's fix the two bugs in the code.

If the array would contain only numbers below -100, your code would think that -100 was the greatest number, located at index -1. That would make the rest of the code remove the last item of the array instead of the greatest one, and try to sum up the remaining to be -100.

Start with the first item as the greatest instead of -100:

var greatest = arr[0];
var index = 0;

for (var i = 1; i < arr.length; i++){
  if (arr[i] > greatest){
    greatest = arr[i];
    index = i;
  }
}

(That bug would however not change the outcome, as an array of numbers below -100 can't be combined to give the sum -100, and an array of all negative numbers can't form a sum according to the specification.)

The splice is using the variable i instead of index. It should be:

arr.splice(index, 1)

Using recursion is a good idea to find a combination. You can make a function that determines if any combination of items from an array can give a specific sum. The function would loop through the items in the array, and call itself to determine if the remaining items could give the sum when the item is subtracted.

Another alternative is to use a bitmask to represent the combinations. If you count from 1 to 2^arr.length-1 you will get all possible combinations. The bitmask 11101 (decimal 29) would give the winning combination [4, 6, 10, 3] from the array [4, 6, 10, 1, 3].


Parsing a Conditional statement with Python

You can use the builtin function all() here to check phrases in a subquery are part of the string passed.

def get_sub_queries(query):
    for subquery in query.split(' OR '):
        yield subquery

def get_phrases(subquery):
    for phrase in subquery.split(' AND '):
        yield phrase

def find(query, string):
    for subquery in get_sub_queries(query):
        if all(phrase in string for phrase in get_phrases(subquery)):
            return True
    return False

Try to use better variable names(I know it's hard though :-)).

Apart from these I have broken your code into 3 functions now.

Contains logic to split queries to subqueries
Contains logic to split subquery to get phrases
Actual find() functionality

The reason behind this is that if the logic related to anyone of them changes later on then it won't complicate your search functionality and you can write separate tests for each of the three functionalities.

If you're on Python 3.3+ then use could also use yield from.


Find maximum value of Point represented by an Array of values for each coordinate

I'm not a Lisp guy, but parenthesis are powerful. Change this:

sum = A[i] + A[j] + (j - i)

to that:

sum = (A[i] - i) + (A[j] + j)

Both things are equivalent, but the second one looks quite different.
Its a sum of two numbers and each one only depends on its own index, there's a term based on i and one on j (and the array A of course).

A sum (of independent summands) becomes max, if each summand is max.

The thing is that being independent means that you can calculate both maximums "parallel" to each other while iterating through the array.
I called them iMax, which is  value - index and jMax which is value + index

Implementation is straight forward:

public class ElementIndexSum
{
    public static void main (String[] args)
    {
        int[] A = {2,3,5};

        int iMax = Integer.MIN_VALUE, jMax = Integer.MIN_VALUE; // minimum possible value serves as neutral starting point to find maximum

        for (int index = 0; index < A.length; ++index)
        {
            // find maximum value from values in array
            iMax = Math.max(iMax, A[index] - index); // with subtraction of its index
            jMax = Math.max(jMax, A[index] + index); // with addition of its index
        }

        System.out.println("maximum( A[i] + A[j] + i - j ) = " + (iMax + jMax));
    }
}

Result in console:

$ java ElementIndexSum
maximum( A[i] + A[j] + i - j ) = 10

I have no clue about this bick Oh stuff, but if your goal was to iterate only once and not in a nested way, I think the above is what you are looking for.


Your functionalmethod is fine, just the place You have defined is a bit anti pattern. (But well, if you really want to use that component in JUST in that scope its still fine.)
But let me try to refactor it in  a react way:
render () {

  return (
            <>
            {
              showContainer
                ? (
                  <Modal>
                    <ChildJsx />
                  </Modal>
                )
                : (

                    <ChildJsx />

                )
            }
            </>
        )
}

function ChildJsx(props){
  return (
    <>

Random Child JSX

    </>
  )
}

React is about reusability. In this case you can use that small component again and again as many as you want.


Randomly generate a list with predetermined mean

Review

The official Python style-guide recommends using lower_case for variables (your variable HT violates this).

I would make all relevant parameters actual parameters of the function. This makes it a lot easier to test.

The main code of a module should be wrapped in a if __name__ == "__main__": guard. This allows you to do in another script:

from random_with_mean import lst_w_mean

without executing the tests.

I would try to find a different name for the function, without too many abbreviations.

Alternative approach

I would use a completely different approach to this.

First, note that the Poisson distribution is a positive-semidefinite distribution for integers. If we want to generate a integers in the range (0, 100) (similar to your example, but note the off-by-one error), with mean 50, We can just take a np.random.poisson(50) (which I will call P(50) from now on), ensuring to throw away all values which are larger than 100 and redraw them.

This also works when generating values in the range (0, 100) but with mean 10. Only when the mean becomes larger than the half-way point do we start getting into trouble. Suddenly we are starting to loose a larger and larger part of the tail to the upper boundary. To avoid this, we can just swap the problem around and declare the upper boundary to be zero and generate the values as high - P(high - target), so we generate how far the value is away from the boundary.

Similarly, when the lower bound is not zero, we need to shift the values upwards and generate low + P(target - low).

An implementation of this is:

import numpy as np

def lst_w_mean(low, high, num, target):
    swap = target > (high - low) / 2
    out = []
    to_generate = num
    while to_generate:
        if swap:
            x = high - np.random.poisson(high - target, size=to_generate)
            x = x[low <= x]  # x can't be larger than high by construction
        else:
            x = low + np.random.poisson(target - low, size=to_generate)
            x = x[x < high]  # x can't be smaller than low by construction
        out.extend(x)
        to_generate = num - len(out)
    return out

if __name__ == "__main__":
    print np.mean(lst_w_mean(0, 100, 50, 50))
    print np.mean(lst_w_mean(0, 100, 50, 10))
    print np.mean(lst_w_mean(0, 100, 50, 70))

Note that I always generate multiple values (enough to fill the out list if all were inside the boundaries) at the same time, then throw away all values outside of the boundaries and loop until the out list is the right size. Most of the time only one iteration is needed, because it can only go outside of the boundary on the side away from the closer boundary.

Note that the variance of the Poisson distribution is the same as its mean and so its standard deviation is the square root of that. This means that you will get some outliers, but the distribution is far from uniform over your range.

To visualize this, here are three different samples (with n=5000), one with mean 10, 50, 75 and 99 each using the Poisson distribution:

As an alternative, you could take the Beta distribution, which is only defined on the interval [0, 1], which helps us a lot here, because we don't need to take care of edge effects, we only need to shift and rescale our values. Given a mean and sigma (I took sigma to be an arbitrary value), we can derive the necessary parameters \$\alpha\$ and \$\beta\$, as given as alternative parametrization on wikipedia:

\$\alpha = \mu \left(\frac{\mu(1 - \mu)}{\sigma^2} - 1\right),\quad \beta = (1 - \mu) \left(\frac{\mu(1 - \mu)}{\sigma^2} - 1\right)\$

which only holds when \$\sigma^2 < \mu(1 - \mu)\$.

With this, I ended up with the following code:

from __future__ import division

def lst_beta(low, high, num, mean):
    diff = high - low
    mu = (mean - low) / diff
    sigma = mu * (1 - mu)
    c = 1 / sigma - 1
    a, b = mu * c, (1 - mu) * c
    return low + diff * np.random.beta(a, b, size=num)

Visualized for \$\mu = 10, 50, 75, 99\$ this looks like this:

In comparison, this is what @Peilonrayz's algorithm produces for these means:

Edit:

Here is the code to generate the graphs:

import matplotlib.pyplot as plt

#function definitions here
def lst_w_mean(low, high, num, target):
    ...

plt.figure()
means = 10, 50, 75, 99
for i, mean in enumerate(means, 1):
    plt.subplot(len(means), 1, i)
    l = lst_w_mean(0, 100, 5000, mean)
    plt.hist(l, bins=100, range=(0, 100))

plt.show()


I haven't found a way to properly test/mock SalesforceRequest when exercising it's consumers.

What it did do was make me realize

Naming the class Request and then providing multiple "request"-like methods on it was a mistake. Each SalesforceRequest subtype was a full blown API provider.
Following from 1, I took the generics approach to make the SalesforceApiGateway type-safe (which was the initial driver for the request classes).

I ended up with the following interface:

interface SalesforceObject {
    val Id: String
    val CreatedById: String
    val LastModifiedDate: Instant
}

interface SalesforceApiGateway {
    val API_VERSION: String
    val MAX_RECENT_DAYS: Duration

    fun <T: SalesforceObject> getLastUpdated(type: KClass<T>, backTill: Duration = Duration.ofDays(1)): LastUpdated

    fun <T: SalesforceObject> getLastUpdated(type: KClass<T>, backTill: Instant): LastUpdated
            = getLastUpdated(type, Duration.between(backTill, Instant.now(Clock.systemUTC())))

    fun <T: SalesforceObject> getDetails(type: KClass<T>, uuid: String, fields: List<String> = type.members.map { it.name }): Details<T>

    data class LastUpdatedResponse(val ids: List<String> = emptyList(),
                                   val latestDateCovered: String = ISO_DATES.format(ZonedDateTime.now(Clock.systemUTC())))
    data class LastUpdated(val error: Throwable? = null, val response: LastUpdatedResponse? = null)

    data class DetailsResponse<T>(val wrapped: T)
    data class Details<T>(val error: Throwable? = null, val response: DetailsResponse<T>? = null)
    companion object {
        val ISO_DATES = DateTimeFormatter.ISO_OFFSET_DATE_TIME
    }
}

The upside is that I can now use Kotlin's awesome defaulted parameters to allow my gateway consumers to not care about fields they want to select, but advanced, future uses can still override that choice. It also allows me to express that I want gateway implementations to be in charge of properly de-serializing responses to the correct requested type. Plus, I still get to keep my interface, so testing is trivial by implementing a dummy.

There's several things that were suggested in the process:

Use the Result class to model success/failure instead of custom "result" classes. I wasn't able to wrap my head around their model of creating a result from an existing basic type (like my List<String>). Maybe next time.
Using Retrofit (thanks orangy for mentioning that!) to generate the code for the gateway. However, Jake Wharton confirmed Retrofit won't allow me to template my method, resulting n methods per SalesforceObject. I tried it and just copy and pasting my methods made my skin crawl.


Here one way to sum a list of integers using ECMAScript 5's functional support

// Sum all values in a list by reducing the list to a single value
array.reduce(function(prev, curr) {
  return prev + curr;
});

Not faster than your approach due to the repeated function calls, but definitely shorter.

Your approach can be further simplified:

// Move everything into the parenthesis of for-loop!
var sum = function(array) {
  for (
    var i = 0, len = array.length, total = 0;
    i < len;
    total += array[i++]
  );
  return total;
};

Not recommended because it's not very readable. I just think it's interesting :)

I'll give you an alternative approach to the "Find length of longest string" problem:

// Sort it by length descending and then get the first
var longestStrLen = array.sort(function(a, b) {
    a.length - b.length;
})[0].length;

Hope these open your eyes to some of the possibilities!

Now, here's an actual review:

var charFreq = function(string){
  var list = {}; // Not a list (implies order). Should name it a dictionary or map
  var length = string.length; // no need to have this be separate line
  for (var i = 0; i < length; i++) {
  if (string.charAt(i) in list)
    // What's with the +1??
    list[string.charAt(i)] += +1;
  else
    // No need to call string.charAt multiple times!
    list[string.charAt(i)] = 1;
  }
  return list;
}

Revised version:

var charFreq = function(string){
  var dict = {};
  for (var i = 0, len = string.length; i < len; i++) {
    var currChar = string.charAt(i);
    if (currChar in dict) {
      dict[currChar] += 1;
    } else {
      dict[currChar] = 1;
    }
  }
  return dict;
}

Hope that helps!


Doing this in a loop will be slow, and doubling the calls by retrieving each column with a different query will make things worse.

Why not use a JOIN between your original query, something like this:-

SELECT database.job_id, job_sheet.qty, job_sheet.row
FROM database
INNER JOIN job_sheet
ON database.job_id = job_sheet.job_id

In your loop this would mean a single query rather than ~20000 queries.

If you do need to do a separate query for each time through the loop then a prepared statement would help but peformance will likely still be poor.


Optimize this code of adapter's overriden method getItemCount()

Code Beautification is suggestive. This is how I would write your code. There is also a possible performance optimization by only calling super.getItemCount() once.

be consistent with parentheses (I'm using a different rule for methods and conditions, but feel free to use your own preference as long as you are consistent)
create one variable to store the item count
get the item count you would like to return from the base class
determine predicate from the perspective of either

(A) the edge case value of item count, when itemCount == 0; an inner condition is used to determine the new value
(B) the combined condition that yields a different result itemCount == 0 && data != null

snippet A

@Override
    public int getItemCount() {
        int itemCount = super.getItemCount();
        if (itemCount == 0)
        {
            itemCount = data != null ? 1 : 0;
        }
        return itemCount;
    }

snippet B

@Override
    public int getItemCount() {
        int itemCount = super.getItemCount();
        if (itemCount == 0 && data != null)
        {
            itemCount = 1;
        }
        return itemCount;
    }


Kotlin Stack using an ArrayList to compare and remove elements

An array to list can be done by the function toList().
list.size-1 is an existing property on a list called lastIndex.
'Math.abs' is from Java. Kotlin has its own abs, which isn't prefixed by a class.
List provides an operator function to access by index:
stack.get(curIndex) can be written as stack[curIndex]
fun asteroidCollision(asteroids: IntArray): IntArray {
    val stack = asteroids.toMutableList()
    var curIndex = stack.lastIndex
    while (curIndex >= 1) {
        val cur = stack[curIndex]
        val prev = stack[curIndex - 1]
        if (prev.isRight() && cur.isLeft()) {
            if (abs(cur) == abs(prev)) {
                stack.removeAt(curIndex)
                stack.removeAt(curIndex - 1)
                if (curIndex - 2 == stack.lastIndex)
                    curIndex -= 2
                else curIndex--
            } else if (abs(prev) > abs(cur)) {
                stack.removeAt(curIndex)
                if (curIndex - 1 == stack.lastIndex)
                    curIndex--
            } else {
                stack.removeAt(curIndex - 1)
                curIndex--
            }
        } else curIndex--
    }
    return stack.toIntArray()
}

flow
The if-else if-else chain can be reduced to two if-statements.
This is because the case where the absolute value of cur and prev are the same is just the other two cases combined.
As far as I know, you do need more variables, to make it possible.
Therefor, this is just another choice, with its own drawbacks:
fun asteroidCollision(asteroids: IntArray): IntArray {
    val stack = asteroids.toMutableList()
    var index = stack.lastIndex
    while (index >= 1) {
        val curIndex = index
        val cur = stack[curIndex]
        val prevIndex = index-1
        val prev = stack[prevIndex]
        if (prev.isRight() && cur.isLeft()) {
            if (abs(prev) >= abs(cur)){
                stack.removeAt(curIndex)
                if (index-1==stack.lastIndex)
                    index--
            }
            if (abs(cur) <= abs(prev)){
                stack.removeAt(prevIndex)
                index--
            }
        } else index--
    }
    return stack.toIntArray()
}


You should init your Stack with the length of your string. This way, you'd be sure never to hit the FullStackError.

Also, it seems to be on purpose but you don't support other characters in your string? I'd expect "(asdasd)" to return true.

This line : tuple([top_item, char]) not in zip(opening_brackets, closing_brackets): is maybe a little hard to understand at first glance. I'd suggest creating a variable for zip(opening_brackets, closing_brackets). It wouldn't change much but it'd give you an opportunity to have a more meaningful name.

From experience, I'd say that code that parses strings is never elegant and even though it's a generally accepted fact that try/catch(except) are ugly, they are most necessary and I think you should keep it this way.

Two slight nitpicks :

I'd rename answer to isBalanced
You should put your comments on separated lines for readability.