Blog

Few examples for AWK text processor.

We would like to stream multiple analogue microphone inputs through Raspberry Pi.

We have a following configuration:

  • Raspberry Pi 3B/4
  • 2 identical USB audio cards

As the Linux kernel might order the USB cards randomly during bootup, we cannot really rely on the arecord -l output. The ls -la /proc/asound/cards does not help to distinguish by device ID either.

How to identify USB sound cards to avoid this situation?

Objective

In this article, we are going to understand how to connect .NET Core Application with MySQL/MariaDB and read data from MySQL (placed in Docker container), using .NET Core MySQL connector.

How to set up VLC to play media content / stream to a different output other than the default?

We would like to stream multiple analogue microphone inputs through Raspberry Pi.

We have a following configuration:

  • Raspberry Pi 3B/4
  • 2 or more identical USB audio cards

How to create script to start HTTP streaming audio inputs when available?

Debian Linux is known for being stable and unchanging. For most, this philosophy is pretty great. Everything works well, and nothing breaks down. However, this stability comes at a cost. Often, users are stuck on an old, outdated Linux kernel.

How do I create or write to images to disk on Apple Mac OS X (macOS) Unix operating system with dd command?

You could call the TryParse method dynamically using Reflection. This way you won't get a time consuming Exception if the conversion fails.

There are some specific scenarios specially when you manipulate the DOM with ng-repeat directive. Lets imagine we have a code that prints a list of element using an ng-repeat. In your controller you have a code to instantiate a bootstrap tooltip for all the elements that are going to be rendered when the ng-repeat is compiled by AngularJs. As a best practice it is better to place this type of code in a directive, for this example purpose, we are going to keep it simple and leave it in the controller.

Yet one other thing I love about OSX is that .iso is a first-class citizen. I’m able to mount/burn iso files without installing any other software (yes, I’m looking at you Windows).

I want to do this command in one line:

git pull && [my passphrase]

How to do it?

After updating to Angular 6, I get the following error on ng serve:

Could not find module "@angular-devkit/build-angular" from "/home/Projects/myProjectName".
Error: Could not find module "@angular-devkit/build-angular" from "/home/Projects/myProjectName".
    at Object.resolve (/home/Projects/myProjectName/node_modules/@angular-devkit/core/node/resolve.js:141:11)
    at Observable.rxjs_1.Observable [as _subscribe] (/home/Projects/myProjectName/node_modules/@angular-devkit/architect/src/architect.js:132:40)

ng update says everything is in order. Deleting node_modules folder and a fresh npm install install did not help either.

Debian Linux is known for being stable and unchanging. For most, this philosophy is pretty great. Everything works well, and nothing breaks down. However, this stability comes at a cost. Often, users are stuck on an old, outdated Linux kernel.

The Raspberry Pi is a fantastic little computer for recording video. For about €50,- you can record in HD with full customizability and for as long as you want or have storage for. However, one issue is that the .h264 container it records in is hard to work with. It is therefore often important to convert videos to widely applicable formats like .mp4 to be able to view them properly and get the right meta information. For this I recommend the program FFmpeg.

Installing ffmpeg on a Raspberry Pi is not as simple as downloading an executable from the command line, but it is also not too difficult.

Is there a nice function to to turn something like

FirstName

to this:

First Name?

After my page is done loading. I want jQuery to nicely scroll to the bottom of the page, animating quickly, not a snap/jolt.

Is there a way to grab a video thumbnail in FFmpeg?

I'd like to grab the middle-most frame as the video and use that as the thumbnail. Video duration is unknown.

If I set TreeViewItem Background it highlights the header only. How can I highlight the whole line?

Nor JavaScript nor TypeScript has no equivalent for the language-integrated-natural-query aspect of LINQ. (hey, isn't that literally the whole acronym?)

A watchdog timer is a special kind of timer commonly found on embedded systems that is used to detect when the running software is hung up on some task. The watchdog timer is basically a countdown timer that counts from some initial value down to zero. When zero is reached, the watchdog timer understands that the system is hung up and resets it. Therefore, the running software must periodically update the watchdog timer with a new value to stop it from reaching zero and causing a reset. When the running software is locked up doing a certain task and cannot update the watchdog timer, the timer will inevitably reach zero and a reset will occur.

Luckily for us, the Broadcom BCM2835 SoC on the Raspberry Pi comes with a hardware-based watchdog timer that can do just that. You will find this specially useful if you have a Raspberry Pi in a remote location and the operating system hangs and there's no one around to reboot it.

Some of my docker containers use NFS mounts that are configured in /etc/fstab. During a reboot, I’ve seen my containers failing to start when docker engine is started before all the mount points are mounted. There is a relatively simple but not too obvious solution to this which involves tweaking systemd rules such as Requires and After.

I'm using logback in my current project.

It offers six levels of logging: TRACE DEBUG INFO WARN ERROR OFF

I'm looking for a rule of thumb to determine the log level for common activities. For instance, if a thread is locked, should the log message be set to the debug level or the info level. Or if a socket is being used, should its specific id be logged at the debug level or the trace level.

I will appreciate answers with more examples for each logging level.

I come from WPF and I don't know if it's possible to make a ListView to distribute items horizontally, with all the extras like mouse-wheel scrolling (mouse devices) and swiping (touch devices).

I've tried this, but it doesn't behave like the vertical one. Example: I cannot scroll with the mouse-wheel.

<ListView ScrollViewer.VerticalScrollBarVisibility="Disabled" 
 ScrollViewer.HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding Collection}" >
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"></StackPanel>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

A fellow emailed me earlier asking how to get the namespaces from an XML document, but he was having trouble because the XML had some XML declarations like <?foo?>.

I want to bind the background color of a button to an enum. I wonder if there is an enum object that can hold multiple values, for example the state and the color. I want to avoid two enums that could be out of sync. Here are two enums that I would like to integrate with each other.

enum StateValue { Player, Wall, Box }
enum StateColor { Colors.Red, Colors.Grey, Colors.Brown }

Then I need to create a binding for the XAML button.

<Button Content="Player" Background="{Binding Source=...?}" />

Maybe, a dictionary like the following is helpful. But still I do not know how the binding needs to be written.

public Dictionary<StateValue, Color> stateValueColor = 
new Dictionary<ElementState, Color>()
{
 { StateValue.Player, Colors.Red },
 { StateValue.Wall, Colors.Grey },
 { StateValue.Box, Colors.Brown }
};

I have a div box (called flux) with a variable amount of content inside. This divbox has overflow set to auto.

Now, what I am trying to do, is, when the use scroll to the bottom of this DIV-box, load more content into the page, I know how to do this (load the content) but I don't know how to detect when the user has scrolled to the bottom of the div tag? If I wanted to do it for the entire page, I'd take .scrollTop and subtract that from .height.

But I can't seem to do that here?

I've tried taking .scrollTop from flux, and then wrapping all the content inside a div called inner, but if I take the innerHeight of flux it returns 564px (the div is set to 500 as height) and the height of 'innner' it returns 1064, and the scrolltop, when at the bottom of the div says 564.

What can I do?

After connecting to the database, can I get the name of all the columns that were returned in my SqlDataReader?

I want to be able to find all parent types (base classes and interfaces) for a specific type.

E. g. if I have

class A : B, C { }
class B : D { }
interface C : E { }
class D { }
interface E { }

I want to see that A is B C D and E and Object

Whats the best way to do this? is there a reflection method to do this or do i need to make myself something.

By default, the Validation.ErrorTemplate in WPF is just a small red border without any ToolTip.

In Silverlight 4, the validation error is nicely styled out-of-the-box.

Here is a comparison of a validation error occuring in Silverlight 4 and WPF

Silverlight 4

WPF

Notice the really flat, boring look of the WPF version compared to the, in my opinion, great look in Silverlight.

Does any similar validation styles/templates exist in the WPF Framework or has anybody created nicely styled validation templates like the Silverlight version above? Or will I have to create them from scratch?

If anybody wants to try it out, the validation error above can be reproduced with the following code, works for both Silverlight and WPF

MainWindow/MainPage.xaml

<StackPanel Orientation="Horizontal" Margin="10" VerticalAlignment="Top">
    <TextBox Text="{Binding Path=TextProperty, 
           Mode=TwoWay, ValidatesOnExceptions=True}"/>
    <Button Content="Tab To Me..." Margin="20,0,0,0"/>
</StackPanel>

MainWindow/MainPage.xaml.cs

public MainWindow/MainPage()
{
    InitializeComponent();
    this.DataContext = this;
}

private string _textProperty;
public string TextProperty
{
    get { return _textProperty; }
    set
    {
        if (value.Length > 5)
        {
            throw new Exception("Too many characters");
        }
        _textProperty = value;
    }
}

I want to get the filename (without extension) and the extension separately.

The best solution I found so far is:

NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`

This is wrong because it doesn't work if the file name contains multiple . characters. If, let's say, I have a.b.js, it will consider a and b.js, instead of a.b and js.

It can be easily done in Python with

file, ext = os.path.splitext(path)

but I'd prefer not to fire up a Python interpreter just for this, if possible.

Any better ideas?

I want all characters in a TextBlock to be displayed in uppercase

<TextBlock Name="tbAbc"
       FontSize="12"
       TextAlignment="Center"
       Text="Channel Name"
       Foreground="{DynamicResource {x:Static
          r:RibbonSkinResources.RibbonGroupLabelFontColorBrushKey}}" />

The strings are taken through Binding. I don't want to make the strings uppercase in the dictionary itself.

How can I generate a random 8 character alphanumeric string in C#?

How do I get rid of all the broken symlinks I just created in a single fell swoop?

Scripts to remove unnecessary packages coming with "Recommended" bundle with Raspbian installer.

using System.Net.NetworkInformation;

public static bool PingHost(string nameOrAddress)
{
    bool pingable = false;
    Ping pinger = null;

    try
    {
        pinger = new Ping();
        PingReply reply = pinger.Send(nameOrAddress);
        pingable = reply.Status == IPStatus.Success;
    }...

Jeff Atwood posted about natural sorting. This is all about making sure that strings that contain numbers sort numerically. I’m slightly surprised to see that he wants to call it alphabetical sorting. Surely by definition, alphabetical sorting is defined by, well, the alphabet. This is an issue about numbers, not letters.

Anyway, he says he tried and gave up on a succinct C# version. He suggests that it will take 40+ lines of code. I believe that’s misleading, because as far as I can tell, the Python versions are only able to be so succinct because Python already appears to know how to sort an array. Both examples he shows rely on this. In .NET, collections aren’t intrinsically sortable.

I'm trying to bind my elements in a datatemplate that is define in dictionary. Let's make it simple.

I have a simple class

public class A { public string Data { get; set; } }

I have a simple view that contains a ListBox, with ItemSources is a list of class A:

<ListBox ItemsSource="{Binding AList}">

The point is, when I define Itemplate in view directly, bind works:

<ListBox.ItemTemplate>
   <DataTemplate >
      <TextBlock Text="{Binding Data}" />
      <Rectangle Fill="Red" Height="10" Width="10"/>
   </DataTemplate>
</ListBox.ItemTemplate>

This works great.

But when I define this ItemTemplate in ResourceDictionary, binding doesn't work?

I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program.

Is it possible to limit a text length to "n" lines using CSS (or cut it when overflows vertically)?

text-overflow: ellipsis; only works for 1 line text.

Original text

Ultrices natoque mus mattis, aliquam, cras in pellentesque tincidunt elit purus lectus, vel ut aliquet, elementum nunc nunc rhoncus placerat urna! Sit est sed! Ut penatibus turpis mus tincidunt! Dapibus sed aenean, magna sagittis, lorem velit

Wanted output (2 lines)

Ultrices natoque mus mattis, aliquam, cras in pellentesque tincidunt elit purus lectus, vel ut aliquet, elementum...

How do I construct this piece of XAML programatically?

<Grid Name="gridMarkets">
    <Grid.RowDefinitions>
        <RowDefinition Height="10" />
        <RowDefinition Height="*" MinHeight="16" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
 </Grid>

Is it any elegant solution for parse and construct controls dynamically?

I was trying to do something:

RowDefinition newRow = new RowDefinition();
newRow.Height = new GridLength(10);
newGrid.RowDefinitions.Add(newRow);

But how do I assign a * sign?

I have this code:

string m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";

XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(m_strFilePath);

foreach (XmlNode RootNode in myXmlDocument.ChildNodes)
{
}

but when I try to execute it, I get this error :

Exception Details: System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.

Why? Where am I wrong? And how can I fix this problem on C#?

Also tried with :

myXmlDocument.Load(m_strFilePath);    

but I get :

Exception Details: System.Xml.XmlException: Invalid character in the given encoding. Line 1, position 503.

I am coding a C# application where the user can specify a name and the program will return the name without the vowels. But how does the program understand that if the name contains A, E, I, O, U, Y, then the letters shall be removed.

How can you enumerate an enum in C#?

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

I am getting the k_BackingField in my returned json after serializing a xml file to a .net c# object.

I've added the DataContract and the DataMember attribute to the .net c# object but then I get nothing on the json, client end.

[XmlRoot("person")]
[Serializable]
public class LinkedIn
{
    [XmlElement("id")]
   public string ID { get; set; }

    [XmlElement("industry")]
    public string Industry { get; set; }

    [XmlElement("first-name")]
    public string FirstName { get; set; }

    [XmlElement("last-name")]
    public string LastName { get; set; }
}

Example of the returned json:

home: Object
<FirstName>k__BackingField: "Storefront"
<LastName>k__BackingField: "Doors"