Skip to content

Instantly share code, notes, and snippets.

View momvart's full-sized avatar

Mohammad Omidvar momvart

  • Simon Fraser University
  • BC, Canada
  • LinkedIn in/momvart
View GitHub Profile
@momvart
momvart / buggy_vec.rs
Last active September 14, 2023 18:31
An example of how unsafe Rust can cause memory deallocation bugs. A case of late `len` update and unsoundness.
#![feature(maybe_uninit_uninit_array)]
#![feature(extend_one)]
use std::mem::MaybeUninit;
fn main() {
let mut v = MyVec::new();
v.push(Box::new(DropReporter));
let mut dest = BadExtend(Default::default());
@momvart
momvart / visit.rs
Last active January 5, 2023 04:19
Inspired by the default generic rustc visitors, here are a set of visitors written for StatementKind, TerminatorKind, and Rvalue
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, Mutability};
use rustc_middle::{
mir::{
AggregateKind, AssertMessage, BasicBlock, BinOp, BorrowKind, CastKind, Coverage,
FakeReadCause, InlineAsmOperand, Local, NonDivergingIntrinsic, NullOp, Operand, Place,
RetagKind, Rvalue, StatementKind, SwitchTargets, TerminatorKind, UnOp, UserTypeProjection,
},
ty::{Const, Region, Ty, Variance},
};
use rustc_span::Span;
@momvart
momvart / ISO8601Parser.cs
Last active April 10, 2022 16:39
A set of functions to parse some data and time data expressed in ISO 8601 format for C#.
using System;
using System.Text.RegularExpressions;
namespace RBC.WorkflowEngine.Core.Utilities;
/// <summary>
/// Provides a set of functions for parsing some of date- and time-related
/// data represented in ISO 8601 formats.
/// </summary>
/// <see href="https://en.wikipedia.org/wiki/ISO_8601">
@momvart
momvart / KotlinObjectExtensions.cs
Created November 24, 2021 16:04
A set of extensions functions written on object, by default available in Kotlin, ported for c#.
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Utilities
{
public static class KotlinObjectExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Also<T>(this T callee, Action<T> action)
@momvart
momvart / ThousandSeparatorVisualTransformation.kt
Last active October 29, 2024 08:15
A VisualTransformation for inserting thousand-separator commas in TextFields inputting numbers. It also has support for fraction parts and can put limit on the number of fraction digits. #android #compose
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import java.text.DecimalFormat
import kotlin.math.min
class ThousandSeparatorVisualTransformation(
var maxFractionDigits: Int = Int.MAX_VALUE,
var minFractionDigits: Int = 0
@momvart
momvart / ObjectToInferredTypesConverter.cs
Last active February 27, 2021 20:35
A converter for `System.Text.Json` that recursively parse converts json to the inferred types. Uses `ExpandoObject` for objects.
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Dynamic;
public class ObjectToInferredTypesConverter : JsonConverter<object>
{
public override object Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) =>
@momvart
momvart / GMM.py
Created January 20, 2021 18:37
Implementation of Gaussian Mixture Models clustering using numpy and scipy.
import numpy as np
from numpy.random import choice
from numpy.linalg import norm
from scipy.stats import multivariate_normal
def train_gmm(data, k, convergence_threshold):
raw_data = data
data = pd.DataFrame(data) # Should be removed
feature_columns = data.columns
pis = np.ones((k, 1)) * 1 / k
@momvart
momvart / GoogleAuthenticatorUtils.kt
Created August 19, 2020 10:29
A helper class which can generate a URI for google authenticator.
import android.net.Uri
object GoogleAuthenticatorUtils {
enum class KeyType(val uriKey: String) {
TIME_BASED("totp"),
COUNTER_BASED("hotp")
}
//Based on https://github.com/google/google-authenticator/wiki/Key-Uri-Format
@momvart
momvart / MarginItemDecoration.kt
Last active August 19, 2020 10:37
An item decoration for recyclerview which adds margin between items.
import android.content.Context
import android.graphics.Rect
import android.util.LayoutDirection
import android.view.View
import androidx.annotation.DimenRes
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MarginItemDecoration(
private val marginLeft: Int,
@momvart
momvart / PlaceholderWithBaseline.kt
Created July 23, 2020 13:56
Add support of baseline to constraintlayout Placeholder. When you want to set baseline constraint on a Placeholder doesn't work because it doesn't support it. With this simple extension you can solve the issue.
import android.content.Context
import android.util.AttributeSet
import androidx.constraintlayout.widget.Placeholder
// You can replace it with Placeholder when you want to set layout_constraintBaseline_toBaselineOf
class PlaceholderWithBaseline @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : Placeholder(context, attrs, defStyleAttr) {
override fun getBaseline(): Int =
content.baseline