static VALUE geographiclib_local_cartesian_initialize(int argc, VALUE *argv, VALUE self)
{
  GeographicLib::Math::real lat = 0.0, lon = 0.0, h = 0.0;
  switch (argc) {
  default:
    rb_raise(rb_eArgError, "Wrong number of arguments. Expecting 0, 1, 2 or 3.");
  case 3:
    h = rb_num2dbl(argv[2]);
  case 2:
    decode_lat_lon(argv[0], argv[1], lat, lon);
  case 0:
    break;
  case 1:
    rb_check_type(argv[0], T_HASH);
    decode_lat_lon(rb_hash_lookup(argv[0], rb_symbol("lat")), rb_hash_lookup(argv[0], rb_symbol("lon")), lat, lon);
    VALUE vh = rb_hash_lookup(argv[0], rb_symbol("h"));
    if (vh != Qnil) {
      h = rb_num2dbl(vh);
    }
    break;
  }
  geographiclib_local_cartesian_free(DATA_PTR(self));
  DATA_PTR(self) = new GeographicLib::LocalCartesian(lat, lon, h);
  return self;
}
static int
rb_crustache__context_get(
	crustache_var *var,
	void *ctx,
	const char *key,
	size_t key_size)
{
	VALUE rb_ctx = (VALUE)ctx;
	VALUE rb_key, rb_val;

	rb_key = rb_str_new(key, (long)key_size);
	rb_val = Qnil;

	if (TYPE(rb_ctx) == T_HASH) {
		rb_val = rb_hash_lookup(rb_ctx, rb_key);
		if (NIL_P(rb_val))
			rb_val = rb_hash_lookup(rb_ctx, rb_str_intern(rb_key));
	} else {
		ID method = rb_to_id(rb_key);

		if (rb_respond_to(rb_ctx, method))
			rb_val = rb_funcall(rb_ctx, method, 0);

		else if (rb_respond_to(rb_ctx, rb_intern("[]")))
			rb_val = rb_funcall(rb_ctx, rb_intern("[]"), 1, key);
	}

	if (NIL_P(rb_val)) /* not found */
		return -1;

	return rb_crustache__setvar(var, rb_val);
}
static VALUE geographiclib_local_cartesian_forward(int argc, VALUE *argv, VALUE self)
{
  GeographicLib::Math::real lat = 0.0, lon = 0.0, h = 0.0, x, y, z;
  switch (argc) {
  default:
    rb_raise(rb_eArgError, "Wrong number of arguments. Expecting 1, 2 or 3.");
  case 3:
    h = rb_num2dbl(argv[2]);
  case 2:
    decode_lat_lon(argv[0], argv[1], lat, lon);
    break;
  case 1:
    rb_check_type(argv[0], T_HASH);
    decode_lat_lon(rb_hash_lookup(argv[0], rb_symbol("lat")), rb_hash_lookup(argv[0], rb_symbol("lon")), lat, lon);
    VALUE vh = rb_hash_lookup(argv[0], rb_symbol("h"));
    if (vh != Qnil) {
      h = rb_num2dbl(vh);
    }
    break;
  }
  GeographicLib::LocalCartesian *lc = geographiclib_local_cartesian_get(self);
  lc->Forward(lat, lon, h, x, y, z);
  VALUE r = rb_hash_new();
  rb_hash_aset(r, rb_symbol("x"), rb_float_new(x));
  rb_hash_aset(r, rb_symbol("y"), rb_float_new(y));
  rb_hash_aset(r, rb_symbol("z"), rb_float_new(z));
  return r;
}
static VALUE geographiclib_local_cartesian_reverse(int argc, VALUE *argv, VALUE self)
{
  GeographicLib::Math::real lat, lon, h, x, y, z = 0.0;
  switch (argc) {
  default:
    rb_raise(rb_eArgError, "Wrong number of arguments. Expecting 1 or 3.");
  case 3:
    x = rb_num2dbl(argv[0]);
    y = rb_num2dbl(argv[1]);
    z = rb_num2dbl(argv[2]);
    break;
  case 1:
    rb_check_type(argv[0], T_HASH);
    x = rb_num2dbl(rb_hash_lookup(argv[0], rb_symbol("x")));
    y = rb_num2dbl(rb_hash_lookup(argv[0], rb_symbol("y")));
    z = rb_num2dbl(rb_hash_lookup(argv[0], rb_symbol("z")));
    break;
  }
  GeographicLib::LocalCartesian *lc = geographiclib_local_cartesian_get(self);
  lc->Reverse(x, y, z, lat, lon, h);
  VALUE r = rb_hash_new();
  rb_hash_aset(r, rb_symbol("lat"), rb_float_new(lat));
  rb_hash_aset(r, rb_symbol("lon"), rb_float_new(lon));
  rb_hash_aset(r, rb_symbol("h"), rb_float_new(h));
  return r;
}
Exemple #5
0
static void
parse_options(VALUE ropts, Options copts) {
    struct _YesNoOpt    ynos[] = {
        { circular_sym, &copts->circular },
        { auto_define_sym, &copts->auto_define },
        { symbol_keys_sym, &copts->sym_key },
        { ascii_only_sym, &copts->ascii_only },
        { Qnil, 0 }
    };
    YesNoOpt    o;
    
    if (rb_cHash == rb_obj_class(ropts)) {
        VALUE   v;
        
        if (Qnil != (v = rb_hash_lookup(ropts, indent_sym))) {
            if (rb_cFixnum != rb_obj_class(v)) {
                rb_raise(rb_eArgError, ":indent must be a Fixnum.\n");
            }
            copts->indent = NUM2INT(v);
        }
#ifdef HAVE_RUBY_ENCODING_H
        if (Qnil != (v = rb_hash_lookup(ropts, encoding_sym))) {
	    if (T_STRING == rb_type(v)) {
		oj_default_options.encoding = rb_enc_find(StringValuePtr(v));
	    } else if (rb_cEncoding == rb_obj_class(v)) {
		oj_default_options.encoding = rb_to_encoding(v);
	    } else {
		rb_raise(rb_eArgError, ":encoding must be nil, a String, or an Encoding.\n");
	    }
        }
#endif
        if (Qnil != (v = rb_hash_lookup(ropts, mode_sym))) {
            if (object_sym == v) {
                copts->mode = ObjectMode;
            } else if (strict_sym == v) {
                copts->mode = StrictMode;
            } else if (compat_sym == v) {
                copts->mode = CompatMode;
            } else if (null_sym == v) {
                copts->mode = NullMode;
            } else {
                rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.\n");
            }
        }
        for (o = ynos; 0 != o->attr; o++) {
            if (Qnil != (v = rb_hash_lookup(ropts, o->sym))) {
                if (Qtrue == v) {
                    *o->attr = Yes;
                } else if (Qfalse == v) {
                    *o->attr = No;
                } else {
                    rb_raise(rb_eArgError, "%s must be true or false.\n", rb_id2name(SYM2ID(o->sym)));
                }
            }
        }
    }
 }
Exemple #6
0
/*
 * call-seq:
 *   CvCapture.open(<i>[dev = -1]</i>)
 *
 * Reading video stream from the specified file or camera device.
 * If <i>dev</i> is string (i.e "stream.avi"), reading video stream from file.
 * If <i>dev</i> is number or symbol(include CvCapture::INTERFACE),
 * reading video stream from camera. 
 * Currently two camera interfaces can be used on Windows:
 * * Video for Windows(VFW)
 * * Matrox Imaging Library(MIL)
 * and two on Linux
 * * V4L
 * * FireWire(IEEE1394).
 * If there is only one camera or it does not matter what camera to use <i>nil</i> may be passed.
 */
VALUE
rb_open(int argc, VALUE *argv, VALUE self)
{
  VALUE device;
  rb_scan_args(argc, argv, "01", &device);
  CvCapture *capture = 0;
  try {
    switch (TYPE(device)) {
    case T_STRING:
      capture = cvCaptureFromFile(StringValueCStr(device));
      break;
    case T_FIXNUM:
      capture = cvCaptureFromCAM(FIX2INT(device));
      break;
    case T_SYMBOL: {
      VALUE cap_index = rb_hash_lookup(rb_const_get(rb_class(), rb_intern("INTERFACE")), device);
      if (NIL_P(cap_index))
        rb_raise(rb_eArgError, "undefined interface.");
      capture = cvCaptureFromCAM(NUM2INT(cap_index));
      break;
    }
    case T_NIL:
      capture = cvCaptureFromCAM(CV_CAP_ANY);
      break;
    }
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }
  if (!capture)
    rb_raise(rb_eStandardError, "Invalid capture format.");
  return Data_Wrap_Struct(rb_klass, 0, cvcapture_free, capture);
}
Exemple #7
0
/* Internal implementation of register after acquiring mutex */
static VALUE NIO_Selector_register_synchronized(VALUE *args)
{
    VALUE self, io, interests, selectables, monitor;
    VALUE monitor_args[3];
    struct NIO_Selector *selector;

    self = args[0];
    io = args[1];
    interests = args[2];

    Data_Get_Struct(self, struct NIO_Selector, selector);
    if(selector->closed) {
        rb_raise(rb_eIOError, "selector is closed");
    }

    selectables = rb_ivar_get(self, rb_intern("selectables"));
    monitor = rb_hash_lookup(selectables, io);

    if(monitor != Qnil)
        rb_raise(rb_eArgError, "this IO is already registered with selector");

    /* Create a new NIO::Monitor */
    monitor_args[0] = io;
    monitor_args[1] = interests;
    monitor_args[2] = self;

    monitor = rb_class_new_instance(3, monitor_args, cNIO_Monitor);
    rb_hash_aset(selectables, rb_funcall(monitor, rb_intern("io"), 0), monitor);

    return monitor;
}
Exemple #8
0
static void
reachable_object_from_root_i(const char *category, VALUE obj, void *ptr)
{
    struct rofr_data *data = (struct rofr_data *)ptr;
    VALUE category_str;
    VALUE category_objects;

    if (category == data->last_category) {
        category_str = data->last_category_str;
        category_objects = data->last_category_objects;
    }
    else {
        data->last_category = category;
        category_str = data->last_category_str = rb_str_new2(category);
        category_objects = data->last_category_objects = rb_hash_new();
        rb_funcall(category_objects, rb_intern("compare_by_identity"), 0);
        if (!NIL_P(rb_hash_lookup(data->categories, category_str))) {
            rb_bug("reachable_object_from_root_i: category should insert at once");
        }
        rb_hash_aset(data->categories, category_str, category_objects);
    }

    if (rb_objspace_markable_object_p(obj) &&
            obj != data->categories &&
            obj != data->last_category_objects) {
        if (rb_objspace_internal_object_p(obj)) {
            obj = iow_newobj(obj);
        }
        rb_hash_aset(category_objects, obj, obj);
    }
}
Exemple #9
0
/*
 * Create font object
 * @overload new(face, font_option = nil)
 * @param face [Symbol] Font name identifier. Only a subset of Hershey fonts (http://sources.isc.org/utils/misc/hershey-font.txt) are supported now:
 *   - :simplex - normal size sans-serif font
 *   - :plain - small size sans-serif font
 *   - :duplex - normal size sans-serif font (more complex than :simplex)
 *   - :complex - normal size serif font
 *   - :triplex - normal size serif font (more complex than :complex)
 *   - :complex_small - smaller version of :complex
 *   - :script_simplex - hand-writing style font
 *   - :script_complex - more complex variant of :script_simplex
 *
 * @param font_option [Hash] should be Hash include these keys.
 * @option font_option [Number] :hscale Horizontal scale. If equal to 1.0, the characters have the original width depending on the font type. If equal to 0.5, the characters are of half the original width.
 * @option font_option [Number] :vscale Vertical scale. If equal to 1.0, the characters have the original height depending on the font type. If equal to 0.5, the characters are of half the original height.
 * @option font_option [Number] :shear Approximate tangent of the character slope relative to the vertical line. Zero value means a non-italic font, 1.0f means ~45 degree slope, etc.
 * @option font_option [Number] :thickness Thickness of the text strokes.
 * @option font_option [Number] :line_type Type of the strokes, see CvMat#Line description.
 * @option font_option [Number] :italic If value is not nil or false that means italic or oblique font.
 *
 * @example Create Font
 *   OpenCV::CvFont.new(:simplex, :hscale => 2, :vslace => 2, :italic => true)
 *   # create 2x bigger than normal, italic type font.
 *
 * @opencv_func cvInitFont
 */
VALUE
rb_initialize(int argc, VALUE *argv, VALUE self)
{
  VALUE face, font_option;
  rb_scan_args(argc, argv, "11", &face, &font_option);
  Check_Type(face, T_SYMBOL);
  face = rb_hash_lookup(rb_const_get(cCvFont::rb_class(), rb_intern("FACE")), face);
  if (NIL_P(face)) {
    rb_raise(rb_eArgError, "undefined face.");
  }
  font_option = FONT_OPTION(font_option);

  int font_face = NUM2INT(face);
  if (FO_ITALIC(font_option)) {
    font_face |= CV_FONT_ITALIC;
  }
  try {
    cvInitFont(CVFONT(self),
	       font_face,
	       FO_HSCALE(font_option),
	       FO_VSCALE(font_option),
	       FO_SHEAR(font_option),
	       FO_THICKNESS(font_option),
	       FO_LINE_TYPE(font_option));
  }
  catch (cv::Exception& e) {
    raise_cverror(e);
  }

  return self;
}
Exemple #10
0
int
rbffi_type_size(VALUE type)
{
    int t = TYPE(type);
    
    if (t == T_FIXNUM || t == T_BIGNUM) {
        return NUM2INT(type);
    
    } else if (t == T_SYMBOL) {
        /*
         * Try looking up directly in the type and size maps
         */
        VALUE nType;
        if ((nType = rb_hash_lookup(typeMap, type)) != Qnil) {
            if (rb_obj_is_kind_of(nType, rbffi_TypeClass)) {
                Type* type;
                Data_Get_Struct(nType, Type, type);
                return (int) type->ffiType->size;
            
            } else if (rb_respond_to(nType, id_size)) {
                return NUM2INT(rb_funcall2(nType, id_size, 0, NULL));
            }
        }

        // Not found - call up to the ruby version to resolve
        return NUM2INT(rb_funcall2(rbffi_FFIModule, id_type_size, 1, &type));
    
    } else {
        return NUM2INT(rb_funcall2(type, id_size, 0, NULL));
    }
}
Exemple #11
0
/*
  Return code page number of the encoding.
  Cache code page into a hash for performance since finding the code page in
  Encoding#names is slow.
*/
static UINT
code_page(rb_encoding *enc)
{
    VALUE code_page_value, name_key;
    VALUE encoding, names_ary = Qundef, name;
    char *enc_name;
    struct RString fake_str;
    ID names;
    long i;

    if (!enc)
	return system_code_page();

    enc_name = (char *)rb_enc_name(enc);

    fake_str.basic.flags = T_STRING|RSTRING_NOEMBED;
    fake_str.basic.klass = rb_cString;
    fake_str.as.heap.len = strlen(enc_name);
    fake_str.as.heap.ptr = enc_name;
    fake_str.as.heap.aux.capa = fake_str.as.heap.len;
    name_key = (VALUE)&fake_str;
    ENCODING_CODERANGE_SET(name_key, rb_usascii_encindex(), ENC_CODERANGE_7BIT);

    code_page_value = rb_hash_lookup(rb_code_page, name_key);
    if (code_page_value != Qnil)
	return (UINT)FIX2INT(code_page_value);

    name_key = rb_usascii_str_new2(enc_name);

    encoding = rb_enc_from_encoding(enc);
    if (!NIL_P(encoding)) {
	CONST_ID(names, "names");
	names_ary = rb_funcall(encoding, names, 0);
    }

    /* map US-ASCII and ASCII-8bit as code page 1252 (us-ascii) */
    if (enc == rb_usascii_encoding() || enc == rb_ascii8bit_encoding()) {
	UINT code_page = 1252;
	rb_hash_aset(rb_code_page, name_key, INT2FIX(code_page));
	return code_page;
    }

    if (names_ary != Qundef) {
	for (i = 0; i < RARRAY_LEN(names_ary); i++) {
	    name = RARRAY_PTR(names_ary)[i];
	    if (strncmp("CP", RSTRING_PTR(name), 2) == 0) {
		int code_page = atoi(RSTRING_PTR(name) + 2);
		if (code_page != 0) {
		    rb_hash_aset(rb_code_page, name_key, INT2FIX(code_page));
		    return (UINT)code_page;
		}
	    }
	}
    }

    rb_hash_aset(rb_code_page, name_key, INT2FIX(INVALID_CODE_PAGE));
    return INVALID_CODE_PAGE;
}
Exemple #12
0
/*
  Return code page number of the encoding.
  Cache code page into a hash for performance since finding the code page in
  Encoding#names is slow.
*/
static UINT
fenix_code_page(rb_encoding *enc)
{
	VALUE code_page_value, name_key;
	VALUE encoding, names_ary = Qundef, name;
	char *enc_name;
	struct RString fake_str;
	ID names;
	long i;

	if (!enc)
		return system_code_page();

	enc_name = (char *)rb_enc_name(enc);

	fake_str.basic.flags = T_STRING|RSTRING_NOEMBED;
	fake_str.basic.klass = rb_cString;
	fake_str.as.heap.len = strlen(enc_name);
	fake_str.as.heap.ptr = enc_name;
	fake_str.as.heap.aux.capa = fake_str.as.heap.len;
	name_key = (VALUE)&fake_str;
	ENCODING_CODERANGE_SET(name_key, rb_usascii_encindex(), ENC_CODERANGE_7BIT);
	OBJ_FREEZE(name_key);

	code_page_value = rb_hash_lookup(rb_code_page, name_key);
	if (code_page_value != Qnil) {
		// printf("cached code page: %i\n", FIX2INT(code_page_value));
		if (FIX2INT(code_page_value) == -1) {
			return system_code_page();
		} else {
			return (UINT)FIX2INT(code_page_value);
		}
	}

	name_key = rb_usascii_str_new2(enc_name);

	encoding = rb_enc_from_encoding(enc);
	if (!NIL_P(encoding)) {
		CONST_ID(names, "names");
		names_ary = rb_funcall(encoding, names, 0);
	}

	if (names_ary != Qundef) {
		for (i = 0; i < RARRAY_LEN(names_ary); i++) {
			name = RARRAY_PTR(names_ary)[i];
			if (strncmp("CP", RSTRING_PTR(name), 2) == 0) {
				int code_page = atoi(RSTRING_PTR(name) + 2);
				rb_hash_aset(rb_code_page, name_key, INT2FIX(code_page));
				return (UINT)code_page;
			}
		}
	}

	rb_hash_aset(rb_code_page, name_key, INT2FIX(-1));
	return system_code_page();
}
Exemple #13
0
bool
tr_table_lookup(struct tr_table *table, uint32_t c)
{
        if (c < lengthof(table->continuous))
                return table->continuous[c];

        VALUE value = NIL_P(table->sparse) ?
                Qnil : rb_hash_lookup(table->sparse, UINT2NUM(c));

        return NIL_P(value) ? table->exclude : RTEST(value);
}
Exemple #14
0
static VALUE
get_media(VALUE self, VALUE media)
{
    if (TYPE(media) == T_HASH) {
        if (NIL_P(rb_hash_lookup(media, ID2SYM(id_core))))
            rb_hash_aset(media, ID2SYM(id_core), rg_core(self));
        return rb_funcall(GTYPE2CLASS(VLC_TYPE_MEDIA), rb_intern("new"), 1, media);
    } else {
        return media;
    }
}
Exemple #15
0
static void rb_redcarpet_md_flags(VALUE hash, unsigned int *enabled_extensions_p)
{
	unsigned int extensions = 0;

	/**
	 * Markdown extensions -- all disabled by default
	 */
	if (rb_hash_lookup(hash, CSTR2SYM("no_intra_emphasis")) == Qtrue)
		extensions |= MKDEXT_NO_INTRA_EMPHASIS;

	if (rb_hash_lookup(hash, CSTR2SYM("no_underscore_emphasis")) == Qtrue)
		extensions |= MKDEXT_NO_UNDERSCORE_EMPHASIS;

	if (rb_hash_lookup(hash, CSTR2SYM("tables")) == Qtrue)
		extensions |= MKDEXT_TABLES;

	if (rb_hash_lookup(hash, CSTR2SYM("fenced_code_blocks")) == Qtrue)
		extensions |= MKDEXT_FENCED_CODE;

	if (rb_hash_lookup(hash, CSTR2SYM("autolink")) == Qtrue)
		extensions |= MKDEXT_AUTOLINK;

	if (rb_hash_lookup(hash, CSTR2SYM("strikethrough")) == Qtrue)
		extensions |= MKDEXT_STRIKETHROUGH;

	if (rb_hash_lookup(hash, CSTR2SYM("spoiler")) == Qtrue)
		extensions |= MKDEXT_SPOILER;

	if (rb_hash_lookup(hash, CSTR2SYM("lax_html_blocks")) == Qtrue)
		extensions |= MKDEXT_LAX_HTML_BLOCKS;

	if (rb_hash_lookup(hash, CSTR2SYM("space_after_headers")) == Qtrue)
		extensions |= MKDEXT_SPACE_HEADERS;

	if (rb_hash_lookup(hash, CSTR2SYM("superscript")) == Qtrue)
		extensions |= MKDEXT_SUPERSCRIPT;

	*enabled_extensions_p = extensions;
}
Exemple #16
0
static VALUE
rhash_create(VALUE klass, SEL sel, int argc, VALUE *argv)
{
    if (argc == 1) {
	VALUE tmp = rhash_try_convert(Qnil, 0, argv[0]);
	if (!NIL_P(tmp)) {
	    VALUE hash = rhash_alloc(klass, 0);
	    if (IS_RHASH(tmp)) {
		GC_WB(&RHASH(hash)->tbl, st_copy(RHASH(tmp)->tbl));
	    }
	    else {
		VALUE keys = rb_hash_keys(tmp);
		for (long i = 0, count = RARRAY_LEN(keys); i < count; i++) {
		    VALUE key = RARRAY_AT(keys, i);
		    VALUE val = rb_hash_lookup(tmp, key);
		    rhash_aset(hash, 0, key, val);  
		}
	    }
	    return hash;
	}

	tmp = rb_check_array_type(argv[0]);
	if (!NIL_P(tmp)) {
	    VALUE hash = rhash_alloc(klass, 0);
	    for (int i = 0; i < RARRAY_LEN(tmp); ++i) {
		VALUE v = rb_check_array_type(RARRAY_AT(tmp, i));
		if (NIL_P(v)) {
		    continue;
		}
		const long len = RARRAY_LEN(v);
		if (len < 1 || 2 < len) {
		    continue;
		}
		rhash_aset(hash, 0, RARRAY_AT(v, 0), RARRAY_AT(v, 1));
	    }
	    return hash;
	}
    }
    if (argc % 2 != 0) {
	rb_raise(rb_eArgError, "odd number of arguments for Hash");
    }

    VALUE hash = rhash_alloc(klass, 0);
    for (int i = 0; i < argc; i += 2) {
        rb_hash_aset(hash, argv[i], argv[i + 1]);
    }

    return hash;
}
Exemple #17
0
static int st_AND_hash(st_data_t key, st_data_t value, VALUE hash)
{
	struct listen_stats *stats = (struct listen_stats *)value;

	if (stats->listener_p) {
		VALUE k = rb_str_new2((const char *)key);

		if (rb_hash_lookup(hash, k) == Qtrue) {
			VALUE v = rb_listen_stats(stats);
			OBJ_FREEZE(k);
			rb_hash_aset(hash, k, v);
		}
	}
	return st_free_data(key, value, 0);
}
Exemple #18
0
VALUE
rbffi_Type_Lookup(VALUE name)
{
    int t = TYPE(name);
    if (t == T_SYMBOL || t == T_STRING) {
        /*
         * Try looking up directly in the type Map
         */
        VALUE nType;
        if ((nType = rb_hash_lookup(typeMap, name)) != Qnil && rb_obj_is_kind_of(nType, rbffi_TypeClass)) {
            return nType;
        }
    } else if (rb_obj_is_kind_of(name, rbffi_TypeClass)) {
    
        return name;
    }

    /* Nothing found - let caller handle raising exceptions */
    return Qnil;
}
static VALUE
lfp_svar_get(rb_thread_t *th, VALUE *lfp, VALUE key)
{
    NODE *svar = lfp_svar_place(th, lfp);

    switch (key) {
      case 0:
	return svar->u1.value;
      case 1:
	return svar->u2.value;
      default: {
	const VALUE hash = svar->u3.value;

	if (hash == Qnil) {
	    return Qnil;
	}
	else {
	    return rb_hash_lookup(hash, key);
	}
      }
    }
}
Exemple #20
0
static void rb_redcarpet_md_flags(VALUE hash, unsigned int *enabled_extensions_p)
{
	unsigned int extensions = 0;

	Check_Type(hash, T_HASH);

	/**
	 * Markdown extensions -- all disabled by default
	 */
	if (rb_hash_lookup(hash, CSTR2SYM("no_intra_emphasis")) == Qtrue)
		extensions |= MKDEXT_NO_INTRA_EMPHASIS;

	if (rb_hash_lookup(hash, CSTR2SYM("tables")) == Qtrue)
		extensions |= MKDEXT_TABLES;

	if (rb_hash_lookup(hash, CSTR2SYM("fenced_code_blocks")) == Qtrue)
		extensions |= MKDEXT_FENCED_CODE;

	if (rb_hash_lookup(hash, CSTR2SYM("disable_indented_code_blocks")) == Qtrue)
		extensions |= MKDEXT_DISABLE_INDENTED_CODE;

	if (rb_hash_lookup(hash, CSTR2SYM("autolink")) == Qtrue)
		extensions |= MKDEXT_AUTOLINK;

	if (rb_hash_lookup(hash, CSTR2SYM("strikethrough")) == Qtrue)
		extensions |= MKDEXT_STRIKETHROUGH;

	if (rb_hash_lookup(hash, CSTR2SYM("underline")) == Qtrue)
		extensions |= MKDEXT_UNDERLINE;

	if (rb_hash_lookup(hash, CSTR2SYM("highlight")) == Qtrue)
		extensions |= MKDEXT_HIGHLIGHT;

	if (rb_hash_lookup(hash, CSTR2SYM("quote")) == Qtrue)
		extensions |= MKDEXT_QUOTE;

	if (rb_hash_lookup(hash, CSTR2SYM("lax_spacing")) == Qtrue)
		extensions |= MKDEXT_LAX_SPACING;

	if (rb_hash_lookup(hash, CSTR2SYM("space_after_headers")) == Qtrue)
		extensions |= MKDEXT_SPACE_HEADERS;

	if (rb_hash_lookup(hash, CSTR2SYM("superscript")) == Qtrue)
		extensions |= MKDEXT_SUPERSCRIPT;

	if (rb_hash_lookup(hash, CSTR2SYM("footnotes")) == Qtrue)
		extensions |= MKDEXT_FOOTNOTES;

	*enabled_extensions_p = extensions;
}
Exemple #21
0
Fichier : oj.c Projet : sadiqj/oj
/* call-seq: default_options=(opts)
 *
 * Sets the default options for load and dump.
 * @param [Hash] opts options to change
 * @param [Fixnum] :indent number of spaces to indent each element in an JSON document
 * @param [true|false|nil] :circular support circular references while dumping
 * @param [true|false|nil] :auto_define automatically define classes if they do not exist
 * @param [true|false|nil] :symbol_keys convert hash keys to symbols
 * @param [true|false|nil] :class_cache cache classes for faster parsing
 * @param [true|false|nil] :ascii_only encode all high-bit characters as escaped sequences if true
 * @param [true|false|nil] :bigdecimal_as_decimal dump BigDecimal as a decimal number or as a String
 * @param [true|false|nil] :bigdecimal_load load decimals as a BigDecimal instead of as a Float
 * @param [:object|:strict|:compat|:null] load and dump mode to use for JSON
 *	  :strict raises an exception when a non-supported Object is
 *	  encountered. :compat attempts to extract variable values from an
 *	  Object using to_json() or to_hash() then it walks the Object's
 *	  variables if neither is found. The :object mode ignores to_hash()
 *	  and to_json() methods and encodes variables using code internal to
 *	  the Oj gem. The :null mode ignores non-supported Objects and
 *	  replaces them with a null.
 * @param [:unix|:xmlschema|:ruby] time format when dumping in :compat mode
 *        :unix decimal number denoting the number of seconds since 1/1/1970,
 *        :xmlschema date-time format taken from XML Schema as a String,
 *        :ruby Time.to_s formatted String
 * @param [String|nil] :create_id create id for json compatible object encoding
 * @param [Fixnum|nil] :second_precision number of digits after the decimal when dumping the seconds portion of time
 * @return [nil]
 */
static VALUE
set_def_opts(VALUE self, VALUE opts) {
    struct _YesNoOpt	ynos[] = {
	{ circular_sym, &oj_default_options.circular },
	{ auto_define_sym, &oj_default_options.auto_define },
	{ symbol_keys_sym, &oj_default_options.sym_key },
	{ class_cache_sym, &oj_default_options.class_cache },
	{ ascii_only_sym, &oj_default_options.ascii_only },
	{ bigdecimal_as_decimal_sym, &oj_default_options.bigdec_as_num },
	{ bigdecimal_load_sym, &oj_default_options.bigdec_load },
	{ Qnil, 0 }
    };
    YesNoOpt	o;
    VALUE	v;
    
    Check_Type(opts, T_HASH);
    v = rb_hash_aref(opts, indent_sym);
    if (Qnil != v) {
	Check_Type(v, T_FIXNUM);
	oj_default_options.indent = FIX2INT(v);
    }
    v = rb_hash_aref(opts, sec_prec_sym);
    if (Qnil != v) {
	int	n;

	Check_Type(v, T_FIXNUM);
	n = FIX2INT(v);
	if (0 > n) {
	    n = 0;
	} else if (9 < n) {
	    n = 9;
	}
	oj_default_options.sec_prec = n;
    }

    v = rb_hash_lookup(opts, mode_sym);
    if (Qnil == v) {
	// ignore
    } else if (object_sym == v) {
	oj_default_options.mode = ObjectMode;
    } else if (strict_sym == v) {
	oj_default_options.mode = StrictMode;
    } else if (compat_sym == v) {
	oj_default_options.mode = CompatMode;
    } else if (null_sym == v) {
	oj_default_options.mode = NullMode;
    } else {
	rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.");
    }

    v = rb_hash_lookup(opts, time_format_sym);
    if (Qnil == v) {
	// ignore
    } else if (unix_sym == v) {
	oj_default_options.time_format = UnixTime;
    } else if (xmlschema_sym == v) {
	oj_default_options.time_format = XmlTime;
    } else if (ruby_sym == v) {
	oj_default_options.time_format = RubyTime;
    } else {
	rb_raise(rb_eArgError, ":time_format must be :unix, :xmlschema, or :ruby.");
    }

    if (Qtrue == rb_funcall(opts, rb_intern("has_key?"), 1, create_id_sym)) {
	if (0 != oj_default_options.create_id) {
	    if (json_class != oj_default_options.create_id) {
		xfree((char*)oj_default_options.create_id);
	    }
	    oj_default_options.create_id = 0;
	    oj_default_options.create_id_len = 0;
	}
	v = rb_hash_lookup(opts, create_id_sym);
	if (Qnil != v) {
	    size_t	len = RSTRING_LEN(v) + 1;

	    oj_default_options.create_id = ALLOC_N(char, len);
	    strcpy((char*)oj_default_options.create_id, StringValuePtr(v));
	    oj_default_options.create_id_len = len - 1;
	}
    }
Exemple #22
0
/* call-seq: default_options=(opts)
 *
 * Sets the default options for load and dump.
 * @param [Hash] opts options to change
 * @param [Fixnum] :indent number of spaces to indent each element in an JSON document
 * @param [String] :encoding character encoding for the JSON file
 * @param [true|false|nil] :circular support circular references while dumping
 * @param [true|false|nil] :auto_define automatically define classes if they do not exist
 * @param [true|false|nil] :symbol_keys convert hash keys to symbols
 * @param [true|false|nil] :ascii_only encode all high-bit characters as escaped sequences if true
 * @param [:object|:strict|:compat|:null] load and dump mode to use for JSON
 *        :strict raises an exception when a non-supported Object is
 *        encountered. :compat attempts to extract variable values from an
 *        Object using to_json() or to_hash() then it walks the Object's
 *        variables if neither is found. The :object mode ignores to_hash()
 *        and to_json() methods and encodes variables using code internal to
 *        the Oj gem. The :null mode ignores non-supported Objects and
 *        replaces them with a null.  @return [nil]
 */
static VALUE
set_def_opts(VALUE self, VALUE opts) {
    struct _YesNoOpt    ynos[] = {
        { circular_sym, &oj_default_options.circular },
        { auto_define_sym, &oj_default_options.auto_define },
        { symbol_keys_sym, &oj_default_options.sym_key },
        { ascii_only_sym, &oj_default_options.ascii_only },
        { Qnil, 0 }
    };
    YesNoOpt    o;
    VALUE       v;
    
    Check_Type(opts, T_HASH);

#ifdef HAVE_RUBY_ENCODING_H
    if (Qtrue == rb_funcall(opts, rb_intern("has_key?"), 1, encoding_sym)) {
	v = rb_hash_lookup(opts, encoding_sym);
	if (Qnil == v) {
	    oj_default_options.encoding = 0;
	} else if (T_STRING == rb_type(v)) {
	    oj_default_options.encoding = rb_enc_find(StringValuePtr(v));
	} else if (rb_cEncoding == rb_obj_class(v)) {
	    oj_default_options.encoding = rb_to_encoding(v);
	} else {
	    rb_raise(rb_eArgError, ":encoding must be nil, a String, or an Encoding.\n");
	}
    }
#endif
    v = rb_hash_aref(opts, indent_sym);
    if (Qnil != v) {
        Check_Type(v, T_FIXNUM);
        oj_default_options.indent = FIX2INT(v);
    }

    v = rb_hash_lookup(opts, mode_sym);
    if (Qnil == v) {
	// ignore
    } else if (object_sym == v) {
        oj_default_options.mode = ObjectMode;
    } else if (strict_sym == v) {
        oj_default_options.mode = StrictMode;
    } else if (compat_sym == v) {
        oj_default_options.mode = CompatMode;
    } else if (null_sym == v) {
        oj_default_options.mode = NullMode;
    } else {
        rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.\n");
    }

    for (o = ynos; 0 != o->attr; o++) {
	if (Qtrue != rb_funcall(opts, rb_intern("has_key?"), 1, o->sym)) {
	    continue;
	}
        if (Qnil != (v = rb_hash_lookup(opts, o->sym))) {
	    if (Qtrue == v) {
		*o->attr = Yes;
	    } else if (Qfalse == v) {
		*o->attr = No;
	    } else {
		rb_raise(rb_eArgError, "%s must be true, false, or nil.\n", rb_id2name(SYM2ID(o->sym)));
	    }
	}
    }
    return Qnil;
}
Exemple #23
0
/* call-seq:
 *    PixelPi::Leds.new( length, gpio, options = {} )
 *
 * Create a new PixelPi::Leds instance that can be used to control a string of
 * NeoPixels from a RaspberryPi. The length of the pixel string must be given as
 * well as the GPIO pin number used to control the string. The remaining options
 * have sensible defaults.
 *
 * length  - the nubmer of leds in the string
 * gpio    - the GPIO pin number
 * options - Hash of arguments
 *   :dma        - DMA channel defaults to 5
 *   :frequency  - output frequency defaults to 800,000 Hz
 *   :invert     - defaults to `false`
 *   :brightness - defaults to 255
 */
static VALUE
pp_leds_initialize( int argc, VALUE* argv, VALUE self )
{
  ws2811_t *ledstring;
  VALUE length, gpio, opts, tmp;
  int resp;

  if (TYPE(self) != T_DATA
  ||  RDATA(self)->dfree != (RUBY_DATA_FUNC) pp_leds_free) {
    rb_raise( rb_eTypeError, "expecting a PixelPi::Leds object" );
  }
  Data_Get_Struct( self, ws2811_t, ledstring );

  /* parse out the length, gpio, and optional arguments if given */
  rb_scan_args( argc, argv, "21", &length, &gpio, &opts );

  /* get the number of pixels */
  if (TYPE(length) == T_FIXNUM) {
    ledstring->channel[0].count = FIX2INT(length);
    if (ledstring->channel[0].count < 0) {
      rb_raise( rb_eArgError, "length cannot be negative: %d", ledstring->channel[0].count );
    }
  } else {
    rb_raise( rb_eTypeError, "length must be a number: %s", rb_obj_classname(length) );
  }

  /* get the GPIO number */
  if (TYPE(gpio) == T_FIXNUM) {
    ledstring->channel[0].gpionum = FIX2INT(gpio);
    if (ledstring->channel[0].gpionum < 0) {
      rb_raise( rb_eArgError, "GPIO cannot be negative: %d", ledstring->channel[0].gpionum );
    }
  } else {
    rb_raise( rb_eTypeError, "GPIO must be a number: %s", rb_obj_classname(gpio) );
  }

  if (!NIL_P(opts)) {
    Check_Type( opts, T_HASH );

    /* get the DMA channel */
    tmp = rb_hash_lookup( opts, sym_dma );
    if (!NIL_P(tmp)) {
      if (TYPE(tmp) == T_FIXNUM) {
        ledstring->dmanum = FIX2INT(tmp);
        if (ledstring->dmanum < 0) {
          rb_raise( rb_eArgError, "DMA channel cannot be negative: %d", ledstring->dmanum );
        }
      } else {
        rb_raise( rb_eTypeError, "DMA channel must be a number: %s", rb_obj_classname(tmp) );
      }
    }

    /* get the frequency */
    tmp = rb_hash_lookup( opts, sym_frequency );
    if (!NIL_P(tmp)) {
      if (TYPE(tmp) == T_FIXNUM) {
        ledstring->freq = FIX2UINT(tmp);
      } else {
        rb_raise( rb_eTypeError, "frequency must be a number: %s", rb_obj_classname(tmp) );
      }
    }

    /* get the brightness */
    tmp = rb_hash_lookup( opts, sym_brightness );
    if (!NIL_P(tmp)) {
      if (TYPE(tmp) == T_FIXNUM) {
        ledstring->channel[0].brightness = (FIX2UINT(tmp) & 0xff);
        if (ledstring->channel[0].brightness < 0) {
          rb_raise( rb_eArgError, "brightness cannot be negative: %d", ledstring->channel[0].brightness );
        }
      } else {
        rb_raise( rb_eTypeError, "brightness must be a number: %s", rb_obj_classname(tmp) );
      }
    }

    /* get the invert flag */
    tmp = rb_hash_lookup( opts, sym_invert );
    if (!NIL_P(tmp)) {
      if (RTEST(tmp)) ledstring->channel[0].invert = 1;
      else            ledstring->channel[0].invert = 0;
    }
  }

  /* initialize the DMA and PWM cycle */
  resp = ws2811_init( ledstring );
  if (resp < 0) {
    rb_raise( ePixelPiError, "Leds could not be initialized: %d", resp );
  }

  return self;
}
Exemple #24
0
VALUE hash_spec_rb_hash_lookup(VALUE self, VALUE hash, VALUE key) {
  return rb_hash_lookup(hash, key);
}
Exemple #25
0
VALUE hash_spec_rb_hash_lookup_nil(VALUE self, VALUE hash, VALUE key) {
  VALUE ret = rb_hash_lookup(hash, key);
  return ret == Qnil ? Qtrue : Qfalse;
}
Exemple #26
0
/*
 * call-seq:
 *   Kernel.backtrace_includes?( method_or_object, ... ) -> true or false
 *   Kernel.backtrace_includes?( number_of_frames, method_or_object, ... ) -> true or false
 *
 * Returns whether specified methods or objects or classes are in the current backtrace context.
 * Kernel.backtrace_includes? begins with the prior frame, so asking if the backtrace includes the current method
 * will only report true if the current method is part of the earlier call chain.
 */
VALUE rb_RPRuby_Sender_Kernel_backtrace_includes(	int		argc,
													VALUE*	args,
													VALUE	rb_self )	{
	
	//	this function is also used for 
	//	* backtrace_includes_one_of?
	//	* backtrace_includes_frame?
	//	* backtrace_includes_one_of_frames?
	
	//	create tracking array
	VALUE	rb_tracking_array	=	rb_ary_new();
	
	//	populate tracking array with methods/objects
	//	optional - if first arg is Qtrue, we are looking for one of the args instead of all of the args
	int		c_which_arg				=	0;
	BOOL	c_requires_all_items	= TRUE;
	if (	args[ 0 ] == Qnil
		||	(	argc > 1
			 &&	args[ 1 ] == Qnil ) )	{
		c_which_arg++;
		c_requires_all_items = FALSE;
	}
	BOOL	c_return_frame	=	FALSE;
	if (	args[ 0 ] == Qfalse
		||	(	argc > 1
			 &&	args[ 1 ] == Qfalse ) )	{
		c_which_arg++;
		c_return_frame = TRUE;
	}
	BOOL	c_return_all_frames	=	FALSE;
	if (	args[ 0 ] == Qtrue
		||	(	argc > 1
			 &&	args[ 1 ] == Qtrue ) )	{
		c_which_arg++;
		c_return_all_frames = TRUE;
	}
	int	c_args_offset	=	c_which_arg;
	for ( ; c_which_arg < argc ; c_which_arg++ )	{
		rb_ary_push(	rb_tracking_array,
						args[ c_which_arg ] );
	}
		
	rb_thread_t*			c_thread					= GET_THREAD();
	//	Get the current frame - we're doing a backtrace, so our current working frame to start is the first previous thread
	rb_control_frame_t*		c_current_context_frame		= RUBY_VM_PREVIOUS_CONTROL_FRAME( RUBY_VM_PREVIOUS_CONTROL_FRAME( c_thread->cfp ) );
	
	//	c_top_of_control_frame describes the top edge of the stack trace
	//	set c_top_of_control_frame to the first frame in <main>
    rb_control_frame_t*		c_top_of_control_frame	=	RUBY_VM_NEXT_CONTROL_FRAME( RUBY_VM_NEXT_CONTROL_FRAME( (void *)( c_thread->stack + c_thread->stack_size ) ) );
	
	VALUE	rb_test_index_array	=	rb_ary_new();
	//	:object
	//	instance or class
	rb_ary_push(	rb_test_index_array,
					ID2SYM( rb_intern( "object" ) ) );
	//	:method				
	rb_ary_push(	rb_test_index_array,
					ID2SYM( rb_intern( "method" ) ) );
	//	:file
	rb_ary_push(	rb_test_index_array,
					ID2SYM( rb_intern( "file" ) ) );
	//	:line
	rb_ary_push(	rb_test_index_array,
					ID2SYM( rb_intern( "line" ) ) );
	
	//	only used if c_return_all_frames == TRUE
	VALUE	rb_frame_hashes_array	=	Qnil;
	if ( c_return_all_frames == TRUE )	{
		rb_frame_hashes_array		=	rb_ary_new();
	}
	
	VALUE	rb_frame_hash	=	Qnil;
	
	//	for each control frame:
    while ( c_current_context_frame < c_top_of_control_frame ) {
	   
		//	iterate each array member 
		int	c_which_member;
		for ( c_which_member = 0 ; c_which_member < RARRAY_LEN( rb_tracking_array ) ; c_which_member++ )	{
		   
			VALUE	rb_this_arg	=	args[ c_which_member + c_args_offset ];
		   
			BOOL		matched	=	FALSE;
		   
			rb_frame_hash	=	rb_RPRuby_Sender_Kernel_internal_backtraceHashForControlFrame(	& c_current_context_frame );
			
			//	if we have a hash we are testing multiple items in a frame
			if ( TYPE( rb_this_arg ) == T_HASH )	{

				VALUE	rb_frame_test_array	=	rb_obj_clone( rb_test_index_array );
			
				//	for each element that we could test for
				int	c_which_index;
				int	c_skipped_index_count	=	0;
				for ( c_which_index = 0 ; c_which_index < RARRAY_LEN( rb_frame_test_array ) ; c_which_index++ )	{
					
					VALUE	rb_this_index	=	RARRAY_PTR( rb_frame_test_array )[ c_which_index ];
					
					//	see if our requested test hash includes the potential test element
					if ( rb_hash_lookup(	rb_this_arg,
											rb_this_index ) != Qnil )	{
						
						VALUE	rb_required_element	=	rb_hash_aref(	rb_this_arg,
																		rb_this_index );
						VALUE	rb_frame_element	=	rb_hash_aref(	rb_frame_hash,
																		rb_this_index	);
									 						
						//	if it does, we need to see if the current frame's element matches this element
						VALUE	rb_required_element_klass;
						if ( rb_required_element == rb_frame_element
							//	if we have a string, which is a filename
							||	(	TYPE( rb_required_element ) == T_STRING
								 &&	rb_funcall( rb_frame_element, rb_intern( "==" ), 1, rb_required_element ) == Qtrue )
							//	if we have a class, which is a special case for :object
							||	(	rb_this_index == ID2SYM( rb_intern( "class" ) ) 
								 &&	( rb_required_element_klass = ( ( TYPE( rb_required_element ) == T_CLASS ) ? rb_required_element : rb_funcall( rb_required_element, rb_intern( "class" ), 0 ) ) )
								 &&	rb_required_element_klass == rb_required_element ) )	{

							rb_ary_delete_at(	rb_frame_test_array,
												c_which_index );
							c_which_index--;
						}
					}
					else {
						c_skipped_index_count++;
					}

					if ( RARRAY_LEN( rb_frame_test_array ) == c_skipped_index_count )	{
						if ( c_return_frame == TRUE )	{
							return rb_frame_hash;
						}
						else if ( c_return_all_frames == TRUE )	{
							rb_ary_push(	rb_frame_hashes_array,
											rb_frame_hash );
						}
						else {
							return Qtrue;							
						}
					}					
				}
			}
			else {

				//	:object => <class:instance>
				if	(	TYPE( rb_this_arg ) == T_OBJECT )	{

					if ( rb_hash_aref(	rb_frame_hash,
										ID2SYM( rb_intern( "object" ) ) ) == rb_this_arg )	{
						matched = TRUE;
					}
				}
				//	:object => <class>
				else if	( TYPE( rb_this_arg ) == T_CLASS )	{
					
					VALUE	rb_frame_object			=	rb_hash_aref(	rb_frame_hash,
																		ID2SYM( rb_intern( "object" ) ) );
					VALUE	rb_frame_object_klass	=	TYPE( rb_frame_object ) == T_CLASS ? rb_frame_object : rb_funcall( rb_frame_object, rb_intern( "class" ), 0 );
					if ( rb_frame_object_klass == rb_this_arg )	{
						matched = TRUE;
					}
				}
				//	:method => :method
				else if	( TYPE( rb_this_arg ) == T_SYMBOL )	{
				   
					if ( rb_hash_aref(	rb_frame_hash,
										ID2SYM( rb_intern( "method" ) ) ) == rb_this_arg )	{
						matched = TRUE;
					}
				}
				//	:file => "filename"
				else if ( TYPE( rb_this_arg ) == T_STRING )	{
					VALUE	rb_filename	=	rb_hash_aref(	rb_frame_hash,
															ID2SYM( rb_intern( "file" ) ) );
					VALUE	rb_comparison	=	rb_funcall( rb_filename, rb_intern( "==" ), 1, rb_this_arg );
					if ( rb_comparison == Qtrue )	{
						matched = TRUE;
					}
				}
				//	:line => number
				else if ( TYPE( rb_this_arg ) == T_FIXNUM )	{
					if ( rb_hash_aref(	rb_frame_hash,
										ID2SYM( rb_intern( "line" ) ) ) == rb_this_arg )	{
						matched = TRUE;
					}
				}
			   
				//	if array member exists in frame, remove from array
				if ( matched )	{
					if ( c_requires_all_items == FALSE )	{
						if ( c_return_frame == TRUE )	{
							return rb_frame_hash;
						}
						else {
							return Qtrue;							
						}

					}
					else {
						
						//	delete this index
						rb_ary_delete_at(	rb_tracking_array,
											c_which_member );
						
						//	decrement the loop iterator so that the increase is offset
						//	this is necessary since we just removed an index and are iterating vs. the length of the array
						c_which_member--;
					}
				}
			}
		}
	   
		//	if array is empty, return true
		//	we check here as well as at the end so we can stop iterating the backtrace if we find all our items
		if ( RARRAY_LEN( rb_tracking_array ) == 0 )	{
			if ( c_return_frame == TRUE )	{
				return rb_frame_hash;
			}
			else if ( c_return_all_frames == TRUE )	{
				rb_ary_push(	rb_frame_hashes_array,
								rb_frame_hash );
				return rb_frame_hashes_array;
			}
			else {
				return Qtrue;							
			}
		}
		c_current_context_frame = RUBY_VM_PREVIOUS_CONTROL_FRAME( c_current_context_frame );		
	}
	
	if (	c_return_all_frames == TRUE
		&&	RARRAY_LEN( rb_frame_hashes_array ) > 0 ) {
		return rb_frame_hashes_array;
	}
	//	if we finish iterating frames and still have items in the array, return false
	else if ( RARRAY_LEN( rb_tracking_array ) > 0 )	{
		if ( c_return_frame == TRUE )	{
			return Qnil;
		}
		else {
			return Qfalse;
		}
	}
	//	otherwise, return true
	else if ( c_return_frame == TRUE )	{
		return rb_frame_hash;
	}
	else {
		return Qtrue;							
	}
	//	we don't get here
	return Qnil;
}
Exemple #27
0
static void
process_arguments_of_image_initialize(int const argc, VALUE* const argv,
	VALUE* buffer_ptr,
	rb_image_file_image_pixel_format_t* pixel_format_ptr,
	long* width_ptr,
	long* height_ptr,
	long* stride_ptr
	)
{
    VALUE params;
    VALUE buffer = Qnil;
    VALUE pixel_format = Qnil;
    VALUE width = Qnil;
    VALUE height = Qnil;
    VALUE stride = Qnil;

    rb_image_file_image_pixel_format_t pf;
    long wd, ht, st;
    long min_len;

    ID id_pixel_format, id_data, id_width, id_height, id_row_stride;
    CONST_ID(id_data,  "data");
    CONST_ID(id_pixel_format,  "pixel_format");
    CONST_ID(id_width,  "width");
    CONST_ID(id_height, "height");
    CONST_ID(id_row_stride,  "row_stride");

    rb_scan_args(argc, argv, "01", &params);
    if (TYPE(params) == T_HASH) {
	buffer = rb_hash_lookup(params, ID2SYM(id_data));
	pixel_format = rb_hash_lookup(params, ID2SYM(id_pixel_format));
	width = rb_hash_lookup(params, ID2SYM(id_width));
	height = rb_hash_lookup(params, ID2SYM(id_height));
	stride = rb_hash_lookup(params, ID2SYM(id_row_stride));
    }

    if (!NIL_P(buffer)) {
	Check_Type(buffer, T_STRING);
	buffer = rb_str_dup(buffer);
    }

    if (NIL_P(pixel_format))
	rb_raise(rb_eArgError, "missing image pixel format");
    if (TYPE(pixel_format) == T_STRING)
	pixel_format = rb_str_intern(pixel_format);
    pf = check_pixel_format(pixel_format);

    if (NIL_P(width))
	rb_raise(rb_eArgError, "missing image width");
    wd = NUM2LONG(width);
    if (wd <= 0)
	rb_raise(rb_eArgError, "zero or negative image width");

    if (NIL_P(height))
	rb_raise(rb_eArgError, "missing image height");
    ht = NUM2LONG(height);
    if (ht <= 0)
	rb_raise(rb_eArgError, "zero or negative image height");

    if (NIL_P(stride)) {
#ifdef HAVE_RB_CAIRO_H
	st = cairo_format_stride_for_width(pixel_format_to_cairo_format(pf), (int)wd) / pixel_format_size(pf);
	stride = INT2NUM(st);
#else
	stride = width;
#endif
    }
    st = NUM2LONG(stride);
    if (st <= 0)
	rb_raise(rb_eArgError, "zero or negative image row-stride");
    else if (st < wd) {
	rb_warning("the given row-stride is less than the given image width.");
	st = wd;
    }

    min_len = minimum_buffer_size(pf, st, ht);
    if (NIL_P(buffer)) {
	buffer = rb_str_new(NULL, min_len);
    }
    else if (RSTRING_LEN(buffer) < min_len) {
	void rb_str_modify_expand(VALUE, long);
	rb_warning("the size of the given data is too short for the given size of image");
	rb_str_modify_expand(buffer, min_len - RSTRING_LEN(buffer));
    }

    *buffer_ptr = buffer;
    *pixel_format_ptr = pf;
    *width_ptr = wd;
    *height_ptr = ht;
    *stride_ptr = st;
}
Exemple #28
0
Fichier : ox.c Projet : sriedel/ox
/* call-seq: ox_default_options=(opts)
 *
 * Sets the default options for load and dump.
 * @param [Hash] opts options to change
 * @param [Fixnum] :indent number of spaces to indent each element in an XML document
 * @param [Fixnum] :trace trace level where 0 is silent
 * @param [String] :encoding character encoding for the XML file
 * @param [true|false|nil] :with_dtd include DTD in the dump
 * @param [true|false|nil] :with_instruct include instructions in the dump
 * @param [true|false|nil] :with_xml include XML prolog in the dump
 * @param [true|false|nil] :circular support circular references while dumping
 * @param [true|false|nil] :xsd_date use XSD date format instead of decimal format
 * @param [:object|:generic|:limited|nil] :mode load method to use for XML
 * @param [:strict|:tolerant|:auto_define] :effort set the tolerance level for loading
 * @param [true|false|nil] :symbolize_keys symbolize element attribute keys or leave as Strings
 * @param [:skip_none|:skip_return|:skip_white] determines how to handle white space in text
 * @param [nil|String] :invalid_replace replacement string for invalid XML characters on dump. nil indicates include anyway as hex. A string, limited to 10 characters will replace the invalid character with the replace.
 * @param [nil|String|true|false] :strip_namespace "" or false result in no namespace stripping. A string of "*" or true will strip all namespaces. Any other non-empty string indicates that matching namespaces will be stripped.
 * @return [nil]
 */
static VALUE
set_def_opts(VALUE self, VALUE opts) {
    struct _YesNoOpt	ynos[] = {
	{ with_xml_sym, &ox_default_options.with_xml },
	{ with_dtd_sym, &ox_default_options.with_dtd },
	{ with_instruct_sym, &ox_default_options.with_instruct },
	{ xsd_date_sym, &ox_default_options.xsd_date },
	{ circular_sym, &ox_default_options.circular },
	{ symbolize_keys_sym, &ox_default_options.sym_keys },
	{ smart_sym, &ox_default_options.smart },
	{ Qnil, 0 }
    };
    YesNoOpt	o;
    VALUE	v;
    
    Check_Type(opts, T_HASH);

    v = rb_hash_aref(opts, ox_encoding_sym);
    if (Qnil == v) {
	*ox_default_options.encoding = '\0';
    } else {
	Check_Type(v, T_STRING);
	strncpy(ox_default_options.encoding, StringValuePtr(v), sizeof(ox_default_options.encoding) - 1);
#if HAS_ENCODING_SUPPORT
	ox_default_options.rb_enc = rb_enc_find(ox_default_options.encoding);
#elif HAS_PRIVATE_ENCODING
	ox_default_options.rb_enc = rb_str_new2(ox_default_options.encoding);
	rb_gc_register_address(&ox_default_options.rb_enc);
#endif
    }

    v = rb_hash_aref(opts, indent_sym);
    if (Qnil != v) {
	Check_Type(v, T_FIXNUM);
	ox_default_options.indent = FIX2INT(v);
    }

    v = rb_hash_aref(opts, trace_sym);
    if (Qnil != v) {
	Check_Type(v, T_FIXNUM);
	ox_default_options.trace = FIX2INT(v);
    }

    v = rb_hash_aref(opts, mode_sym);
    if (Qnil == v) {
	ox_default_options.mode = NoMode;
    } else if (object_sym == v) {
	ox_default_options.mode = ObjMode;
    } else if (generic_sym == v) {
	ox_default_options.mode = GenMode;
    } else if (limited_sym == v) {
	ox_default_options.mode = LimMode;
    } else {
	rb_raise(ox_parse_error_class, ":mode must be :object, :generic, :limited, or nil.\n");
    }

    v = rb_hash_aref(opts, effort_sym);
    if (Qnil == v) {
	ox_default_options.effort = NoEffort;
    } else if (strict_sym == v) {
	ox_default_options.effort = StrictEffort;
    } else if (tolerant_sym == v) {
	ox_default_options.effort = TolerantEffort;
    } else if (auto_define_sym == v) {
	ox_default_options.effort = AutoEffort;
    } else {
	rb_raise(ox_parse_error_class, ":effort must be :strict, :tolerant, :auto_define, or nil.\n");
    }

    v = rb_hash_aref(opts, skip_sym);
    if (Qnil == v) {
	ox_default_options.skip = NoSkip;
    } else if (skip_none_sym == v) {
	ox_default_options.skip = NoSkip;
    } else if (skip_return_sym == v) {
	ox_default_options.skip = CrSkip;
    } else if (skip_white_sym == v) {
	ox_default_options.skip = SpcSkip;
    } else {
	rb_raise(ox_parse_error_class, ":skip must be :skip_none, :skip_return, :skip_white, or nil.\n");
    }

    v = rb_hash_lookup(opts, convert_special_sym);
    if (Qnil == v) {
	// no change
    } else if (Qtrue == v) {
	ox_default_options.convert_special = 1;
    } else if (Qfalse == v) {
	ox_default_options.convert_special = 0;
    } else {
	rb_raise(ox_parse_error_class, ":convert_special must be true or false.\n");
    }

    v = rb_hash_aref(opts, invalid_replace_sym);
    if (Qnil == v) {
	ox_default_options.allow_invalid = Yes;
    } else {
	long	slen;

	Check_Type(v, T_STRING);
	slen = RSTRING_LEN(v);
	if (sizeof(ox_default_options.inv_repl) - 2 < slen) {
	    rb_raise(ox_parse_error_class, ":invalid_replace can be no longer than %ld characters.",
		     sizeof(ox_default_options.inv_repl) - 2);
	}
	strncpy(ox_default_options.inv_repl + 1, StringValuePtr(v), sizeof(ox_default_options.inv_repl) - 1);
	ox_default_options.inv_repl[sizeof(ox_default_options.inv_repl) - 1] = '\0';
	*ox_default_options.inv_repl = (char)slen;
	ox_default_options.allow_invalid = No;
    }

    v = rb_hash_aref(opts, strip_namespace_sym);
    if (Qfalse == v) {
	*ox_default_options.strip_ns = '\0';
    } else if (Qtrue == v) {
	*ox_default_options.strip_ns = '*';
	ox_default_options.strip_ns[1] = '\0';
    } else if (Qnil != v) {
	long	slen;

	Check_Type(v, T_STRING);
	slen = RSTRING_LEN(v);
	if (sizeof(ox_default_options.strip_ns) - 1 < slen) {
	    rb_raise(ox_parse_error_class, ":strip_namespace can be no longer than %ld characters.",
		     sizeof(ox_default_options.strip_ns) - 1);
	}
	strncpy(ox_default_options.strip_ns, StringValuePtr(v), sizeof(ox_default_options.strip_ns) - 1);
	ox_default_options.strip_ns[sizeof(ox_default_options.strip_ns) - 1] = '\0';
    }

    for (o = ynos; 0 != o->attr; o++) {
	v = rb_hash_lookup(opts, o->sym);
	if (Qnil == v) {
	    *o->attr = NotSet;
	} else if (Qtrue == v) {
	    *o->attr = Yes;
	} else if (Qfalse == v) {
	    *o->attr = No;
	} else {
	    rb_raise(ox_parse_error_class, "%s must be true or false.\n", rb_id2name(SYM2ID(o->sym)));
	}
    }
    return Qnil;
}
Exemple #29
0
/* subColorPixel {{{ */
unsigned long
subColorPixel(VALUE red,
  VALUE green,
  VALUE blue,
  XColor *xcolor)
{
  XColor xcol = { 0 };

  /* Check object type */
  switch(rb_type(red))
    {
      case T_FIXNUM:
      case T_BIGNUM:
        if(NIL_P(green) && NIL_P(blue))
          {
            xcol.pixel = NUM2LONG(red);

            ColorPixelToRGB(&xcol);
          }
        else
          {
            xcol.red   = NUM2INT(red);
            xcol.green = NUM2INT(green);
            xcol.blue  = NUM2INT(blue);

            ColorRGBToPixel(&xcol);
          }
        break;
      case T_STRING:
        xcol.pixel = subSharedParseColor(display, RSTRING_PTR(red));

        ColorPixelToRGB(&xcol);
        break;
      case T_ARRAY:
        if(3 == FIX2INT(rb_funcall(red, rb_intern("size"), 0, NULL)))
          {
            xcol.red   = NUM2INT(rb_ary_entry(red, 0));
            xcol.green = NUM2INT(rb_ary_entry(red, 1));
            xcol.blue  = NUM2INT(rb_ary_entry(red, 2));

            ColorRGBToPixel(&xcol);
          }
        break;
      case T_HASH:
          {
            xcol.red   = NUM2INT(rb_hash_lookup(red, CHAR2SYM("red")));
            xcol.green = NUM2INT(rb_hash_lookup(red, CHAR2SYM("green")));
            xcol.blue  = NUM2INT(rb_hash_lookup(red, CHAR2SYM("blue")));

            ColorRGBToPixel(&xcol);
          }
        break;
      case T_OBJECT:
          {
            VALUE klass = rb_const_get(mod, rb_intern("Color"));

            /* Check object instance */
            if(rb_obj_is_instance_of(red, klass))
              {
                xcol.red   = NUM2INT(rb_iv_get(red, "@red"));
                xcol.green = NUM2INT(rb_iv_get(red, "@green"));
                xcol.blue  = NUM2INT(rb_iv_get(red, "@blue"));
                xcol.pixel = NUM2LONG(rb_iv_get(red, "@pixel"));
              }
          }
        break;
      default:
        rb_raise(rb_eArgError, "Unexpected value-type `%s'",
          rb_obj_classname(red));
    }

  if(xcolor)
    {
      xcolor->red   = xcol.red;
      xcolor->green = xcol.green;
      xcolor->blue  = xcol.blue;
      xcolor->pixel = xcol.pixel;
    }


  return xcol.pixel;
} /* }}} */
Exemple #30
0
Fichier : ox.c Projet : edanaher/ox
/* call-seq: ox_default_options=(opts)
 *
 * Sets the default options for load and dump.
 * @param [Hash] opts options to change
 * @param [Fixnum] :indent number of spaces to indent each element in an XML document
 * @param [Fixnum] :trace trace level where 0 is silent
 * @param [String] :encoding character encoding for the XML file
 * @param [true|false|nil] :with_dtd include DTD in the dump
 * @param [true|false|nil] :with_instruct include instructions in the dump
 * @param [true|false|nil] :with_xml include XML prolog in the dump
 * @param [true|false|nil] :circular support circular references while dumping
 * @param [true|false|nil] :xsd_date use XSD date format instead of decimal format
 * @param [:object|:generic|:limited|nil] :mode load method to use for XML
 * @param [:strict|:tolerant|:auto_define] :effort set the tolerance level for loading
 * @param [true|false|nil] :symbolize_keys symbolize element attribute keys or leave as Strings
 * @return [nil]
 */
static VALUE
set_def_opts(VALUE self, VALUE opts) {
    struct _YesNoOpt	ynos[] = {
	{ with_xml_sym, &ox_default_options.with_xml },
	{ with_dtd_sym, &ox_default_options.with_dtd },
	{ with_instruct_sym, &ox_default_options.with_instruct },
	{ xsd_date_sym, &ox_default_options.xsd_date },
	{ circular_sym, &ox_default_options.circular },
	{ symbolize_keys_sym, &ox_default_options.sym_keys },
	{ Qnil, 0 }
    };
    YesNoOpt	o;
    VALUE	v;
    
    Check_Type(opts, T_HASH);

    v = rb_hash_aref(opts, ox_encoding_sym);
    if (Qnil == v) {
	*ox_default_options.encoding = '\0';
    } else {
	Check_Type(v, T_STRING);
	strncpy(ox_default_options.encoding, StringValuePtr(v), sizeof(ox_default_options.encoding) - 1);
    }

    v = rb_hash_aref(opts, indent_sym);
    if (Qnil != v) {
	Check_Type(v, T_FIXNUM);
	ox_default_options.indent = FIX2INT(v);
    }

    v = rb_hash_aref(opts, trace_sym);
    if (Qnil != v) {
	Check_Type(v, T_FIXNUM);
	ox_default_options.trace = FIX2INT(v);
    }

    v = rb_hash_aref(opts, mode_sym);
    if (Qnil == v) {
	ox_default_options.mode = NoMode;
    } else if (object_sym == v) {
	ox_default_options.mode = ObjMode;
    } else if (generic_sym == v) {
	ox_default_options.mode = GenMode;
    } else if (limited_sym == v) {
	ox_default_options.mode = LimMode;
    } else {
	rb_raise(rb_eArgError, ":mode must be :object, :generic, :limited, or nil.\n");
    }

    v = rb_hash_aref(opts, effort_sym);
    if (Qnil == v) {
	ox_default_options.effort = NoEffort;
    } else if (strict_sym == v) {
	ox_default_options.effort = StrictEffort;
    } else if (tolerant_sym == v) {
	ox_default_options.effort = TolerantEffort;
    } else if (auto_define_sym == v) {
	ox_default_options.effort = AutoEffort;
    } else {
	rb_raise(rb_eArgError, ":effort must be :strict, :tolerant, :auto_define, or nil.\n");
    }
    for (o = ynos; 0 != o->attr; o++) {
	v = rb_hash_lookup(opts, o->sym);
	if (Qnil == v) {
	    *o->attr = NotSet;
	} else if (Qtrue == v) {
	    *o->attr = Yes;
	} else if (Qfalse == v) {
	    *o->attr = No;
	} else {
	    rb_raise(rb_eArgError, "%s must be true or false.\n", rb_id2name(SYM2ID(o->sym)));
	}
    }
    return Qnil;
}