void
cb_observe_callback(lcb_t handle, const void *cookie, lcb_error_t error, const lcb_observe_resp_t *resp)
{
    struct cb_context_st *ctx = (struct cb_context_st *)cookie;
    struct cb_bucket_st *bucket = ctx->bucket;
    VALUE key, res, exc;

    if (resp->v.v0.key) {
        key = STR_NEW((const char*)resp->v.v0.key, resp->v.v0.nkey);
        exc = cb_check_error(error, "failed to execute observe request", key);
        if (exc != Qnil) {
            ctx->exception = exc;
        }
        res = rb_class_new_instance(0, NULL, cb_cResult);
        rb_ivar_set(res, cb_id_iv_completed, Qfalse);
        rb_ivar_set(res, cb_id_iv_error, ctx->exception);
        rb_ivar_set(res, cb_id_iv_operation, cb_sym_observe);
        rb_ivar_set(res, cb_id_iv_key, key);
        rb_ivar_set(res, cb_id_iv_cas, ULL2NUM(resp->v.v0.cas));
        rb_ivar_set(res, cb_id_iv_from_master, resp->v.v0.from_master ? Qtrue : Qfalse);
        rb_ivar_set(res, cb_id_iv_time_to_persist, ULONG2NUM(resp->v.v0.ttp));
        rb_ivar_set(res, cb_id_iv_time_to_replicate, ULONG2NUM(resp->v.v0.ttr));
        switch (resp->v.v0.status) {
            case LCB_OBSERVE_FOUND:
                rb_ivar_set(res, cb_id_iv_status, cb_sym_found);
                break;
            case LCB_OBSERVE_PERSISTED:
                rb_ivar_set(res, cb_id_iv_status, cb_sym_persisted);
                break;
            case LCB_OBSERVE_NOT_FOUND:
                rb_ivar_set(res, cb_id_iv_status, cb_sym_not_found);
                break;
            default:
                rb_ivar_set(res, cb_id_iv_status, Qnil);
        }
        if (bucket->async) { /* asynchronous */
            if (ctx->proc != Qnil) {
                cb_proc_call(bucket, ctx->proc, 1, res);
            }
        } else {             /* synchronous */
            if (NIL_P(ctx->exception)) {
                VALUE stats = rb_hash_aref(ctx->rv, key);
                if (NIL_P(stats)) {
                    stats = rb_ary_new();
                    rb_hash_aset(ctx->rv, key, stats);
                }
                rb_ary_push(stats, res);
            }
        }
    } else {
        if (bucket->async && ctx->proc != Qnil) {
            res = rb_class_new_instance(0, NULL, cb_cResult);
            rb_ivar_set(res, cb_id_iv_completed, Qtrue);
            cb_proc_call(bucket, ctx->proc, 1, res);
        }
        ctx->nqueries--;
        ctx->proc = Qnil;
        if (bucket->async) {
            cb_context_free(ctx);
        }
    }
    (void)handle;
}
VALUE decode(const char *pszImageFile)
{
	VALUE ary = rb_ary_new();

	__int64 llFormat = (OneD |QR_CODE);
	int iMaxCount = 0x7FFFFFFF;
	int iIndex = 0;
	ReaderOptions ro = {0};
	pBarcodeResultArray paryResult = NULL;
	int iRet = -1;
	char * pszTemp = NULL;
	char * pszTemp1 = NULL;
	struct timeval begin, end;

	if (NULL == pszImageFile)
	{
		printf("The syntax of the command is incorrect.\n");
		return 1;
	}

	// Set license
	DBR_InitLicense("B8DF4560D0953299D5454C71A38D1FEB");

	// Read barcode
	gettimeofday(&begin, NULL);
	ro.llBarcodeFormat = llFormat;
	ro.iMaxBarcodesNumPerPage = iMaxCount;
	iRet = DBR_DecodeFile(pszImageFile, &ro, &paryResult);
	gettimeofday(&end, NULL);

	// Output barcode result
	pszTemp = (char*)malloc(4096);
	if (iRet != DBR_OK)
	{
		sprintf(pszTemp, "Failed to read barcode: %s\r\n", DBR_GetErrorString(iRet));
		printf("%s", pszTemp);
		free(pszTemp);
		return 1;
	}

	if (paryResult->iBarcodeCount == 0)
	{
		sprintf(pszTemp, "No barcode found. Total time spent: %.3f seconds.\r\n",
					((float)((end.tv_sec * 1000 * 1000 +  end.tv_usec) - (begin.tv_sec * 1000 * 1000 + begin.tv_usec))/(1000 * 1000)));
		printf("%s", pszTemp);
		DBR_FreeBarcodeResults(&paryResult);
		return 0;
	}

	sprintf(pszTemp, "Total barcode(s) found: %d. Total time spent: %.3f seconds\r\n\r\n", paryResult->iBarcodeCount,
					((float)((end.tv_sec * 1000 * 1000 +  end.tv_usec) - (begin.tv_sec * 1000 * 1000 + begin.tv_usec))/(1000 * 1000)));
	printf("%s", pszTemp);
	for (iIndex = 0; iIndex < paryResult->iBarcodeCount; iIndex++)
	{
		sprintf(pszTemp, "Barcode %d:\r\n", iIndex + 1);
		// printf("%s", pszTemp);
		sprintf(pszTemp, "%s    Page: %d\r\n", pszTemp, paryResult->ppBarcodes[iIndex]->iPageNum);
		// printf("%s", pszTemp);
		sprintf(pszTemp, "%s    Type: %s\r\n", pszTemp, GetFormatStr(paryResult->ppBarcodes[iIndex]->llFormat));
		// printf("%s", pszTemp);
		pszTemp1 = (char*)malloc(paryResult->ppBarcodes[iIndex]->iBarcodeDataLength + 1);
		memset(pszTemp1, 0, paryResult->ppBarcodes[iIndex]->iBarcodeDataLength + 1);
		memcpy(pszTemp1, paryResult->ppBarcodes[iIndex]->pBarcodeData, paryResult->ppBarcodes[iIndex]->iBarcodeDataLength);
		sprintf(pszTemp, "%s    Value: %s\r\n", pszTemp, pszTemp1);
		// printf("%s", pszTemp);
		free(pszTemp1);
		// sprintf(pszTemp, "    Region: {Left: %d, Top: %d, Width: %d, Height: %d}\r\n\r\n",
		// 	paryResult->ppBarcodes[iIndex]->iLeft, paryResult->ppBarcodes[iIndex]->iTop,
		// 	paryResult->ppBarcodes[iIndex]->iWidth, paryResult->ppBarcodes[iIndex]->iHeight);
		// printf("%s", pszTemp);
		rb_ary_push(ary, rb_str_new_cstr(pszTemp));
	}

	free(pszTemp);
	DBR_FreeBarcodeResults(&paryResult);

	return ary;
}
static void process_relations(VALUE out, OSMPBF__PrimitiveGroup *group, OSMPBF__StringTable *string_table, int32_t ts_granularity)
{
  unsigned j, k;
  size_t i = 0;

  for(i = 0; i < group->n_relations; i++)
  {
    OSMPBF__Relation *relation = group->relations[i];
    VALUE relation_out = rb_hash_new();

    rb_hash_aset(relation_out, STR2SYM("id"), LL2NUM(relation->id));

    // Extract tags
    VALUE tags = rb_hash_new();

    for(j = 0; j < relation->n_keys; j++)
    {
      char *key   = parse_binary_str(string_table->s[relation->keys[j]]);
      char *value = parse_binary_str(string_table->s[relation->vals[j]]);

      rb_hash_aset(tags, str_new(key), str_new(value));

      free(key);
      free(value);
    }

    // Extract members
    VALUE members   = rb_hash_new();
    VALUE nodes     = rb_ary_new();
    VALUE ways      = rb_ary_new();
    VALUE relations = rb_ary_new();

    int64_t delta_memids = 0;
    char *role;

    for(k = 0; k < relation->n_memids; k++)
    {
      VALUE member = rb_hash_new();

      delta_memids += relation->memids[k];

      rb_hash_aset(member, STR2SYM("id"), LL2NUM(delta_memids));

      if(relation->roles_sid[k])
      {
        role = parse_binary_str(string_table->s[relation->roles_sid[k]]);
        rb_hash_aset(member, STR2SYM("role"), str_new(role));
        free(role);
      }

      switch(relation->types[k])
      {
        case OSMPBF__RELATION__MEMBER_TYPE__NODE:
          rb_ary_push(nodes, member);
          break;
        case OSMPBF__RELATION__MEMBER_TYPE__WAY:
          rb_ary_push(ways, member);
          break;
        case OSMPBF__RELATION__MEMBER_TYPE__RELATION:
          rb_ary_push(relations, member);
          break;
      }
    }

    rb_hash_aset(members, STR2SYM("nodes"), nodes);
    rb_hash_aset(members, STR2SYM("ways"), ways);
    rb_hash_aset(members, STR2SYM("relations"), relations);

    // Extract info
    if(relation->info)
      add_info(relation_out, relation->info, string_table, ts_granularity);

    rb_hash_aset(relation_out, STR2SYM("tags"), tags);
    rb_hash_aset(relation_out, STR2SYM("members"), members);
    rb_ary_push(out, relation_out);
  }
}
Beispiel #4
0
static VALUE sa_new_array(VALUE self) {
  VALUE ret;
  ret = rb_ary_new();
  return ret;
}
Beispiel #5
0
VALUE rho_ruby_create_array()
{
    return rb_ary_new();
}
Beispiel #6
0
static VALUE
rf_int_protected(VALUE args) {
    static VALUE empty_ary = Qnil;
    if (empty_ary == Qnil) empty_ary = rb_ary_new();
    return rb_apply(args,id_to_i,empty_ary);
}
Beispiel #7
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;
}
Beispiel #8
0
VALUE db_mysql_result_load(VALUE self, MYSQL_RES *result, size_t insert_id, size_t affected) {
    size_t n, rows, cols;
    const char *type, *data;
    MYSQL_FIELD *fields;

    Result *r    = db_mysql_result_handle(self);
    r->fields    = rb_ary_new();
    r->types     = rb_ary_new();
    r->r         = result;
    r->affected  = affected;
    r->insert_id = insert_id;
    r->selected  = 0;
    r->lengths   = 0;
    r->is_null   = 0;
    r->bind      = 0;
    r->cols      = 0;

    /* non select queries */
    if (!result)
        return self;

    rows   = mysql_num_rows(result);
    cols   = mysql_num_fields(result);
    fields = mysql_fetch_fields(result);

    r->cols     = cols;
    r->selected = rows;

    for (n = 0; n < cols; n++) {
        rb_ary_push(r->fields, ID2SYM(rb_intern(fields[n].name)));

        switch (fields[n].type) {
            case MYSQL_TYPE_TINY:
                rb_ary_push(r->types, (fields[n].length == 1 ? INT2NUM(SWIFT_TYPE_BOOLEAN) : INT2NUM(SWIFT_TYPE_INT)));
                break;
            case MYSQL_TYPE_SHORT:
            case MYSQL_TYPE_LONG:
            case MYSQL_TYPE_INT24:
            case MYSQL_TYPE_LONGLONG:
            case MYSQL_TYPE_YEAR:
                rb_ary_push(r->types, INT2NUM(SWIFT_TYPE_INT));
                break;
            case MYSQL_TYPE_DECIMAL:
            case MYSQL_TYPE_NEWDECIMAL:
                rb_ary_push(r->types, INT2NUM(SWIFT_TYPE_NUMERIC));
                break;
            case MYSQL_TYPE_FLOAT:
            case MYSQL_TYPE_DOUBLE:
                rb_ary_push(r->types, INT2NUM(SWIFT_TYPE_FLOAT));
                break;
            case MYSQL_TYPE_TIMESTAMP:
            case MYSQL_TYPE_DATETIME:
                rb_ary_push(r->types, INT2NUM(SWIFT_TYPE_TIMESTAMP));
                break;
            case MYSQL_TYPE_TIME:
                rb_ary_push(r->types, INT2NUM(SWIFT_TYPE_TIME));
                break;
            case MYSQL_TYPE_DATE:
                rb_ary_push(r->types, INT2NUM(SWIFT_TYPE_DATE));
                break;
            default:
                rb_ary_push(r->types, (fields[n].flags & BINARY_FLAG) ? INT2NUM(SWIFT_TYPE_BLOB) : INT2NUM(SWIFT_TYPE_TEXT));
        }
    }

    return self;
}
Beispiel #9
0
/*
 * call-seq:
 *    parser.parse(yaml)
 *
 * Parse the YAML document contained in +yaml+.  Events will be called on
 * the handler set on the parser instance.
 *
 * See Psych::Parser and Psych::Parser#handler
 */
static VALUE parse(VALUE self, VALUE yaml)
{
    yaml_parser_t parser;
    yaml_event_t event;
    int done = 0;
#ifdef HAVE_RUBY_ENCODING_H
    int encoding = rb_enc_find_index("ASCII-8BIT");
    rb_encoding * internal_enc;
#endif
    VALUE handler = rb_iv_get(self, "@handler");


    yaml_parser_initialize(&parser);

    if(rb_respond_to(yaml, id_read)) {
	yaml_parser_set_input(&parser, io_reader, (void *)yaml);
    } else {
	StringValue(yaml);
	yaml_parser_set_input_string(
		&parser,
		(const unsigned char *)RSTRING_PTR(yaml),
		(size_t)RSTRING_LEN(yaml)
		);
    }

    while(!done) {
	if(!yaml_parser_parse(&parser, &event)) {
	    size_t line   = parser.mark.line + 1;
	    size_t column = parser.mark.column;

	    yaml_parser_delete(&parser);
	    rb_raise(ePsychSyntaxError, "couldn't parse YAML at line %d column %d",
		    (int)line, (int)column);
	}

	switch(event.type) {
	  case YAML_STREAM_START_EVENT:

#ifdef HAVE_RUBY_ENCODING_H
	    switch(event.data.stream_start.encoding) {
	      case YAML_ANY_ENCODING:
		break;
	      case YAML_UTF8_ENCODING:
		encoding = rb_enc_find_index("UTF-8");
		break;
	      case YAML_UTF16LE_ENCODING:
		encoding = rb_enc_find_index("UTF-16LE");
		break;
	      case YAML_UTF16BE_ENCODING:
		encoding = rb_enc_find_index("UTF-16BE");
		break;
	      default:
		break;
	    }
	    internal_enc = rb_default_internal_encoding();
#endif

	    rb_funcall(handler, id_start_stream, 1,
		       INT2NUM((long)event.data.stream_start.encoding)
		);
	    break;
	  case YAML_DOCUMENT_START_EVENT:
	    {
		/* Get a list of tag directives (if any) */
		VALUE tag_directives = rb_ary_new();
		/* Grab the document version */
		VALUE version = event.data.document_start.version_directive ?
		    rb_ary_new3(
			(long)2,
			INT2NUM((long)event.data.document_start.version_directive->major),
			INT2NUM((long)event.data.document_start.version_directive->minor)
			) : rb_ary_new();

		if(event.data.document_start.tag_directives.start) {
		    yaml_tag_directive_t *start =
			event.data.document_start.tag_directives.start;
		    yaml_tag_directive_t *end =
			event.data.document_start.tag_directives.end;
		    for(; start != end; start++) {
			VALUE handle = Qnil;
			VALUE prefix = Qnil;
			if(start->handle) {
			    handle = rb_str_new2((const char *)start->handle);
#ifdef HAVE_RUBY_ENCODING_H
			    PSYCH_TRANSCODE(handle, encoding, internal_enc);
#endif
			}

			if(start->prefix) {
			    prefix = rb_str_new2((const char *)start->prefix);
#ifdef HAVE_RUBY_ENCODING_H
			    PSYCH_TRANSCODE(prefix, encoding, internal_enc);
#endif
			}

			rb_ary_push(tag_directives, rb_ary_new3((long)2, handle, prefix));
		    }
		}
		rb_funcall(handler, id_start_document, 3,
			   version, tag_directives,
			   event.data.document_start.implicit == 1 ? Qtrue : Qfalse
		    );
	    }
	    break;
	  case YAML_DOCUMENT_END_EVENT:
	    rb_funcall(handler, id_end_document, 1,
		       event.data.document_end.implicit == 1 ? Qtrue : Qfalse
		);
	    break;
	  case YAML_ALIAS_EVENT:
	    {
		VALUE alias = Qnil;
		if(event.data.alias.anchor) {
		    alias = rb_str_new2((const char *)event.data.alias.anchor);
#ifdef HAVE_RUBY_ENCODING_H
		    PSYCH_TRANSCODE(alias, encoding, internal_enc);
#endif
		}

		rb_funcall(handler, id_alias, 1, alias);
	    }
	    break;
	  case YAML_SCALAR_EVENT:
	    {
		VALUE anchor = Qnil;
		VALUE tag = Qnil;
		VALUE plain_implicit, quoted_implicit, style;
		VALUE val = rb_str_new(
		    (const char *)event.data.scalar.value,
		    (long)event.data.scalar.length
		    );

#ifdef HAVE_RUBY_ENCODING_H
		PSYCH_TRANSCODE(val, encoding, internal_enc);
#endif

		if(event.data.scalar.anchor) {
		    anchor = rb_str_new2((const char *)event.data.scalar.anchor);
#ifdef HAVE_RUBY_ENCODING_H
		    PSYCH_TRANSCODE(anchor, encoding, internal_enc);
#endif
		}

		if(event.data.scalar.tag) {
		    tag = rb_str_new2((const char *)event.data.scalar.tag);
#ifdef HAVE_RUBY_ENCODING_H
		    PSYCH_TRANSCODE(tag, encoding, internal_enc);
#endif
		}

		plain_implicit =
		    event.data.scalar.plain_implicit == 0 ? Qfalse : Qtrue;

		quoted_implicit =
		    event.data.scalar.quoted_implicit == 0 ? Qfalse : Qtrue;

		style = INT2NUM((long)event.data.scalar.style);

		rb_funcall(handler, id_scalar, 6,
			   val, anchor, tag, plain_implicit, quoted_implicit, style);
	    }
	    break;
	  case YAML_SEQUENCE_START_EVENT:
	    {
		VALUE anchor = Qnil;
		VALUE tag = Qnil;
		VALUE implicit, style;
		if(event.data.sequence_start.anchor) {
		    anchor = rb_str_new2((const char *)event.data.sequence_start.anchor);
#ifdef HAVE_RUBY_ENCODING_H
		    PSYCH_TRANSCODE(anchor, encoding, internal_enc);
#endif
		}

		tag = Qnil;
		if(event.data.sequence_start.tag) {
		    tag = rb_str_new2((const char *)event.data.sequence_start.tag);
#ifdef HAVE_RUBY_ENCODING_H
		    PSYCH_TRANSCODE(tag, encoding, internal_enc);
#endif
		}

		implicit =
		    event.data.sequence_start.implicit == 0 ? Qfalse : Qtrue;

		style = INT2NUM((long)event.data.sequence_start.style);

		rb_funcall(handler, id_start_sequence, 4,
			   anchor, tag, implicit, style);
	    }
	    break;
	  case YAML_SEQUENCE_END_EVENT:
	    rb_funcall(handler, id_end_sequence, 0);
	    break;
	  case YAML_MAPPING_START_EVENT:
	    {
		VALUE anchor = Qnil;
		VALUE tag = Qnil;
		VALUE implicit, style;
		if(event.data.mapping_start.anchor) {
		    anchor = rb_str_new2((const char *)event.data.mapping_start.anchor);
#ifdef HAVE_RUBY_ENCODING_H
		    PSYCH_TRANSCODE(anchor, encoding, internal_enc);
#endif
		}

		if(event.data.mapping_start.tag) {
		    tag = rb_str_new2((const char *)event.data.mapping_start.tag);
#ifdef HAVE_RUBY_ENCODING_H
		    PSYCH_TRANSCODE(tag, encoding, internal_enc);
#endif
		}

		implicit =
		    event.data.mapping_start.implicit == 0 ? Qfalse : Qtrue;

		style = INT2NUM((long)event.data.mapping_start.style);

		rb_funcall(handler, id_start_mapping, 4,
			   anchor, tag, implicit, style);
	    }
	    break;
	  case YAML_MAPPING_END_EVENT:
	    rb_funcall(handler, id_end_mapping, 0);
	    break;
	  case YAML_NO_EVENT:
	    rb_funcall(handler, id_empty, 0);
	    break;
	  case YAML_STREAM_END_EVENT:
	    rb_funcall(handler, id_end_stream, 0);
	    done = 1;
	    break;
	}
    }

    return self;
}
Beispiel #10
0
VALUE db_mysql_result_fields(VALUE self) {
    Result *r = db_mysql_result_handle(self);
    return r->fields ? r->fields : rb_ary_new();
}
Beispiel #11
0
VALUE db_mysql_result_types(VALUE self) {
    Result *r = db_mysql_result_handle(self);
    return r->types ? typecast_description(r->types) : rb_ary_new();
}
Beispiel #12
0
static VALUE t_init(VALUE self){
  VALUE arr;
  arr = rb_ary_new();
  rb_iv_set(self, "@arr", arr);
  return self;
}
Beispiel #13
0
int
rb_scan_args(int argc, const VALUE *argv, const char *fmt, ...)
{
    int i;
    const char *p = fmt;
    VALUE *var;
    va_list vargs;
    int f_var = 0, f_hash = 0, f_block = 0;
    int n_lead = 0, n_opt = 0, n_trail = 0, n_mand;
    int argi = 0;
    VALUE hash = Qnil;

    if (ISDIGIT(*p)) {
	n_lead = *p - '0';
	p++;
	if (ISDIGIT(*p)) {
	    n_opt = *p - '0';
	    p++;
	    if (ISDIGIT(*p)) {
		n_trail = *p - '0';
		p++;
		goto block_arg;
	    }
	}
    }
    if (*p == '*') {
	f_var = 1;
	p++;
	if (ISDIGIT(*p)) {
	    n_trail = *p - '0';
	    p++;
	}
    }
  block_arg:
    if (*p == ':') {
	f_hash = 1;
	p++;
    }
    if (*p == '&') {
	f_block = 1;
	p++;
    }
    if (*p != '\0') {
	rb_fatal("bad scan arg format: %s", fmt);
    }
    n_mand = n_lead + n_trail;

    if (argc < n_mand)
	goto argc_error;

    va_start(vargs, fmt);

    /* capture an option hash - phase 1: pop */
    if (f_hash && n_mand < argc) {
	VALUE last = argv[argc - 1];

	if (NIL_P(last)) {
	    /* nil is taken as an empty option hash only if it is not
	       ambiguous; i.e. '*' is not specified and arguments are
	       given more than sufficient */
	    if (!f_var && n_mand + n_opt < argc)
		argc--;
	}
	else {
	    hash = rb_check_hash_type(last);
	    if (!NIL_P(hash))
		argc--;
	}
    }
    /* capture leading mandatory arguments */
    for (i = n_lead; i-- > 0; ) {
	var = va_arg(vargs, VALUE *);
	if (var) *var = argv[argi];
	argi++;
    }
    /* capture optional arguments */
    for (i = n_opt; i-- > 0; ) {
	var = va_arg(vargs, VALUE *);
	if (argi < argc - n_trail) {
	    if (var) *var = argv[argi];
	    argi++;
	}
	else {
	    if (var) *var = Qnil;
	}
    }
    /* capture variable length arguments */
    if (f_var) {
	int n_var = argc - argi - n_trail;

	var = va_arg(vargs, VALUE *);
	if (0 < n_var) {
	    if (var) *var = rb_ary_new4(n_var, &argv[argi]);
	    argi += n_var;
	}
	else {
	    if (var) *var = rb_ary_new();
	}
    }
    /* capture trailing mandatory arguments */
    for (i = n_trail; i-- > 0; ) {
	var = va_arg(vargs, VALUE *);
	if (var) *var = argv[argi];
	argi++;
    }
    /* capture an option hash - phase 2: assignment */
    if (f_hash) {
	var = va_arg(vargs, VALUE *);
	if (var) *var = hash;
    }
    /* capture iterator block */
    if (f_block) {
	var = va_arg(vargs, VALUE *);
	if (rb_block_given_p()) {
	    *var = rb_block_proc();
	}
	else {
	    *var = Qnil;
	}
    }
    va_end(vargs);

    if (argi < argc) {
      argc_error:
	rb_error_arity(argc, n_mand, f_var ? UNLIMITED_ARGUMENTS : n_mand + n_opt);
    }

    return argc;
}
Beispiel #14
0
int start_array_callback(void *ctx) {
  start_object(ctx,rb_ary_new());
  return 1;
}
Beispiel #15
0
static VALUE
rb_thread_keys(VALUE self, SEL sel)
{
    VALUE h = rb_vm_thread_locals(self, false);
    return h == Qnil ? rb_ary_new() : rb_hash_keys(h);
}
Beispiel #16
0
Objects::Objects()
{
    objects = rb_ary_new();
    rb_gc_register_address(&objects);
}
Beispiel #17
0
static VALUE get_value(const char* buffer, int* position, int type) {
    VALUE value;
    switch (type) {
    case -1:
        {
            value = rb_class_new_instance(0, NULL, MinKey);
            break;
        }
    case 1:
        {
            double d;
            memcpy(&d, buffer + *position, 8);
            value = rb_float_new(d);
            *position += 8;
            break;
        }
    case 2:
    case 13:
        {
            int value_length;
            value_length = *(int*)(buffer + *position) - 1;
            *position += 4;
            value = STR_NEW(buffer + *position, value_length);
            *position += value_length + 1;
            break;
        }
    case 3:
        {
            int size;
            memcpy(&size, buffer + *position, 4);
            if (strcmp(buffer + *position + 5, "$ref") == 0) { // DBRef
                int offset = *position + 10;
                VALUE argv[2];
                int collection_length = *(int*)(buffer + offset) - 1;
                char id_type;
                offset += 4;

                argv[0] = STR_NEW(buffer + offset, collection_length);
                offset += collection_length + 1;
                id_type = buffer[offset];
                offset += 5;
                argv[1] = get_value(buffer, &offset, (int)id_type);
                value = rb_class_new_instance(2, argv, DBRef);
            } else {
                value = elements_to_hash(buffer + *position + 4, size - 5);
            }
            *position += size;
            break;
        }
    case 4:
        {
            int size, end;
            memcpy(&size, buffer + *position, 4);
            end = *position + size - 1;
            *position += 4;

            value = rb_ary_new();
            while (*position < end) {
                int type = (int)buffer[(*position)++];
                int key_size = strlen(buffer + *position);
                VALUE to_append;

                *position += key_size + 1; // just skip the key, they're in order.
                to_append = get_value(buffer, position, type);
                rb_ary_push(value, to_append);
            }
            (*position)++;
            break;
        }
    case 5:
        {
            int length, subtype;
            VALUE data, st;
            VALUE argv[2];
            memcpy(&length, buffer + *position, 4);
            subtype = (unsigned char)buffer[*position + 4];
            if (subtype == 2) {
                data = rb_str_new(buffer + *position + 9, length - 4);
            } else {
                data = rb_str_new(buffer + *position + 5, length);
            }
            st = INT2FIX(subtype);
            argv[0] = data;
            argv[1] = st;
            value = rb_class_new_instance(2, argv, Binary);
            *position += length + 5;
            break;
        }
    case 6:
        {
            value = Qnil;
            break;
        }
    case 7:
        {
            VALUE str = rb_str_new(buffer + *position, 12);
            VALUE oid = rb_funcall(str, rb_intern("unpack"), 1, rb_str_new2("C*"));
            value = rb_class_new_instance(1, &oid, ObjectID);
            *position += 12;
            break;
        }
    case 8:
        {
            value = buffer[(*position)++] ? Qtrue : Qfalse;
            break;
        }
    case 9:
        {
            long long millis;
            VALUE seconds, microseconds;
            memcpy(&millis, buffer + *position, 8);
            seconds = LL2NUM(millis / 1000);
            microseconds = INT2NUM((millis % 1000) * 1000);

            value = rb_funcall(Time, rb_intern("at"), 2, seconds, microseconds);
            value = rb_funcall(value, rb_intern("utc"), 0);
            *position += 8;
            break;
        }
    case 10:
        {
            value = Qnil;
            break;
        }
    case 11:
        {
            int pattern_length = strlen(buffer + *position);
            VALUE pattern = STR_NEW(buffer + *position, pattern_length);
            int flags_length, flags = 0, i = 0;
            char extra[10];
            VALUE argv[3];
            *position += pattern_length + 1;

            flags_length = strlen(buffer + *position);
            extra[0] = 0;
            for (i = 0; i < flags_length; i++) {
                char flag = buffer[*position + i];
                if (flag == 'i') {
                    flags |= IGNORECASE;
                }
                else if (flag == 'm') {
                    flags |= MULTILINE;
                }
                else if (flag == 'x') {
                    flags |= EXTENDED;
                }
                else if (strlen(extra) < 9) {
                    strncat(extra, &flag, 1);
                }
            }
            argv[0] = pattern;
            argv[1] = INT2FIX(flags);
            argv[2] = rb_str_new2(extra);
            value = rb_class_new_instance(3, argv, RegexpOfHolding);
            *position += flags_length + 1;
            break;
        }
    case 12:
        {
            int collection_length;
            VALUE collection, str, oid, id, argv[2];
            collection_length = *(int*)(buffer + *position) - 1;
            *position += 4;
            collection = STR_NEW(buffer + *position, collection_length);
            *position += collection_length + 1;

            str = rb_str_new(buffer + *position, 12);
            oid = rb_funcall(str, rb_intern("unpack"), 1, rb_str_new2("C*"));
            id = rb_class_new_instance(1, &oid, ObjectID);
            *position += 12;

            argv[0] = collection;
            argv[1] = id;
            value = rb_class_new_instance(2, argv, DBRef);
            break;
        }
    case 14:
        {
            int value_length;
            memcpy(&value_length, buffer + *position, 4);
            value = ID2SYM(rb_intern(buffer + *position + 4));
            *position += value_length + 4;
            break;
        }
    case 15:
        {
            int code_length, scope_size;
            VALUE code, scope, argv[2];
            *position += 4;
            code_length = *(int*)(buffer + *position) - 1;
            *position += 4;
            code = STR_NEW(buffer + *position, code_length);
            *position += code_length + 1;

            memcpy(&scope_size, buffer + *position, 4);
            scope = elements_to_hash(buffer + *position + 4, scope_size - 5);
            *position += scope_size;

            argv[0] = code;
            argv[1] = scope;
            value = rb_class_new_instance(2, argv, Code);
            break;
        }
    case 16:
        {
            int i;
            memcpy(&i, buffer + *position, 4);
            value = LL2NUM(i);
            *position += 4;
            break;
        }
    case 17:
        {
            int i;
            int j;
            memcpy(&i, buffer + *position, 4);
            memcpy(&j, buffer + *position + 4, 4);
            value = rb_ary_new3(2, LL2NUM(i), LL2NUM(j));
            *position += 8;
            break;
        }
    case 18:
        {
            long long ll;
            memcpy(&ll, buffer + *position, 8);
            value = LL2NUM(ll);
            *position += 8;
            break;
        }
    case 127:
        {
            value = rb_class_new_instance(0, NULL, MaxKey);
            break;
        }
    default:
        {
            rb_raise(rb_eTypeError, "no c decoder for this type yet (%d)", type);
            break;
        }
    }
    return value;
}
Beispiel #18
0
/*
 * Array parser functions are thankfully borrowed from here:
 * https://github.com/dockyard/pg_array_parser
 */
static VALUE
read_array(t_pg_type *conv, int *index, char *c_pg_array_string, int array_string_length, char *word, int enc_idx, int tuple, int field, t_pg_type_dec_func dec_func)
{
	/* Return value: array */
	VALUE array;
	int word_index = 0;

	/* The current character in the input string. */
	char c;

	/*  0: Currently outside a quoted string, current word never quoted
	*  1: Currently inside a quoted string
	* -1: Currently outside a quoted string, current word previously quoted */
	int openQuote = 0;

	/* Inside quoted input means the next character should be treated literally,
	* instead of being treated as a metacharacter.
	* Outside of quoted input, means that the word shouldn't be pushed to the array,
	* used when the last entry was a subarray (which adds to the array itself). */
	int escapeNext = 0;

	array = rb_ary_new();

	/* Special case the empty array, so it doesn't need to be handled manually inside
	* the loop. */
	if(((*index) < array_string_length) && c_pg_array_string[(*index)] == '}')
	{
		return array;
	}

	for(;(*index) < array_string_length; ++(*index))
	{
		c = c_pg_array_string[*index];
		if(openQuote < 1)
		{
			if(c == ',' || c == '}')
			{
				if(!escapeNext)
				{
					if(openQuote == 0 && word_index == 4 && !strncmp(word, "NULL", word_index))
					{
						rb_ary_push(array, Qnil);
					}
					else
					{
						VALUE val;
						word[word_index] = 0;
						val = dec_func(conv, word, word_index, tuple, field, enc_idx);
						rb_ary_push(array, val);
					}
				}
				if(c == '}')
				{
					return array;
				}
				escapeNext = 0;
				openQuote = 0;
				word_index = 0;
			}
			else if(c == '"')
			{
				openQuote = 1;
			}
			else if(c == '{')
			{
				(*index)++;
				rb_ary_push(array, read_array(conv, index, c_pg_array_string, array_string_length, word, enc_idx, tuple, field, dec_func));
				escapeNext = 1;
			}
			else
			{
				word[word_index] = c;
				word_index++;
			}
		}
		else if (escapeNext) {
			word[word_index] = c;
			word_index++;
			escapeNext = 0;
		}
		else if (c == '\\')
		{
			escapeNext = 1;
		}
		else if (c == '"')
		{
			openQuote = -1;
		}
		else
		{
			word[word_index] = c;
			word_index++;
		}
	}

	return array;
}
Beispiel #19
0
static VALUE ctx_stack_to_value(struct state *state, int index)
{
  duk_context *ctx = state->ctx;
  size_t len;
  const char *buf;
  int type;

  state->was_complex = 0;

  type = duk_get_type(ctx, index);
  switch (type) {
    case DUK_TYPE_NULL:
    case DUK_TYPE_UNDEFINED:
      return Qnil;

    case DUK_TYPE_NUMBER:
      return rb_float_new(duk_get_number(ctx, index));

    case DUK_TYPE_BOOLEAN:
      return duk_get_boolean(ctx, index) ? Qtrue : Qfalse;

    case DUK_TYPE_STRING:
      buf = duk_get_lstring(ctx, index, &len);
      VALUE str = rb_str_new(buf, len);
      return decode_cesu8(state, str);

    case DUK_TYPE_OBJECT:
      if (duk_is_function(ctx, index)) {
        state->was_complex = 1;
        return state->complex_object;
      } else if (duk_is_array(ctx, index)) {
        VALUE ary = rb_ary_new();
        duk_enum(ctx, index, DUK_ENUM_ARRAY_INDICES_ONLY);
        while (duk_next(ctx, -1, 1)) {
          rb_ary_store(ary, duk_to_int(ctx, -2), ctx_stack_to_value(state, -1));
          duk_pop_2(ctx);
        }
        duk_pop(ctx);
        return ary;
      } else if (duk_is_object(ctx, index)) {
        VALUE hash = rb_hash_new();
        duk_enum(ctx, index, DUK_ENUM_OWN_PROPERTIES_ONLY);
        while (duk_next(ctx, -1, 1)) {
          VALUE key = ctx_stack_to_value(state, -2);
          VALUE val = ctx_stack_to_value(state, -1);
          duk_pop_2(ctx);
          if (state->was_complex)
            continue;
          rb_hash_aset(hash, key, val);
        }
        duk_pop(ctx);
        return hash;
      } else {
        state->was_complex = 1;
        return state->complex_object;
      }

    case DUK_TYPE_BUFFER:
    case DUK_TYPE_POINTER:
    default:
      return state->complex_object;
  }

  return Qnil;
}
Beispiel #20
0
static VALUE segmenter_segment(VALUE klass, VALUE input_, VALUE output_prefix_, VALUE duration_ ) {

    const char *input;
    const char *output_prefix;
    int segment_duration;
    long max_tsfiles = 0;
    double prev_segment_time = 0;
    unsigned int output_index = 1;
    AVInputFormat *ifmt;
    AVOutputFormat *ofmt;
    AVFormatContext *ic = NULL;
    AVFormatContext *oc;
    AVStream *video_st;
    AVStream *audio_st;
    AVCodec *codec;
    char *output_filename;
    char *remove_filename;
    int video_index;
    int audio_index;
    unsigned int first_segment = 1;
    unsigned int last_segment = 0;
    int decode_done;
    int ret;
    unsigned int i;
    int remove_file;
    
	bool soundOnly = false;

    VALUE sArray = rb_ary_new();
    av_register_all();
    av_log_set_level(AV_LOG_PANIC);

    input = RSTRING_PTR(input_);
    output_prefix = RSTRING_PTR(output_prefix_);
    segment_duration = (FIX2INT(duration_));
	
    char *folder = dirname2(strdup(input));
    
    remove_filename = malloc(sizeof(char) * (strlen(output_prefix) + 15));
    if (!remove_filename) {
        rb_raise(rb_eNoMemError, "Could not allocate space for remove filenames");
    }
    
    output_filename = malloc(sizeof(char) * (strlen(output_prefix) + strlen(folder) + 15));
    if (!output_filename) {
        rb_raise(rb_eNoMemError, "Could not allocate space for output filenames");
    }
    
        
    ifmt = av_find_input_format("mpegts");
    if (!ifmt) {
        rb_raise(rb_eException, "Could not find MPEG-TS demuxer");
    }
    
    ret = av_open_input_file(&ic, input, ifmt, 0, NULL);
    if (ret != 0) {
        rb_raise(rb_eException, "Could not open input file, make sure it is an mpegts file: %d %s", ret, input);
    }
    
    if (av_find_stream_info(ic) < 0) {
        rb_raise(rb_eException, "Could not read stream information");
    }
    
    ofmt = av_guess_format("mpegts", NULL, NULL);
    if (!ofmt) {
        rb_raise(rb_eException, "Could not find MPEG-TS muxer");
    }
    
    oc = avformat_alloc_context();
    if (!oc) {
        rb_raise(rb_eException, "Could not allocated output context");
    }
    oc->oformat = ofmt;

    ic->flags |= AVFMT_FLAG_IGNDTS;
    
    video_index = -1;
    audio_index = -1;
    
    for (i = 0; i < ic->nb_streams && (video_index < 0 || audio_index < 0); i++) {
        switch (ic->streams[i]->codec->codec_type) {
            case CODEC_TYPE_VIDEO:
                video_index = i;
                ic->streams[i]->discard = AVDISCARD_NONE;
                video_st = add_output_stream(oc, ic->streams[i]);
                break;
            case CODEC_TYPE_AUDIO:
                audio_index = i;
                ic->streams[i]->discard = AVDISCARD_NONE;
                audio_st = add_output_stream(oc, ic->streams[i]);
                break;
            default:
                ic->streams[i]->discard = AVDISCARD_ALL;
                break;
        }
    }

	if(!soundOnly) {
		soundOnly = (video_st != NULL);
	}

    if (av_set_parameters(oc, NULL) < 0) {
        rb_raise(rb_eException, "Invalid output format parameters");
    }
    
    dump_format(oc, 0, output_prefix, 1);



	if (!soundOnly) {
		if(video_st == NULL) {
			fprintf(stderr, "video_st is fail\n");
			rb_raise(rb_eException, "video_st fail");
			exit(1);
		}

		if(video_st->codec == NULL) {
			fprintf(stderr,"codec is fail\n");
			rb_raise(rb_eException, "codec fail");
			exit(1);
		}

		if(video_st->codec->codec_id == NULL) {
			fprintf(stderr, "codec_id is fail\n");
			rb_raise(rb_eException, "codec fail");
			exit(1);
		}

		codec = avcodec_find_decoder(video_st->codec->codec_id);
	    if (!codec) {
	        rb_raise(rb_eException, "Could not find video decoder, key frames will not be honored");
	    }
		
	    if (avcodec_open(video_st->codec, codec) < 0) {
	        rb_raise(rb_eException, "Could not open video decoder, key frames will not be honored");
	    }
    
    
	    if (video_st->codec->ticks_per_frame > 1) {
	        // h264 sets the ticks_per_frame and time_base.den but not time_base.num
	        // since we don't use ticks_per_frame, adjust time_base.num accordingly.
	        video_st->codec->time_base.num *= video_st->codec->ticks_per_frame;
	    }
	}
    
    snprintf(output_filename, strlen(output_prefix) + strlen(folder) + 15, "%s/%s-%u.ts", folder, output_prefix, output_index++);
    if (url_fopen(&oc->pb, output_filename, URL_WRONLY) < 0) {
        rb_raise(rb_eException, "Could not open '%s'", output_filename);
    }
    
    if (av_write_header(oc)) {
        rb_raise(rb_eException, "Could not write mpegts header to first output file");
    }
    
    //write_index = !write_index_file(index, tmp_index, segment_duration, output_prefix, http_prefix, first_segment, last_segment, 0, max_tsfiles);
    int64_t initial_audio_pts = -1;
    int64_t initial_video_pts = -1;
	double segment_time;
    do {
		
        AVPacket packet;
        //av_init_packet(&packet);
        decode_done = av_read_frame(ic, &packet);
        if (decode_done < 0) {
            break;
        }
        
        if (av_dup_packet(&packet) < 0) {
            rb_raise(rb_eException, "Could not duplicate packet");
            av_free_packet(&packet);
            break;
        }
		
		if (!soundOnly) {
	        if (packet.stream_index == video_index) {
	            if (initial_video_pts < 0) 
					initial_video_pts = packet.pts;
					
	            packet.pts -= initial_video_pts;
	            packet.dts = packet.pts;
	            if (packet.flags & AV_PKT_FLAG_KEY) {
	                segment_time = (double)packet.pts * video_st->time_base.num / video_st->time_base.den;
	            } else {
	                segment_time = prev_segment_time;            }
	        } else if (packet.stream_index == audio_index) {
	            if (initial_audio_pts < 0) initial_audio_pts = packet.pts;
	            packet.pts -= initial_audio_pts;
	            packet.dts = packet.pts;
	            segment_time = prev_segment_time;
	        } else {
	            segment_time = prev_segment_time;
	            segment_time = prev_segment_time;
	        }			
		} else {

			if (packet.stream_index == audio_index) {
				
	            if (initial_audio_pts < 0) 
					initial_audio_pts = packet.pts;
				
				if (packet.flags & AV_PKT_FLAG_KEY) {
					segment_time = (double)packet.pts * audio_st->time_base.num / audio_st->time_base.den;
				} else {
	            	segment_time = prev_segment_time;	
				}
					
	            packet.pts -= initial_audio_pts;
	            packet.dts = packet.pts;

	        } else {
	            segment_time = prev_segment_time;
	            segment_time = prev_segment_time;
	        }
		
		}



        if (segment_time - prev_segment_time >= segment_duration) {
            put_flush_packet(oc->pb);
            url_fclose(oc->pb);
            
            if (max_tsfiles && (int)(last_segment - first_segment) >= max_tsfiles - 1) {
                remove_file = 1;
                first_segment++;
            }
            else {
                remove_file = 0;
            }
            
            
            // Create Segment object
            VALUE seg = rb_obj_alloc(rb_cAvSegment);            

            rb_obj_call_init(seg, 0, 0);
            rb_iv_set(seg, "@index", INT2FIX(++last_segment));
            rb_iv_set(seg, "@duration",INT2FIX((int)floor((segment_time - prev_segment_time))));
            rb_iv_set(seg, "@filename", rb_str_new2(output_filename));
            
            rb_ary_push(sArray, seg);
            
            if (remove_file) {
                snprintf(remove_filename, strlen(output_prefix) + strlen(folder) + 15, "%s/%s-%u.ts", folder, output_prefix, first_segment - 1);
                //snprintf(remove_filename, strlen(output_prefix) + 15, "%s-%u.ts", output_prefix, first_segment - 1);
                remove(remove_filename);
            }
            
//            snprintf(output_filename, strlen(output_prefix) + 15, "%s-%u.ts", output_prefix, output_index++);
            snprintf(output_filename, strlen(output_prefix) + strlen(folder) + 15, "%s/%s-%u.ts", folder, output_prefix, output_index++);
            if (url_fopen(&oc->pb, output_filename, URL_WRONLY) < 0) {
                fprintf(stderr, "Could not open '%s'\n", output_filename);
                break;
            }
            
            prev_segment_time = segment_time;
        }

        ret = av_interleaved_write_frame(oc, &packet);
        if (ret < 0) {
            fprintf(stderr, "Warning: Could not write frame of stream\n");
        }
        else if (ret > 0) {
            fprintf(stderr, "End of stream requested\n");
            av_free_packet(&packet);
            break;
        }
        
        av_free_packet(&packet);
    } while (!decode_done);

    av_write_trailer(oc);

	if (!soundOnly)
    	avcodec_close(video_st->codec);

    for(i = 0; i < oc->nb_streams; i++) {		
		if(&oc->streams[i]->codec != NULL)
        	av_freep(&oc->streams[i]->codec);

		if (&oc->streams[i] != NULL)
        	av_freep(&oc->streams[i]);
    }

    url_fclose(oc->pb);
    av_free(oc);
    
    if (max_tsfiles && (int)(last_segment - first_segment) >= max_tsfiles - 1) {
        remove_file = 1;
        first_segment++;
    }
    else {
        remove_file = 0;
    }
 
    if (remove_file) {
        snprintf(remove_filename, strlen(output_prefix) + strlen(folder) + 15, "%s/%s-%u.ts", folder, output_prefix, first_segment - 1);
        remove(remove_filename);
    }
    return sArray;
}
Beispiel #21
0
static VALUE
reduce0(VALUE val, VALUE data, VALUE self)
{
    struct cparse_params *v;
    VALUE reduce_to, reduce_len, method_id;
    long len;
    ID mid;
    VALUE tmp, tmp_t = Qundef, tmp_v = Qundef;
    long i, k1, k2;
    VALUE goto_state;

    Data_Get_Struct(data, struct cparse_params, v);
    reduce_len = RARRAY_PTR(v->reduce_table)[v->ruleno];
    reduce_to  = RARRAY_PTR(v->reduce_table)[v->ruleno+1];
    method_id  = RARRAY_PTR(v->reduce_table)[v->ruleno+2];
    len = NUM2LONG(reduce_len);
    mid = value_to_id(method_id);

    /* call action */
    if (len == 0) {
        tmp = Qnil;
        if (mid != id_noreduce)
            tmp_v = rb_ary_new();
        if (v->debug)
            tmp_t = rb_ary_new();
    }
    else {
        if (mid != id_noreduce) {
            tmp_v = GET_TAIL(v->vstack, len);
            tmp = RARRAY_PTR(tmp_v)[0];
        }
        else {
            tmp = RARRAY_PTR(v->vstack)[ RARRAY_LEN(v->vstack) - len ];
        }
        CUT_TAIL(v->vstack, len);
        if (v->debug) {
            tmp_t = GET_TAIL(v->tstack, len);
            CUT_TAIL(v->tstack, len);
        }
        CUT_TAIL(v->state, len);
    }
    if (mid != id_noreduce) {
        if (v->use_result_var) {
            tmp = rb_funcall(v->parser, mid,
                             3, tmp_v, v->vstack, tmp);
        }
        else {
            tmp = rb_funcall(v->parser, mid,
                             2, tmp_v, v->vstack);
        }
    }

    /* then push result */
    PUSH(v->vstack, tmp);
    if (v->debug) {
        PUSH(v->tstack, reduce_to);
        rb_funcall(v->parser, id_d_reduce,
                   4, tmp_t, reduce_to, v->tstack, v->vstack);
    }

    /* calculate transition state */
    if (RARRAY_LEN(v->state) == 0)
        rb_raise(RaccBug, "state stack unexpectedly empty");
    k2 = num_to_long(LAST_I(v->state));
    k1 = num_to_long(reduce_to) - v->nt_base;
    D_printf("(goto) k1=%ld\n", k1);
    D_printf("(goto) k2=%ld\n", k2);

    tmp = AREF(v->goto_pointer, k1);
    if (NIL_P(tmp)) goto notfound;

    i = NUM2LONG(tmp) + k2;
    D_printf("(goto) i=%ld\n", i);
    if (i < 0) goto notfound;

    goto_state = AREF(v->goto_table, i);
    if (NIL_P(goto_state)) {
        D_puts("(goto) table[i] == nil");
        goto notfound;
    }
    D_printf("(goto) table[i]=%ld (goto_state)\n", NUM2LONG(goto_state));

    tmp = AREF(v->goto_check, i);
    if (NIL_P(tmp)) {
        D_puts("(goto) check[i] == nil");
        goto notfound;
    }
    if (tmp != LONG2NUM(k1)) {
        D_puts("(goto) check[i] != table[i]");
        goto notfound;
    }
    D_printf("(goto) check[i]=%ld\n", NUM2LONG(tmp));

    D_puts("(goto) found");
  transit:
    PUSH(v->state, goto_state);
    v->curstate = NUM2LONG(goto_state);
    return INT2FIX(0);

  notfound:
    D_puts("(goto) not found: use default");
    /* overwrite `goto-state' by default value */
    goto_state = AREF(v->goto_default, k1);
    goto transit;
}
Beispiel #22
0
VALUE
subViewClients(VALUE self)
{
  int i, nclients = 0;
  Window *clients = NULL;
  VALUE id = Qnil, klass = Qnil, meth = Qnil, array = Qnil, client = Qnil;
  unsigned long *view_tags = NULL;

  /* Check ruby object */
  rb_check_frozen(self);
  GET_ATTR(self, "@id", id);

  subSubtlextConnect(NULL); ///< Implicit open connection

  /* Fetch data */
  klass     = rb_const_get(mod, rb_intern("Client"));
  meth      = rb_intern("new");
  array     = rb_ary_new();
  clients   = subSubtlextWindowList("_NET_CLIENT_LIST", &nclients);
  view_tags = (unsigned long *)subSharedPropertyGet(display,
    DefaultRootWindow(display), XA_CARDINAL,
    XInternAtom(display, "SUBTLE_VIEW_TAGS", False), NULL);

  /* Check results */
  if(clients && view_tags)
    {
      for(i = 0; i < nclients; i++)
        {
          unsigned long *client_tags = NULL, *flags = NULL;

          /* Fetch window data */
          client_tags = (unsigned long *)subSharedPropertyGet(display,
            clients[i], XA_CARDINAL,
            XInternAtom(display, "SUBTLE_CLIENT_TAGS", False), NULL);
          flags       = (unsigned long *)subSharedPropertyGet(display,
            clients[i], XA_CARDINAL,
            XInternAtom(display, "SUBTLE_CLIENT_FLAGS", False), NULL);

          /* Check if there are common tags or window is stick */
          if((client_tags && view_tags[FIX2INT(id)] & *client_tags) ||
              (flags && *flags & SUB_EWMH_STICK))
            {
              if(RTEST(client = rb_funcall(klass, meth,
                  1, LONG2NUM(clients[i]))))
                {
                  subClientUpdate(client);

                  rb_ary_push(array, client);
                }
            }

          if(client_tags) free(client_tags);
          if(flags)       free(flags);
        }
    }

  if(clients)   free(clients);
  if(view_tags) free(view_tags);

  return array;
} /* }}} */
Beispiel #23
0
/*
 * call-seq:
 *    ProcTable.ps(pid=nil)
 *    ProcTable.ps(pid=nil){ |ps| ... }
 *
 * In block form, yields a ProcTableStruct for each process entry that you
 * have rights to.  This method returns an array of ProcTableStruct's in
 * non-block form.
 *
 * If a +pid+ is provided, then only a single ProcTableStruct is yielded or
 * returned, or nil if no process information is found for that +pid+.
 */
static VALUE pt_ps(int argc, VALUE* argv, VALUE klass){
   kvm_t *kd;
   char errbuf[_POSIX2_LINE_MAX];
   char cmdline[_POSIX_ARG_MAX+1];
   char state[8];
   char** args = malloc(sizeof(char*));
   struct kinfo_proc* procs;
   int count;                     /* Holds total number of processes */
   int i = 0;
   VALUE v_pid, v_tty_num, v_tty_dev, v_start_time;
   VALUE v_pstruct = Qnil;
   VALUE v_array = Qnil;

   rb_scan_args(argc, argv, "01", &v_pid);

   if(!rb_block_given_p())
      v_array = rb_ary_new();

   // Open the kvm interface, get a descriptor
   if ((kd = kvm_open(NULL, NULL, NULL, 0, errbuf)) == NULL)
      rb_raise(cProcTableError, errbuf);

   // Get the list of processes
   if ((procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count)) == NULL) {
      strcpy(errbuf,kvm_geterr(kd));
      kvm_close(kd);
      rb_raise(cProcTableError, errbuf);
   }

   for(i=0; i<count; i++){
      // Reset some variables
      v_tty_num = Qnil;
      v_tty_dev = Qnil;
      v_start_time = Qnil;

      // If a PID is provided, skip unless the PID matches
      if(!NIL_P(v_pid)){
#ifdef HAVE_ST_KP_PROC
         if(procs[i].kp_proc.p_pid != NUM2INT(v_pid))
            continue;
#else
         if(procs[i].ki_pid != NUM2INT(v_pid))
            continue;
#endif
      }

      // Get the command line arguments for the process
      cmdline[0] = '\0';
      args = kvm_getargv(kd, (const struct kinfo_proc *)&procs[i], 0);
      if(args){
         int j = 0;
         while (args[j] && strlen(cmdline) <= _POSIX_ARG_MAX) {
            strcat(cmdline, args[j]);
            strcat(cmdline, " ");
            j++;
          }
      }

      // Get the start time of the process
      v_start_time = rb_time_new(
#ifdef HAVE_ST_E_STATS
         procs[i].kp_eproc.e_stats.p_start.tv_sec,
         procs[i].kp_eproc.e_stats.p_start.tv_usec
#else
         0,0
#endif
      );

      // Get the state of the process
#ifdef HAVE_ST_KP_PROC
      switch(procs[i].kp_proc.p_stat)
#else
      switch(procs[i].ki_stat)
#endif
      {
         case SIDL:
            strcpy(state, "idle");
            break;
         case SRUN:
            strcpy(state, "run");
            break;
         case SSLEEP:
            strcpy(state, "sleep");
            break;
         case SSTOP:
            strcpy(state, "stop");
            break;
         case SZOMB:
            strcpy(state, "zombie");
            break;
         default:
            strcpy(state, "unknown");
            break;
      }

      // Get ttynum and ttydev. If ttynum is -1, there is no tty
#ifdef HAVE_ST_KP_EPROC
      v_tty_num = INT2FIX(procs[i].kp_eproc.e_tdev),
      v_tty_dev = rb_str_new2(devname(procs[i].kp_eproc.e_tdev, S_IFCHR));
#elif HAVE_ST_U_KPROC
      v_tty_num = INT2FIX(procs[i].u_kproc.ki_tdev),
      v_tty_dev = rb_str_new2(devname(procs[i].u_kproc.ki_tdev, S_IFCHR));
#else
      v_tty_num = INT2FIX(procs[i].ki_tdev),
      v_tty_dev = rb_str_new2(devname(procs[i].ki_tdev, S_IFCHR));
#endif

#ifdef HAVE_ST_KP_PROC
      v_pstruct = rb_struct_new(
         sProcStruct,
         INT2FIX(procs[i].kp_proc.p_pid),
         INT2FIX(procs[i].kp_eproc.e_ppid),
         INT2FIX(procs[i].kp_eproc.e_pgid),
         INT2FIX(procs[i].kp_eproc.e_pcred.p_ruid),
         INT2FIX(procs[i].kp_eproc.e_pcred.p_rgid),
         rb_str_new2(procs[i].kp_proc.p_comm),
         rb_str_new2(state),
         rb_float_new(procs[i].kp_proc.p_pctcpu),
#ifdef HAVE_ST_P_ONCPU
         INT2FIX(procs[i].kp_proc.p_oncpu),
#else
         Qnil,
#endif
         v_tty_num,
         v_tty_dev,
         rb_str_new2(procs[i].kp_eproc.e_wmesg),
#ifdef HAVE_ST_P_RUNTIME
         INT2FIX(procs[i].kp_proc.p_runtime/1000000),
#else
         Qnil,
#endif
         INT2FIX(procs[i].kp_proc.p_priority),
         INT2FIX(procs[i].kp_proc.p_usrpri),
         INT2FIX(procs[i].kp_proc.p_nice),
         rb_str_new2(cmdline),
         v_start_time,
#ifdef HAVE_ST_E_STATS
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_maxrss),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_ixrss),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_idrss),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_isrss),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_minflt),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_majflt),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_nswap),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_inblock),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_oublock),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_msgsnd),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_msgrcv),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_nsignals),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_nvcsw),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_nivcsw),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_utime.tv_sec),
         LONG2NUM(procs[i].kp_eproc.e_stats.p_ru.ru_stime.tv_sec)
#else
         Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil,
         Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil
#endif
      );
#else
      v_pstruct = rb_struct_new(
         sProcStruct,
         INT2FIX(procs[i].ki_pid),
         INT2FIX(procs[i].ki_ppid),
         INT2FIX(procs[i].ki_pgid),
         INT2FIX(procs[i].ki_ruid),
         INT2FIX(procs[i].ki_rgid),
         rb_str_new2(procs[i].ki_ocomm),
         rb_str_new2(state),
         rb_float_new(procs[i].ki_pctcpu),
         INT2FIX(procs[i].ki_oncpu),
         v_tty_num,
         v_tty_dev,
         rb_str_new2(procs[i].ki_wmesg),
         INT2FIX(procs[i].ki_runtime/1000000),
         INT2FIX(procs[i].ki_pri.pri_level),
         INT2FIX(procs[i].ki_pri.pri_user),
         INT2FIX(procs[i].ki_nice),
         rb_str_new2(cmdline),
         v_start_time,
         Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil,
         Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil
      );
#endif

      OBJ_FREEZE(v_pstruct); /* Read-only data */

      if(rb_block_given_p())
         rb_yield(v_pstruct);
      else
         rb_ary_push(v_array, v_pstruct);
   }

   free(args);

   if(kd)
      kvm_close(kd);

   if(!NIL_P(v_pid))
      return v_pstruct;

   return v_array; // Nil if block given
}
Beispiel #24
0
VALUE listaalunos(VALUE self) {
  rb_ary_new();
}
Beispiel #25
0
static void
vm_backtrace_alloc(void *arg)
{
    VALUE *aryp = arg;
    *aryp = rb_ary_new();
}
Beispiel #26
0
static VALUE rb_mysql_result_each(int argc, VALUE * argv, VALUE self) {
  VALUE defaults, opts, block;
  ID db_timezone, app_timezone, dbTz, appTz;
  mysql2_result_wrapper * wrapper;
  unsigned long i;
  int symbolizeKeys = 0, asArray = 0, castBool = 0, cacheRows = 1;

  GetMysql2Result(self, wrapper);

  defaults = rb_iv_get(self, "@query_options");
  if (rb_scan_args(argc, argv, "01&", &opts, &block) == 1) {
    opts = rb_funcall(defaults, intern_merge, 1, opts);
  } else {
    opts = defaults;
  }

  if (rb_hash_aref(opts, sym_symbolize_keys) == Qtrue) {
    symbolizeKeys = 1;
  }

  if (rb_hash_aref(opts, sym_as) == sym_array) {
    asArray = 1;
  }

  if (rb_hash_aref(opts, sym_cast_booleans) == Qtrue) {
    castBool = 1;
  }

  if (rb_hash_aref(opts, sym_cache_rows) == Qfalse) {
    cacheRows = 0;
  }

  dbTz = rb_hash_aref(opts, sym_database_timezone);
  if (dbTz == sym_local) {
    db_timezone = intern_local;
  } else if (dbTz == sym_utc) {
    db_timezone = intern_utc;
  } else {
    if (!NIL_P(dbTz)) {
      rb_warn(":database_timezone option must be :utc or :local - defaulting to :local");
    }
    db_timezone = intern_local;
  }

  appTz = rb_hash_aref(opts, sym_application_timezone);
  if (appTz == sym_local) {
    app_timezone = intern_local;
  } else if (appTz == sym_utc) {
    app_timezone = intern_utc;
  } else {
    app_timezone = Qnil;
  }

  if (wrapper->lastRowProcessed == 0) {
    wrapper->numberOfRows = mysql_num_rows(wrapper->result);
    if (wrapper->numberOfRows == 0) {
      wrapper->rows = rb_ary_new();
      return wrapper->rows;
    }
    wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
  }

  if (cacheRows && wrapper->lastRowProcessed == wrapper->numberOfRows) {
    // we've already read the entire dataset from the C result into our
    // internal array. Lets hand that over to the user since it's ready to go
    for (i = 0; i < wrapper->numberOfRows; i++) {
      rb_yield(rb_ary_entry(wrapper->rows, i));
    }
  } else {
    unsigned long rowsProcessed = 0;
    rowsProcessed = RARRAY_LEN(wrapper->rows);
    for (i = 0; i < wrapper->numberOfRows; i++) {
      VALUE row;
      if (cacheRows && i < rowsProcessed) {
        row = rb_ary_entry(wrapper->rows, i);
      } else {
        row = rb_mysql_result_fetch_row(self, db_timezone, app_timezone, symbolizeKeys, asArray, castBool);
        if (cacheRows) {
          rb_ary_store(wrapper->rows, i, row);
        }
        wrapper->lastRowProcessed++;
      }

      if (row == Qnil) {
        // we don't need the mysql C dataset around anymore, peace it
        rb_mysql_result_free_result(wrapper);
        return Qnil;
      }

      if (block != Qnil) {
        rb_yield(row);
      }
    }
    if (wrapper->lastRowProcessed == wrapper->numberOfRows) {
      // we don't need the mysql C dataset around anymore, peace it
      rb_mysql_result_free_result(wrapper);
    }
  }

  return wrapper->rows;
}
static int parse_osm_header(VALUE obj, FILE *input)
{
  OSMPBF__BlobHeader *header = read_blob_header(input);

  // EOF reached
  if(header == NULL)
    rb_raise(rb_eEOFError, "EOF reached without finding data");

  if(strcmp("OSMHeader", header->type) != 0)
    rb_raise(rb_eIOError, "OSMHeader not found, probably the file is corrupt or invalid");

  void *blob = NULL;
  size_t blob_length = 0, datasize = header->datasize;
  OSMPBF__HeaderBlock *header_block = NULL;

  osmpbf__blob_header__free_unpacked(header, NULL);

  blob = read_blob(input, datasize, &blob_length);
  header_block = osmpbf__header_block__unpack(NULL, blob_length, blob);

  free(blob);

  if(header_block == NULL)
    rb_raise(rb_eIOError, "Unable to unpack the HeaderBlock");

  VALUE header_hash = rb_hash_new();
  VALUE bbox_hash   = rb_hash_new();

  VALUE required_features = Qnil;
  VALUE optional_features = Qnil;
  VALUE writingprogram    = Qnil;
  VALUE source            = Qnil;

  VALUE osmosis_replication_timestamp       = Qnil;
  VALUE osmosis_replication_sequence_number = Qnil;
  VALUE osmosis_replication_base_url        = Qnil;

  int i = 0;

  if(header_block->n_required_features > 0)
  {
    required_features = rb_ary_new();

    for(i = 0; i < (int)header_block->n_required_features; i++)
      rb_ary_push(required_features, str_new(header_block->required_features[i]));
  }

  if(header_block->n_optional_features > 0)
  {
    optional_features = rb_ary_new();

    for(i = 0; i < (int)header_block->n_optional_features; i++)
      rb_ary_push(optional_features, str_new(header_block->optional_features[i]));
  }

  if(header_block->writingprogram)
    writingprogram = str_new(header_block->writingprogram);

  if(header_block->source)
    source = str_new(header_block->source);

  if(header_block->bbox)
  {
    rb_hash_aset(bbox_hash, STR2SYM("top"),    rb_float_new(header_block->bbox->top * NANO_DEGREE));
    rb_hash_aset(bbox_hash, STR2SYM("right"),  rb_float_new(header_block->bbox->right * NANO_DEGREE));
    rb_hash_aset(bbox_hash, STR2SYM("bottom"), rb_float_new(header_block->bbox->bottom * NANO_DEGREE));
    rb_hash_aset(bbox_hash, STR2SYM("left"),   rb_float_new(header_block->bbox->left * NANO_DEGREE));
  }

  if(header_block->has_osmosis_replication_timestamp)
    osmosis_replication_timestamp = ULL2NUM(header_block->osmosis_replication_timestamp);

  if(header_block->has_osmosis_replication_sequence_number)
    osmosis_replication_sequence_number = ULL2NUM(header_block->osmosis_replication_sequence_number);

  if(header_block->osmosis_replication_base_url)
    osmosis_replication_base_url = str_new(header_block->osmosis_replication_base_url);

  rb_hash_aset(header_hash, str_new("bbox"), bbox_hash);
  rb_hash_aset(header_hash, str_new("required_features"), required_features);
  rb_hash_aset(header_hash, str_new("optional_features"), optional_features);
  rb_hash_aset(header_hash, str_new("writing_program"), writingprogram);
  rb_hash_aset(header_hash, str_new("source"), source);
  rb_hash_aset(header_hash, str_new("osmosis_replication_timestamp"), osmosis_replication_timestamp);
  rb_hash_aset(header_hash, str_new("osmosis_replication_sequence_number"), osmosis_replication_sequence_number);
  rb_hash_aset(header_hash, str_new("osmosis_replication_base_url"), osmosis_replication_base_url);

  rb_iv_set(obj, "@header", header_hash);

  osmpbf__header_block__free_unpacked(header_block, NULL);

  return 1;
}
Beispiel #28
0
VALUE sfcc_cimdata_to_value(CIMCData data)
{
  CIMCString *cimstr = NULL;
  VALUE rbval;
  CIMCStatus status;

  if (data.type & CMPI_ARRAY) {
    int k = 0;
    int n = 0;
    VALUE rbarray = rb_ary_new();

    if (!data.value.array)
      return rb_ary_new();

    n = data.value.array->ft->getSize(data.value.array, &status);
    if (!status.rc) {
      for (k = 0; k < n; ++k) {
        CIMCData element = data.value.array->ft->getElementAt(data.value.array, k, NULL);
        rb_ary_push(rbarray, sfcc_cimdata_to_value(element));
      }
      return rbarray;
    }
    sfcc_rb_raise_if_error(status, "Can't retrieve array size");
    return Qnil;
  }
  else if (data.type & CMPI_ENC) {
    switch (data.type) {
    case CMPI_instance:
      return data.value.inst ? Sfcc_wrap_cim_instance(data.value.inst->ft->clone(data.value.inst, NULL)) : Qnil;
    case CMPI_class:
      return data.value.cls ? Sfcc_wrap_cim_class(data.value.cls->ft->clone(data.value.cls, NULL)) : Qnil;
    case CMPI_ref:
      return data.value.ref ? Sfcc_wrap_cim_object_path(data.value.ref->ft->clone(data.value.ref, NULL)) : Qnil;
    case CMPI_args:
      return data.value.args ? sfcc_cimargs_to_hash(data.value.args) : Qnil;
    case CMPI_filter:
      return Qnil;
    case CMPI_numericString:
    case CMPI_booleanString:
    case CMPI_dateTimeString:
    case CMPI_classNameString:
      break;
    case CMPI_string:
      return data.value.string ? rb_str_new2((char*)data.value.string->ft->getCharPtr(data.value.string, NULL)) : Qnil;
    case CMPI_charsptr:
      return data.value.chars ? rb_str_new((char*)data.value.dataPtr.ptr, data.value.dataPtr.length) : Qnil;
    case CMPI_dateTime:
      cimstr = data.value.dateTime ? CMGetStringFormat(data.value.dateTime,NULL) : NULL;
      rbval = cimstr ? rb_str_new2(cimstr->ft->getCharPtr(cimstr, NULL)) : Qnil;
      if (cimstr) CMRelease(cimstr);
      return rbval;
    }
  }
  else if (data.type & CMPI_SIMPLE) {
    switch (data.type) {
    case CMPI_boolean: return data.value.boolean ? Qtrue : Qfalse;
    case CMPI_char16: return UINT2NUM(data.value.char16);
    }
  }
  else if (data.type & CMPI_INTEGER) {
    switch (data.type) {
    case CMPI_uint8: return UINT2NUM(data.value.uint8);
    case CMPI_sint8: return INT2NUM(data.value.sint8);
    case CMPI_uint16: return UINT2NUM(data.value.uint16);
    case CMPI_sint16: return INT2NUM(data.value.sint16);
    case CMPI_uint32: return UINT2NUM(data.value.uint32);
    case CMPI_sint32: return INT2NUM(data.value.sint32);
    case CMPI_uint64: return UINT2NUM(data.value.uint64);
    case CMPI_sint64: return INT2NUM(data.value.sint64);
    }
  }
  else if (data.type & CMPI_REAL) {
    switch (data.type) {
    case CMPI_real32: return LONG2NUM(data.value.real32);
    case CMPI_real64: return LONG2NUM(data.value.real64);
    }
  }
  else if (data.type & CMPI_null ) {
    return Qnil;
  }
  rb_raise(rb_eTypeError, "unsupported data data type %d", data.type);
  return Qnil;
}
Beispiel #29
0
/* FIXME: DON'T WORK!!! */
static VALUE
rb_grn_view_sort (int argc, VALUE *argv, VALUE self)
{
    VALUE rb_result = Qnil;

#ifdef WIN32
    rb_raise(rb_eNotImpError, "grn_view_add() isn't available on Windows.");
#else
    grn_ctx *context = NULL;
    grn_obj *view;
    grn_obj *result;
    grn_table_sort_key *keys;
    int i, n_keys;
    int offset = 0, limit = -1;
    VALUE rb_keys, options;
    VALUE rb_offset, rb_limit;
    VALUE *rb_sort_keys;
    grn_table_cursor *cursor;
    VALUE exception;
    grn_obj id;

    rb_grn_table_deconstruct(SELF(self), &view, &context,
			     NULL, NULL,
			     NULL, NULL, NULL,
			     NULL);

    rb_scan_args(argc, argv, "11", &rb_keys, &options);

    if (!RVAL2CBOOL(rb_obj_is_kind_of(rb_keys, rb_cArray)))
	rb_raise(rb_eArgError, "keys should be an array of key: <%s>",
		 rb_grn_inspect(rb_keys));

    n_keys = RARRAY_LEN(rb_keys);
    rb_sort_keys = RARRAY_PTR(rb_keys);
    keys = ALLOCA_N(grn_table_sort_key, n_keys);
    for (i = 0; i < n_keys; i++) {
	VALUE rb_sort_options, rb_key, rb_resolved_key, rb_order;

	if (RVAL2CBOOL(rb_obj_is_kind_of(rb_sort_keys[i], rb_cHash))) {
	    rb_sort_options = rb_sort_keys[i];
	} else if (RVAL2CBOOL(rb_obj_is_kind_of(rb_sort_keys[i], rb_cArray))) {
	    rb_sort_options = rb_hash_new();
	    rb_hash_aset(rb_sort_options,
			 RB_GRN_INTERN("key"),
			 rb_ary_entry(rb_sort_keys[i], 0));
	    rb_hash_aset(rb_sort_options,
			 RB_GRN_INTERN("order"),
			 rb_ary_entry(rb_sort_keys[i], 1));
	} else {
	    rb_sort_options = rb_hash_new();
	    rb_hash_aset(rb_sort_options,
			 RB_GRN_INTERN("key"),
			 rb_sort_keys[i]);
	}
	rb_grn_scan_options(rb_sort_options,
			    "key", &rb_key,
			    "order", &rb_order,
			    NULL);
	if (RVAL2CBOOL(rb_obj_is_kind_of(rb_key, rb_cString))) {
	    rb_resolved_key = rb_grn_table_get_column(self, rb_key);
	} else {
	    rb_resolved_key = rb_key;
	}
	keys[i].key = RVAL2GRNOBJECT(rb_resolved_key, &context);
	if (!keys[i].key) {
	    rb_raise(rb_eGrnNoSuchColumn,
		     "no such column: <%s>: <%s>",
		     rb_grn_inspect(rb_key), rb_grn_inspect(self));
	}
	if (NIL_P(rb_order)) {
	    keys[i].flags = 0;
	} else if (rb_grn_equal_option(rb_order, "desc") ||
		   rb_grn_equal_option(rb_order, "descending")) {
	    keys[i].flags = GRN_TABLE_SORT_DESC;
	} else if (rb_grn_equal_option(rb_order, "asc") ||
		   rb_grn_equal_option(rb_order, "ascending")) {
	    keys[i].flags = GRN_TABLE_SORT_ASC;
	} else {
	    rb_raise(rb_eArgError,
		     "order should be one of "
		     "[nil, :desc, :descending, :asc, :ascending]: %s",
		     rb_grn_inspect(rb_order));
	}
    }

    rb_grn_scan_options(options,
			"offset", &rb_offset,
			"limit", &rb_limit,
			NULL);

    if (!NIL_P(rb_offset))
	offset = NUM2INT(rb_offset);
    if (!NIL_P(rb_limit))
	limit = NUM2INT(rb_limit);

    result = grn_table_create(context, NULL, 0, NULL, GRN_TABLE_VIEW,
			      NULL, NULL);
    /* use n_records that is return value from
       grn_table_sort() when rroonga user become specifying
       output table. */
    grn_table_sort(context, view, offset, limit, result, keys, n_keys);
    exception = rb_grn_context_to_exception(context, self);
    if (!NIL_P(exception)) {
        grn_obj_unlink(context, result);
        rb_exc_raise(exception);
    }

    rb_result = rb_ary_new();
    cursor = grn_table_cursor_open(context, result, NULL, 0, NULL, 0,
				   0, -1, GRN_CURSOR_ASCENDING);
    GRN_TEXT_INIT(&id, 0);
    while (grn_table_cursor_next_o(context, cursor, &id) == GRN_SUCCESS) {
	rb_ary_push(rb_result, rb_grn_view_record_new(self, &id));
    }
    GRN_OBJ_FIN(context, &id);
    grn_table_cursor_close(context, cursor);
    grn_obj_unlink(context, result);
#endif

    return rb_result;
}
Beispiel #30
0
void
Init_QGF_Graphics() {

	qgf_graphics_width      = QGF_GRAPHICS_DEFAULT_WIDTH;
	qgf_graphics_height     = QGF_GRAPHICS_DEFAULT_HEIGHT;
	qgf_graphics_frame_rate = QGF_GRAPHICS_DEFAULT_FRAME_RATE;
	qgf_graphics_frame_count = 0;
	qgf_graphics_brightness = 255;
	qgf_graphics_frame_skip = qgf_graphics_frame_rate / 10;
	qgf_graphics_needed_frame_skips = 0;
	qgf_graphics_last_ticks = qgf_tools_time_getTicks();
	qgf_graphics_next_ticks = qgf_tools_time_getTicks() + 1000 / qgf_graphics_frame_rate;
	rb_mGraphics = rb_define_module("Graphics");

	rb_cv_set(rb_mGraphics, "@@wndw_title", rb_str_new2("QGF Window"));
	rb_cv_set(rb_mGraphics, "@@drawable_objects", rb_ary_new());

	rb_define_singleton_method(rb_mGraphics, "update", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_update), 0);
	rb_define_singleton_method(rb_mGraphics, "wait", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_wait), 1);
	rb_define_singleton_method(rb_mGraphics, "fadein", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_fadein), 1);
	rb_define_singleton_method(rb_mGraphics, "fadeout", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_fadeout), 1);
	rb_define_singleton_method(rb_mGraphics, "freeze", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_freeze), 0);
	rb_define_singleton_method(rb_mGraphics, "transition", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_transition), -1);
	rb_define_singleton_method(rb_mGraphics, "snap_to_bitmap", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_snap_to_bitmap), 0);
	rb_define_singleton_method(rb_mGraphics, "frame_reset", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_frame_reset), 0);
	rb_define_singleton_method(rb_mGraphics, "width", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_width), 0);
	rb_define_singleton_method(rb_mGraphics, "height", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_height), 0);
	rb_define_singleton_method(rb_mGraphics, "resize_screen", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_resize_screen), 0);
	rb_define_singleton_method(rb_mGraphics, "play_movie", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_play_movie), 0);

	rb_define_singleton_method(rb_mGraphics, "frame_rate", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_GETframe_rate), 0);
	rb_define_singleton_method(rb_mGraphics, "frame_rate=", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_SETframe_rate), 1);

	rb_define_singleton_method(rb_mGraphics, "frame_count", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_GETframe_count), 0);
	rb_define_singleton_method(rb_mGraphics, "frame_count=", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_SETframe_count), 1);

	rb_define_singleton_method(rb_mGraphics, "brightness", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_GETbrightness), 0);
	rb_define_singleton_method(rb_mGraphics, "brightness=", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_SETbrightness), 1);

	rb_define_singleton_method(rb_mGraphics, "window_title", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_GETwindow_title), 0);
	rb_define_singleton_method(rb_mGraphics, "window_title=", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_SETwindow_title), 1);

	rb_define_singleton_method(rb_mGraphics, "frame_skip", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_GETframe_skip), 0);
	rb_define_singleton_method(rb_mGraphics, "frame_skip=", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_SETframe_skip), 1);

	rb_define_singleton_method(rb_mGraphics, "real_frame_rate", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_real_frame_rate), 0);

	rb_define_singleton_method(rb_mGraphics, "to_bmp", RUBY_METHOD_FUNC(rb_mGraphicsCLASS_to_bmp), 1);

	Init_QGF_Graphics_Color();
	Init_QGF_Graphics_Tone();
	Init_QGF_Graphics_Bitmap();
	Init_QGF_Graphics_Font();
	Init_QGF_Graphics_Rect();
	Init_QGF_Graphics_Sprite();
	Init_QGF_Graphics_Plane();
	Init_QGF_Graphics_Table();
	Init_QGF_Graphics_Viewport();

	rb_cv_set(rb_mGraphics, "@@bckgrnd_clr", rb_color_new());

}