Skip to content

Instantly share code, notes, and snippets.

@ognian-
ognian- / gist:c8aff5cb6d4ac9a3ceea78fd5c50bb8c
Created April 2, 2017 16:08
Converting errno to exception
#include <cerrno>
#include <system_error>
#include <type_traits>
void check_errno() {
const auto e = errno;
if (e) {
errno = 0;
throw std::system_error(e, std::system_category());
}
@ognian-
ognian- / finally
Created January 19, 2017 23:14
c++11 finally block emulation via lambda
struct finally {
inline explicit finally(const std::function<void()>& code) noexcept: m_code{code} {}
inline ~finally() noexcept { try { m_code(); } catch(...) {} }
private:
finally(const finally&) = delete;
finally(finally&&) = delete;
finally& operator=(const finally&) = delete;
finally& operator=(finally&&) = delete;
std::function<void()> m_code;
};
@ognian-
ognian- / java_InputStream_to_String
Created November 18, 2014 12:12
Convert UTF-8 InputStream to String
public static String toString(InputStream is) throws IOException {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, "UTF-8");
char[] buf = new char[512];
StringBuilder str = new StringBuilder();
int i = 0;
while ( (i = isr.read(buf)) != -1 ) str.append(buf, 0 ,i);
return str.toString();
} finally {
@ognian-
ognian- / java_LEDataInputStream
Created October 2, 2014 07:15
Little endian DataInputStream
import java.io.DataInput;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class LEDataInputStream extends FilterInputStream implements DataInput {
private final byte[] buffer = new byte[8];
@ognian-
ognian- / android_ANRDetector
Created September 12, 2014 18:46
Android: detect long blocks on the main thread, and log a stack trace. Construct the object on the main thread and check the log output. Pass the threshold to trigger a stack dump in milliseconds.
import android.os.Looper;
import android.os.MessageQueue;
import android.util.Log;
import android.util.Printer;
public class ANRDetector {
public static final String TAG = "ANRDetector";
private final Looper looper;
private final MessageQueue queue;
@ognian-
ognian- / android_getLowBatteryWarningLevel
Created September 6, 2014 12:38
Android: get battery low warning level
public static int getLowBatteryWarningLevel() {
return Resources.getSystem().getInteger(
Resources.getSystem().getIdentifier("config_lowBatteryWarningLevel", "integer", "android"));
}
@ognian-
ognian- / android_makeCircleAvatar
Created August 21, 2014 15:31
Android circle avatar image
/*
* Create a circle avatar from a Bitmap. Use in ImageView
* with setImageDrawable()
*/
public static Drawable makeCircleAvatar(Bitmap bmp) {
ShapeDrawable dr = new ShapeDrawable(new OvalShape());
dr.getPaint().setShader(new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP));
dr.setIntrinsicWidth(bmp.getWidth());
dr.setIntrinsicHeight(bmp.getHeight());
return dr;