Analog clock in React.js, rendered using CSS rotation

Yes - whenever the DOM is being queried (e.g. calls to document.querySelector(), etc.), that might likely be a sign that the Virtual DOM is not being utilized properly.

Use the React component state for storing values for degree values

The styles can be added inline such that the degree values of the transform-rotate styles reference values in the state:

<div className="hand hour-hand" style={{transform: `rotate(${this.state.hourDegrees}deg)`}}>

<div className="hand min-hand" style={{transform: `rotate(${this.state.minuteDegrees}deg)`}}>

<div className="hand second-hand" style={{transform: `rotate(${this.state.secondDegrees}deg)`}}>

To set those values in the state, update setDate() to call setState() with those values:

setDate() {
    const now = new Date();
    const second = now.getSeconds();
    const minute = now.getMinutes();
    const hour = now.getHours();
    this.setState({
        secondDegrees:  (second/60) * 360 + 90,
        minutesDegrees: (minute/60) * 360 + 90,
        hourDegrees: (hour/12) * 360 + 90
    });
}

And in order for the closure to reference this of the component properly in the interval callback, it can be bound using Function.bind()- use that when calling setInterval():

constructor(props) {
    super(props);
    this.state = {
        timer: setInterval(this.setDate.bind(this), 1000)
    }
}

The style attributes could also be bound to plain-old Javascript objects- this would be useful in case there were multiple in-line styles to attach. For example:

render() {
    const hourStyle = {
        transform: `rotate(${this.state.hourDegrees}deg)`
    };
    return (

a

Click here for a demonstration in JSFiddle, or expand the snippet below.

var logged = false;
class Clock extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      timer: setInterval(this.setDate.bind(this), 1000),
      secondDegrees: 0,
      minuteDegress: 0,
      hourDegrees: 0
    }
  }
  componentWillUnmount() {
    clearInterval(this.state.timer);
  }
  setDate() {

    const now = new Date();
    const second = now.getSeconds();
    const minute = now.getMinutes();
    const hour = now.getHours();

    const secondDegrees = (second / 60) * 360 + 90;
    const minutesDegrees = (minute / 60) * 360 + 90;
    const hourDegrees = (hour / 12) * 360 + 90;;
    this.setState({
      secondDegrees: (second / 60) * 360 + 90,
      minutesDegrees: (minute / 60) * 360 + 90,
      hourDegrees: (hour / 12) * 360 + 90
    });
  }
  render() {
    const secondStyle = {
      transform: `rotate(${this.state.secondDegrees}deg)`
    };
    const minuteStyle = {
      transform: `rotate(${this.state.minuteDegrees}deg)`
    };
    const hourStyle = {
      transform: `rotate(${this.state.hourDegrees}deg)`
    };
    return ( <
      div className = "col-md-6" >
      <
      div className = "clock" >
      <
      div className = "clock-face" >
      <
      div className = "hand hour-hand"
      style = {
        hourStyle
      } >
 <
      div className = "hand min-hand"
      style = {
        minuteStyle
      } >
 <
      div className = "hand second-hand"
      style = {
        secondStyle
      } >
 <
      /div> <
      /div> <
      /div>
    );
  }
}

ReactDOM.render( <
  Clock / > ,
  document.getElementById('container')
);
/*Matt Litzinger - http://codepen.io/mlitzinger/pen/ruEyz*/

.clock {
  width: 200px;
  height: 200px;
  background: -webkit-radial-gradient(#3b3b3b, #000);
  background: radial-gradient(#3b3b3b, #000);
  box-shadow: inset 0px 0px 30px #777, 0px 2px 18px rgba(0, 0, 0, 0.5), 0px 20px 40px #bbb;
  border: 6px solid #222;
  border-radius: 106px;
  margin: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.hand {
  background: #fff;
  position: absolute;
  -webkit-transform-origin: 50% 100%;
  -moz-transform-origin: 50% 100%;
  -o-transform-origin: 50% 100%;
  -ms-transform-origin: 50% 100%;
  transform-origin: 50% 100%;
}
.hour-hand {
  width: 4px;
  height: 55px;
  box-shadow: 0px 0px 7px #000;
  top: 45px;
  left: 98px;
}

.min-hand {
  width: 4px;
  height: 80px;
  box-shadow: 0px 0px 4px #000;
  top: 20px;
  left: 98px;
}

.second-hand {
  width: 2px;
  height: 80px;
  background: #bbb;
  box-shadow: 0px 0px 7px #000;
  top: 20px;
  left: 99px;
}

.pin {
  width: 10px;
  height: 10px;
  background: #111;
  border-radius: 10px;
  margin: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.hour-hand,
.minute-hand,
.second-hand {
}


Handler for bidirectional unit conversion form

Instead of inlining the script, use addEventListener instead. To retrieve the elements, you'd need something like getElementsByClassName or querySelectorAll to return an array-like structure of elements. You loop through them, and attach a listener each.

var formInputs = Array.prototype.slice.call(document.querySelectorAll('.form-input'));
formInputs.forEach(function(element){
  element.addEventListener('blur', function(){
    // blur code
  });
  element.addEventListener('keyup', function(){
    // blur code
  });
});

The Array.prototype.slice.call is to convert the array-like structure returned by querySelectorAll into a real array. That's so I can use forEach. But a regular for loop will do, since a NodeList (the array-like structure) has a length property.

Now instead of alert and return, why not throw an error instead?

if(isNaN(value)) throw new Error('Non-numeric value');

Also, instead of putting all your conversions in a single function and sending a "sense", why not create a function for each kind of conversion? It's more verbose, but you don't have to pile up everything in one function.


Solution for Parent/Child circular references: WeakReference class

Amazing code as always, Mathieu and Comintern; many thanks.

I'm here only two add two cents:

Probably you tested it in a 32 bits setup; to compile in a 64 bits you need to (only differences):

    #If Win64 Then
    Private Declare PtrSafe Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As LongPtr)
    Private Type TReference
        Address As LongPtr
    End Type
    #Else
    Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)
    Private Type TReference
        Address As Long
    End Type
    #End If
         ...
    #If Win64 Then
    Public Property Get Address() As LongPtr
        Address = this.Address
    End Property
    Public Property Let Address(ByVal value As LongPtr)
        this.Address = value
    End Property
    #Else
    Public Property Get Address() As Long
        Address = this.Address
    End Property
    Public Property Let Address(ByVal value As Long)
        this.Address = value
    End Property
    #End If

And your test works:

Public Sub Test()
    Dim p As TheParent
    Set p = New TheParent
    Debug.Print ObjPtr(p)
    Set p = Nothing
End Sub

And now things seems to be OK. But...

Now, try to do something useful with Parent property of Child class, not only assure GC:

Slightly modified Parent Class; Child class the same:

 Option Explicit
Private Type tTheParent
    Child As TheChild
    CollectionName As String
End Type
Private this As tTheParent

Private Sub Class_Initialize()
    Set this.Child = New TheChild
    Set this.Child.Parent = Me
    Debug.Print this.Child.Parent.CollectionName
End Sub
Public Property Get GetChild() As TheChild
    Set GetChild = this.Child
End Property
Private Sub Class_Terminate()
    Set this.Child = Nothing
End Sub

Public Property Get CollectionName() As String
    CollectionName = IIf(this.CollectionName = vbNullString, "COLLECTION", this.CollectionName)
End Property

New Test:

 Public Sub TestChildParent()
    Dim p As TheParent
    Set p = New TheParent
    Dim c As TheChild
    Set c = p.GetChild
    Debug.Print c.Parent.CollectionName
    Debug.Print ObjPtr(p)

    Set p = Nothing
 End Sub

And what we get? I crashed Excel, Word and the Video driver!

And now the @this's comment shines; now I got illuminated by his (this?) words:

  Please don't hard-code the size... ever. LenB is to VBA what sizeof is
  to C. Use it to size the allocation for the copy memory API. – this

I was directed here because yesterday I posted at SO an error 53 getting kernel, and until I crash windows I didn't understood that the correct Bruce McKinney's code for getting an Object from the object pointer is:

Dim objT As Object
CopyMemory objT, this.Address, LenB(this.Address) 'not 4
Set IWeakReference_Object = objT
CopyMemory objT, 0&, LenB(this.Address) 'not 4

And this answer my question at SO too, because the kernel 53 error gone...

PS: Please, don't be surprised at this enigmatic approach using this as Private Type
someone that I follow teached me ;)

PS2: And this, thanks for that! sorry, couldn't hold myself


Place arithmetic signs in correct order to get the number

There is one technique, of transforming a problem to a more comfortable one.
Here one could do it a couple of times:

First the original problem sum = term[0] ± term[1] ± ....

static boolean additive(int sum, int... terms) {
    if (terms.length == 0) {
        return sum == 0;
    }
    if (terms.length == 1) {
        return sum == terms[0];
    }
    int sum2 = sum - terms[0];
    int[] terms2 = IntStream.of(terms).skip(1).map(Math::abs).sorted().toArray();
    // Also an occasion to use Arrays.copyOfRange(terms, 1, terms.length);
    return additive2(sum2, terms2);
}

You can subtract the first term from the sum, and then have the possibly more regular problem sum == ∑i ±term[i]. All terms positive, and sorted.

/**
 * @param sum to be formed by the sum of every term * ± 1.
 * @param terms, all absolute, and sorted.
 */
static boolean additive2(int sum, int... terms) {
    int termsSum = IntStream.of(terms).sum();
    if (sum > termsSum) {
        return false;
    }
    int tooMuch = termsSum - sum;
    // Split the terms in added and subtracted ones.
    // The sum of the subtracted ones * 2 == tooMuch.
    if (tooMuch % 2 != 0) {
        return false;
    }
    if (tooMuch == 0) { // All positive terms.
        return true;
    }
    // Find subtracted terms:
    int subtractedSum = tooMuch / 2;
    return findSubtracted(subtractedSum, terms.length - 1, terms);
}

Then math properties appear: the difference between the sum of absolute terms and the requested sum must be twice the sum of the negative/subtracted terms.
An odd difference means failure. Nice.

Now one only needs to recursively find the subtracted terms, starting with the largest terms. O(2n) but with some cuts: if the term is too large, in the recursion sum < 0, and done: sum is decreased as fast as possible.

static boolean findSubtracted(int sum, int i, int[] terms) {
    if (sum <= 0) {
        return sum == 0;
    }
    if (i < 0) {
        return false;
    }
    return findSubtracted(sum - terms[i], i - 1, terms)
            || findSubtracted(sum, i - 1, terms);
}

public static void main(String[] args) throws XMLStreamException {
    System.out.println(additive(12, 1, 2, 3, 4, 5, 7)); // true, because 1 + 2 + 3 + 4 - 5 + 7 = 12
    System.out.println(additive(7, 5, 3)); // false, because neither 5 + 3 != 7 or 5 - 3 != 7
}

Take

Problem: 1 + 2 + 3 + 4 - 5 + 7 = 12
1 + 2 + 3 + 4 + 5 + 7 = 22; tooMuch = 10, subtractedSum = 5
-7? - false
-5? - true

This might not be the best solution, but it exposes some math intelligence.
For instance 1 + 2 + 3 + 4 - 5 + 7 = 13 will fail fast.

Dynamic programming, operations research and such are indeed worthwile in real life problems, especially if approximations / near solutions count too. Traffic optimisation and such.

A remark on iterating upto 2n with bit tests: nice and I did it myself on occasion. However here my code accomplishes the same with 2 recursive calls in the function. Which certainly is less effective, but more readable. Do this (micro-)optimisation last, as it hampers mental flexibility on the mathematical properties themselves. I think.


I would rename loop to demo.
The spec says that the value argument to digitalWrite may only be HIGH or LOW, and it doesn't spell out their bit representations. Even though your code works (I presume), it is better to stick with the spec.
LEDP never changes. You don't have to invert each individual bit in the loop. It looks better to invert the whole bitmap at once:

if (LEDP == LOW) {
    bitmap ^= 0xff;
}

Now the body of display7 loop could be streamlined to

for (uint8_t i=0; i<8; ++i) {
    digitalWrite(displayPins[i], (bitmap & 0x01)? HIGH: LOW);
    bitmap >>= 1;
}

Notice that segment and state disappear altogether.


Using case and switch macros for strings

switch is usually assumed to have nearly O(1). I'm suggesting to introduce additional level for parsing. It is known as lexical analysis. You parse you fixed set of cases to enum values and then switch as you want.

enum { B1, C1, D1 } token_t;

token_t lexer(const char *s)
{
    // TODO: consider hash table here
    static struct entry_s {
        const char *key;
        token_t token;
    } token_table[] = {
        { "abcdef", B1 },
        { "ghijkl", C1 },
        { NULL, D1 },
    };
    struct entry_s *p = token_table;
    for(; p->key != NULL && strcmp(p->key, s) != 0; ++p);
    return p->token;
}

int main()
{
    char buf[256];

    printf("\nString - Enter your string: ");
    scanf ("%s", buf);

    switch(lexer(buf)) {
        case B1:
            printf ("B1!\n");
            break;
        case C1:
            printf ("C1!\n");
            break;
        case D1:
            printf ("D1!\n");
            break;
    }
}

Note that your SWITCH(S) will work only in C++ since C doesn't allow variables definition in the middle of blocks. Usually such macro uses something like:

#define BEGIN_SEPARATION(S, T) { const char *_tail = (T), *_sep = (S); \
    size_t _sep_len = strlen(_token); \
    for(const char *_next = strstr(_tail); _tail != NULL; _tail = (_next != NULL) ? _next + _sep_len : NULL) {
#define SEPARATION_TOKEN() (_next == NULL ? strdup(_tail) : strndup(_tail, _next - _tail))
#define END_SEPARATION } }

And as far as I know it's common practice to wrap macro arguments (i.e _S = (S);).


Reading values from a file and assigning to another class

Convention violations

Java conventions generally impose "egyptian bracing style", with the opening brace on the same line as the block start. Yes, also for classes.

Java convention governs that fields should be named camelCase. This means that FileDetails should have the fields url, port, userName and password

It's convention to restrict the visibility of fields as much as possible. All fields in FileDetails should be private.

Constructor responsibilities
So... let me get this straight... You're using a constructor of a separate object to set the properties of an object you pass into the constructor, that is of a supertype and ...
This is wrong in more ways than I imagined one could get constructors wrong ...
Let me break down, what constructors are for:

Constructors construct objects
Constructors construct objects
NOTHING ELSE

What the FileService constructor does is the following:

It takes a FileDetails object.
It loads a FileDetails object from a (hardcoded) json file.
It copies over the loaded object's values to the passed object.

At no point it does initialize the object it's responsible for. Neither does it perform validation or any other useful constructor things.
What this constructor basically is is called "factory method". You're using the constructor of a separate class to initialize the properties of a class you control.
Where did the separate class come from???
Instead of doing it this way, it would make much more sense to have the FileDetails constructor be responsible for the work you do there...
Consider the following:
public class FileDetails {
    private String url;
    private String port;
    private String userName;
    private String password;

    public FileDetails(String url, String port, String userName, String password) {
         this.url = url;
         this.port = port;
         this.userName = userName;
         this.password = password;
    }

    public FileDetails(Path detailsFile) {
         try (InputStream in = Files.newInputStream(detailsFile, StandardOpenOption.READ)) {
             ObjectMapper mapper = new ObjectMapper();
             mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
             FileDetails details = mapper.readValue(in, FileDetails.class);

            this.url = details.url;
            this.port = details.port;
            this.userName = details.userName;
            this.password = details.password;
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }
    // getters and setters omitted
}

Along the side this resolves the following additional problems in the code:

Overlarge scope of objectMapper.
Overuse of getters and setters inside a class.
Missing lifetime control of Resources.
Hardcoded path value for the file with resources in it.

Now here comes the fun part. The second constructor I wrote is really unnecessary. It's a "factory method" (as I mentioned above). What that means is, it can be rewritten like so:
public static FileDetails fromFile(Path detailsFile) {
    try (InputStream in = Files.newInputStream(detailsFile, StandardOpenOption.READ)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(in, FileDetails.class);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}


Converting Kinect Methods from Beta 2, to Version 1

Since I have this same question on Stack Overflow now, the answer can be found here. The updated version is:

private Point getDisplayPosition(DepthImageFrame depthFrame, Joint joint)
{
    float depthX, depthY;
    DepthImagePoint depthPoint = kineticSensor.MapSkeletonPointToDepth(joint.Position, depthImageFormat);

    depthX = depthPoint.X;
    depthY = depthPoint.Y;

    depthX = Math.Max(0, Math.Min(depthX * 320, 320));
    depthY = Math.Max(0, Math.Min(depthY * 240, 240));

    int colorX, colorY;
    ColorImagePoint colorPoint = depthFrame.MapToColorImagePoint(depthPoint.X, depthPoint.Y, sensor.ColorStream.Format);
    colorX = colorPoint.X;
    colorY = colorPoint.Y;

    return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
}


Construct a monochromatic graph flipping nodes of the edges

This is not a review, but a comment too long to be a comment.

Brute force is almost always wrong. In the tasks like this it is always wrong.

Let the graph has a nodes colored A, and b nodes colored B.

First notice that flipping an edge doesn't change the parity of neither a nor b. From this, it follows immediately that the if both a and b are odd, the graph cannot be made monochromatic.

It is a bit harder to prove the opposite, that is if at least one of a and b is even, a connected graph can be made monochromatic. Prove that given two vertices of a given color there is a sequence of A-B flips so that two vertices of a given color become adjacent. Then use induction.

Summing up, the solution is to identify the connected components of the graph, and for each of them count the color's parities.


The above classes are used by entity framework for persistance, don't confuse these with the Models in MVC. While its possible to use them directly in MVC, its considered bad practise to so tightly couple your presentation layer to your persistance layer.

Look at tools like AutoMapper that can help you map from the above classes to your actual View Models. Try and have one view model per page and populate them with properties that make sense to the presentation of the data, not its storage.

ie:

public class User
{
    [Key]
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class UserModel
    {
        public string Name { get; set; }
    }

Mapper.CreateMap<User,UsersModel>()
    .ForMember(dst => dst.Name, m => m.MapFrom(src => src.FirstName + " " + src.LastName))

and

var userModel = Mapper.Map<User, UserModel>(user);

Then use the userModel in your view.


Your program has a bug. is_prime returns true in all possible return situations. You don't notice that because your prime factors already use a nice property of prime factors which we inspect later. Here's a short list of improvements first:

return condition instead of if condition return true; else return false;
return early.
Use appropriate return types.
Modify algorithms.

Now let's focus on the bug first.

is_prime

First, the obvious: both return statements only return true. However, there are some improvements we can apply. First, if two conditions are exclusive and cover the whole range of possible conditions use if/else without a second if:

if (flag == 1)
{
    return true;
}
else // no if here!
{
    return true;
}

Note that this still contains your bug above. This brings us to our next improvement: instead of

if (condition) {
    return true;
} else {
    return false;
}

just return condition:

return (flag == 1);

Note that this completely removes the bug already. But we can go further. flag itself introduces a source for possible bugs. We could accidentally use flag = 3 (which can be mediated by bool flag) or forget to set flag (which can be checked by statical analysis).

But we don't need flag. Either we break the loop (and therefore flag = 0) and we return false, or we won't and return true. This is a perfect opportunity to use early returns:

bool is_prime(int x)
{
    for (int i = 2; i <= x/2; i++)
    {
        if (x % i == 0)
        {
            return false;
        }
    }
    return true;
}

There are two optimizations that are left for exercise. First, we don't need to check every i, but only every second. If x % 2 != 0, then x % i != 0 for all even i. Also, for any pair of factors \$ab=x\$ holds \$a\le b\$ and therefore \$a\le \sqrt{x}\$. Both optimizations are left as an exercise.

find_prime_factors

We now have a look at 3., "use appropriate return types". Your function's result is a vector. Nothing in its interface prevents a user to supply an already filled vector, e.g.:

std::vector<int> example = {1,2,3,4,5};
find_prime_factors(10, example); // whoops!

So instead have find_prime_factors return its result:

std::vector<int> find_prime_factors(int n)
{
    int val = n;
    std::vector<int> result;
    for (int i = 2; i <= n; i++)
    {
        if (is_prime(i))
        {
            while (val % i == 0 && val != 1)
            {
                result.push_back(i);
                val = val/i;
            }
            if (val == 1)
            {
                break;
            }
        }
    }
    return result;
}

Next, we'll focus on the algorithm. As you noticed, find_prime_factors worked, even though is_prime is broken. Why?

When you divide a number by its smallest prime factor, the next number that will divide the new number must be a prime factor. Let's try it by hand:

$$
\begin{align}
420 &= 2\cdot 2 \cdot 105 &\text{ the next factor is } 3 \\
&= 2\cdot 2 \cdot 3 \cdot 35 &\text{ the next factor is } 5 \\
&= 2\cdot 2 \cdot 3 \cdot 5 \cdot 7 &\text{ the next factor is } 7 \\
&= 2\cdot 2 \cdot 3 \cdot 5 \cdot 7 \cdot 1
\end{align}
$$
We don't need the is_prime check at all:

std::vector<int> find_prime_factors(int n)
{
    int val = n;
    std::vector<int> result;
    for (int i = 2; i <= n; i++)
    {
        while (val % i == 0 && val != 1)
        {
            result.push_back(i);
            val = val/i;
        }
        if (val == 1)
        {
            break;
        }
    }
    return result;
}

Also, we can stop as soon as i > val, because at that point val == 1.
 In fact, we can get rid of val altogether and just modify n:

std::vector<int> find_prime_factors(int n)
{
    std::vector<int> result;
    for (int i = 2; i <= n; i++)
    {
        while (n % i == 0)
        {
            result.push_back(i);
            n /= i;
        }
    }
    return result;
}

At some point n == i and n /= i will yield n == 1, so we don't have to worry about an infinite loop. This algorithm is also known as trial division. Note that we can also apply the optimization for even numbers here (left as another exercise).

There are other optimizations that one can apply:

reserve memory beforehand (a number \$N\$ can have at most \$\log_2 N\$ factors, so std::vector::reserve can be used)
use methods that yields both quotient and divisor at the same time (very platform specific).

For a fun exercise, you can rewrite it with iterators in mind:

template <typename OutputIt> OutputIt(int n, OutputIt out) {
    // exercise
}

Note that this is somewhat an overkill, since n will contain at most 64 prime factors if your int uses 64 bits.

Bottom line

Check all your functions. is_prime contained a nasty bug. Other than that your code is nicely structured, doesn't use using namespace and was easy to read.


This is a solution that doesn't use lists, and only goes through the input once.

maxOdd = None

for _ in range(10):
    num = int (raw_input("enter num: "))
    if num & 1:
        if maxOdd is None or maxOdd < num:
            maxOdd = num

if maxOdd:
    print "The max odd number is", maxOdd
else:
    print "There were no odd numbers entered"


I believe you had to put typename before std::vector<...>::iterator to make it compile. iterator is a dependent name, thus compiler needs a hint (well, in reality it doesn't need it in context of type alias declaration, it is just how syntax is defined before C++20).

Interface

Lets address the elephant in the room first. This class trims down the features of std::vector<std::pair<T, U>> without any visible benefit. Things like std::back_inserter will not work because members are named with different name, comparison operators will not work, there are no type aliases inside the class so users will have to write template metaprogramming for simple things, and so on.

I do not see any benefit of using this instead of std::vector<std::pair<T, U>>.

Implementation

There is no need to have void in the parameter list, empty parameter list means the functions doesn't take any parameters.

numElem looks redundant.

Access functions should be const, possibly noexcept.

Some functions are defined inline, some are not, although they are of the same complexity. This might lead to nasty linker issues.

Putting return value in () might get problematic. When using things like decltype, that will actually alter the result.

Designing interfaces

Wrappers are usually made to streamline one way of usage, possibly without losing any expressive power over original. I believe the main idea was to provide a two-way mapping from two continuous ranges. When designing such wrappers, it is important to understand under which constraints the wrappers are going to work. Let me throw some from top of my head:

The input will be in the form {index-like, index-like}
Two ranges are continuous (from 1 to 26, from 'a' to 'z' given ASCII)
It is possible to normalize the values (e.g. substract a value to make the first one 0), for example for letters it will be substract the value of 'a'
No values outside of the given ranges are ever to be queried
The mapping is one-to-one and onto, e.g. for each value on one side, there is corresponding value on the other side, and it is unique.

If the (1) and/or (2) don't hold. one will need to consider std::map and siblings.

The usage scenarios are as following:

User can somehow read/provide the mapping in the form of a range of std::pair<T, U> or as two separate ranges
User wants to query both ways, e.g. mapping[right] would return an object of Left type, and mapping[left] will return an object of Right type: mapping[3] == 'c' && mapping['c'] == 3.
User might want to know if two mapping are equal, e.g. operator== and operator!= should be provided.
Users might want to define some relationships after the object was created, thus insertion functions like define(const Left& left, const Right& right) are needed. Perfect forwarding might be needed.
Users do not modify the relationships (the pair itself) after they are defined
Users might want to remove a relationship

With those, I believe something like this could fit in:

template <typename Left, typename Right>
class mapping
{
    // internals
public:
    template <typename InputIterator>
    mapping(InputIterator first, InputIterator last); //extract mappings from iteator range

    // C++20 range version here
    // ditto for version where mappings provided as two ranges

    // rule of 0/3/5 depending on the implementation

    const Right& operator[](const Left& left) const; // no need for non-const version
    const Left& operator[](const Right& right) const;

    // returns false if either side is already in some relationship
    bool define(const Left& left, const Right& right) noexcept;
    // overload for `std::pair` version

    // throws f either side is already in some relationship
    void try_define(const Left& left, const Right& right);
    // overload for `std::pair` version

    // returns true if the relationship existed and now removed
    bool remove(const Left& left, const Right& right) noexcept(destructor(Left) && destructor(Right)); //pseudocode for noexcept
    // pair version
    // throwing version

    template <typename Left, typename Right>
    friend bool operator==(const mapping<Left, Right>& lhs, const mapping<Left, Right>& rhs);

    template <typename Left, typename Right>
    friend bool operator!=(const mapping<Left, Right>& lhs, const mapping<Left, Right>& rhs);

    template <typename Left, typename Right>
    friend void swap(mapping<Left, Right>& lhs, mapping<Left, Right>& rhs);
};

There are other things one might need, since those are basically sets, operations like

Merge
Difference
Intersection

might be needed for the user.


Extension methods to save and load form size, position, and state

Unnecessary code

The windowState variable isn't used in the SaveFormSizeAndLocation method. And I believe you don't need such variable at all, because form.WindowState.ToString() returns exactly the same string.

Suggestions

The SaveFormSizeAndLocation method.
You check the key for null value, and if it is null nothing happens. Maybe it makes sense to omit that check and to handle (or raise) the exception in order to inform user or to save the reason in the application log.

The LoadFormSizeAndLocation method.
You can reduce nesting by inverting the condition:

using (RegistryKey key = Application.UserAppDataRegistry.OpenSubKey(form.Name))
{
    if (key == null)
    {
        return;
    }

    form.Left = (int)key.GetValue("Left",form.Left);
    form.Top = (int)key.GetValue("Top",form.Top);
    ...
}

Naming

I believe that extension methods for the Form class shouldn't contain the word 'Form' in their names. Consider to shorten names: SaveSizeAndLocation and LoadSizeAndLocation.

Styling

It looks unnatural for me:

Spaces after ( and before ). I'd prefer to insert spaces before the ( in operators:

if (x != y)

and to omit spaces in method declarations and calls:

someMethod(int a, float b, string c);
someMethod(a, b, c);

No spaces between method arguments. I'd prefer to add a space after each comma:

SomeMethod(firstArg, secondArg, thirdArg);

This should improve readability.
Personally, I cannot easily distinguish between

SomeMethod(abc,def,ghi); // 3 arguments

and

SomeMethod(abc.def.ghi); // 1 argument


I need a better way to add css per each page on wordpress

Simpler approach
I haven’t tested this but based on this SO answer using global $post and $post->page_title to set $pagename should allow you to remove the loop.
function website_files_per_page() {
    global $post;
    $pagename = $post->post_title;
    if ($pagename) {
        return; //no page name
    }
    $styleName = "website_".$pagename."_styles";
    $styleDir = get_theme_file_uri("/style/".$pagename.".css");
    wp_enqueue_style($styleName, $styleDir);
}
add_action("wp_print_styles", "website_files_per_page");

That would allow the code to run in \$O(1)\$ time instead of \$O(n)\$.
Let PHP handle the iteration
If the suggestion to use $post doesn’t work, you may be able to change the while loop to a foreach. foreach provides an easy way to iterate over arrays:
foreach ($pagelist as $post) {
    $pagename = $post->post_name;
    if (is_page($pagename)) {
        ...

With this approach there is no need to initialize and update a counter (e.g. `$index) to dereference elements in the array.
If there was a need to access the index/counter variable the second syntax can be used for that:
foreach ($pagelist as $index => $post) {


Threshed and Malachi'd: Sieve of Eratosthenes

This line here is horrible, terrible, and miserable:

if (number % i == 0) { primes.Remove(number); }

That one line is basically (behind the scenes) doing the following:

scan all the data from the beginning until you find the member with the value number
if you find that value:

for every remaining value, shift it one back (replace each n with the value at n + 1).
shrink the size of the List by 1.

The above is an \$O(n)\$ operation.

Using an indexed method to remove the value would be much faster, and a data structure like a Linked list with a \$O(1)\$ remove, would make a huge difference.


Processing eBay category list for database import

I don't have many comments regarding your style, as it seems to follow PEP8 (to my knowledge), so lets review the actual code:

Implementation of Stack – A straight forward implementation without to much fuzz. You don't have any error checking related to popping something of an empty stack, which might give you a problem at some point
Implementation of extract_info – No error handling if faulty input, which could let it return nothing at all if nothing matches on the if field: line
rdr is not a good name – It is not clear what next(rdr) actually does, try finding a better name here
Simplify if structure – You repeat statements within the if structure, and these could be moved outside of the if structure, which would help readability. In addition you pop/push too many times. Try the following:

if level <= last_level:
    id_stack.pop(last_level - level + 1)

parent_id = id_stack.peek()

id_stack.push(cat_id)
last_level = level

Change to newer print – The currently recommended standard for printing seems to be of the form: print('{} {} {} {} {}'.format(level, '..'*level, name, cat_id, parent_id)). In your case it complicates stuff, but in the long run you can pretty print much better using the newer form and variation thereover

Edit: Original code had a little flaw regarding the parent_id. The now corrected code gives the same output when using the provided CSV file as the output from original code.


It looks good to me, except for a couple of things:

private static long saturate(boolean negative) {
    return negative ? Long.MIN_VALUE : Long.MAX_VALUE;
}

Is there a particular reason you did negative instead of positive? It feels like an arbitrary choice to me. If it's not, add a brief comment explaining why. If it is, the convention (well, that I've seen, which means that it might well be the opposite) is to have true mean positive, not negative.

private static long powSpecial(long base, int exp) {

How is it special? Explain in the method name or a Javadoc comment (/** */). Here, it seems like it's for small numbers, so a better method name would be powSmallBases. It may only be used here, but it's rather convenient to be able to read your own code later, if you want to change it later.

Anyway, aside from that (and the things you mention in your coding style page thingamabobber) it looks good! Nicely done.


Applying a currency symbol based on a tested string value

I'd create an NSDictionary holding those prefixes and wrap that whole thing into its own method, like so:

-(NSString *) prefixForCurrency:(NSString *)currency{
    NSDictionary *currencyPrefixes = @{@"EUR": @"€", @"USD" : @"$", @"GBP" : @"£", @"NOK" : @"kr." };
    NSString *returnString = [currencyPrefixes objectForKey:currency];

    return returnString;
}

Then, instead of your current mass of if-statements you'd have something like the following:

NSString *currency = [item objectForKey:@"currency"];
NSString *currencyPrefix = [self prefixForCurrency: currency];

NSString *price = [item objectForKey:@"price"];
NSString *priceString = [NSString stringWithFormat:@"%@ %@", currencyPrefix, price];

In case you were wondering: the main reason I wrap the prefixDictionary in its own method is in case you'd for instance prefer to fetch this list from a file later on. Then you can just alter the innards of that one method...


Comment on Question
Can tell if your code matches the problem statement.
Because I can't understand the problem statement.
Input

"VISITOR_INFO1_LIVE=USv90B-7CzI; LOGIN_INFO=e486e37a395be3f0e3b3237d090a6829c1oAAAB7IjQiOiAiREVMRUdBVEVEIiwgIjciOiAwLCAiMSI6IDEsICIzIjogMjAxMTk0MTMwNiwgIjgiOiA2MDgwMTg0NTEzNjQsICIxMCI6IDIzOTYyMTEyODczNH0=; PREF=f5=30;HSID=AHuJQBOVR0lQoRt_3; APISID=QaParXGsQcEPCzKg/A1smCfYrfMjxvfEPT; YSC=Vm3Amq5loFM";

Output

"VISITOR_INFO1_LIVE=L80EDuHCEF8; PREF=f5=30";

Questions

Is the first and last quote and the last semi colon part of the input or just your formatting?
*SID (HSID,APISID here) upto ';'
I see none of these things in the output. there is no SID no HSID no APISID
Whey is  'VISITOR_INFO1_LIVE' in the output?
It is not specified as something you want in the output.
Why is PREF in the output.
This PREF=f5=30 seems like an illegal parameter. is = allowed in the parameter.

Review of code
OK. I assume there is a function wrapper here that defines str!! What is the type of str? I am going to assume char const* as you seem to be coding using C (rather than real C++). Types are super important in C++ please make sure we know all the types of all identifiers.
Why split up the declaration from the initialization?
 char *Cookie = NULL;
 ......
 Cookie = new char[strlen(str)];
 strncpy(Cookie,str,len);
 ......
 delete[] Cookie;

This just gives you the opportunity to misuse Cookie in the code. If you declare and initialize in the same statement then no misuse.
Also C++ code should never contain a delete (especially when you are learning). It should have very few calls (if any calls) to new. Dynamic memory management should be controled via an object. This is usually a smart pointer or a container depending on your usage.
Thirdly why use the C-String API. C++ has its own string that handles memory management for you and does a better job. Currently your code is not exception safe. An exception thrown in your code will result in leaked memory.
Thirdly you actually did it wrong and did not allocate enough space (you forgot to allocate space for the '\0' character that terminates a C-String). I know you used the strncpy to compensate for this. But all the other string functions are expecting it so something is likely to go wrong.
Forgot to check the result of a string function.
      p2 = strstr(p1,";")+1;

If strstr() returns NULL then we add 1 to it and now it is no longer NULL and your next test will always work. Even if it is not supposed too.
Are you sure the second test id correct?
      while((*ID != ';') && (*ID != Cookie[0]) && (*ID != ' ')){
           --ID;
      }

I think you are testing here *ID != Cookie[0] to make sure that you don't fall off the front of the string. But you are checking the content of the characters not the position of the pointers. A better test is (ID > Cookie)


Your inner loop contains an addition, multiplication, subtraction and two assignments. The multiplication is unnecessary as you can do with two additions and two assignments:

int totalTimeSpent = 0;
int sumOfPair = lego.get(0);
for (int i = 1; i < lego.size(); i++) {
    sumOfPair += lego.get(i);
    totalTimeSpent += sumOfPair;
}

Regarding the data structures: were you forced to use a List? An int array with Arrays.sort(int[]) would have been more efficient.


Copying one array to the end of another array

Be aware that sizeof is actually an operator, not a function.  It also returns std::size_t, which is an unsigned integer type.  You currently have size as an int, which is a signed type.  If you had your compiler warnings up high (and they should be), then you probably would've been warned about this.

std::size_t size = sizeof(fromArray)/sizeof(fromArray[0]);


As far as I can tell, you're returning error only in case of read_dir failure. Not sure if anyone ever really needs it, but you could change upmost Some() to Ok(), remove .ok() and fix the signature so that my version works just like yours. Note: the code below wasn't tested. I didn't like nested structure of your function, so I came up with this:

use std::fs;
use std::path::PathBuf;

fn list_files(pathname: &PathBuf, filter: &str) -> Option<Vec<PathBuf>> {
    Some(fs::read_dir(pathname).ok()?
        .filter_map(|entry| {
            Some(
                entry
                    .ok()?
                    .path()
                    .strip_prefix(pathname)
                    .ok()?
                    .to_path_buf(),
            )
        })
        .filter(|path| path.starts_with(filter))
        .collect())
}

Explanation: .ok() maps Result<T, K> to Option<T>, ? operator returns early in case if Option or Result aren't Some()/Ok()


Merge two sorted arrays that can be of different sizes

I think considering approach that you chose, your code is alright. A few points:

What I don't like is that you get error when passing 2 empty arrays? Why would you do that? Imagine I am generating arrays of different sizes and using your code to merge and sometimes I would pass 2 empty arrays. Should I really need to handle that as special case in my code? No, just return empty array too.
I'd eliminate targetSize variable and check for j < arr2.length && i < arr1.length instead.
Checking valueToPush for undefined feels a bit off for me. It works, but doesn't really feel right. In many languages you would get something like IndexOutOfRange error or something. Maybe it's idiomatic in Javascript (probably not), but I think nicer and cleaner would be to check if you are still in range of array, ex j < arr2.length.


MySQL queries with try-except error handling

If you're just going to re-raise the exception you caught, then there is no point in catching it in the first place. Instead of:

try:
    code block A
except Exception:
    raise
else:
    code block B

you can write:

code block A
code block B

and the behaviour is just the same.


This depends on how the rest of your app feels about the function you're publishing and how modular you want your app to be. If you want absolute modularity, you'll put the functionality in a service and inject & publish it anywhere you want to use it. The same goes for functionality that is reused just in some very specific areas, not really by the whole application.

Sharing functionality using scope hierarchy (especially by putting it on the outer-most scope) is just a way to simplify your code by sacrificing transparency (of dependencies), so in the end, it's up to you to evaluate whether the gain is worth the price in your particular situation.


Deleting the head node of a circular linked list

Since you are dealing with a circularly linked list (meaning the tail's next points to head and the head's prev points to the tail) and assuming each node has a prev and next, you might consider this easier approach which does not require traversal of the entire list.

public ListNode deleteAtHead(ListNode head) {
    if (head == null) {
        return head;
    }

    ListNode newHead = head.next;
    newHead.prev = head.prev;
    head.prev.next = newHead;

    head.next = null;
    head.prev = null;

    return newHead;
}

This should also work for a list with only 1 node (e.g. a head) assuming it is initialized with prev and next referencing itself.


Median vs. Mean

mean in math is commonly referred to as 'average'. Median means 'the number in the middle'.

The mean for (1, 4, 11) would be (1+4+11)/3.0 == 5.3333...
The median for (1, 4, 11) would be [1,4,11][(3/2.0).floor] == 4

Using your code, when I enter 2 2 3 ( take a list of 2 entries. Give me the value for 2 and 3) I get back 2.5. That's a mean, not a median. I guess there really is no median for 2 and 3, but for the sake of conversation let's say we use the logic above, it'd be 2.

I'm going to assume you want a mean instead of a median, because implementations speak more to intent than technical words.

Return Value Causing Timeout?

  The issue I am facing is that the program times out on some inputs,
  and, most likely, the reason is that I return a variable that is
  passed to a routine. I need to do this because this variable changes
  inside the routine and I can't pass by reference in Ruby.

It's not clear to me why you think a timeout is caused when you "return a variable that is passed to a routine." I'm pretty sure that is not the reason.

Passing by Reference doesn't include Immutables

  Is there any workaround for this inability to pass by reference? I
  have seen the code involving "binding" but I found it clumsy. Why does
  Ruby not have a simple, straightforward pass-by-reference as do C++,
  C# and Java?

Ruby uses pass-by-reference. However, if you "throw away" the referenced object, it will appear that Ruby used pass-by-value. Immutable items like numbers, symbols, strings, etc will always act this way because if they are changed, their reference will always be lost. If you increment or reassign a number, you aren't changing an object. You are point to a different object.

For a trivial example, just drop into IRB:

>> x = 8
=> 8
>> x.object_id
=> 17
>> x+=1
=> 9
>> x.object_id
=> 19

Without going to far afield of your question, this is because when you change from 8 to 9, you aren't changing the internal state of some object. You're actually pointing to a new object. And if you replaced a mutable object reference in ruby, you'd lose that reference, too.

 def change_number(num)
   num = num + 1
 end

 def change_object(obj)
   obj = {}
 end

 def add_to_object(obj)
   obj[:bar] = :baz
 end

>> score = 8

>> score.object_id
=> 17

>> out = change_number(score)
=> 9

>> out.object_id
=> 19

>> score.object_id
=> 17  # number 9 is object 19. A new object.

>> mutable = {fu: 'bar'}
=> {:fu=>"bar"}

>> mutable.object_id
=> 6553100

>> out = change_object(mutable) # this is pass-by-reference
=> {}

>> mutable.object_id
=> 6553100 # same object we passed in

>> out.object_id
=> 7488280 # a new object was created, despite pass-by-reference.

>> out = add_to_object(mutable)
=> :baz

>> mutable.object_id
=> 6553100 # same object

>> mutable
=> {:fu=>"bar", :bar=>:baz}  # object was passed by reference!

Mean Value

This is Code Review. If this were posted on Stack Overflow, I would say, "Don't do it that way. Just keep a single sorted list of the values you've seen. Then use the sum and count."

But since this is a code review site, I'll give you some thoughts on your code.

Where are your unit tests?
I highly recommend using full variable names instead of v, k, m, d, etc. We live in a time where computers have more than enough memory to remember an entire word. And there's typically autocomplete. So just type out the full word so when you go back 3 months later you won't have to figure out what each letter meant.
This is an object-oriented language, so using classes would be helpful. For instance, let's create a NumberList class.

Refactor using OO

(I'm assuming that insert(v,"max",max) should be insert(value,"max",max))

Node=Struct.new(:v,:l,:r)do
end

class NumberList
  def initialize()
    @max = 0
    @min = 0
  end

  def count(m)
    m==0 ? 0 : 1 + count(m.l) + count(m.r)
  end

  def delete(d,type)
    if d==0
      return 0
    end
    if type=="max"
      if d.l==0 && d.r==0
        return 0
      elsif d.l!=0 && d.r!=0
        if  d.l.v > d.r.v
          d.v= d.l.v
          d.l=delete(d.l,type)
        else
          d.v= d.r.v
          d.r= delete(d.r,type)
        end
      elsif d.l == 0
        d.v= d.r.v
        d.r=delete(d.r,type)
      else
        d.v= d.l.v
        d.l=delete(d.l,type)
      end
    else
      if d.l==0 && d.r==0
        return 0
      elsif d.l!=0 && d.r!=0
        if  d.l.v < d.r.v
            d.v= d.l.v
            d.l=delete(d.l,type)
        else
            d.v= d.r.v
            d.r= delete(d.r,type)
        end
      elsif d.l == 0
        d.v= d.r.v
        d.r=delete(d.r,type)
      else
        d.v= d.l.v
        d.l=delete(d.l,type)
      end
    end

    return d
  end

  def insert(v,type,t)
    if t==0
      return t=Node.new(v,0,0)
    end
      if type=="max"
        if v>t.v
        tmp=t.v
        t.v=v
        t.l=insert(tmp, type,t.l)
      else
        t.l=insert(v,type,t.l)
      end
    else
      if v<t.v
        tmp=t.v
        t.v=v
        t.l=insert(tmp, type,t.l)
      else
        t.l=insert(v,type,t.l)
      end
    end

    return t
  end

  def add_value( value )
    if (k=count(@max)-count(@min))==1
      if value<@max.v
        tmp=@max.v
        @max=delete(@max,"max")
        @min=insert(tmp,"min",@min)
        @max=insert(value,"max",@max)
      else
        @min=insert(value,"min",@min)
      end

      p (@max.v+@min.v)/2.0
    elsif  k==0
      if @max==0 || value<=@max.v
        @max=insert(value,"max",@max)
        p @max.v/1.0
      else
        @min=insert(value,"min",@min)
        p @min.v/1.0
      end
    else
      if value>@min.v
        tmp=@min.v
        @min=delete(@min,"min")
        @max=insert(tmp,"max",@max)
        @min=insert(value,"min",@min)
     else
       @max=insert(value,"max",@max)
     end

     p (@max.v+@min.v)/2.0
    end
  end
end

keeper = NumberList.new

n=gets.chomp.to_i

n.times do
  keeper.add_value( gets.chomp.to_i )
end

Now that we have it in an object, I could write some tests. But since you posted this 3 months ago, I'm not sure you're even going to read it.

Other things you should change

This is more complicated than necessary. Think harder about your problem rather than jumping in!
Ruby has loose typing, so it is possible to put either a number or an object in a variable. But if you're going to do that, your code shouldn't have to know about it. The object should have basically the same interface as a number. In this case, you initialize with an integer 0 and then later use a Node, which response to v, l and r. Not at all the same. I'm a little confused about how this works but I'd think an empty Node would be your best choice.
Your methods are hard to read. Method names should be "executable comments" ... in other words, you should know on a granular level what's happening just by reading the method name. And they should be written with the idea that a stranger should understand them.
Use more, shorter methods

Getting the Mean, the Ruby Way

Finally, here's how I'd implement a mean value in Ruby. Since Ruby allows you to add methods to core classes like Array, it makes some sense to add mean and sum to those classes. Of course, this will break if you try to do ['Jim', 'Spock', 'McCoy'].sum. So don't do that.

require 'bigdecimal'

class Array
  def sum
    self.inject(0){|sum,x| sum + x }
  end

  def mean
    BigDecimal.new(self.sum) / self.count
  end
end

in the console, you'd do this:

>> [2,4,66,32,3].mean.to_f
=> 21.4


The warning is trying to tell you that the return is pointless,
because it's the last statement anyway.
Here's a better way to rewrite that,
which will make the warning naturally go away:

if (!pwd.equals(pwd1)) {
    onShake(edt_password, "Passwords do not match");
    onShake(edt_password1, "Passwords do not match");
    return;
}

startbackgroundtask("formBased");

I simply inverted the condition, and removed the else branch.
If you think about it, all the else branches are unnecessary when the if branch returns. You can apply this to all the conditions in the posted code.

Many of your conditions handle the invalid case in the if and the normal case in the else, but not all.
It would be better to consistently handle the invalid case first everywhere,
and use early returns so you can get rid of the else. Like this:

    if (TextUtils.isEmpty(edt_name.getText().toString().trim())) {
        onShake(edt_name, "Please enter a valid name");
        return;
    }
    name = edt_name.getText().toString().trim();

    if (!isValidEmail(edt_email.getText().toString().trim())) {
        onShake(edt_email, "Please enter a valid email ID");
        return;
    }
    email = edt_email.getText().toString().trim();

    if (((edt_password.getText().length() < 6) || (TextUtils.isEmpty(edt_password.getText().toString().trim())))) {
        onShake(edt_password, "Password must be at least six characters long");
        return;
    }
    pwd = edt_password.getText().toString().trim();

    if (TextUtils.isEmpty(edt_password1.getText().toString().trim())) {
        onShake(edt_password1, "Not valid");
        return;
    }
    pwd1 = edt_password1.getText().toString().trim();

    if (!pwd.equals(pwd1)) {
        onShake(edt_password, "Passwords do not match");
        onShake(edt_password1, "Passwords do not match");
        return;
    }

    startbackgroundtask("formBased");

Notice that the code contains many duplicated logic, for example here,
the code to extract and clean edt_name is written twice:

    if (TextUtils.isEmpty(edt_name.getText().toString().trim())) {
        onShake(edt_name, "Please enter a valid name");
        return;
    }
    name = edt_name.getText().toString().trim();

It would be better to rewrite without duplication, like this:

    String cleanedName = edt_name.getText().toString().trim();
    if (cleanedName.isEmpty()) {
        onShake(edt_name, "Please enter a valid name");
        return;
    }
    name = cleanedName;

I also removed TextUtils.isEmpty, which was either a bug or pointless:

It's a bug if edt_name can be null, or if edt_name.getText() might return null: in both of these cases you will get a NullPointerException
If there won't be nulls, then you don't need TextUtils, you can use isEmpty method of String

There are several elements of poor coding style:

Variable names and method names should be camelCase, not like "edt_name" or "clientsideauth"
pwd and pwd1 are also poorly named, since pwd is the first password and pwd1 is the second. pwd1 and pwd2, or even pwd and pwdConfirmation would have been even better.

The clientsideauth method is doing too much:

Validate input
If successful, start background task
It mutates variables defined outside the method

Instead of mutating variables defined outside,
it would be better to validate,
collect the cleaned values in local variables,
and then pass these variables to the authentication task.

Since you do .getText().toString().trim() so often,
a helper method to do this for you would be a good idea,
to reduce your typing and the noise for readers.


Kudos for doing math groundwork, particularly for noticing multiplicative property of \$rad\$.
I see no reason to resort to double. 14399760001 is well within the long range.
Computing notcoprime costs a lot. Replacing it with

for (int a = 1; a < lim; a++) {
    for (int b = a + 1; b + a < lim; b++) {
        if(gcd(a, b) == 1) {
            ....

reduces the execution time by the factor of 1.5 even for the most naive gcd implementation.
On my system your code as is runs for about 0.06 sec. The reported 25+ sec must have some other explanation. What system do you have?


Cleaning sensitive information returned from a REST API

The solution is clear but seems too complicated for just sanitizing two URLs. Few suggestions:

The test only covers the method cleanUrls and only the expected case. There should be at least one test for each public method with the expected input, plus other tests for edge cases.
Limit the interface of SanitationService by setting internal methods to private. For example cleanDeal.
The name cleanUrls is too general. The result is removing the query parameters from the URLs so a better name might be stripUrlsParams.

My suggestion is to simplify cleanApiKeys like this:
public List<Deal> cleanApiKeys(List<Deal> deals) {
    deals.stream().forEach(deal -> {
        deal.stripUrlsParams();
    });
    return deals;
}

The class Deal will "deal" with its URLs:
public class Deal{
    //...
    public void stripUrlsParams() {
        this.url = this.url == null ? null : url.split("\\?")[0];
        this.imageUrl = this.imageUrl == null ? null : imageUrl.split("\\?")[0];
    }
}

If for some reason you can't change Deal then add a private method in SanitationService.


Formatting a string in Python with three possible replacement fields

Build a kwargs dictionary, rather than using an if-else.
You don't have to treat yes and no as mutually exclusive.
You could use a 'key, function' list to create a dictionary comprehension that builds the dictionary for you.

This can lead to:

kwargs = {}
if '{value}' in reply:
    kwargs['value'] = value
if '{yes}' in reply:
    kwargs['yes'] = get_yes()
if '{no}' in reply:
    kwargs['no'] = get_no()
reply = reply.format(**kwargs)

params = [
    ('value', lambda:value),
    ('yes', get_yes),
    ('no', get_no)
]

def format_format(format, params):
    return format.format({
        key: fn()
        for key, fn in params
        if f'{{{key}}}' in format
    })

reply = format_format(reply, params)


I took the liberty to make the exercise as well to see how our approaches differ. I don't think there are many remarks in terms of performance although StringBuilder.Remove() is a red flag in that area.

All together I think my code provides a more easily readable solution which should help in terms of human-reading efficiency. In the end I pretty much abstracted the things you do under library features.

public void SplitPath(string mainText, out string firstPart, out string secondPart)
{
  const string pivot = "Fixed";
  const char delimiter = '\\';

  var entries = mainText.Split(delimiter);
  int pivotIndex = entries.Length;
  for (var i = 0; i < entries.Length; i++)
  {
      if (entries[i] == pivot)
      {
          // Take index + 2 because linq.Take/Skip is 1-based
          // Optionally take index + 1 to avoid out-of-bounds when the pivot is the last element
          pivotIndex = (i == entries.Length) ? i + 1 : i + 2;
          break;
      }
  }

  firstPart = string.Join(delimiter.ToString(), entries.Take(pivotIndex));
  secondPart = string.Join(delimiter.ToString(), entries.Skip(pivotIndex));
}

I have tested this code with inputs C:\Abc\Fixed\MyTemp\Japan\Tokyo, C:\Abc\Fixed and C:\Abc.

If you'd want to take your approach after all, a few remarks:

Try to early return by using a negated if-statement condition.
Put your delimiter in a variable
Avoid magic values
Avoid removing data from the StringBuilder


Getting essential computer info for network admins

It looks quite fine to me.

I'm mainly surprised by the massive duplication in the CreateCSVdocument function:

function CreateCSVdocument {
    Get-MACAddress | New-Item C:\Users\$($env:username)\Documents\$($env:username).txt -type file -force
    Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt " "

Get-IPAddress | Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt
Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt " "

Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt "Hostname:"
Get-Hostname | Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt
Add-Content C:\Users\$($env:username)\Documents\$($env:username).txt " "

It would be better to introduce a variable there and use that, for example:

function CreateCSVdocument {
    $Dir="C:\Users\$($env:username)\Documents\$($env:username).txt"

    Get-MACAddress | New-Item $Dir -type file -force

    Add-Content $Dir " "
    Get-IPAddress | Add-Content $Dir
    Add-Content $Dir " "

    Add-Content $Dir "Hostname:"
    Get-Hostname | Add-Content $Dir
    Add-Content $Dir " "

Actually, this is still too repetitive.
Probably there is a better way to output all the text and pipe the whole thing to ... | Add-Content $Dir once at the end,
but I don't know how to do that in powershell.

The formatting is inconsistent:

In function definitions, sometimes you put a space between function name and { and sometimes you don't:

function Get-MACAddress {
function Get-UserName{

I recommend to put a space always, consistently.
Indentation is inconsistent:

You correctly indented the body of Get-MACAddress, Get-IPAddress and others
But you didn't follow the same logic in Get-HostName, Get-UserName, Get-DomainName and others


I suggest defining an ask for free-form answers and a choose function for multiple-choice questions.  The choose function can perform validation.

You can use case-when instead of if-else.

def ask(msg)
  puts msg
  gets.chomp
end

def choose(msg, choices)
  loop do
    down_choices = choices.map(&:downcase)
    puts "#{msg} (#{choices.join('/')})"
    result = gets.chomp.downcase
    return result if down_choices.include?(result)
    puts "That answer is invalid"
  end
end

name = ask "Hello, what's you're name, dude?"
case choose "Are you a boy?", ["yes", "no"]
when "yes" # boy
  case choose "Do you like soccer #{name}?", ["yes", "no"]
  when "yes" # likes soccer
    case choose "And beer?", ["yes", "no"]
    when "yes" # likes beer
      puts "Nice buddy!"
    else # doesn't likes beer
      puts "Too bad #{name}! But you like soccer!"
    end
  else # doesn't like soccer
    puts "You're complicated #{name}!!!"
  end
else # girl
  ask "Do you like romantics movies?"
end

Note that nothing is done with the answer to the question, "Do you like romantics movies?".


Checking hash and passwords with a wordlist, more efficient

Some suggestions:

Run the code through at least one linter such as flake8 or pycodestyle to produce more idiomatic code.
Don't read all the lines into a variable before starting processing - this will slow things down and use much more memory than necessary for large files. Instead you can use for line in file.readlines().
You are doing ten calculations in order to run a single print statement. Either get rid of them or do something simpler like print("{}/{} complete".format(k, long)).
If you know y has exactly one newline at the end you can do y[:-1] instead of y.rstrip('\n').
Capitalizing each word is expensive. Avoid it if at all possible.
If you don't need a bunch of the fields in an input file add a limit to your split() and mark the last stuff as discarded by using the _ variable. For example: usr, hshd, _ = x.split(':', 3)
Rather than keeping track of k manually you can just do for k, y in enumerate(grupo1).
Rather than having a list of usernames and a list of their hashed passwords, a Dict[str, str] of username to hash should be easier to keep track of.


Use yield instead of building a list. There is no need for an explicit list.
At start of method or input with [] for cleaner None checks.
Move interpolation into a function. This avoid repeated code.
Move all the casework into the interpolation function.

def graph_value(L, i, x):
    if x == L[i][0]: return L[i][1]
    if i == 0: return 0
    m = (L[i][1] - L[i - 1][1]) / (L[i][0] - L[i - 1][0])
    return m * (x - L[i - 1][0]) + L[i - 1][1]

def graph_addition(A, B):
    A = A or []
    B = B or []
    i = j = 0
    while i < len(A) and j < len(B):
        x = min(A[i][0], B[j][0])
        y = graph_value(A, i, x) + graph_value(B, j, x)
        i += (x == A[i][0])
        j += (x == B[j][0])
        yield (x,y)
    yield from A[i:]
    yield from B[j:]

Exercise to the reader: write a version that takes in two arbitrary iterables and performs the same functionality.


Returning Function Calls from an Array within a JavaScript Function

Normally, is a good practice create sub functions instead of add all on an array.

var button = function() {

};

Always use var in front of the variables to scope to the context. (good practice).

A good choice is take advantage of the evaluation of data types on javascript, for variables.

var variable = paramValue || "defaultValue";

this evaluates paramaValue, if is true, is assigned, if not, assign "defaultValue"

Also, if is possible, considere use a template engine like:

http://handlebarsjs.com
http://mustache.github.io

Final Code


A simple Java class for implementing code stop watches

public final class StopWatch {

    private long earliestMillis = Long.MAX_VALUE;

There is no reason to initialize this field at this point. Both constructors will overwrite it immediately.

    public StopWatch() {
        this(System.currentTimeMillis());
    }

    public StopWatch(long earliestMillis) {
        this.earliestMillis = earliestMillis;
    }

There should be no reason for the user to provide their own initial start time. The only reason could be to use an entirely different clock for testing this code. For that case, you should use a MillisProvider instead of calling System.currentTimeMillis directly. As of now, you have a wild mixture of calling currentTimeMillis and accepting caller-provided timestamps, which can easily lead to confusion.

    public void push(long earliestMillis) {

Again, I don't see any reason not to hard-code System.currentTimeMillis here.

        if (earliestMillis < this.earliestMillis) {
            throw new IllegalArgumentException("Cannot go back in time.");
        }

When you measure code for performance, you usually don't expect additional exceptions to be thrown. Changing the system clock backwards should not happen anyway, but still this code should deal a little softer with this situation by just ignoring it.

        this.earliestMillis = earliestMillis;
    }

    public long pop() {
        return System.currentTimeMillis() - earliestMillis;
    }

    public long popAndPush() {
        long ret = pop();
        this.earliestMillis = System.currentTimeMillis();
        return ret;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(")
                     .append(System.currentTimeMillis() - earliestMillis)
                     .append(" starting from ")
                     .append(earliestMillis)
                     .append(" ms -> ")
                     .append(System.currentTimeMillis())
                     .append(")");

        return stringBuilder.toString();
    }

Using a StringBuilder here is unnecessary. It is only needed if you have some parts that are added conditionally to the string. Just use plain string concatenation, which is far easier to read. Alternatively, since the toString method is probably not called in the performance-critial part, it's probably ok to use String.format here, to separate the general format of the message from the parameters.

Oh, I just saw that toString calls currentTimeMillis. That's wrong. It's even wronger to call it twice in a row (and expecting both calls to return the same timestamp). Measuring the time should be as fast and light-weight as possible. Building a nice presentation out of the raw measurement values should be clearly separated from the measurement.

To increase the precision of the measurement, you should determine how long it takes to call currentTimeMillis and subtract that from the reported durations.

    public static void main(String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();

        Thread.sleep(3_000L);
        System.out.println(sw.pop());
        System.out.println(sw);

        Thread.sleep(2_000L);
        System.out.println(sw.pop());

        sw.popAndPush();
        Thread.sleep(1_230L);
        System.out.println(sw);
    }
}

As danielspaniol already said in a comment, having a stopwatch with buttons labelled "push" and "pop" feels strange. Looking at Wikipedia, the second image, your methods should rather be called start, stop, reset, lap, split, recall, pause.


Initialize C array at definition depending on runtime input

This code is not correct. The r[4] and c[4] arrays you have are stored on the stack, which means that as soon as they go out of scope the data is no longer valid and you get undefined behavior because rr and cc now point to unused (and possibly overwritten) areas on the stack.

If you wanted to do this correctly, you could ensure that the arrays are kept alive either by storing on the heap, static memory, or high enough on the stack that they will live as long as rr and cc are used.

After reading it again, I realized I made a mistake. While the temporary r and c arrays are initialized in their own scopes that are immediately exited, the arrays themselves live on the same stack with the rest of the function. Still, it's definitely a bad habit to have use variables after they've left the scope even if they're technically still on the stack, so I would make the same changes anyway.

For example, you could do:

// Somewhere in a high enough scope (possibly the current one) or static
char r_1[4] = { 0, -1, 0, 1 };
char c_1[4] = { 1, 0, -1, 0 };

char r_2[4] = { -1, -1, 1, 1 };
char c_2[4] = { 1, -1, -1, 1 };

// In the current scope
char *rr;
char *cc;

if (cycle % 2 == 0) {
  rr = r_1;
  cc = c_1;
}
else {
  rr = r_2;
  cc = c_2;
}


Best way to create SVG from database? (Using PHP)

<?php
$formats = array(
    '1' => array(
        'x1' => 820,
        'y1' => 120
    ),
    '2' => array(
        'x1' => 905,
        'y1' => 180
    )
);
?>

<?php foreach( $formats as $key => $format ) : ?>
    <?php if ( in_array( (int) $key, $services ) ) : ?>
        <line x1="<?php print $format['x1']; ?>" y1="<?php print $format['y1']; ?>" />
    <?php endif; ?>
<?php endforeach; ?>

I didn't do it for every field, but you get the idea.

This is tedious to write the array. But you have to write it somewhere. If there is no logic, the computer can't guess.

I think it's easier to read/write a simple array than all this XML though.


Most rectangles have a length and a width.  I’ve never heard of a rectangle with a radius, but it would be known as a square.

More constructively:

System.out.print(String.format("(%d,%d) ", x - r + i, y - r));

Could be written as:

System.out.format("(%d,%d) ", x - r + i, y - r);


Simple (Very Easy to Make) RPG Game Simulation in Python and Turtle

jedi_gif = "/home/asus/Arief_tempo/images/random/jedi.gif"

It's unclear why this image has an absolute path but no others do. They should probably all be relative, as the other three are.

Especially if this is for a tutorial, you need to add docstrings to all of your functions.

This:

self.img.setpos(enemy.img.pos()[0], enemy.img.pos()[1])

can use argument expansion, i.e.:

self.img.setpos(*enemy.img.pos())

That pattern can be used elsewhere you're indexing into the position.

This:

enemy.health += - self.power

should be

enemy.health -= self.power


Use std::move where appropriate

When you take an object parameter by value with the intent of copying it, use std::move to take advantage of move semantics if the object supports it. This is the case with std::string. But be aware that after moving a string, the original will be left empty, so it is better to restructure CFG::Init to something like the following:

bool CFG::Init(std::string filename)
{
    if (filename.empty())
    {
        return false;
    }

    std::ifstream fileIn(filename);
    if (!fileIn.is_open())
    {
        return false;
    }

    m_buffer << fileIn.rdbuf();

    m_cfgFilename = std::move(filename);
    // 'filename' is now empty. It's contents were take by 'm_cfgFilename'

    Parse();
    return true;
}

It's probably also better to only assign m_cfgFilename at the end, so you don't set that member if you fail to open the file, but that might not be the behaviour you want. Otherwise, you can still move filename to the member string at the top and then use the member string instead.

Also notice that I've renamed the ifstream t in my example. Single letter names are pretty bad, with the exception of a few specific places like in for-loop counters.

CFG::Parse()

This line here is overly complicated:

if (!line.empty() && line.compare(0, commentKey.length(), commentKey))
{
    ...
}

std::string has the == operator overloaded, so you can compare two strings like you would compare a number. But since a comment is any line starting with '#', you might as well just test line[0].

Going further, it's better to avoid deep nesting when you can. Just continue if the condition is true.

if (line.empty() || line[0] == '#')
{
    continue;
}

Better string trim

You can cut down the size of your main reading loop by introducing a small helper function to trim the string. Having such simple utility function at hand can also be useful in other places. You can find a couple nice samples in here. This one in particular might be faster, since it doesn't create the temporary stringstream.

While you are at it, go ahead and turn that to-lowercase transform into a separate function as well:

inline std::string lowercase(std::string str)
{
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    return str;
}

A tiny optimization

This is arguably a micro-optimization, but at scale it might have impact. If you move the declaration of your vector seglist and the temporary segment string to the top level of the function, that will avoid recreating the objects at each iteration of the loop. You just have to clear() them at the start of the loop. vector and string might be allocating and freeing dynamic memory on construction/destruction, so if they are only constructed once and just cleared, the memory stays allocated until the end of the function.

The downside of doing this is that you go against the recommendation of declaring variables as close as possible to the first point of usage, so it might not be worth it. Since this is a loop with potential hot code in it, might be interesting.


Speeding up VBA Code that Sets Pivot Table Filters

I find that when you set PivotTable.ManualUpdate = True, Excel seems to often set that back to False for many of the changes you can make to PivotTables.  It does depend on the change, but I think changing PivotFields is one of those things that triggers this.

So you could try going to every PivotField change and resetting ManualUpdate to True after it.  Such as this:

With Sheet5.PivotTables("PivotTable21")
    .ManualUpdate = True
    .PivotFields("Division2").CurrentPage = DivRef
    .ManualUpdate = True
    .PivotFields("Region2").CurrentPage = RegRef
    .ManualUpdate = True
    .PivotFields("District2").CurrentPage = DistRef
    .ManualUpdate = False
End With

I know it seems silly, but I've seen this work.


Looks good at a first glance.  For reusability the code should be
divided into functions instead of just being a single script file.

I'd load the multiple environment keys in a loop and into a separate
dictionary instead of globals.  That's nicer to refactor later and
it's easy to pass around, or even update from command line arguments
as well (e.g. using argparse).  You can also look at
dotmap or something similar to
get a bit nicer syntax.  E.g.:

options = {}
for name in ["MIN_DAYS",
            "TRELLO_KEY",
            "TRELLO_TOKEN",
            "TRELLO_BOARD",
            "MANDRILL_KEY",
            "MSG_FROM_EMAIL",
            "MSG_FROM_NAME",
            "MSG_SUBJECT",
            "MEMBER_EMAILS"]:
    options[name] = os.environ.get(name)

The loop at the end can be exited early with
if ... not in ...: continue to remove one level of indentation.
The print should be using function call syntax for forwards
compatibility with Python 3 and similarly the except handler should
also use the except ... as e: syntax instead.  I.e.:

...
        print(result)
    except mandrill.Error as e:
...

The iteration over members can use iteritems to get both name and
cards in the same step.
For the date comparison I'd recommend using a dedicated library, that
way both the code will be easier to read and one less wheel is
reinvented.  E.g. I had good experiences with
arrow.
For the HTTP requests you can also look at
requests for a nicer
interface.


Accessing Data inside Presentation Layer from API: Laravel 5.2.27

This looks like a good place to use a shared repository. If you used a repository that was shared between your android api server app and your web server app you could avoid the need for inter-server communications and translating to and from json. You'd get better performance and the repository would function as the middle tier of your 3-tier architecture.

Repositories in Laravel are a fairly large topic so I'll just point you at Laracasts for that. For using a shared model in more than one project, this thread gives an example of doing it via composer:

https://laracasts.com/discuss/channels/general-discussion/share-models-between-two-laravel-projects?page=1

That's not to say there is anything particularly wrong with the architecture you're describing. It shouldn't have too much of a performance hit but it will have a hit from the communications aspect and the translation to and from json aspect. Both of which are small as long as you stay within your local LAN. You seem to be accessing localhost for the API so it shouldn't be a problem.


A lot of your vector initialization can be handled by vector's constructor. Not only is that much shorter and less error prone, it's also more efficient since it lets the vector avoid resizing over and over again.

As an example:

std::vector< std::vector< std::pair<int, int> > > vecHash;

for(int i =0; i < (size*size); i++)
{
    vecHash.push_back(std::vector< std::pair<int, int> > ());
}

This can be:

std::vector< std::vector< std::pair<int, int> > > vecHash(size*size);

if(vecHash[input3 - i].size() > 0)

This should be if(!vecHash[input3 - i].empty()) as empty() reads clearer.

Your logic and your IO should be handled separately. You should add a function for printing solutions so your validCombo isn't doing quite so much. That will mean returning the solutions instead of the number of solutions, but that makes more sense anyway.

For small little programs like this it doesn't really matter, but for anything non-trivial, you want each function to only do one thing. That allows you to control and modify things in a much easier way. (Even though we're not talking about OOP, this is essentially the essence of the SRP.

count = solution.size();
std::cout << "solution size = "  << solutionSet.size();

// ...

return count;

Either use count consistently, or don't bother assigning it.

Also, declare variables as close to use as possible. It's confusing to try to figure out where in the world count came from when it's declared a few dozen lines up.


Interpreting strings with C-style escapes

Use <cctype> for character classification

Instead of defining is_hex() (and depending on abcdef and ABCDEF being contiguously coded), better to use the standard isxdigit().

get_nibble makes a similar assumption - it's arguably safer to use a switch for this.

On the whole, the logic looks good.  I'm not a fan of names beginning with _ - even if you do fully understand the rules about reserved identifiers, many of your readers will not!

Some expressions can be simplified with post-increment.  Consider this fragment:

if (!_err)
    tmp[_len] = esc, ++_len;
} else {
    tmp[_len] = *in; ++in, ++_len;
}

That could be

if (!_err)
    tmp[_len++] = esc;
} else {
    tmp[_len++] = *in++;
}

That's fairly idiomatic usage, and should be familiar to anyone who's looked at strcpy or the like.  In fact, slightly more idiomatic would be to use a pointer, rather than indexing:

char *post_string(char *const in, size_t *len, const char **err) {
    if (!in || !len)
        return NULL;

    char *out = in, *p = in;
    const char *int_err = NULL;

    while (*p && !int_err) {
        if (*p != '\\') {
            /* normal case */
            *out++ = *p++;
        } else {
            /* escape sequence */
            switch (*++p) {
            case 'a': *out++ = '\a'; ++p; break;
            case 'b': *out++ = '\b'; ++p; break;
            case 'f': *out++ = '\f'; ++p; break;
            case 'n': *out++ = '\n'; ++p; break;
            case 'r': *out++ = '\r'; ++p; break;
            case 't': *out++ = '\t'; ++p; break;
            case 'v': *out++ = '\v'; ++p; break;

            case '"': case '\'': case '\\': *out++ = *p++; case '?': break;

            case 'x': case 'X':
                if (!isxdigit(p[1]) || !isxdigit(p[2])) {
                    int_err = "Invalid character on hexadecimal escape.";
                } else {
                    *out++ = (char)(get_nibble(p[1]) * 0x10 + get_nibble(p[2]));
                    p += 3;
                }
                break;

            default:
                int_err = "Unexpected '\\' with no escape sequence."; break;
            }
        }
    }

    *out = '\0';                /* Set the end of string. */
    *len = p - in;              /* Set the final string length. */
    if (int_err && err)         /* Set error message back. */
        *err = int_err;
    return in;
}

Testing

Some of the code appears completely untested (and I've fixed above).  In particular, passing NULL as the err parameter - as in the sample main() - will provoke undefined behaviour if your string is invalid).

Modified code

I've also added code to accept 1-3 octal digits, and modified the hexadecimal reader to accept 1+ digits, and included tests of each error branch.

#include <ctype.h>
#include <limits.h>
#include <stddef.h>

static unsigned int get_nibble(char c)
{
    switch(c) {
        case '0': return 0;
        case '1': return 1;
        case '2': return 2;
        case '3': return 3;
        case '4': return 4;
        case '5': return 5;
        case '6': return 6;
        case '7': return 7;
        case '8': return 8;
        case '9': return 9;
        case 'A': case 'a': return 0xa;
        case 'B': case 'b': return 0xb;
        case 'C': case 'c': return 0xc;
        case 'D': case 'd': return 0xd;
        case 'E': case 'e': return 0xe;
        case 'F': case 'f': return 0xf;
    }
    /* shouldn't happen */
    return 0;
}

char *post_string(char *const in, size_t *len, const char **err) {
    if (!in || !len)
        return NULL;

    char *out = in, *p = in;
    const char *int_err = NULL;

    while (*p && !int_err) {
        if (*p != '\\') {
            /* normal case */
            *out++ = *p++;
        } else {
            /* escape sequence */
            switch (*++p) {
            case 'a': *out++ = '\a'; ++p; break;
            case 'b': *out++ = '\b'; ++p; break;
            case 'f': *out++ = '\f'; ++p; break;
            case 'n': *out++ = '\n'; ++p; break;
            case 'r': *out++ = '\r'; ++p; break;
            case 't': *out++ = '\t'; ++p; break;
            case 'v': *out++ = '\v'; ++p; break;

            case '"': case '\'': case '\\': case '?': *out++ = *p++; break;

            case 'x': case 'X':
                if (!isxdigit(*++p)) {
                    int_err = "Invalid character on hexadecimal escape."; break;
                } else {
                    unsigned int x = 0;  /* assuming int is larger than char */
                    while (isxdigit(*p)) {
                        x *= 0x10;
                        x += get_nibble(*p++);
                        if (x > UCHAR_MAX) {
                            int_err = "Out of range hexadecimal escape."; break;
                        }
                    }
                    *out++ = (char)x; break;
                }

            default:
                if (isdigit(*p) && *p < '8') {
                    /* octal escape */
                    unsigned int x = 0;  /* assuming int is larger than char */
                    for (int i = 0;  i < 3 && isdigit(*p) && *p < '8';  ++i) {
                        x = x * 010 + (unsigned)*p++ - '0';
                    }
                    if (x > UCHAR_MAX) {
                        int_err = "Out of range octal escape."; break;
                    }
                    *out++ = (char)x; break;
                } else {
                    int_err = "Unexpected '\\' with no escape sequence."; break;
                }
            }
        }
    }

    *out = '\0';                /* Set the end of string. */
    *len = (size_t)(p - in);    /* Set the final string length. */
    if (int_err && err)         /* Set error message back. */
        *err = int_err;
    return in;
}

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

int main(void) {
  char t[256] = "This is a \\\"string\\\" with \\x43 \\X063 hex\\"
      "nnewline\\ttab\\t\\?\\'\\\"\\\\octal\\132\\538 \\0null";
  size_t len = 0;
  printf("Before: %s\n", t);
  post_string(t, &len, NULL);
  printf("After : %s\n\n", t);

  const char *err = NULL;
  strcpy(t, "This has a hex error: \\xg");
  printf("Before: %s\n", t);
  post_string(t, &len, &err);
  printf("Error: %s\n\n", err);

  strcpy(t, "Hex beyond ASCII: \\xfff");
  printf("Before: %s\n", t);
  post_string(t, &len, &err);
  printf("Error: %s\n\n", err);

  strcpy(t, "Octal beyond ASCII: \\777");
  printf("Before: %s\n", t);
  post_string(t, &len, &err);
  printf("Error: %s\n\n", err);

  strcpy(t, "not an escape: \\9");
  printf("Before: %s\n", t);
  post_string(t, &len, &err);
  printf("Error: %s\n\n", err);

  strcpy(t, "backslash at end: \\");
  printf("Before: %s\n", t);
  post_string(t, &len, &err);
  printf("Error: %s\n\n", err);
}


Find foreign key membership including owner in SQL Server

The query will return the schema name properly.  However, note that a foreign key may not necessarily reference the primary key; a unique constraint or unique index may also be referenced.  I suggest renaming the PK_Name column to a more generic name like KEY_Name to more accurately describe the column in cases where it's a unique constraint or index instead of primary key.

With a foreign key referencing a unique index, the relationship will be missed entirely by the query because unique indexes are not reflected in sys.key_constraints.  Consider using sys.indexes instead of sys.key_constraints to avoid that problem.

SELECT
    s1.name AS FK_schema,
    o1.name AS FK_table,
    c1.name AS FK_column,
    fk.name AS FK_name,
    s2.name AS PK_schema,
    o2.name AS PK_table,
    c2.name AS PK_column,
    i.name AS KEY_name,
    fk.delete_referential_action_desc AS Delete_Action,
    fk.update_referential_action_desc AS Update_Action
FROM sys.objects o1
    INNER JOIN sys.schemas s1
        ON o1.schema_id = s1.schema_id
    INNER JOIN sys.foreign_keys fk
        ON o1.object_id = fk.parent_object_id
    INNER JOIN sys.foreign_key_columns fkc
        ON fk.object_id = fkc.constraint_object_id
    INNER JOIN sys.columns c1
        ON fkc.parent_object_id = c1.object_id
        AND fkc.parent_column_id = c1.column_id
    INNER JOIN sys.columns c2
        ON fkc.referenced_object_id = c2.object_id
        AND fkc.referenced_column_id = c2.column_id
    INNER JOIN sys.objects o2
        ON fk.referenced_object_id = o2.object_id
    INNER JOIN sys.schemas s2
        ON o2.schema_id = s2.schema_id
    INNER JOIN sys.indexes i
        ON fk.referenced_object_id = i.object_id
        AND fk.key_index_id = i.index_id
ORDER BY s1.name, o1.name, s2.name, o2.name, fkc.constraint_column_id;


Dynamic Programming for printing additive numbers up to digits n

1. Review

I like that you've written a docstring, but it is not quite correct. It claims that the function returns:

A dictionary mapping each number of digits to all
possible additive numbers.

but when I run it I get a more complicated data structure:

>>> from pprint import pprint
>>> pprint(additive_numbers(3))
{3: {1: ['01', '12', '23', '34', '45', '56', '67', '78', '89'],
     2: ['02', '13', '24', '35', '46', '57', '68', '79'],
     3: ['03', '14', '25', '36', '47', '58', '69'],
     4: ['04', '15', '26', '37', '48', '59'],
     5: ['05', '16', '27', '38', '49'],
     6: ['06', '17', '28', '39'],
     7: ['07', '18', '29'],
     8: ['08', '19']}}

Either the docstring or the result should be changed so that they match.
The code is not portable to Python 3 due to the use of the raise and print statements and the xrange function. It would be easy to make it portable, using range instead of xrange, the print function instead of the statement, and the modern form of raise:

raise ValueError("additive numbers always have 3 or more digits")

The function print_additive_numbers does three things: (i) it computes the numbers, (ii) it prints them, and (iii) it returns an internal data structure used in the computation. It's generally good practice for a function to have a single purpose, and then compose or combine functions to make a program. So I would redesign the function so that it does task (i); we can call print on the result if we need (ii). I don't think (iii) is necessary at all.
The code stores the last two digits of each additive number in the trellis structure in the form of a string. But this means that when it gets the digits out again it has to call int. This conversion back and forth is wasteful: it would be better to store the tuple (j, i + j) instead of the string str(j) + str(i + j).
The initial loop looks like this:

for i in xrange(1, 9):

but Python ranges are exclusive at the top, so this never generates the digit 9 and thus fails to find the additive numbers 909 and 9099. The initial loop needs to say range(1, 10).
The initial two loops look like this after correcting the problems noted above:

trellis[BASE_CASE] = {}
for i in range(1, 10):
    row = []
    for j in range(0, 10):
        if i + j <= 9:
            row.append((j, i + j))
    trellis[BASE_CASE][i] = row

but the if could be omitted if we changed the bounds on j, like this:

trellis[BASE_CASE] = {}
for i in range(1, 10):
    row = []
    for j in range(10 - i):
        row.append((j, i + j))
    trellis[BASE_CASE][i] = row

or, using a list comprehension:

trellis[BASE_CASE] = {}
for i in range(1, 10):
    trellis[BASE_CASE][i] = [(j, i + j) for j in range(10 - i)]

2. A better algorithm

This is a problem for which dynamic programming is unnecessary! That's because dynamic programming is a technique that you use when you have to consult the answers to multiple overlapping subproblems in order to answer the current problem. But when generating additive numbers, there isn't really a problem to solve. Once you've chosen the first two digits, all the other digits follow without any choice.

So I would implement it like this:

def additive_numbers(n):
    """Generate additive numbers up to n digits, in numerical order.

    Additive numbers are numbers of the form 123, 1235, etc. where the
    sum of every 2 digits is equal to the third digit in the digit
    expansion of the number.

    >>> list(additive_numbers(3))
    ... # doctest: +NORMALIZE_WHITESPACE
    [101, 112, 123, 134, 145, 156, 167, 178, 189, 202, 213, 224, 235,
     246, 257, 268, 279, 303, 314, 325, 336, 347, 358, 369, 404, 415,
     426, 437, 448, 459, 505, 516, 527, 538, 549, 606, 617, 628, 639,
     707, 718, 729, 808, 819, 909]

    The longest additive number is 8 digits long:

    >>> list(additive_numbers(8)) == list(additive_numbers(9))
    True
    >>> max(additive_numbers(8))
    10112358

    """
    for digits in range(3, n + 1):
        # Choose the first two digits.
        for i in range(1, 10):
            for j in range(10 - i):
                # m is the number generated so far, z is its last
                # digit, and y the penultimate digit.
                m, y, z = i * 10 + j, i, j
                for _ in range(digits - 2):
                    y, z = z, y + z
                    if z > 9:
                        break
                    m = m * 10 + z
                else:
                    yield m

The examples in the docstring can be executed using the doctest module.


SICP Exercise 1.3: Sum of squares of two largest numbers out of three, Haskell Version

If you don't need a value, don't bind it, use a wildcard instead.

[a, b, c] = sort [x, y, z] # and btw, add a space after the function name

becomes

[_, b, c] = sort [x, y, z]

Perhaps its just personal preference (I don't use much Haskell myself), but I usually see the where clause in the next line, with an extra tab, like:

sumSquareLargest x y z = b ** 2 + c ** 2
    where [_, b, c] = sort [x, y, z]

Moreover, the b and c values are not obvious at first glance, and you need to read the second line before the first. In these cases, a let expression can be a more nice alternative:

sumSquareLargest x y z =
    let [_, b, c] = sort [x, y, z]
    in b ** 2 + c ** 2

This is a very small function, but consider having more meaningful names for your bindings:

sumSquareLargest x y z =
    let [_, medium, maxim] = sort [x, y, z]
    in medium ** 2 + maxim ** 2

Also, consider writing some unit tests in a library like QuickCheck.


This is the solution I came up with using the Fibonacci succession closed form:

that uses the golden radio:

First we can see that for any even Fibonacci number the sum of all the previous even and odd Fibonacci is equal.

Each even Fibonacci number is preceded by 2 odd Fibonacci numbers.

o o e o o e

1 1 2 3 5 8....

This means that we can transform each of the even Fibonacci in the sum of the 2 previous odd Fibonacci .

So n being any even Fibonacci and f(n) the sum of all even Fibonacci up to n we have:

Also the sum of all Fibonacci numbers up to fib(x) is equal to fib(x+2)-1.

So given any number f we find x by calculating the closest Fibonacci  number fib(x) that is even and less than or equal to f. We then can finally compute  fib(x+2)-1.

The code (this is C++ but it can easily be translated to C#):

long fib ( int i, double golden )
{
    return pow ( golden, i ) / sqrt ( 5 ) + 0.5 ;
}

long findSumEvenFibUpto ( int number )
{
    const double golden = ( 1 + sqrt ( 5 ) ) / 2 ;
    long nearest = round ( log ( sqrt ( 5 ) * number ) / log ( golden ) );

    int fibo = 0 ;
    while ( ( fibo = fib( nearest -- , golden ) ) % 2 || fibo > number ) ;

    return ( fib ( nearest + 3 , golden ) - 1 ) / 2 ;
}


If you really intend that this be used only on arrays, you can simplify its use somewhat by turning the function into a function template that receives its argument by reference (and since we're making it a template anyway, we might as well make it accept a variety of types, not just int).

template <class T, size_t size>
T peak(const T (&arr)[size]) {
    // ...

This way you can just pass the array itself, without explicitly passing the size, so the call in main turns into something like this:

int arr[] = {1,1,8,9,22,2};

auto elem = peak(arr);

...and the compiler uses its existing knowledge of the number of elements in arr instead of our having to pass it explicitly (but note that this simply won't work at all for a collection of items allocated with new or malloc--if you try to pass a pointer, the code will be rejected).

The obvious alternative (and possibly a superior one) would be to pass iterators instead. This would let us make this algorithm look and feel a lot more like the others in the standard library. A sub-alternative (so to speak) would be to use a range library (e.g., Eric Neibler's) and pass a range instead of separate iterators.

In keeping with the idea of using a template, I'd also consider changing your conditions so they all use the same comparison operator--traditionally C++ has only required operator< to be defined, and figures everything out from it. In this case it may be more work than it's worth though. It makes no difference for int, but minimizes the interface required by the template, so it can be applied to types that define <, but not any other comparison operators. If you don't anticipate applying it to such types, it may be easier to leave it alone.

I'd also consider renaming some of the variables. I see little gain from using arr instead of array, for one obvious example.

Headers: right now you have #include <iostream>, but you use printf instead of an iostream. I don't see any reason to use printf in this case--I'd use std::cout << elem; instead. If, for whatever reason, you want to continue using printf, include the right header (<cstdio>) instead of <iostream> though.

The one question you've asked is eliminated by turning the code into a template. If, for whatever reason, you decide not to do that, you don't need to use decltype. Rather, to compute the number of elements in an array you typically want to use: (sizeof(arr)/sizeof(arr[0])) (but the template is clearly the better approach).

I'd also prefer to fail loudly, and use some special name for code that checks a pre-condition, such as ensure or requires, so if you did pass a pointer, you'd start the code with something like this:

int peak(int const *array, size_t size) {
    ensure(array != nullptr);
    ensure(size > 0);

...with ensure defined something like this:

#define ensure(cond) (bool(cond) || fputs(#cond, stderr))