Candy splitting - lower memory usage needed

Your code is a bit messy, and buggy, and you have a significant memory problem in the event of there being a lot of test cases.

Buggy

The problem specifies that the number of candies (N) and children (K) is a value \$0 \le N,K \le 2^{33} - 1\$ The telling part is \$2^{33} - 1\$. That number is larger than a Java int value. You need to use long in order to support the specified input values.

Messy

You declare the variables:

int candieStuds;
int candieT;

outside the loop they are used in. You should declare variables in their scope. It is more readable, and less error prone.

On the other hand, you declare the StringBuilder inside the loop, but that is a system which can be reused, so you should. Declare it outside the loop, then call str.setLength(0) to reset it.

Memory

You declare an array, and store the results of all tests in that array. Once all tests are complete, you report on all the results. In one sense, this is good, because lots of println operations will slow things down. On the other hand, this is bad, because lots of tests cases will fill up memory.....

A compromise is to wrap the System.out in a BufferedWriter, and then write to the buffer for each test, and then let the buffer occasionally flush when it's full (and at the end).

Buffering the System.in is also a good idea.

Performance

Loading all your logic in to a method that is only called once is not a great plan for either readability, or performance.

Java performance is heavily dependent on the JIT compiler. In essence, the basic unit of compilation in Java is a method. You only have one method, and it only gets called once, so it is not likely to be compiled down very well. By giving the compiler more methods, called more often, you give it more to work with in terms of ways to compile things. More is good.

In your case, I would recommend a method for parsing the input lines in to numbers, a method for doing the computations, and another method for preparing the output...

I hacked together the following, which I think will do better (not sure how much better though...). Use it to see what I mean when I talk about the functions, and the buffering.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class CCCandy {

    public static void main(String[] args) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
            try {
                String line = reader.readLine();

                if (line == null) {
                    throw new IllegalStateException("Expecting test count input");
                }

                while ((line = reader.readLine()) != null) {
                    processCandySplit(line, writer);
                }
            } finally {
                writer.flush();
            }
        }
    }

    private static void processCandySplit(String line, BufferedWriter writer)
            throws IOException {
        line = line.trim();
        String[] inputs = line.split("\\s+");
        long candies = Long.parseLong(inputs[0]);
        long kids = Long.parseLong(inputs[1]);

        computeSplit(candies, kids, writer);

    }

    private static void computeSplit(long candies, long kids, BufferedWriter writer)
            throws IOException {
        if (kids == 0) {
            writer.write(String.format("%d %d\n", 0, candies));
        } else {
            writer.write(String.format("%d %d\n", candies / kids, candies % kids));
        }
    }

}


Vertically Merged Cells

I did NOT test against vertically merged cells, but it should not trigger an error (just unmerge them).

You code will unmerge the cells and set each cells .HorizontalAlignment = xlCenterAcrossSelection.
Target Area
Changing the target area from a Worksheet to a Range would make your code more versatile.

Sub fixMergedCells(sh As Worksheet)

Sub fixMergedCells(Target As Range)
    Set Target = Intersect(Target, Target.parent.UsedRange)

SpecialCells
SpecialCells are a PITA.  I would use Range.Find("*", SearchFormat:=True).

   Application.FindFormat.MergeCells = True
   Set c = Target.Find("*", SearchFormat:=True)
   Do Until c is Nothing

Unfortunately neither SpecialCells or Range.Find are going to find Merged cells if they are blank.  It might be better to search each cell in the range.
Center Across Selection
Merged cells are not always centered.  You might want to add a condition that if centered then Center Across Selection.

 If .HorizontalAlignment = xlCenter Then .HorizontalAlignment = xlCenterAcrossSelection


Here's what I've come up with;

import expect from 'expect';

const is2dArrayParsableToJsonList = () => true;

const convert2dArrayToJsonList = (array) => {

    if (!is2dArrayParsableToJsonList(array)) {
        throw new Error("The 2D array cannot be converted to a json list" + array);
    }

    const [propertyKeys, ...rows] = array;
    const rowToObject = row => Object.assign(... propertyKeys.map( (key,idx) => ({ [key]: row[idx] })));
    return rows.map(rowToObject);
}

const input = [
    ['foo', 'bar', 'baz'],
    [1,2,3],
    [4,5,6]
];

const output = [
    {foo:1, bar:2, baz:3},
    {foo:4, bar:5, baz:6},
];

expect(convert2dArrayToJsonList(input)).toEqual(output);

Core idea is that map gives you both a value and index. So when you map over the keys, we see 'foo/1', 'bar/2', 'baz/3'.


Instead of a top-down (very memory intensive) approach, I would recommend a somewhat bottom-up approach, where you add one column at a time then do the reductions, add another column, etc. Try this:

expand.mat <- function(mat, vec) {
   out <- matrix(0L, nrow = nrow(mat) * length(vec),
                     ncol = ncol(mat) + 1)
   for (i in 1:ncol(mat)) out[, i] <- mat[, i]
   out[, ncol(mat) + 1] <- rep(vec, each = nrow(mat))
   return(out)
}

valid.counts3 <- function(x, cvec) {
   l   <-  length(cvec) + 1
   vec <- seq(from = 0, to = cvec[1])
   mat <- matrix(vec, ncol = 1)

   for (j in 2:l) {

      mat  <- expand.mat(mat, vec)
      rsum <- rowSums(mat)
      mat  <- mat[rsum <= x & rsum + cvec[1] * (l - j) >= x, ]

      for (i in 1:(j-1)) {
         k <- j - i + 1
         if (k == l) next
         rsum <- rowSums(mat[, i:j])
         mat  <- mat[rsum <= cvec[k], ]
      }
   }

   return(mat)
}

system.time({
   res <- valid.counts3(x = 148, cvec = c(36, 67, 92, 119))
})
#    user  system elapsed
#   0.279   0.036   0.319

Edit: And to handle a vector of x as input, make these slight changes. It will return a list of matrices.

valid.counts3 <- function(x, cvec) {
   l   <-  length(cvec) + 1
   vec <- seq(from = 0, to = cvec[1])
   mat <- matrix(vec, ncol = 1)

   for (j in 2:l) {

      mat  <- expand.mat(mat, vec)
      rsum <- rowSums(mat)
      mat  <- mat[rsum <= max(x) & rsum + cvec[1] * (l - j) >= min(x), ]

      for (i in 1:(j-1)) {
         k <- j - i + 1
         if (k == l) next
         rsum <- rowSums(mat[, i:j])
         mat  <- mat[rsum <= cvec[k], ]
      }
   }

   mat <- mat[rowSums(mat) %in% x, ]
   idx <- split(seq(nrow(mat)), rowSums(mat))
   return(lapply(idx, function(i, x) x[i, ], mat))
}

system.time({
   res <- valid.counts3(x = seq(from = 148, to = 155), cvec = c(36, 67, 92, 119))
})
#    user  system elapsed
#   0.333   0.048   0.381

sapply(res, nrow)
#  148  149  150  151  152  153  154  155
# 8649 5776 3600 2025 1024  441  144   25


Better yielding tuple-d union case values in list generation

Why not use nested loops?

let OreDataMap =
    [
        for common in [ Common; Uncommon; Rare ] do
            for compressed in [ IsCompressed; IsNotCompressed] do
                for oreType in FSharpType.GetUnionCases typeof<EveOnline.OreDomain.Types.OreType> do
                    let ore = FSharpValue.MakeUnion (oreType, [| |]) |> unbox
                    yield (RawOreName ore).Value, (ore, common, compressed)
    ]
    |> Map.ofList

That's probably the idiomatic way, but if you don't like excessive indentation you can always align your successive for loops - I think this looks nicer. Also, you can replace the last do with -> to eliminate the need for the yield keyword.

let OreDataMap =
    [
        for common in [ Common; Uncommon; Rare ] do
        for compressed in [ IsCompressed; IsNotCompressed] do
        for oreType in FSharpType.GetUnionCases typeof<EveOnline.OreDomain.Types.OreType> ->
            let ore = FSharpValue.MakeUnion (oreType, [| |]) |> unbox
            (RawOreName ore).Value, (ore, common, compressed)
    ]
    |> Map.ofList


First of all, as Karl said, you should minimize the code in IO monad and make sure most of your code is in pure functions

Second your Command type is not properly designed

data Command = Command { name  :: String
                         , key   :: Maybe String
                         , value :: Maybe String
                       }

Having the name as String is not cool. You could have a type something like

data CommandType = Get | Set

...but still your command type has too many invalid combinations which the type system cannot help you with (for example: name="get", key="xyz", value="asdfasdf"). Your type should be designed such that you avoid these combinations and you make the type system work for you.

Given this I would define the Command type like this:

data Command = Invalid | End | Get String | Set String String

if your type is like this then execCmd will become:

exec (Get key) = ....
exec (Set key value) = ...
exec Exit = ...
exec Invalid = ...

If you only address these two issues you will see a lot of simplification in your code. Other things would be:

Using the State monad will help you with the passing of the current db state between the functions operating on it. If you do this then passing the state will not be your concern and your result could be either a tuple or a record:

data Result = Result { output: String ; end:Bool}

Then your displayResult will look like this:

UPDATE

If you don't want the a command to output anything then the output field in Result could have the type "Maybe String" instead of String. \

data Result = Result { output: Maybe String ; end:Bool}

Then you will have to choose only the Just outputs before you display the results.


Threads listening on TCP and rendering in a loop

No, this is absolutely not a good way. Thread.Abort() should never be used, because it is very hard to write correct code when an exception can happen at almost any point in your code.

Instead, you should implement cooperative cancellation either by using a volatile bool flag, or, even better, CancellationToken.

With that your code could look like this:

Thread ListenThread;
Thread RenderThread;
CancellationTokenSource CTS;

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    try
    {
        if (ReceiveCheck.Checked)
        {
            tcplisten.Start();
            CTS = new CancellationTokenSource();
            ListenThread = new Thread(() => Listen(CTS.Token)));
            ListenThread.Start();
            RenderThread = new Thread(() => Render(CTS.Token)));
            RenderThread.Start();
        }
        else
        {
            tcplisten.Stop();
            CTS.Cancel();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Checkbox");
    }
}

Your Listen() and Render() methods would then periodically check IsCancellationRequested of the passed in token and return if it's true.


You're right that the duplicate code in the sorters looks bad.
To solve this, each sorter should only define the compare function, and all the rest should be done by the enum class. Or not even this. It took me a little while of experimenting until the code compiled, but here it is:
enum class AudioRecordSort(
        private val cmp: Comparator<AudioRecordEmpty>
) {
    SortByDate(AudioRecordDateComparator()),
    SortByName(AudioRecordNameComparator()),
    SortBySize(AudioRecordSizeComparator()),
    SortByTime(AudioRecordTimeComparator());

    fun sort(empties: MutableList<AudioRecordEmpty>, asc: Boolean) {
        val cmp = if (asc) cmp else cmp.reversed()
        empties.sortWith(cmp)
    }
}

I don't think it can get any simpler than this.
I also fixed the type of the empties parameter. You had List<>, which in Kotlin is an immutable list. I changed that to MutableList<>.
I also fixed the reversed call to be reverse. I bet your IDE has warned you about the "unused result of reversed". This in turn means that you didn't test your code thoroughly before posting it here, since otherwise you would have noticed that it doesn't work for isIncrease == false.
Next time please post complete, compilable code. The missing parts for this question are:
class AudioRecordEmpty

class AudioRecordDateComparator : Comparator<AudioRecordEmpty> {
    override fun compare(o1: AudioRecordEmpty?, o2: AudioRecordEmpty?) = 0
}

class AudioRecordNameComparator : Comparator<AudioRecordEmpty> {
    override fun compare(o1: AudioRecordEmpty?, o2: AudioRecordEmpty?) = 0
}

class AudioRecordSizeComparator : Comparator<AudioRecordEmpty> {
    override fun compare(o1: AudioRecordEmpty?, o2: AudioRecordEmpty?) = 0
}

class AudioRecordTimeComparator : Comparator<AudioRecordEmpty> {
    override fun compare(o1: AudioRecordEmpty?, o2: AudioRecordEmpty?) = 0
}


Node JS delete multiple MySQL linked records and delete physical file

I am not primarily a JS developer, therefore I won't assist you with the JavaScript part itself, but I can give you a few hints regarding several issues I've found.
Lack of transactional safety
In your example, you're executing two DELETE statements on the database.
1) delete t1, t2 from postschema t1 join commentschema t2 on t1.id = t2.postid where t1.id = ?

2) delete from postschema where id = ?

Those statements are isolated in their own transactions and commit right after their execution. The problem here is, if the statement 1) succeeds, but 2) fails, all the records deleted with the statement 1) will remain deleted, which can easily lead to unexpected database state.
In order to prevent this, you want to wrap the statements which should either all succeed or all fail in a database transaction.
DELETE statement ambiguity and difficult readability
Although MySQL supports deleting records through JOIN, effectively allowing you to delete data from multiple tables in a single go, such statements are difficult to track what gets actually deleted. On top of that, certain database engines do not support such mechanism at all.
I highly recommend you to change the statement, so that it deletes only the comments, which makes the query much easier to follow and to read.
DELETE FROM commentschema WHERE postid = ?

Removing a file from the FS before removing a database record
This may introduce an unintentional side effect, if deletion of database records fails, leading to a situation where the database record points to a file location which no longer exists.
In order to solve this, the order of operation should be swapped:

delete data from the database,
(now that nothing points to the file) delete the file from the file system.

I have also noticed you're loading images for comments (plural!) by postId, but only removing the image of the first comment in the returned collection.
This may be an accidental error in your implementation, since later you're deleting all comments, which makes me believe you want to delete all images, too.
Code nesting
Your code is quite nested, due to callbacks. In order to resolve this, you can:

introduce smaller functions with different responsibilities (e.g. a function to load data from the database, a function to delete a file,...),
convert functions which output result through callbacks to promises and cleanup the code a little bit through promise-chaining (even better if you use async/await).


From a once over:

drop functions, it is too long and it's obvious that alert in ChatProvider.utils.alert() is a function. Furthermore, specifically for alert, that should be under UI in my mind
Your functions are all over the place, I would think that adding a friend would be ChatProvider.friends.add() but you put it in ChatProvider.Utils.functions.addFriend()
You treat your object as 1 singleton, what if you need more than 1 instance ?
Maybe you are from a Java background, but namespacing the way you approach it should be avoided


My original assertion (Outdated):

  Sorting a string (Or any array) is inefficient because even the
  fastest algorithm will sort no faster than O(n log n) in an average
  case. The most efficient way would use a hash map to count letters in
  each word. Something like:

Although reading from a hash map can be as quick as O(1), writing to a hash map is significantly slower. By using a 26-value array (0-25) to represent lowercase letters, the speed of operations can be sped up significantly:

function isAnagram(word1, word2) {
  if (typeof word1 !== 'string' || typeof word2 !== 'string') {
    throw new Error('isAnagram requires two strings to be passed.')
  }

  var normalizedWord1 = word1.replace(/[^A-Za-z]+/g, '').toLowerCase();
  var normalizedWord2 = word2.replace(/[^A-Za-z]+/g, '').toLowerCase();

  var counts = [];
  var word1Length = normalizedWord1.length;
  var word2Length = normalizedWord2.length

  if (word1Length !== word2Length) { return false; }

  for (var i = 0; i < word1Length; i++) {
    var index = normalizedWord1.charCodeAt(i)-97;
    counts[index] = (counts[index] || 0) + 1;
  }

  for (var i = 0; i < word2Length; i++) {
    var index = normalizedWord2.charCodeAt(i)-97;
    if (!counts[index]) { return false; }
    else { counts[index]--; }
  }

  return true;
}

EDIT: A speed comparison between using a hash and using a 26-value array:
http://jsperf.com/anagram-algorithms


Creating a list of pairs after splitting the string containing all of the sets

You could create your own custom section in your config file.

First define what each record looks like:

public class Department : ConfigurationSection
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get { return (string)this["name"]; }
        set { this["name"] = value; }
    }

    [ConfigurationProperty("assignee", IsRequired = true)]
    public string Assignee
    {
        get { return (string)this["assignee"]; }
        set { this["assignee"] = value; }
    }
}

Define the a collection so the framework can work with your section

public class DepartmentCollection : ConfigurationElementCollection
{
    public override ConfigurationElementCollectionType CollectionType
    {
        get { return ConfigurationElementCollectionType.BasicMap; }
    }

    protected override string ElementName
    {
        get { return "Department"; }
    }

    protected override ConfigurationPropertyCollection Properties
    {
        get { return new ConfigurationPropertyCollection(); }
    }

    public Department this[int index]
    {
        get { return (Department) BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            base.BaseAdd(index, value);
        }
    }

    public Department this[string name]
    {
        get { return (Department) BaseGet(name); }
    }

    public void Add(Department item)
    {
        base.BaseAdd(item);
    }

    public void Remove(Department item)
    {
        BaseRemove(item);
    }

    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new Department();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return (element as Department).Name;
    }
}

Define what the list looks like

public class DepartmentList : ConfigurationSection
{
    private static readonly ConfigurationPropertyCollection DepartmentListProperties;
    private static readonly ConfigurationProperty DepartmentProperty;

    static DepartmentList()
    {
        DepartmentProperty = new ConfigurationProperty(
            "",
            typeof (DepartmentCollection),
            null,
            ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsDefaultCollection
            );

        DepartmentListProperties = new ConfigurationPropertyCollection
                                       {
                                           DepartmentProperty
                                       };
    }

    public DepartmentCollection Departments
    {
        get { return (DepartmentCollection) base[DepartmentProperty]; }
        set { base[DepartmentProperty] = value; }
    }

    protected override ConfigurationPropertyCollection Properties
    {
        get { return DepartmentListProperties; }
    }
}

Now, in your .config file specify the new type:

<configSections>
    <section name="DepartmentAssigneeMapping" type="DatabaseCleanup.DepartmentList, DatabaseCleanup, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>

and add your section

<DepartmentAssigneeMapping>
    <Department name="Depart1" assignee="PersonAssignTo1" />
    <Department name="Depart2" assignee="PersonAssignTo2" />
</DepartmentAssigneeMapping>

Now, in your class:

public List<string> departmentList;
public List<string> assignedtoList;

var mappings = (DepartmentList) ConfigurationManager.GetSection("DepartmentAssigneeMapping");

departmentList = (
    from Department department in mappings.Departments
    select department.Name).ToList();
assignedtoList = (
    from Department department in mappings.Departments
    select department.Assignee).ToList();

Your class is much nicer, and the config is way cleaner.

This is fully tested, and the results you are looking for are replicated.


I think, as per your solution, in every case you'll get a list of objects not the list of actual class you need. If you want to use this array you have to cast the object to your desired class. To do that you have to check if you can cast the object to your desired class as the down casting can cause error if you don't use instanceOf.
In short you have to do all this by your self every time you want to use this method for any kind of list. On the other hand the generic code will always return you the array of your class not object.  I think the generic code has 2 advantage over your code which are:

No casting needed
Can be used any where with any kind of list.


Serializing tabular data in ruby -- is map, flatten, hash the correct approach?

Feedback:

Instead of ||= lambda { ... }.call, you can use ||= begin ... end
Instead of Hash[*arr] you can use arr.to_h in Ruby 2.0+
You don't need to convert everything to a hash if you just want to use it for .map later -- [[1, 2], [3, 4]].map { |k, v| k + v } #=> [3, 7]
Instead of .map { ... }.flatten(1), you can use .flat_map { ... }
If you won't be using a variable in a block, you can use _ instead, like .map { |key, _| key }

I rewrote the code to be like what I'd code it today.

require 'yaml'

def do_it(raw)
  map = raw["v_eng"].split.zip(raw["v_jap"].split)

  raw.select do |k, _|
    k.size == 1
  end.flat_map do |pre, japs|
    map.zip(japs.split).map do |(post, _), jap|
      [pre + post, jap] unless jap == '_'
    end.compact
  end.to_h
end

want = {"katakana"=>{"Ka"=>"カ", "Ki"=>"キ", "Ku"=>"ク", "Ke"=>"ケ", "Ko"=>"コ", "Sa"=>"サ", "Si"=>"シ", "Su"=>"ス", "Se"=>"セ", "So"=>"ソ", "Ta"=>"タ", "Ti"=>"チ", "Tu"=>"ツ", "Te"=>"テ", "To"=>"ト", "Na"=>"ナ", "Ni"=>"ニ", "Nu"=>"ヌ", "Ne"=>"ネ", "No"=>"ノ", "Ha"=>"ハ", "Hi"=>"ヒ", "Hu"=>"フ", "He"=>"ヘ", "Ho"=>"ホ", "Ma"=>"マ", "Mi"=>"ミ", "Mu"=>"ム", "Me"=>"メ", "Mo"=>"モ", "Ya"=>"ヤ", "Yu"=>"ユ", "Yo"=>"ヨ", "Ra"=>"ラ", "Ri"=>"リ", "Ru"=>"ル", "Re"=>"レ", "Ro"=>"ロ", "Wa"=>"ワ", "Wi"=>"ヰ", "We"=>"ヱ", "Wo"=>"ヲ"}, "hiragana"=>{"ka"=>"か", "ki"=>"き", "ku"=>"く", "ke"=>"け", "ko"=>"こ", "sa"=>"さ", "si"=>"し", "su"=>"す", "se"=>"せ", "so"=>"そ", "ta"=>"た", "ti"=>"ち", "tu"=>"つ", "te"=>"て", "to"=>"と", "na"=>"な", "ni"=>"に", "nu"=>"ぬ", "ne"=>"ね", "no"=>"の", "ha"=>"は", "hi"=>"ひ", "hu"=>"ふ", "he"=>"へ", "ho"=>"ほ", "ma"=>"ま", "mi"=>"み", "mu"=>"む", "me"=>"め", "mo"=>"も", "ya"=>"や", "yu"=>"ゆ", "yo"=>"よ", "ra"=>"ら", "ri"=>"り", "ru"=>"る", "re"=>"れ", "ro"=>"ろ", "wa"=>"わ", "wi"=>"ゐ", "we"=>"ゑ", "wo"=>"を"}}

raw = YAML.load_file 'japanese.dic'

p do_it(raw["katakana"]) == want["katakana"] #=> true
p do_it(raw["hiragana"]) == want["hiragana"] #=> true

Hope that helps. Let me know if you want any other clarification(s) in a comment below.


A couple of points that may help you.

When you see yourself copy and pasting or writing duplicated code, consider refactoring.  I could only see one difference in your code in the case statements.  You could move all that to a method and pass in the necessary struct.  Even further, once you have done this you will see further code duplication you could probably further refactor into seperate methods.
I'm not sure about having exposed fields on the struct start with _.  You might want to read Jon Skeets Answer on stack overflow.
I would probably consider removing your struct and using a single class.  Then I would create 4 instances of that class with the values required.  I might even consider populating the text for those from a resource file.
I'm not really sure on this, but in old versions (Vb 6....) you could create controls which were arrays of each other.  So instead of panelSubBtn1, panelSubBtn2 etc you would just have panelSubBtn and reference it by panelSubBtn[0] etc  If this was possible you could seriously simplify your code.  I'll let you figure that out though...

These are a few quick things which may or may not help.


Given sum and product, find the two variables

Before we start guessing, lets solve the equations properly. We can substitute the equations so that we get product = x · (sum - x) = -x² + sum·x ⇔ 0 = x² - sum·x + product, with y = sum - x.

The equation can be solved by x = sum/2 ± √(sum²/4 - product) (see Reduced Quadratic Equation). Note that we get zero, one or two  distinct solutions. For example the special case of product = 0 leads to x = sum/2 ± sum/2 ⇒ {x = 0, x = sum}. It is up to you if you pick a specific solution or output both. We have no solutions in ℝ when the expression inside the square root is negative. However, there would still be complex solutions.

Restricting yourself to integers only isn't valid, and will miss some solutions. Consider product = 1, sum = 4. This is solved by x=3.73205, y=0.267949.

Note that as this equation can be solved arithmetically, there is no need for guessing via loops.

Because you resort to guessing, your code contains various bugs, e.g. it will fail to handle parameters with no solution like sum = 4, product = 5. Instead, you will go into an unterminated loop.

When unit-testing your code, you should be using a proper test harness instead of  some test cases in a main. You might like JUnit. If you want to thoroughly test a method, do not only test a few simple cases:

Explicitly test failure cases, e.g. parameters with no solution.
Test especially large inputs to see if you correctly guarded against overflows (you didn't).
Test random input (and record the seed!). It is easy to verify the correctness of the solution. This fuzzy testing may hit cases you didn't consider.
Cover inputs around zero especially well, e.g. vary each parameter from -2 to 2 by 0.5-increments (after verifying manually that each parameter combination actually has a solution). Although this wouldn't hit another bug in your code, the combination 0, 0 is suspiciously absent. The combination 1, 0 would have exposed the bug that you don't handle inputs without solutions.


The HashSet<int> won't be changed hence make it readonly.
Instead of calling Contains() prior to the call to Add(), if this evaluates to false, can be simplified to just return _set.Add(val); because the Add() method returns false if the value is allready in the HashSet. Reference
Instead of calling Contains() prior to calling Remove() can be simplified as well to just return _set.Remove(val); because Remove() will return false if the item isn't in the HashSet. Reference
Calling GetRandom() in repeatedly short order  may result in the same element because the Seed of a created Random in .NET framework is based on the current timestamp. It is better to create a class-level Random to be used.

Summing up leads to
public class RandomizedSet {

    private readonly HashSet<int> _set;
    /** Initialize your data structure here. */
    public RandomizedSet()
    {
        _set = new HashSet<int>();
    }

    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public bool Insert(int val)
    {
        return _set.Add(val);
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public bool Remove(int val)
    {
        return _set.Remove(val);
    }

    private readonly Random rand = new Random();
    /** Get a random element from the set. */
    public int GetRandom()
    {
        int key = rand.Next(_set.Count);
        return _set.ElementAt(key);
    }
}


Display data based on read configuration file from ssh sessions

usr = raw_input("Enter username for " + server.address + ": ")
    pwd = getpass.unix_getpass("Enter passphrase for " + server.address + ": ")
    con = paramiko.SSHClient()

I'd avoid using abbreviations. Call them username and password and connection. You don't gain anything using abbreviations and it reduces readability.

    for session in sessions:

for server in sessions:

Are they servers or sessions?

I'd also move the contents of the loop into methods on your session objects.


One thing that comes to mind is probability.

In all winning cases of tic-tac-toe, the middle spot of the involved row/column/diagonal is always occupied.  Therefore, I would look to spread my chances and test from the most frequently occupied space(s) in the middle and keep trying to test one adjacent space outward at a time in an evenly spread fashion.

The benefit of this really comes into focus when you think about the fact that the whole check is really done in one pass in a spiral kind of manner.  Having the check in one pass means that as soon as you run into a space that eliminates the possibility of a win being present, you stop checking it.  Therefore, the spiral will go faster and faster until a win is found or until the whole check is completed.  Pretty cool to think about.

I may code this...but for now that's just an idea of one interesting approach you can take :)


Select second field in text table with shell script

Your idea to transform the table so that the implied keys explicitly appear on every row is an interesting one, but I think that it is overcomplicated.

The backslashes to indicate continuation lines are actually superfluous here, since an unfinished $( substitution automatically causes the command to be incomplete.  Similarly, ending a line with a | pipe would also cause the command to be continued, so that would be a better convention to follow than putting the | at the beginning of the following line.

In general, any combination of sed, awk, and grep would be better expressed using just an AWK script.  The AWK script below reads a key and value if there is a colon on a line, or just a value if there is no colon.

SECRET_NAME=$(
    oc describe sa sa-build-webhook-realworld |
    awk -F: '
        $2  { KEY=$1 ; VALUE=$2; sub("^ *", "", VALUE); }
        !$2 {          VALUE=$1; sub("^ *", "", VALUE); }
        KEY=="Mountable secrets" && VALUE !~ /docker/ { print VALUE }
    '
)


WCF wrapper implementing dispose-finalize pattern

Given that much of the code seems to rely on Service being an IClientChannel, and the name of the class implies as such, it may be worth simply adding IClientChannel to your type constraints and remove all the type conversion code.

Building upon that thought, I notice that IClientChannel extends IChannel, and everything you use seems to be present on IChannel.  You may consider using that interface instead, and renaming your class to reflect that it is not limited to IClientChannel.


Converting vector of bytes to base64 string and back

Here are a few suggestions:

1. Don't write this

Many before you have needed, and gotten, a fast Base64 decoder. Why should you write this yourself? You don't seem to have a special twist on the decoding/encoding - unless you want "base85 decoding", a term I'm not quite sure I understand.

Specifically, here is a nice treatment of the subject (although still far from the optimum):

Fast Base64 encode and decode

(and see also the suggestion in the comments there - by now only available on archive.org)

2. Don't work on 8-bit values

The fact that base64 encoding has a 1-byte (or 1-ASCII-character) resolution the way it's defined does not mean that's how you need to decode it. Your machine is (probably) a 64-bit machine. So work on in 64-bits units unless you have reason to use another size (which you very well might - but probably not 8 bits). Work out the math for the larger sizes.

Now you might say "but what if the length of my output isn't divisible by 8?" - well, just handle the slack at the end, outside your main tight loop.

Similarly, you shouldn't use 4 distinct 8-bit variables for your input - use something bigger.

3. Don't mix decoding and allocation + don't force the use of std::vector

You should not be using an std::vector. Take a pointer to a nicely-aligned output buffer, or better yet - a gsl::span. (You could also take a templated iterator but I wouldn't bother) with sufficient memory pre-allocated, and write there.

If you insist on doing the allocation yourself for some reason, have a wrapper function do it. Right now you're allocating \$log(n)\$ times for decoding \$\frac{n}{6}\$ bits! C-R-A-Z-Y!.

At any rate, there's no reason to force the client code for your decoder to take an std::vector.

4. Are both lookup tables really helping you?

Using a look-up table means doing less computational work. But is the trade-off worth it? Not always. Now, if you be making your lookup table larger (which you may very well do, see the linked blog post and remember we want to work with more than 8 bits at a time) you might hit cache limits. And even if you aren't - maybe in-register arithmetic is good enough?

Now, I might be worrying you for nothing here, and maybe lookup tables are the best thing to do - but at least profile to make sure. In fact,

5. Profile profile profile

If @DJuracu wrote already - profile to find out what needs optimization. You can speed up something a zillion times, but if it's only 5% of the execution time you haven't saved much (Amdahl's law). Of course, after you've improved something else, those 5% may now become 50%, making it worthwhile to work on that part of the code after all. Still, you need to know what worked and what didn't.

6. You have to look at the compiled code

When you're writing code that's this low-level, you can't allow yourself the slack of ignoring the assembly. Learn to read it and do so. I know that's a tall order but you're the one who said you want to write something that's "fast"...

7. Multi-thread

If this is part of an application which already has multiple threads running, then forget this point. Otherwise - why use only one core, and with one thread on it? Assuming you're on a typical modern PC, you have 2 or 4 cores, and with 'HyperThreading', they can execute instructions from 4 or 8 threads overall. While you could theoretically be bottlenecked on memory bandwidth or some other resource at full 4 or 8 thread capacity, you might not. Especially if you're not well-enough SIMDized

8. Use SIMD for parallelism

Your processor supports vectorized instructions. Your decoding (and your decoding) does not have "dependency chains" between the values of consecutive characters, except at most when composing a larger word from fewer bits. So - you should be able to SIMDize all or almost all of this work. I'm a GPU guy more than a CPU guy, so I can't tell you which instructions you'll want to be using, but that would definitely be necessary for maximum speed. Probably best to work on this before going multi-threaded.


Since it's a template function, it doesn't need to be marked inline.

It would be nice to handle custom deleters too. We can access the deleter with ptr_.get_deleter().


Find the longest sequence of increasing numbers in an array

The thing I dislike the most is the check I make for the last element in order to avoid ArrayIndexOutOfBounds exception.

So let's avoid that check. Let's structure our loop such that we're back-comparing. That is, instead of comparing index i to index i+1, we compare index i to index i-1. That way, if we start at 1, we'll always have a valid comparison - since otherwise our loop invariant would've triggered:

for (int i = 1; i < vals.length; ++i) {
    if (vals[i] > vals[i-1]) {
        // continuing this sequence
    }
    else {
        // start a new sequence, of length 1, from i
    }
}

No further checks against vals.length are necessary, once we handle the empty case. The rest of the algorithm involves just keeping track of a current running sequence and the best sequence so far, which you could do with a local ArrayList<Integer> but better to just do with a couple ints.


PEP 8

PEP 8 complains about this line:

for i in range(1,rights+1):

You should have a single space after the comma and before rights+1:

for i in range(1, rights+1):

Straight to business

Taking on the advice of Raziman T. V.: you are allowed to move \$u\$ steps up and \$r\$ steps right. Now denote a move upward by u and the move to the right by r. The total number of moves is \$u + r\$. Next, every valid path is a string of length \$u + r\$ containing \$u\$ characters u and \$r\$ characters r; clearly, any such string denotes a valid path.

Now, you can permute a string of length \$u + r\$ in \$(u + r)!\$ ways. However, since all us (respectively, rs) are equal, you divide \$(u + r)!\$ by \$u!r!\$ since there is \$u!\$ ways to permute the subsequence of \$u\$ characters u and each of them are equal; same for characters r.

The above leads to

$$\frac{(u + r)!}{u!r!},$$

and, finally, to the code

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

def count_paths(r, u):
    return factorial(r + u) / factorial(r) / factorial(u)

Edit

You can optimize the above a little bit:

def count_paths_v2(r, u):
    min_ru, max_ru = min(r, u), max(r, u)
    value = 1
    for i in range(max_ru + 1, r + u + 1):
        value *= i
    return value / factorial(min_ru)

count_paths performs \$(u + r) + u + r\$ steps, and count_paths_v2 only \$\min(u, r) + (r + u) - \max(r, u).\$

Cleaning a bit

What comes to your version, you can write it a little bit more succintly:

def move_right_up_count(rights, ups):
    grid = [[1 for _ in range(rights + 1)] for _ in range(ups + 1)]
    for y in range(1, ups + 1):
        for x in range(1, rights + 1):
            grid[y][x] = grid[y - 1][x] + grid[y][x - 1]
    return grid[-1][-1]

Hope that helps.


I'd replace the ArrayList with a hashtable for faster lookup and less code. Replace:

$csv = Import-Csv $csvFileName
$subWeb = get-spweb -identity "$sharePointWebUrl"
$mylistitems = $subWeb.Lists["MyList"].Items | sort Title

$csvCollection = New-Object System.Collections.ArrayList
$csv | ForEach-Object {
        $temp = "" | select "Topics", "Column1"
        $temp.Topics = $_.Topic
        $temp.Column1 = $_.NewTopic
        $csvCollection.Add($temp) | Out-Null
}

try
{
        foreach ($li in $mylistitems) {
                $loopcount=0
                :loop foreach ($si in $csvCollection)
                {
                    $loopcount =$loopcount + 1
                    if ($li["Topics"] -eq $si.Topics)
                    {
                        $li["Topics"] = $si.Column1
                        $isFound =$true
                        $li.Update()
                        break loop
                    }
                }
        }
}

With:

#Create hashtable for topics to update
$TopicUpdates = @{}
Import-Csv $csvFileName | ForEach-Object {
    #Assuming you only have one line per Topic (old value) as hashtable keys needs to be unique
    $TopicUpdates[$_.Topic] = $_.NewTopic
}

$subWeb = get-spweb -identity "$sharePointWebUrl"
$mylistitems = $subWeb.Lists["MyList"].Items | Sort-Object Title

try
{
    foreach ($li in $mylistitems) {

        if($TopicUpdates.ContainsKey($li["Topics"]) {
            #Found Topic in hashtable - Updating
            $li["Topics"] = $TopicUpdates[($li["Topics"])]
            #Not sure what this variable is for
            $isFound = $true
            $li.Update()
        }
    }
}

You should also cleanup your try/catch-design. There's no need for the inner try/catch as it does exactly the same as the parent try/catch.


Count occurrence of words in a .txt file

Let's take a look at word_count, which appears to be the central function:

def word_count(_file, max_to_min=False):
    txt = open(_file, "rU")
    word_dict = {}
    for line in txt:
        if line.replace(" ", "") != ("\n" or None):
            process_line(filter(None, split("[^a-zA-Z']+", line.lower())), word_dict)

    txt.close()
    final_list = process_dict(word_dict)
    format_print(final_list, max_to_min, len(word_dict))

_file is not a suitable name as according to PEP 8. It is more Pythonic to use with open(_file, "rU") as f too (known as context managers). With that, I rename _file to filename. These two points are mentioned in vnp's answer; however, I disagree with vnp's suggestion to catch the exception, as there is no need for a graceful exit. The program should crash if the file cannot be opened.

def word_count(filename, max_to_min=False):
    with open(filename, "rU") as f:
        word_dict = {}
        for line in f:
            if line.replace(" ", "") != ("\n" or None):
                process_line(filter(None, split("[^a-zA-Z']+", line.lower())), word_dict)

    final_list = process_dict(word_dict)
    format_print(final_list, max_to_min, len(word_dict))

Your function calls the process_line function:

def process_line(words, word_dict):
    for word in words:
        if word in word_dict:
            word_dict[word] += 1
        else:
            word_dict[word] = 1

There's a builtin Python class for this called Counter. It has a dictionary interface too. With that, the process_line function is no longer necessary and we can rewrite this as:

from collections import Counter
.
.
.
def word_count(filename, max_to_min=False):
    with open(filename, "rU") as f:
        counter = Counter()
        for line in f:
            if line.replace(" ", "") != ("\n" or None):
                counter.update(filter(None, split("[^a-zA-Z']+", line.lower())))

    final_list = process_dict(counter)
    format_print(final_list, max_to_min, len(counter))

Secondly, you appear to be removing all spaces from the line so as to find out if the line is just a series of whitespace and contains no actual words. This can be easily done using the strip function.

from collections import Counter
.
.
.
def word_count(filename, max_to_min=False):
    with open(filename, "rU") as f:
        counter = Counter()
        for line in f:
            line = line.strip().lower()
            if not line:
                continue
            counter.update(filter(None, split("[^a-zA-Z']+", line)))

    final_list = process_dict(counter)
    format_print(final_list, max_to_min, len(counter))

filter can be rewritten as a generator, which feels more natural to me. That also uses less parenthesis, making the code more readable.

from collections import Counter
.
.
.
def word_count(filename, max_to_min=False):
    with open(filename, "rU") as f:
        counter = Counter()
        for line in f:
            line = line.strip().lower()
            if not line:
                continue
            counter.update(x for x in split("[^a-zA-Z']+", line) if x)

    final_list = process_dict(counter)
    format_print(final_list, max_to_min, len(counter))

Now, let's take a look at process_dict.

def process_dict(word_dict):
    temp_list = []
    for key, value in word_dict.items():
        temp_list.append((value, key))

    temp_list.sort()
    return temp_list

The first few lines can be done with a lambda. The new function looks like this:

def process_dict(counter):
    temp_list = map(lambda (a, b): (b, a), counter.items())
    temp_list.sort()
    return temp_list

But was there really a need for a function on its own? In fact, I'd argue that since your function is named word_count, the function should only count words. Hence, we should just return the counter object and let the printing be handled. Also, we usually name functions as verbs, so I'll change the name to count_words.

The above change affects our whole program structure. Hence, I'll show the final code before explaining the changes I made.

from collections import Counter
from re import split

BANNER = "-" * 35

def format_print(counter, is_reverse=False):
    lst = counter.items()
    lst.sort(key=lambda (a, b): (b, a), reverse=is_reverse)
    print ("[Unique Words: %d]" % len(lst)).center(35, "=")
    print "%-16s | %16s" % ("Word", "Count")
    print BANNER
    for word, count in lst:
        print "%-16s | %16d" % (word, count)

def count_words(filename):
    counter = Counter()
    with open(filename, "rU") as f:
        for line in f:
            line = line.strip().lower()
            if not line:
                continue
            counter.update(x for x in split("[^a-zA-Z']+", line) if x)
    return counter

format_print(count_words("Gettysburg.txt"), is_reverse=False)

I've removed max_to_min=False since we no longer sort the items in count_words.

In format_print, I renamed reverse to is_reverse, assigned it to False by default and removed num_words.

Afterwards, I rewrote the function that sorts the list such that it would sort by the count, then the word, without affecting the structure of the list. This makes the later loop more intuitive.

I've also seperated print statements that had strings seperated by commas, since they were confusing. I declared BANNER as a global variable (which is alright in Python, as long as it is used as a constant). In the process, I made a few minor changes to the output; I hope you don't mind!

It took a long time, but the end result is worth it. I hope that I've managed to show you the process of clearing up your code. :)

EDIT: The code here is not yet tested; I am currently checking all of the code I posted here.

EDIT 2: Updated the fixed version.


Discussing performance of methods which are almost entirely in the main method, is sort of pointless. Java performance requires hot-spot compiling, and that does not really happen until methods are run many, many times. The main method is run just once, so is seldom compiled efficiently. Perhaps it's only ever interpreted.

In terms of efficiency, the algorithm you are using is documented as being the best for this puzzle. Essentially there is no better way.

Your subsequent question about how to incorporate additional multiples is complicated....

the way the algorithm works right now, is to calculate the sum of multiple sequences. One sequence is:

3, 6, 9, 12, 15, ...

The second sequence is:

5, 10, 15, 20, .....

The algorithm works by taking the sum of the two sequences, and subtracting the 'double-count', those values that are double-counted because they intersect (like 15, above).

If you have multiple sequences, say, 3, 5, and 7, you will need to sum up all the individual sequences, then subtract the double, and triple counts.

You will need to subtract the intersection with 3*5 (15), as well as 3*7 (21), and also the triple-add 3*5*7 (105)

As you add numbers in to the multiples, you will need to find more of the combinations of parameters that intersect, and need to be subtracted.


Importing and deleting product data in WordPress

Looking at your importProducts() method, firstly ask if this needs to be public, private or protected see PHP visibility

Now the importProducts() method in question, I would separate and have three methods as follows:

/**
 * @param $brand string
 * @param $productsToDelete array
 */
protected function _deletePreparedProducts($brand = null, $productsToDelete = array()) {
    if(empty($brand)) {
        /* Do we need a brand? If not throw an Exception or log to your debug logger */
    }
    /* deletion logic here */
}

/**
 * @param $brand string
 * @param $productsToCreate array
 */
protected function _createPreparedProducts($brand = null, $productsToCreate = array()) { /* create logic here */ }

/**
 * @param $brand string
 * @param $productsToUpdate array
 */
protected function _updatePreparedProducts($brand = null, $productsToUpdate = array()) { /* prepare logic here */ }

I would therefore change the importProducts() method as follows (assuming that you still want this as a private method):

<?php
private function importProducts($brand)
{
    $products = $this->dsApi->getProductsByBrand($brand);

    $preparedProducts = $this->prepareProducts($products, $brand);

    if(!empty($preparedProducts['delete'])) {
        $this->_deletePreparedProducts($brand, $preparedProducts['delete']);
    }

    if(!empty($preparedProducts['create'])) {
        $this->_createPreparedProducts($brand, $preparedProducts['create']);
    }

    if(!empty($preparedProducts['update'])) {
        $this->_updatePreparedProducts($brand, $preparedProducts['update']);
    }
}

Using this approach, if you need to change the logic to update a product, you will only have to worry about your update method, rather than having lots of logic in one method. And in your main method you will be checking if there are any products to delete, update or create first rather than assuming that there is, as is the case in your original script.

If there are no products to import then why was this method called? This is where you could throw an exception, or log to a debug file, like this:

    if(empty($preparedProducts['delete'])
        && empty($preparedProducts['create'])
        && empty($preparedProducts['update'])) {
        throw new \Exception("Import products called without any products to import");
    }

I might also consider preparing the data first before calling the importProducts() method, rather than preparing that data within the method - this will depend on your dataflow.

I would finally suggest that as you are updating and deleting products, the method name may be incorrect. manageProducts() or something similar might be a better name for this method.


Should I re-throw exceptions within a method, or is there a better way to handle it?

Deciding which exceptions to handle, rethrow, wrap in other exceptions is a design decision. Some exceptions might be caught to branch to a different flow. Naively catching all exceptions is a bad call. Guidelines for handling and throwing exceptions

Some exceptions should be propagated all the way up, because of the integrity of the application or even your machine cannot be preserved. Be careful when encountering OutOfMemoryException, BadImageFormatException, StackOverflowException.

Would you really want to wrap/hide the aforementioned exceptions in a custom exception?

catch (Exception ex)
{
    // Capture any generic exception and retrhow it as a 'WhException'.
    throw new WhException("An error occurred whilst ..", ex.Message, ex);
}

Keep in mind that detail is lost when you catch and throw ex;. A new stacktrace is created.

catch (WhException ex)
{
    // Capture and rethrow a 'WhException', ensurig that the detail is not lost.
    throw ex;
}

Use throw; to preserve stacktrace.

catch (WhException ex)
{
    throw; // preserves stacktrace
}

If you want to rethrow outside the catch block you could use ExceptionDispatchInfo. Suppose Exception error is declared before the try:

catch (WhException ex)
{
    error = ExceptionDispatchInfo.Capture(ex);
}

error?.Throw(); // preserves stacktrace

Consider throwing these well-known exceptions for common situations:

ArgumentNullException : when a mandatory argument is not provided
ArgumentException: when an argument does not meet the preconditions to run
AggregateException: when packing multiple exceptions together


I've implemented a few social apps before.  What you've done is pretty standard practice when it comes to oauth authentication and is secure.

The one thing you could change:

 where(id: fb_user.id).first_or_create do |user|
   user.name = fb_user.name
 end

When you use first_or_create when it creates it'll set the where query as attributes.  So in your case the id will already be set as fb_user.id.


Replacing consecutive equal elements in a list with a new element

You can remove the elements directly while iterating to avoid the back-iterating which would remove most of the method body. The add-call can be combined with one of the remove-calls to allow using set instead.

To reduce the amount of data to copy in case that your list is an ArrayList, the iterator should iterate the list backwards (assuming that you don't want to have a separated version for random-access lists):

private static void replaceConsecutiveEqualElements(
        final List<String> list) {
    ////
    for (final ListIterator<String> it = list.listIterator(list.size()); it.hasPrevious();) {
        final String sentinel = it.previous();
        int c = 0;
        for (; it.hasPrevious(); c++, it.remove()) {
            if (!it.previous().equals(sentinel)) {
                it.next();
                break;
            }
        }
        if (c != 0) {
            it.next();
            it.set(String.join("", Collections.nCopies(c + 1, sentinel)));
            it.previous();
        }
    }
}


Split a character string based on change of character

Algorithm

At least at first glance, your algorithm appears to be unnecessarily complex. I'm not entirely sure what firstCommaPast is intended to accomplish. It seems to be trying to give some sort of special treatment to commas, even though the directions explicitly state that commas should be treated exactly like any other character.

Whitespace

I prefer to see a blank line between the #includes and other code. I also prefer to see a space between the include and the < or " that follows it:

#include <string>
#include <iostream>

auto spliter(const std::string &input) {

These don't make any difference to functionality, but fit pretty well with widely accepted practice. I won't try to comment on whether the opening curly brace ({) belongs on the same line as the function header, or on the next line by itself. That's widely debated, and I don't think there's any real consensus on which is preferred.

Initialization

Given that it's going to be an empty string either way, I'd rather use std::string res; rather than std::string res="";. The latter will typically add a little extra work without accomplishing anything useful.

Iterators vs. indexing

The primary reason for using iterators is to support generic algorithms. Using them for a loop outside of a generic algorithm is somewhat questionable. In this case, I see no real improvement over just using an integer type and indexing into the string.

Logic Error

Right now, your code assumes that the first character of a string can't be a '\0'. While that's probably at least somewhat unusual, unlike with C strings, it is actually allowed/supported in a std::string (and if it's present, your code won't really work as intended).

Personally, I think it's easier to initialize prev to the first character of the input string, then have the loop proceed from input[1] through the end of the string. This way we don't have to initialize prev to a value that can't be in the string (which is good, because there is no such character).

Function Naming

A function does something. As such, its name should normally be a verb, not a noun. Although it may be open to argument whether the best name for what it does is splitting, let's just go with that general idea--in which case its name should be split, not splitter.

Resulting Code

Incorporating the elements above, the code could end up something like this:

#include <string>
#include <iostream>

auto split(const std::string &input) {
    auto prev = input[0];
    std::string res{ prev };

    for (size_t i = 1; i < input.length(); i++) {
        if (input[i] != prev)
            res += ", ";
        prev = input[i];
        res += prev;
    }
    return res;
}

int main() {
    auto input = R"(gHHH5  ))YY++,,,///\)";
    std::cout << split(input);
}


I know nothing of OpenGL and what a correct implementation of a VertexArrayObject should look like, but I do have a couple of observations:

I like that the ID private field is readonly, ...but its naming breaks the naming convention for private fields, which should be either id or _id - looking at the other private fields _id would be more consistent.
I don't see why the other fields vertexCount and vertexBufferID (should be vertexBufferId) aren't prefixed with an underscore as well.
Vertical whitespace between methods/members isn't consistent either. Skip a line between } and the next member, it'll breathe better.

public VertexArray()
    : base()

The : base() part is redundant. Base constructor always gets called.

In the Release() override, you're doing this:

    int id = ID;
    GL.DeleteBuffers(1, ref vertexBufferID);
    GL.DeleteVertexArrays(1, ref id);

Whatever DeleteVertexArrays is doing with id (passed by reference), you're not doing anything with the [possibly] modified value, I'm guessing because ID is readonly. But this is clearly a case where the "why" would be nicely explained with a short comment.

Lastly, properties like DrawMode that use a non-readonly backing field...

DrawMode _drawMode;
public DrawMode DrawMode
{
    get { return _drawMode; }
    set { _drawMode = value; }
}

...would probably be better off rewritten as auto-properties:

public DrawMode DrawMode { get; set; }
public BufferUsageHint BufferUsag { get; set; }
public int VertexCount { get; private set; }


Capping values in a map while keeping one fixed

Your verify-alloc function is badly named: it doesn't verify, it normalises.

A normalisation function that preserves the proportions of the other values and limits the sum to MaxAlloc is

(defn normalise [m k]
  (let [remains (dissoc m k)
        allowance (- MaxAlloc (m k))
        weight (->> remains
                    vals
                    (apply +))
        factor (/ allowance weight)]
    (if (<= weight allowance)
      m
      (merge m (zipmap (keys remains) (map #(* factor %) (vals remains)))))))

This is written to be concise, not to be fast.

If there'd nothing to be done, everything is hunky-dory:

(normalise {:a 0 :b 30 :c 40} :c)
;{:a 0, :b 30, :c 40}

But if the values need scaling, we can run into problems with arithmetic:

(normalise {:a 90 :b 40 :c 70} :b)
;{:a 135/4, :b 40, :c 105/4}

If you want these as integers, you may have to forego some precision. How you do this is up to you.


Swap the names/properties in a JavaScript object

So the idea is to change the key of a given pair. Few issues:

Your code doesn't guard against existing keys. If my newKey is an already existing key, it would overwrite the existing value, and delete the old key.
Like mentioned, mutation. Unless you're fully aware of the things that reference the object or have mechanisms in place to capture suddenly missing properties, you shouldn't mutate in-place. In the case above, if you accidentally delete an existing key another piece of code expects to exist, this will cause unexpected breakage.
Your condition will return true for prototype members. Always do a hasOwnProperty check to ensure that you're only checking the instance, not the prototype.


Generating a word bigram co-occurrence matrix

A 106 × 106 matrix would contain 1012 entries.  Optimistically assuming one byte per entry, that would already be 1 TB.  I would expect that most of the matrix entries will be 0. Consider looking into sparse matrices.


Ulam numbers (calculates your life expectancy if you want to)

This is a senseless use of objects.  What exactly is an UlamNumber object?  Consider how you might use this class:

 UlamNumber ulam = new UlamNumber(0);
 ulam.setNumber(20);
 ulam.ulamAlgorithm();    // ← prints something about your age
 ulam.getNumber();        // ← returns 1, not 20

That code tells you nothing about the task that it performs (if you ignore the comments).  In particular, ulamAlgorithm() does several things (count steps, compose a remark, and print it) — none of which is obvious from the name of the function.

What you want to write is

System.out.println(AgeCommenter.commentAbout(UlamSequence.countSteps(20)));

To make that happen:

public class UlamSequence {
    public static int countSteps(long number) {
        int steps;
        for (steps = 0; number > 1; steps++) {
            number = (number % 2 == 0) ? number / 2
                                       : 3 * number + 1;
        }
        return steps;
    }
}

Note the use of the for-loop for counting.

And the AgeCommenter:

public class AgeCommenter {
    public static String commentAbout(int age) {
        String fmt =
            (age ==  1) ? "Unfortunately you will only become: %d year old >:=)"
          : (age < 100) ? "Unfortunately you will only become: %d years old =("
          :               "Congratulations, you will become %d years old =)";
        return String.format(fmt, age);
    }
}


State management is a pretty complex topic currently in the cljs-sphere. Not because it is so hard to do, but because people are still trying to figure out what the simplest approach to it might be. And this causes some very interesting solutions.

However, as you are new I will start with the simplest and most accepted one.
Use an atom.

;initialize state
(def xy-atom (atom {:x 0 :y 0}))

(defn inc-x! [i]
  (swap! xy-atom update-in [:x] + i))
(defn inc-y! [i]
  (swap! xy-atom update-in [:y] + i))

; or use a method to update any of the keys
(defn inc-any! [key i]
  (swap! xy-atom update-in [key] + i))

Your addEventListener function is ok, just change:

 (print (.-x js/window) (.-y js/window))

to

(print (:x @xy-atom) (:y @xy-atom)) ;or
(print @xy-atom)

If you're curious about more sophisticated approaches to handling state in cljs look here:

https://github.com/tonsky/datascript which mimics a database in the frontend
https://github.com/Day8/re-frame Which resembles a data flow approach and provides strict patterns for updates and event listeners to state.

Both of them are very interesting, just from the concept point of view. However, to get started, take it slow and play around with the atom thing.


Your code falls into a classic trap, which IMO is a design error by Microsoft. 99% of the time, await Foo(); should be await Foo().ConfigureAwait(false);. The semi-official guidance is

  To summarize this third guideline, you should use ConfigureAwait when possible. Context-free code has better performance for GUI applications and is a useful technique for avoiding deadlocks when working with a partially async codebase. The exceptions to this guideline are methods that require the context.

I think that it would have been far better for ConfigureAwait(false) to be the default and to require ConfigureAwait(true) in those cases which require context, but it's too late now for Microsoft to change this, so we should all get into the habit of using ConfigureAwait(false) by default and in those rare cases documenting the reason for leaving it off (or even explicitly using ConfigureAwait(true) and supplementing it with a comment which gives the reason).


I don't know how much runtime you'll save, but you're iterating 175 more times  than you need to here.

int[] map = Enumerable.Repeat(-1, 175).ToArray();
bool[] marked = Enumerable.Repeat(false, 175).ToArray();

You can replace this with an old fashioned for loop and set them both at once.

const int maxChars = 175;

int[] map = new int[maxChars];
bool[] marked = new bool[maxChars];

for (var i = 0; i < maxChars; i++)
{
    map[i] = -1;
    marked[i] = false;
}

It's more verbose, but might save you a millisecond or 2.


Make it regex with named groups:

var matcher = new Regex(@"(?<assesment>.+?),\s*(?<zone>.+)");
var match = matcher.Match("assessment1, Firewall");
var assesment = match.Groups["assesment"].Value;
var zone = match.Groups["zone"].Value;

where

(?<assesment>.+?) - catches assesment ungreedy ? so that it stops at ,
,\s* - the separator is , with an optional white space (zero or more times)
(?<zone>.+) - catches zone greedy

Sample at regex101.com

I wasn't aware of that but @Vogel612 kindly mentioned that backtracking as I use it in my solution above might be sometimes a problem: Why Using the Greedy .* in Regular Expressions Is Almost Never What You Actually Want and The Explosive Quantifier Trap.

Using the (?<assessment>[^,]+) expression would be much faster and safer here.

  That change drops the match you propose from 30 steps until matching to 9, so it saves roughly 60% of execution time.

Another valuable remark by @forsvarir suggests using the statick Regex.IsMatch method over creating a new instance each time. This should be much faster here.

  The difference in performance is due to the caching of regular expressions used in static method calls.

There is a lot more to that with pleny of examples on Optimizing Regular Expression Performance, Part I: Working with the Regex Class and Regex Objects [Ron Petrusha]

Why do I prefer the regex solution?

I can test it with regex101
I can use the same pattern for validation and data extraction. I know whether the data is in the correct format without checking each element of the array values[i] separately.
I can easier restrict the characters or casing or splitting rules
I can use named groups which I find easier to understand because I can see what I work with rather then just having a string[] especially that each filed has a meaning - otherwise I'd use the Regex.Split method if was just an array of some values
I can trim the data at the same time (requires some additional \s*)
I can use the same pattern for Regex.Replace if I wanted to change it


Euler-Mascheroni Single Thread Speed Improvements

Firstly, this code has a couple of dozen PEP8 formatting violations. Following conventions generally helps readability.

Also on the subject of readability, comments providing references for the formulae used should be considered essential in mathematical software.

def agm(a, b):      #Arithmetic Geometric Mean

The conventional way of documenting a function is with a docstring. That also allows you to document the expected input types (decimal.Decimal? float?).

def pi_agm():       #Pi via AGM and lemniscate
    print('Computing Pi...')
    a, b, t, p, pi, k = 1, D(2).sqrt()/2, 1/D(2), 2, 0, 0
    while 1:
        an    = (a+b)/2
        b     = (a*b).sqrt()
        t    -= p*(a-an)**2
        a, p  = an, 2**(k+2)
        piold = pi
        pi    = ((a+b)**2)/(2*t)
        k    += 1
        if pi == piold:
            break
    return pi

The while loop is unnecessarily ugly: while True would be preferable. I would say that it would be even better to use the loop index as a loop index with for k in itertools.count(), but actually that variable is wholly unnecessary.

If find it unhelpful to initialise six variables in one line where some of them are quite complicated. On the other hand, it could be more helpful to combine some of the updates in the loop body. Perhaps the happy medium is something like

    a, b, t = 1, D(0.5).sqrt(), 1
    p, pi = 1, 0
    while True:
        a, b, t = (a+b)/2, (a*b).sqrt(), t - p*(a-b)**2
        p, piold, pi = 2*p, pi, (a+b)**2 / t

I'm not entirely convinced by

        if pi == piold:
            break

Sometimes iterative approaches in finite data types oscillate around the solution rather than converging definitively. It might be more robust to track the last two or three values and, on finding a loop, return the average of the values in the loop.

def factorial(x ,pfact, pfactprd):
    x = int(x)

Do you expect to pass a non-int? See previous note about using docstrings to document types.

    if pfact == (x-1):
        return pfactprd*x
    else:
        factorial = D(1)
        for i in range(1, x+1):
            factorial *= i
        return factorial

Is the else ever actually used? Might it be more maintainable to remove this function entirely?

    def lntwosum(n, d, b):
        logsum, logold, e = D(0), D(0), 0
        while 1:
            logold = logsum
            logsum += D(1/((D(b**e))*((2*e)+1)))
            e += 1
            if logsum == logold:
                return (D(n)/D(d))*logsum

Here the previous comment about itertools.count is relevant.

I'm confused as to why D is invoked where it is. Without any comments to justify it, it appears to be done at random.

def lnagm(x):   #Natural log of via AGM,
    try:
        if int(x) == 1:
            return 0
        if int(x) == 2:
            return lntwo()
    except:
        pass

??? Are you expecting int(x) to throw an exception?

    pi = D(pi_agm())

See previous comments about appearing to use D at random. Here, if pi_agm() returns a decimal.Decimal then it's unnecessary, and if it doesn't then surely that would be a bug because pi won't have the necessary precision? I don't see any further polishing of its error.

    decimal.getcontext().prec = m
    ...
    logr = D(str(result)[:m//2])
    decimal.getcontext().prec = prec
    return logr

Would the following work?

    decimal.getcontext().prec = m
    ...
    decimal.getcontext().prec = prec
    return D(result)

    k = D(prec//2)
    ...
    upper = int((12*k)+2)

Why not just upper = 6*prec + 2 with no need to coerce?

Other earlier comments also apply to gamma.

#Calling Gamma
prec = int(input('Precision for Gamma: '))*8
decimal.getcontext().prec = prec
gam = gamma()
print('\n')
print(gam)

It's a Python best practice, which serves to make the file reusable as a library, to guard this with if __name__ == "__main__":.

A comment explaining the *8 would be useful. At a guess, prec is in bits?


An attempt at a Haskell Servant API - repetition of Left/Right case matching

Here's how to use ExceptT to brighten the day a little. You may have hoped for a way to do handle only once after combining the Handlers with :<|>... but I also don't know how to do that. If withExceptT went to arbitrary MonadError instances, handle could have been more concise.

import Control.Monad.Trans.Except

siteServer :: Server SiteAPI
siteServer = site :<|> addPage where
  handle :: ExceptT String IO a -> Handler a
  handle = liftIO . runExceptT >=> \case
    Left err -> throwError $ err404 { errBody = "Site not found!" <> BS.pack err }
    Right x -> return x

  site :: Int -> Handler Site
  site i = handle $ ExceptT $ loadSite i

  addPage :: Int -> Page -> Handler ()
  addPage i p = handle $ do
    Site name pages <- ExceptT $ loadSite i
    withExceptT (\e -> "Failed to write to file: " ++ show i ++ ". " ++ show (e :: IOException))
      $ ExceptT $ try $ BS.writeFile (getSiteFilename i) $ encode $ Site name $ p:pages


It's better to use nested grids that are easy to read, than complex spanning.  I try to avoid spanning in most scenarios, unless it's just 1 simple span.  But when in doubt, nest the grids, because that way future layout changes won't break everything where as spanning is directly tied to the number of columns you have.

A great example of this is headers and footers, you wouldn't want them to not fill the width of an app,


Is there a better way to count seconds in python

I'm not sure this code does what you think it does, at least on a *nix OS. According to the documentation, time.clock() returns processor time, which basically means that any time spent in time.sleep() is not counted. However, on Windows, time.clock() returns the actual time since it was first called.

A better way to determine the time since the function was first called is to use time.time(), which returns the number of seconds since the epoch. We can still use time.clock() to determine the process time if we are using a *nix OS. (If you are using Windows, you may want to upgrade to Python 3.3 which introduces the platform independent function time.process_time(). (There may be another way to do it if you are using 2.x, but I don't know what it is.)

#!/usr/bin/python
import time

def stopwatch(seconds):
    start = time.time()
    # time.time() returns the number of seconds since the unix epoch.
    # To find the time since the start of the function, we get the start
    # value, then subtract the start from all following values.
    time.clock()
    # When you first call time.clock(), it just starts measuring
    # process time. There is no point assigning it to a variable, or
    # subtracting the first value of time.clock() from anything.
    # Read the documentation for more details.
    elapsed = 0
    while elapsed < seconds:
        elapsed = time.time() - start
        print "loop cycle time: %f, seconds count: %02d" % (time.clock() , elapsed)
        time.sleep(1)
        # You were sleeping in your original code, so I've stuck this in here...
        # You'll notice that the process time is almost nothing.
        # This is because we are spending most of the time sleeping,
        # which doesn't count as process time.
        # For funsies, try removing "time.sleep()", and see what happens.
        # It should still run for the correct number of seconds,
        # but it will run a lot more times, and the process time will
        # ultimately be a lot more.
        # On my machine, it ran the loop 2605326 times in 20 seconds.
        # Obviously it won't run it more than 20 times if you use time.sleep(1)

stopwatch(20)

If you find the comments more confusing than helpful, here's a non-commented version...

#!/usr/bin/python
import time

def stopwatch(seconds):
    start = time.time()
    time.clock()
    elapsed = 0
    while elapsed < seconds:
        elapsed = time.time() - start
        print "loop cycle time: %f, seconds count: %02d" % (time.clock() , elapsed)
        time.sleep(1)

stopwatch(20)


Updating list of Dictionaries from other such list

A list of 1-pair dictionaries makes no sense as data structure. You should join them to create a single dictionary. This way all your code reduces to:

d1 = {'a': 2, 'b': 2}
d2 = {'a': 4, 'c': 4, 'e': 5}
d3 = dict(d1, **d2)
# {'a': 4, 'b': 2, 'c': 4, 'e': 5}

If you are going to union/merge dicts a lot, you can create a handy abstraction, more general than dict(d1, **d2):

def merge_dicts(d1, d2):
    return dict(itertools.chain(d1.items(), d2.items()))

To convert list of dictionaries to a dictionary is simple:

d2 = dict(list(d.items())[0] for d in new_list)
# {'a': 4, 'c': 4, 'e': 5}


Removing nested for loops to hasten API call response time

I think you will see a performance improvement by using GroupBy.

Let's start by calculating the earliest year we're interested in:

startingYear = startingYear ?? DateTime.Now.Year;
var minYear = startingYear - numberOfYears + 1;

Then filter the rows

var deals = db.VDealParticipations
    .Where(deal => deal.IsPrimaryParticipant &&
                   deal.EffectiveDate.Value.Year >= minYear &&
                   deal.EffectiveDate.Value.Year <= startingYear);
if (brokerID.HasValue)
{
    deals = deals.Where(deal => deal.BrokerID == brokerID);
}

Finally we group the rows by their year/month.

var dealsPerMonth = deals
    .GroupBy(deal => new { deal.EffectiveDate.Value.Year, deal.EffectiveDate.Value.Month })
    .Select(g => new { g.Key.Year, g.Key.Month, Deals = g.Count() });
return new JavaScriptSerializer().Serialize(dealsPerMonth.ToArray());

Note that this does not return months with a deal count of 0.


IsAppliedCouponValid()

Don't omit braces although they might be optional. Omitting braces can lead to hidden and therfor hard to find bugs.
The intermediate variables startDate and endDate won't buy you much. Instead I would just use the coupon.StartDate and coupon.EndDate. Don't get me wrong, using intermediate variables can be a good thing but not for such simple stuff.
A construct like

if (!bool)
{
    return false;
}
return true;

can be rewritten as return bool;
You "validate"  the passed Coupon coupon but you don't validate string userID. The method parameters Order order, int? categoryID aren't used and should be removed.
Sometimes you use if (bool == false) and sometimes you use if (!bool) where I prefer the first because it is easier to see that we check if the value is false. Whatever style you choose, you should stick to it.
The check for the coupon regarding null and coupon.Status could be added in a condition using ||.
Comments like //check date range or //check coupon applied limitations are superflous and unneeded comments because they tell the reader of the code what is done by the code. Telling what the code is doing should be done by the code itself by having meaningful names. The why something is done in the way it is done is where we need and want comments.

Applying these points will lead to

public async Task<bool> IsAppliedCouponValid(Coupon coupon, string userID)
{
    if (userID==null) { throw new ArgumentNullException(nameof(userID)); }

    if (coupon == null || coupon.Status == false)
    {
        return false;
    }

    var now = DateTime.UtcNow;

    if (coupon.StartDate.CompareTo(now) > 0)
    {
        return false;
    }

    if (coupon.EndDate.CompareTo(now) < 0)
    {
        return false;
    }

    return await CheckCouponLimitations(coupon, userID);
}


Not the board, store the moves

A TicTacToe board can be mapped to two 9bit numbers that represent each player's moves then the test for winning moves is just a simple bitwise test against the 8 possible combinations of move that are a win.

  My question is if there's a better way of achieving the same results without having to use two for loops to get the columns and second diagonals.

The following may be what you want

// top left is low bit, bottom right is high bit
// coord to bit pos is x + y * 3
// Bit positions on board
// 0,1,2
// 3,4,5
// 6,7,8

const board = [['x','o','x'], ['o','o','o'], ['o','o','x']];
const players = ["x","o"];
const winMoves = [448,56,7,292,146,73,273,84];

const getMoves = (board, player) => {
  var moves = 0;
  for(var i = 0; i < 9; i ++){
     moves += board[i / 3 | 0][i % 3] === player ? 1 << i : 0;
  }
  return moves;
}
const checkWin = (board, player) =>{
  const moves = getMoves(board, player);
  return winMoves.some(win => (win & moves) === win);
}
if(!players.some(player => {
    if(checkWin(board, player)) {
        console.log("Player " + player + " wins");
        return true;
    }
}){
  console.log("No winner");
}

Complete game state in 18bits

If you look into the problem further you can reverse the board/moves relationship so that the board is created from two sets of moves. This means you can store the complete game state with only 2 9bit numbers and you would not have to examine the board to find the win

const move = (player, x, y) => player |= 1 << (x + y * 3);
const checkWin = moves => winMoves.some(win => (win & moves) === win);
const winMoves = [448,56,7,292,146,73,273,84];
var movesX = 0, movesO = 0; // moves for each player game start

// or from your example the moves would be
// x o x
// o o o
// o o x
movesX = 0b100000101;
movesO = 0b011111010;

// with
console.log(checkWin(movesX)); // >> false
console.log(checkWin(movesO)); // >> True


You have lots of redundant code, and you don't use objects at all (even methods).

You should separate drawing logic from navigation logic.

Try to write something like this:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    //  logic for selecting specific option
    public class Menu
    {
        public Menu (IEnumerable<string> items)
        {
            Items = items.ToArray ();
        }

        public IReadOnlyList<string> Items { get; }

        public int SelectedIndex { get; private set; } = -1; // nothing selected

        public string SelectedOption => SelectedIndex != -1 ? Items[SelectedIndex] : null;

        public void MoveUp () => SelectedIndex = Math.Max (SelectedIndex - 1, 0);

        public void MoveDown () => SelectedIndex = Math.Min (SelectedIndex + 1, Items.Count - 1);
    }

    // logic for drawing menu list
    public class ConsoleMenuPainter
    {
        readonly Menu menu;

        public ConsoleMenuPainter (Menu menu)
        {
            this.menu = menu;
        }

        public void Paint (int x, int y)
        {
            for (int i = 0; i < menu.Items.Count; i++)
            {
                Console.SetCursorPosition (x, y + i);

                var color = menu.SelectedIndex == i ? ConsoleColor.Yellow : ConsoleColor.Gray;

                Console.ForegroundColor = color;
                Console.WriteLine (menu.Items[i]);
            }
        }
    }

    internal class Program
    {
        public static void Main (string[] args)
        {
            var menu = new Menu (new string[] { "John", "Bill", "Janusz", "Grażyna", "1500", ":)" });
            var menuPainter = new ConsoleMenuPainter (menu);

            bool done = false;

            do
            {
                menuPainter.Paint (8, 5);

                var keyInfo = Console.ReadKey ();

                switch (keyInfo.Key)
                {
                    case ConsoleKey.UpArrow   : menu.MoveUp ();   break;
                    case ConsoleKey.DownArrow : menu.MoveDown (); break;
                    case ConsoleKey.Enter     : done = true;      break;
                }
            }
            while (!done);

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine ("Selected option: " + (menu.SelectedOption ?? "(nothing)"));
            Console.ReadKey ();
        }
    }
}


Your code should have a function IsGrayscale(bmp as Bitmap) as Boolean. It should look like this:

Function IsGrayscale(bmp as Bitmap) as Boolean
    For x As Integer = 0 To bmp.Width - 1 Do
        For y As Integer = 0 To bmp.Height - 1 Do
          If Not IsGrayscalePixel(bmp.GetPixel(x, y)) Then
              Return False
          End If
        End For
    End For
    Return True
End Function

Function IsGrayscalePixel(col as Color) as Boolean
    Return col.R = col.G and col.G = col.B
End Function

At least this is what I think your program should do, based on your description. You don't need the concept of a "color key" to check whether an image is grayscale or not.

The main point is that the function returns as soon as it has found a colored pixel, since then there is no point in checking the rest of the image.

Note that I don't know Visual Basic well, so there might be syntax errors in the above code. So focus more on the ideas than one the grammar.


well, first of all your first query is extremely ineffective

contender.subscriber.videos.collect { |v| w_hash["comments"] << v.comments.where("created_at > DATE_SUB( NOW(), INTERVAL 1 DAY)") }

this will query you db for each video you've got

second, you really shouldn't duplicate you SQL queries, i propose that you add scope to your Comment model (you are using Rails 3, right?)

scope :recent, where("created_at > ?", 1.day.ago)

to make your queries more effective you should use .joins method of ActiveRecord

after all this you code would be something like that

comments = Comment.joins(:videos).where(:videos => { :subscriber => contender.subscriber }).recent
comments << contender.profile.comments.recent

w_hash = {}
w_hash["vid_comments"] = comments.collect { |c| !c.media_id.nil? }
w_hash["wall_comments"] = comments.collect { |c| c.parent_id == 0 }


Your example implementation is not good enough. It's not very complicated at all, as you suggest with the title; rather, it is really simple.

The Hello abstract class is not needed. There is no reason why a class (like a WelcomeEmailContentBuilder or something of the sort) should want to extend Hello - something like a WelcomeEmailContentBuilder might already be extending a ContentBuilder or a EmailContentBuilder. You are abusing the is-a relationship.

Consider this rewrite of your code:

interface Greeting {
    void sayHello(String greeting, String name);
}

public class Test implements Greeting {

    public void sayHello(String greeting, String name) {
        System.out.print(greeting + " " + name);
    }

    public static void main(String[] args) {
        Greeting g = new Test();
        g.sayHello("Hello", "World!");
    }

}

This code is just as functional as your original code. But it's both way shorter and doesn't muck about with an abstract class that you don't need. It also makes use of the Greeting interface for a variable - showing off that you can call functions on objects if you only have an interface.

As for making your code actually show off the use of inheritance and polymorphism, that's up to you to figure out.


You are using Conditional, and i would recommend replacing these with Visitor.

See Replace Conditional with Visitor article by Martin Fowler.

The generic visitor pattern in the code snippet belo is useful for all kind of added operation types on the hierrarchy:

using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace Traversal.Tests
{
    class VisitorTests
    {
        [Test]
        public void TestThis()
        {
            var topLevelResponse = new GroupResponse(
                new Response[]
                {
                    new ElementResponse("foo value", "foo"),
                    new GroupResponse(new[]
                        {
                            new ElementResponse("bar value", "bar")
                        })
                });

            var actualElement =
                topLevelResponse.Accept(new TraverseElementsVisitor()).FirstOrDefault(el => el.Reference == "bar");

            Assert.IsNotNull(actualElement);

            Assert.AreEqual("bar value", actualElement.Value);
        }
    }

    public interface IResponseVisitor<T>
    {
        T Visit(ElementResponse elementResponse);
        T Visit(GroupResponse groupResponse);
    }

    public abstract class Response
    {
        public abstract T Accept<T>(IResponseVisitor<T> visitor);
    }

    public class ElementResponse : Response
    {
        public ElementResponse(string value, string reference)
        {
            Reference = reference;
            Value = value;
        }

        public string Value { get; private set; }
        public string Reference { get; private set; }

        public override T Accept<T>(IResponseVisitor<T> visitor)
        {
            return visitor.Visit(this);
        }
    }

    public class GroupResponse : Response
    {
        public GroupResponse(IEnumerable<Response> responses)
        {
            Responses = responses;
        }

        public IEnumerable<Response> Responses { get; private set; }

        public override T Accept<T>(IResponseVisitor<T> visitor)
        {
            return visitor.Visit(this);
        }
    }

    public class TraverseElementsVisitor : IResponseVisitor<IEnumerable<ElementResponse>>
    {
        public IEnumerable<ElementResponse> Visit(ElementResponse elementResponse)
        {
            yield return elementResponse;
        }

        public IEnumerable<ElementResponse> Visit(GroupResponse groupResponse)
        {
            return groupResponse.Responses.SelectMany(r => r.Accept(this));
        }
    }
}

Your class hierarchy is not obvious to me, not sure i completely understand the class hierarchy you are using, so in the code example i provided a simplified one.

I'd say *Type postfix is redundant in this case, because you are using the objects to represent objects of a type, not the types themselves. Compare to usage of class name in System.Type, instances of which actually represent types.

Looks like you are putting same responsibility to multiple classes. Try to cleanly separate what is what, and what is common.


Creates a class that searches for the elements in a list that contain a sequence

naming

Based on reading your comment, I propose this name:

class SearchableCollection(object):

Rely on duck typing, rather than trying to write java code in python:

def __init__(self, words):
    # (delete this line) assert hasattr(lis,"__iter__")
    self.words = {}
    for word in words:
        self._add_word(word)

It appears that add_word is not part of your public API. Mark it so with a leading underscore, or make it a nested def. Do not assert that type is str.

    for index,val in enumerate(word[:-1]):

Please name it letter rather than the very vague val. Or cur_letter, parallel with next_letter.

You are using setdefault() in a sensible way. But you might be happier using defaultdict.

You named it words_list, but apparently you meant words_set.

style

Run $ flake8 WWF_DDC.py and follow its advice, please.


Determining the largest sum of contiguous integers in a list

Unit testing

As it currently stands, testing your class means having to feed it a filesystem-based input (even if it's using something in-memory like Jimfs). You should consider implementing your application logic such that the input is the form of Stream<String>, so that the source of that stream is independent of the processing here.

String splitting as Stream<String>

Array.asList(string.split(",")).stream()

This can be better represented using Pattern.splitAsStream(CharSequence)

// consider making Pattern.compile(",") a static Pattern field too
Pattern.compile(",").splitAsStream(string)


A few points, though I'm not a Clojure expert:

Indentation. You use four-space indentation, but two-space indentation is more common for Lisp in general and also generally preferred for Clojure. (there seems to be a Clojure community style guide)
Instead of take-last, you may want to use drop. Since you're traversing the whole list anyway, you could also just use split-at (though that's basically the same as using both take and drop).


First, yes, this is functional, and yes, this is how to use loop properly.

  . . . using recur on every loop iteration instead of mutating variables.

This is the intent of loop. Instead of mutating a variable, you just pass the "altered data" to the next iteration via recur.

You also aren't abusing side effects by misusing def or atoms, so that's good.

My main concern with this code is how it's really just one giant function. There's no function names indicating what certain code is doing, and no comments noting the significance of any lines. Now, I'm personally a stickler for breaking code down into functions, but it's generally regard as best practice as well. As this answer notes (ignoring the mention of "imperative"):

  Having a large imperative function that conveys many ideas is hard to digest and reuse.

I think the size of this function does make it hard to digest.

Just as an extreme counter example, here's the same algorithm that I wrote a year ago*. It's almost 4x longer as yours, but it's also much clearer what each bit of code is doing (and has ~10 lines dedicated to documentation). Code like

(-> equation
    (tokenize-equation)
    (infix->RPN-tokens op-attr-map)
    (tokens-to-string)) ; Should arguably be called token->string

makes it fairly clear what it's responsible for, even without taking into consideration the function name that it's in.

I'm won't try to break your code down (mostly because I burned my hand pretty bad, and typing this is hard enough), but if you take a look at my example, you may be able to find some inspiration and strike a middle ground for granularity.

Good luck

*  Although my version doesn't evaluate the expression since I'm translating it into a String and in my example, the data isn't available at compile-time.


Optimization of matrix determinant calculation

Sorry, it is not a divide and conquer, it's a combinatorial explosion. The timing complexity

$$T(n) = nT(n-1)$$

evaluates to n! - exponential growth. There is no way to heal the code; you have to choose another algorithm.


Declare variables in the smallest possible scope

It's recommended to declare variables in the smallest scope where they are needed.
That way, the variable will not be visible where it should not be,
and therefore it cannot be modified accidentally by mistake.
It also makes understanding a program easier when you don't need to keep more variables in your head than necessary.

Therefore, since most of the variables are not needed in the global scope,
move those declarations to the functions that need them.

Be careful with variable scope in JavaScript.
Looking at this code,
you may be mislead that the variable i is only visible within the loop:

  for (var i = section.length - 1; i >= 0; i--) {
    section[i].style.position = "fixed";
  }

But that's not the case. The variable is visible after the loop,
and even before the loop (with value undefined).

In this particular example you want to replace the var with the let keyword,
if your version of JavaScript supports it (like any non-ancient implementation).
Using let, the variable will only be visible within the loop.

Avoid redundant variable initializations

In the posted code all variables are initialized at the time of declaration.
But if the variables don't need an initial value, then this is just noise.

Order conditional terms by their values

It can improve readability when the terms in conditionals are in a consistent order. Take for example this piece:

  if (y >= 0 && y < h) {
    // ...
  }
  if (y >= h && y < h * 2) {
    // ...
  }

The first condition means y is between 0 and h,
and the second means y is between h and h * 2.
Although this is easy enough to see,
the current writing style doesn't really help to see it.

Consider this alternative:

  if (0 <= y && y < h) {
    // ...
  }
  if (h <= y && y < h * 2) {
    // ...
  }

Now, the meaning hasn't changed, but it's much easier to see.
And with this writing style,
it's also easier to see that the two conditions will not be true at the same time,
so the second if should in fact be an else if.


Script to execute arbitrary command on each Git project in a directory

Instead of using find and testing whether .git is a directory, you could make a simplification:

for git_dir in */.git ; do
(
    cd "$git_dir/.." &&
    pwd &&
    $@
    echo
)
done

Admittedly, this causes an error when .git exists but is not a directory:

-bash: cd: blah/.git/..: Not a directory

… instead of silently skipping that entry as your script does.  But I would consider the error message to be a feature, not a bug.  =)  Note my use of && after cd to ensure that the command is not executed if the cd fails.  (That could happen if the directory lacks the executable bit.)

If you wanted to support compound commands like echo hey; echo bye, you could use eval $@.  Using eval feels a bit risky, but it's OK if the script is for your own personal use and won't be attacked.


I think the value variable in the dequeue method is potentially destructive. rather than printing "the queue is empty cant dequeue", and returning the default value of the value variable, I think it's better to throw an exception and catch it. For example on why it is destructive:

    if (        q.dequeue() == 5) // this will return 0 if the array is empty.

This is not good. The user will think the value that is being returned is 0 though it's already empty.

You initialized the size variable, but you didn't really do anything to it in your queue operations (E.G. size-1 when you dequeue an item). It doesn't make sense for the size variable to not change if you enqueue/dequeue items from the queue. But I'm not sure why it's there yet you don't have a size() method. If you're not going to implement a size method() (you should), I think the size variable is useless.
I think it would be more flexible if the array is resizable (E.G. size*2 if full, size/4 if too large).
Make it generic so you can add other types.


Is there a better "Go" way to implement LC Add Two Numbers solution

Go does not have tail recursion: Wikipedia: Tail call. Use iteration rather than recursion.
Simplify your sprawling, hard-to-read code.

type ListNode struct {
    Val  int
    Next *ListNode
}

// Add Two Numbers
// https://leetcode.com/problems/add-two-numbers/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    root := &ListNode{} // at end, start = root.Next
    end := root

    c := 0
    for {
        if l1 == nil && l2 == nil && c == 0 {
            break
        }

        v := c
        if l1 != nil {
            v += l1.Val
            l1 = l1.Next
        }
        if l2 != nil {
            v += l2.Val
            l2 = l2.Next
        }
        c = v / 10
        v = v % 10

        end.Next = &ListNode{
            Val:  v,
            Next: nil,
        }
        end = end.Next
    }

    return root.Next // start
}