Friedrich Ewald My Personal Website

Posts


  • Using a Newtonsoft.JSON DLL in multpiple projects

    When building a Visual Studio solution, I had the problem that I got a TargetInvocationException when calling a method from a referenced DLL file. When running the unit tests on the DLL file, everything seemed to work fine and I could not track down the problem. The inner exception of the exception brought me then on the right track: The Newtonsoft.JSON module was installed in different versions across each DLL file and the main project.

    ' Write the exception to the console.
    Try
            response = Await client.Login("a", "b")
        Catch ex As Exception
            Console.WriteLine(ex.InnerException)
        End Try
    
    The solution is simple. I just had to make sure, that the DLL is used in the same version in every project. This can simply be done with the console of the package manager.
    PM> Update-Package Newtonsoft.JSON -reinstall
    PM> Update-Package Newtonsoft.JSON
    

  • Experiences with Jekyll (2016)

    My first post on this blog was in December 2015 and since then, this blog is running with Jekyll. I want to take the time to summarize my experiences with Jekyll over the past year. The first thing I did, was creating a build script which I then used within a git-hook. The build script just runs jekyll build and then uses rsync to synchronize the changes to my webserver. This way, I can keep the webserver very light, serving only HTML, CSS and some JavaScript. This script is located in the root folder of the site.

    #!/bin/bash
    jekyll build
    rsync --update --progress -r _site/* [email protected]:/.../html/
    
    Now, every time I write a new post, commit it, it will be automatically published on the web and the corresponding html sites will be updated. This also works for any change in any template file.Since I wanted to allow some dynamic content on my website, I added Disqus. This adds a comment box under each blog post via JavaScript. With this technique, I am able to keep the sites static but also allow feedback. The Javascript is added just before the closing body tag which keeps the loading times very low. Google Page Speed Insights rates this page currently with a score of 71/100 for mobile and 85/100 for desktop. This is obviously far away from the optimal solution and will be a topic in another post. What I can see so far, the changes to the code should be minor and can be easily integrated into the build script. The theme for this site is from the page Jekyllthemes. This page hosts a lot of open source themes for Jekyll which are ready to use. A theme consists of a bunch of files, which have to be places in the the main folder. An easy to understand tutorial can be found here. Overall my experience with Jekyll is very positive and it makes creating a website very easy. Of course one loses a lot of dynamic features, but the point that I don’t have to worry about any security issue ever, justifies this decision. Also, load times are much fast, especially on a shared server.

  • Merging two ordered lists efficiently in Python

    To merge two lists l1, l2 in python, one can use the following

    1. Create two pointers, p1, p2
    2. Use a while loop, which is terminated, when one of the lists reaches the end
    3. Compare the entries of the list pairwise at the pointer position
      • If the entries are equal, add l1[p1] to result and increment p1 and p2 by 1
      • If l1[p1] < l2[p2], then add l1[p1] to result, then increment p1
      • If l1[p1] > l2[p2], then add l2[p2] to result, then increment p2
    4. Check, which list is not at the end and concat the tail of this list with result
    In Python code, this looks the following:
    l1 = [1, 3, 5, 7, 9, 11]
    l2 = [2, 4, 6]
    p1 = 0
    p2 = 0
    result = []
    # Loop over both lists until one list is at the end
    while p1 < len(l1) and p2 < len(l2):
        # If the values at the positions are the same,
        # copy the value to the result
        if l1[p1] == l2[p2]:
            result.append(l1[p1])
            result[-1] = l1[p1] + l2[p2]
            p1 += 1
            p2 += 1
            # One entry is smaller, increment the smaller pointer
        elif l1[p1] < l2[p2]:
            result.append(l[p1])
            p1 += 1
        # One entry is smaller, increment the smaller pointer
        elif l1[p1] > l2[p2]:
            result.append(l2[p2])
            p2 += 1
    rest = []
    if p1 < len(l1):
        rest = l1[p1:len(l1)]
    elif p2 < len(l2):
        rest = list2[p2:len(l2)]
    result += rest
    # [1, 2, 4, 5, 6, 7, 9, 11]

  • Syntax for Crontab

    Just a quick reminder for the syntax of the crontab for cronjobs:

    # 1. Entry: Minute when the process will be started [0-60]
    # 2. Entry: Hour when the process will be started [0-23]
    # 3. Entry: Day of the month when the process will be started [1-28/29/30/31]
    # 4. Entry: Month of the year when the process will be started [1-12]
    # 5. Entry: Weekday when the process will be started [0-6] [0 is Sunday]
    #
    # all x min = */x
    
    Found on Stackoverflow

  • Angular2 - Loading indicator for Http service

    I wanted to notifiy the user, whenever I am doing an AJAX request in Angular2. To achieve this in an existing project, the goal was, to edit as little files as possible. The solution to this problem is very straightforward: The class Http needs to be extended which allows own code to be used. First, I needed to create the EventHttpService with the following code:

    import { Http } from '@angular/http';
    export class EventHttpService extends Http{}
    
    So far this class does nothing, it just extends the Http class, providing the same functionality. Therefore I needed to override all the methods which should perform a different action. Below is an example for the get method, with all the required imports. Of course, the whole class needs to be decorated with Injectable() so that we can inject it via Dependency Injection.
    import { Injectable } from '@angular/core';
    import { Http, RequestOptions, RequestOptionsArgs, Response, ConnectionBackend } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class EventHttpService extends Http {
    	public get(url: string, options?: RequestOptionsArgs) : Observable<Response> {
    			// Own code before the request is performed
    			var response = super.get(url, options);
    			response.subscribe(null, error => {
    				// Own code on error
    			}, () => {
    				// Own code on success
    			});
    			return response;
    	}
    }
    
    The comments in the source code above mark the points where the developer can implement own code. I used it, to increment and decrement a counter. When the counter starts from 0, an injected loading bar is shown and when the counter finally reaches 0, the loading bar is hidden. So far, the class does nothing, since we are not using it. The right place to use it, is app.module.ts:
    @NgModule({
      imports:      [],
      declarations: [],
      providers: [
        HTTP_PROVIDERS,
        provide(Http, {
          useFactory: (xhrBackend: XHRBackend, requestOptions: Request) => new EventHttpService(xhrBackend, requestOptions),
          deps: [XHRBackend, RequestOptions]})
        ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    
    With this example, whenever Http.get is used, the EventHttpService is used automatically, executing my custom code. If you want to inject other services into Http, this is also straightforward, just add these to the constructor of the EventHttpService so that it looks as follows. In my case, I am using the awesome ng2-slim-loading-bar to show a loading bar, when the first AJAX request is performed.
    public constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions, private loadingBar: SlimLoadingBarService) {
    	super(_backend, _defaultOptions);
    }
    
    Below is the complete code of the event-http.service.ts:
    import { Injectable } from '@angular/core';
    import { Http, RequestOptions, RequestOptionsArgs, Response, ConnectionBackend } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import { SlimLoadingBarService } from 'ng2-slim-loading-bar';
    
    @Injectable()
    export class EventHttpService extends Http {
    	private currentRequests: number = 0;
    
    	public constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions, private loadingBar: SlimLoadingBarService) {
    		super(_backend, _defaultOptions);
    	}
    
    	public get(url: string, options?: RequestOptionsArgs) : Observable<Response> {
    		this.incrementRequestCount();
    		var response = super.get(url, options);
    		response.subscribe(null, error => {
    			this.decrementRequestCount();
    		}, () => {
    			this.decrementRequestCount();
    		});
    		return response;
    	}
    
    	private decrementRequestCount() {
    		if (--this.currentRequests == 0) {
    			this.loadingBar.complete();
    		}
    	}
    
    	private incrementRequestCount() {
    		if (this.currentRequests++ == 0) {
    			this.loadingBar.start();
    		}
    	}
    }
    

Page: 25 of 28