示例#1
0
bool
IOSCSITape::LOAD_UNLOAD(
	SCSITaskIdentifier	request,
	SCSICmdField1Bit	IMMED,
	SCSICmdField1Bit	HOLD,
	SCSICmdField1Bit	EOT,
	SCSICmdField1Bit	RETEN,
	SCSICmdField1Bit	LOAD,
	SCSICmdField1Byte	CONTROL)
{
	bool result = false;
	
	require(IsParameterValid(IMMED, kSCSICmdFieldMask1Bit), ErrorExit);
	require(IsParameterValid(HOLD, kSCSICmdFieldMask1Bit), ErrorExit);
	require(IsParameterValid(EOT, kSCSICmdFieldMask1Bit), ErrorExit);
	require(IsParameterValid(RETEN, kSCSICmdFieldMask1Bit), ErrorExit);
	require(IsParameterValid(LOAD, kSCSICmdFieldMask1Bit), ErrorExit);
	require(IsParameterValid(CONTROL, kSCSICmdFieldMask1Byte), ErrorExit);
	
	SetCommandDescriptorBlock(request, 
							  kSCSICmd_LOAD_UNLOAD, 
							  IMMED, 
							  0x00, 
							  0x00, 
							  (HOLD  << 3) |
							  (EOT   << 2) |
							  (RETEN << 1) |
							   LOAD, 
							  CONTROL);
	
	SetDataTransferDirection(request, kSCSIDataTransfer_NoDataTransfer);
	
	SetTimeoutDuration(request, SCSI_MOTION_TIMEOUT);
	
	result = true;
	
ErrorExit:
	
	return result;
}
示例#2
0
pairing_node_t
pairing_node_init(
	pairing_node_t self,
	nyoci_node_t parent,
	const char* name,
	const char* path
) {
	FILE* file = fopen(path, "r");
	char* line = NULL;
	size_t line_len = 0;

	NYOCI_LIBRARY_VERSION_CHECK();

	require(name != NULL, bail);

	require(self || (self = pairing_node_alloc()), bail);
	require(nyoci_node_init(
			&self->node,
			(void*)parent,
			name
	), bail);

	self->node.has_link_content = 1;
//	self->node.is_observable = 1;
	self->interface = nyoci_get_current_instance();

	smcp_pairing_mgr_init(&self->pairing_mgr, self->interface);

	((nyoci_node_t)&self->node)->request_handler = (void*)&smcp_pairing_mgr_request_handler;
	((nyoci_node_t)&self->node)->context = (void*)&self->pairing_mgr;

	self->next_observer_refresh = nyoci_plat_cms_to_timestamp(NYOCI_OBSERVATION_KEEPALIVE_INTERVAL - MSEC_PER_SEC);

	require(file != NULL, bail);

	while(!feof(file) && (line=fgetln(file,&line_len))) {
		char *cmd = get_next_arg(line, &line);
		if (!cmd) {
			continue;
		} else if (strcaseequal(cmd, "Pairing")) {
			char* pairing_id_str = get_next_arg(line, &line);
			char* pairing_local_path_str = get_next_arg(line, &line);
			char* pairing_remote_url_str = get_next_arg(line, &line);
			char* pairing_enabled_str = get_next_arg(line, &line);
			char* pairing_content_type_str = get_next_arg(line, &line);
			if ( (pairing_id_str == NULL)
			  || (pairing_local_path_str == NULL)
			  || (pairing_remote_url_str == NULL)
			  || (pairing_enabled_str == NULL)
			  || (pairing_content_type_str == NULL)
			) {
				break;
			}
			smcp_pairing_t pairing = smcp_pairing_mgr_new_pairing(
				&self->pairing_mgr,
				pairing_local_path_str,
				pairing_remote_url_str,
				(uint8_t)atoi(pairing_id_str)
			);

			smcp_pairing_set_content_type(pairing, (coap_content_type_t)atoi(pairing_content_type_str));

			if (atoi(pairing_enabled_str) != 0) {
				smcp_pairing_set_enabled(pairing, true);
			}

			smcp_pairing_set_stable(pairing, true);
		}
	}

bail:
	if (path && (path[0] != 0)) {
		self->pairing_mgr.commit_stable_pairings = (void*)&pairing_node_commit_stable;
		self->pairing_mgr.context = strdup(path);
	}

	if (file) {
		fclose(file);
	}

	return self;
}
示例#3
0
void Nes_Fme7_Apu::run_until( blip_time_t end_time )
{
	require( end_time >= last_time );
	
	for ( int index = 0; index < osc_count; index++ )
	{
		int mode = regs [7] >> index;
		int vol_mode = regs [010 + index];
		int volume = amp_table [vol_mode & 0x0F];
		
		Blip_Buffer* const osc_output = oscs [index].output;
		if ( !osc_output )
			continue;
		
		// check for unsupported mode
		#ifndef NDEBUG
			if ( (mode & 011) <= 001 && vol_mode & 0x1F )
				dprintf( "FME7 used unimplemented sound mode: %02X, vol_mode: %02X\n",
						mode, vol_mode & 0x1F );
		#endif
		
		if ( (mode & 001) | (vol_mode & 0x10) )
			volume = 0; // noise and envelope aren't supported
		
		// period
		int const period_factor = 16;
		unsigned period = (regs [index * 2 + 1] & 0x0F) * 0x100 * period_factor +
				regs [index * 2] * period_factor;
		if ( period < 50 ) // around 22 kHz
		{
			volume = 0;
			if ( !period ) // on my AY-3-8910A, period doesn't have extra one added
				period = period_factor;
		}
		
		// current amplitude
		int amp = volume;
		if ( !phases [index] )
			amp = 0;
		
		{
			int delta = amp - oscs [index].last_amp;
			if ( delta )
			{
				oscs [index].last_amp = amp;
				osc_output->set_modified();
				synth.offset( last_time, delta, osc_output );
			}
		}
		
		blip_time_t time = last_time + delays [index];
		if ( time < end_time )
		{
			int delta = amp * 2 - volume;
			osc_output->set_modified();
			if ( volume )
			{
				do
				{
					delta = -delta;
					synth.offset_inline( time, delta, osc_output );
					time += period;
				}
				while ( time < end_time );
				
				oscs [index].last_amp = (delta + volume) >> 1;
				phases [index] = (delta > 0);
			}
			else
			{
				// maintain phase when silent
				int count = (end_time - time + period - 1) / period;
				phases [index] ^= count & 1;
				time += count * period;
			}
		}
IOReturn
PrintSMARTData ( io_service_t service )
{

    IOCFPlugInInterface     **              cfPlugInInterface       = NULL;
    IOATASMARTInterface     **              smartInterface          = NULL;
    HRESULT herr                            = S_OK;
    IOReturn err                                     = kIOReturnSuccess;
    SInt32 score                           = 0;
    Boolean conditionExceeded       = false;
    CFStringRef description                     = NULL;
    UInt8 buffer[512];
    UInt32 bytesRead;
    ATASMARTLogDirectory logData;
    
    err = IOCreatePlugInInterfaceForService (       service,
        kIOATASMARTUserClientTypeID,
        kIOCFPlugInInterfaceID,
        &cfPlugInInterface,
        &score );

    require_string ( ( err == kIOReturnSuccess ), ErrorExit, "IOCreatePlugInInterfaceForService" );
    herr = ( *cfPlugInInterface )->QueryInterface (
        cfPlugInInterface,
        CFUUIDGetUUIDBytes ( kIOATASMARTInterfaceID ),
        ( LPVOID ) &smartInterface );

    require_string ( ( herr == S_OK ), ReleasePlugIn, "QueryInterface" );


    require_string ( ( smartInterface != NULL ), ReleasePlugIn, "smartInterface" );

    description = GetDriveDescription ( service );
    printf ( "SAT Drive: " );
    fflush ( stdout );
    CFShow ( description );
    CFRelease ( description );
    
    err = ( *smartInterface )->SMARTEnableDisableOperations ( smartInterface, true );
    require_string ( ( err == kIOReturnSuccess ), ReleaseInterface, "SMARTEnableDisableOperations" );

    err = ( *smartInterface )->SMARTEnableDisableAutosave ( smartInterface, true );
    require ( ( err == kIOReturnSuccess ), ReleaseInterface );

    err = ( *smartInterface )->SMARTReturnStatus ( smartInterface, &conditionExceeded );
    require ( ( err == kIOReturnSuccess ), ReleaseInterface );

    if ( conditionExceeded )
    {
        printf ( "SMART condition exceeded, drive will fail soon\n" );
    }

    else
    {
        printf ( "SMART condition not exceeded, drive OK\n" );
    }

    err = ( *smartInterface )->GetATAIdentifyData (smartInterface, &buffer, sizeof buffer, &bytesRead );
    require ( ( err == kIOReturnSuccess ), ReleaseInterface );
    require ( ( bytesRead == sizeof buffer ), ReleaseInterface );
    printf ( "Model: %s\n", buffer + 2 * kATAIdentifyModelNumber ); // FIXME not null terminated
    
    err = ( *smartInterface )->SMARTReadLogDirectory (smartInterface, &logData );
    require ( ( err == kIOReturnSuccess ), ReleaseInterface );
    for (int i = 0; i < 255; i++) {
        if (logData.entries[i].numberOfSectors > 0)
            printf ( "entry[%d]: %d\n", i, logData.entries[i].numberOfSectors);
    }
    err = ( *smartInterface )->SMARTReadLogAtAddress ( smartInterface,
                                                      224,
                                                 buffer,
                                                 sizeof buffer);
    require ( ( err == kIOReturnSuccess ), ReleaseInterface );
    for (int i = 0; i < 512; i++) {
        if (buffer[i])
        printf ( "buffer[%d]: %d\n", i, buffer[i]);
    }
#if 0
    err = ( *smartInterface )->SMARTWriteLogAtAddress ( smartInterface,
                                                      224,
                                                      buffer,
                                                      sizeof buffer);
    require ( ( err == kIOReturnSuccess ), ReleaseInterface );
#endif
    
ReleaseInterface:

    printf ("status %s\n", getStatus(err));

    ( *smartInterface )->Release ( smartInterface );
    smartInterface = NULL;


ReleasePlugIn:


    err = IODestroyPlugInInterface ( cfPlugInInterface );
    require ( ( err == kIOReturnSuccess ), ErrorExit );


ErrorExit:
    return err;

}
/* user main function, called by AppFramework after system init done && wifi
 * station on in user_main thread.
 */
OSStatus user_main( app_context_t * const app_context )
{
  user_log_trace();
  OSStatus err = kUnknownErr;
  unsigned char rdata[64];
  unsigned char sdata[64];
  uint16_t datalen;

  require(app_context, exit);

  // platform initialize
  AaSysComInit();
  AaSysLogInit();

  // application initialize
  ControllerBusInit();
  OuterTriggerInit(NULL);
  TemperatureInit();  // will be support in release 2
  BatteryInit();

  // reset f411 and wait until it startup
  ResetF411();

#if 1
  MOInit();
#endif

  err = SntpInit(app_context);
  if(kNoErr != err) {
    AaSysLogPrint(LOGLEVEL_ERR, "SntpInit finished with err code %d", err);
  }
  else {
    AaSysLogPrint(LOGLEVEL_INF, "SntpInit success");
  }

#if 1
  DeviceInit(app_context);
  HealthInit(app_context);
  LightsInit(app_context);
  MusicInit(app_context);

  // start the downstream thread to handle user command
  err = mico_rtos_create_thread(&user_downstrem_thread_handle, MICO_APPLICATION_PRIORITY, "user_downstream", 
                                user_downstream_thread, STACK_SIZE_USER_DOWNSTREAM_THREAD, 
                                app_context );
  require_noerr_action( err, exit, user_log("ERROR: create user_downstream thread failed!") );
#endif


  user_log("[DBG]net_main: Appilcation Initialize success @"SOFTWAREVERSION);

  // user_main loop, update oled display every 1s
  while(1){

#if 1
    mico_thread_sleep(MICO_WAIT_FOREVER);
#else

    mico_thread_sleep(5);

    datalen = user_uartRecv(rdata, 5);
    if(datalen) {
      user_log("[DBG]user_main: Usart recevice datalen %d", datalen);
      user_log("[DBG]user_main: receive %.*s", datalen, rdata);
    }
    else {
      user_log("[DBG]user_main: Usart didn't recevice data");
    }

    mico_thread_sleep(2);

    sprintf(sdata, "hello, world!\r\n");
    user_uartSend(sdata, strlen(sdata));
#endif

  }

exit:
  if(kNoErr != err){
    user_log("[ERR]user_main: user_main thread exit with err=%d", err);
  }
  mico_rtos_delete_thread(NULL);  // delete current thread
  return err;
}
示例#6
0
/*****************************************************
*
* Do_NewWindowFromIB(outWindow) 
*
* Purpose:  called to create a new window that has been constructed with Interface Builder
*
* Notes:    called by Do_NewWindow()
*
* Inputs:   outWindow   - if not NULL, the address where to return the WindowRef
*                       - if not NULL, the callee will have to ShowWindow
*
* Returns:  OSStatus    - error code (0 == no error) 
*/
static OSStatus Do_NewWindowFromIB(WindowRef * outWindow)
{
	OSStatus status;
	WindowRef aWindowRef = NULL;
	CFStringRef theTitle = NULL;
	CFMutableStringRef theNewTitle = NULL;
	
	// Create a window. "MainWindow" is the name of the window object. This name is set in 
	// InterfaceBuilder when the nib is created.
	status = CreateWindowFromNib(gIBNibRef, CFSTR("MainWindow"), &aWindowRef);
	require_noerr(status, CreateWindowFromNib);
	require(aWindowRef != NULL, CreateWindowFromNib);
	
	WindowDataPtr wdr = (WindowDataPtr)calloc(1, sizeof(WindowDataRec));
	require(wdr != NULL, CantAllocateWindowData);

	SetWRefCon(aWindowRef, (long)wdr);
	
	status = CopyWindowTitleAsCFString(aWindowRef, &theTitle);
	require_noerr(status, CopyWindowTitleAsCFString);
	
	theNewTitle = CFStringCreateMutableCopy(NULL, 0, theTitle);
	require(theNewTitle != NULL, CFStringCreateMutableCopy);
	
	CFStringAppendFormat(theNewTitle, NULL, CFSTR(" %ld"), ++gWindowCount);
	status = SetWindowTitleWithCFString(aWindowRef, theNewTitle);
	require_noerr(status, SetWindowTitleWithCFString);
	
	EventTypeSpec eventTypeCP = {kEventClassCommand, kEventCommandProcess};
	status = InstallWindowEventHandler(aWindowRef, Handle_WindowCommandProcess, 1, &eventTypeCP, (void *)aWindowRef, NULL);
	require_noerr(status, CantInstallEventHandler);
	
	EventTypeSpec eventTypeWC = {kEventClassWindow, kEventWindowClosed};
	status = InstallWindowEventHandler(aWindowRef, Handle_WindowIsClosing, 1, &eventTypeWC, (void *)aWindowRef, NULL);
	require_noerr(status, CantInstallEventHandler);
	
	HIViewID littleArrowsId = { 'LARC', 100 };
	HIViewRef littleArrows;
	status = HIViewFindByID(HIViewGetRoot(aWindowRef), littleArrowsId, &littleArrows);
	require_noerr(status, HIViewFindByID);
	require(littleArrows != NULL, HIViewFindByID);

	SetControlAction(littleArrows, LittleArrowsControlAction);

	EventTypeSpec eventTypeCVFC = {kEventClassControl, kEventControlValueFieldChanged};
	status = HIViewInstallEventHandler(littleArrows, Handle_PostLittleArrowsClick, 1, &eventTypeCVFC, (void *)littleArrows, NULL);
	require_noerr(status, CantInstallEventHandler);

	// The window was created hidden so show it if the outWindow parameter is NULL, 
	// if it's not, it will be the responsibility of the caller to show it.
	if (outWindow == NULL)
		ShowWindow(aWindowRef);
	
	SetWindowModified(aWindowRef, false);

HIViewFindByID:
CantInstallEventHandler:
SetWindowTitleWithCFString:
CFStringCreateMutableCopy:
CopyWindowTitleAsCFString:

	if (theTitle != NULL)
		CFRelease(theTitle);
	if (theNewTitle != NULL)
		CFRelease(theNewTitle);

CantAllocateWindowData:
CreateWindowFromNib:
	
	if (outWindow != NULL)
		*outWindow = aWindowRef;
	
	return status;
}   // Do_NewWindowFromIB
示例#7
0
// Parse a where clause:
//
//    where-clause:
//      'requires' logical-or-expression
Expr&
Parser::requires_clause()
{
  require(tk::requires_tok);
  return logical_or_expression();
}
示例#8
0
//直接遍历边块,寻找要插入的边所在的块,确保这个块还可以容纳边
b_type Subgraph::not_index_edge(Vertex* v,v_type id,t_type ts,b_type num,char is_repeat,char is_hash){
	b_type res;//要返回的边块的块号
	if(v->head==INVALID_BLOCK){
		//如果顶点还没有边块,则新建一个块
		res=require(2);//获取一个边块号
		BlockHeader<Edge> *insert_b=(BlockHeader<Edge>*)get_block(res,1,is_hash);//获取边块,这个块一直是块头,采取分裂方式扩容
		//把块加入到顶点的边链表中,作为块头,同时把顶点所在块脏位置1
		v->head=res;
		insert_b->pre=INVALID_BLOCK;
		insert_b->next=INVALID_BLOCK;
		BlockHeader<Vertex> *bv=(BlockHeader<Vertex> *)get_block(num,0,is_hash,0);//记得用无锁方式
		bv->clean=1;
		//初始化该块
		insert_b->init_block();
		insert_b->clean=1;
		return res;
	}else{
		BlockHeader<Edge> *b=NULL;  
		//时间戳不用去重
		b_type _blocknum=v->head;
		//旧块用0,新块用1,一定要记住,这里bug弄了好久
		b=(BlockHeader<Edge> *)get_block(_blocknum,0,is_hash);
		while(true){
			if(b->min==INVALID_VERTEX||id<b->min){
				if(is_repeat==1){
					//要根据边的时间戳去重,则要先确认这两个顶点之间的边有没有存在这个时间戳的
					if(b->ts_is_in_all(id,ts,this)){
						unlock2block(b);//如果存在,则释放该边块,返回无效块
						return INVALID_BLOCK;
					}
				}
				//不去重,或者没有重复的,则开始添加边
				if(b->size<b->capacity){
					//如果块没满,则返回块号 
					return b->number;
				}else{
					//如果块满了,则要分裂
					b_type _new_blocknum=require(2);
					BlockHeader<Edge> *_new_block=(BlockHeader<Edge> *)get_block(_new_blocknum,1,is_hash);
					b->split(_new_block,this);//分裂块,新块在后面,旧块在前面
					b->clean=1;
					_new_block->clean=1;
					if(id<b->min){
						//边插入旧块,释放新块的锁
						unlock2block(_new_block);
						return b->number;
					}else{
						//边插入新块,释放旧块的锁
						unlock2block(b);
						return _new_block->number;
					}
				}
			}else{
				_blocknum=b->next;//在释放该块之前得到下一个索引块,以免在中间把该块移除出去了
                unlock2block(b);//释放索引块
				b=(BlockHeader<Edge> *)get_block(_blocknum,0,is_hash);
			}
		}
			
	}
}
// Prepare the specified movie for extraction:
//	Open an extraction session.
//	Set the "All Channels Discrete" property if required.
//	Set the ASBD and output layout, if specified.
//      Set the extraction start time. 
// Return the audioExtractionSessionRef.
OSStatus PrepareMovieForExtraction( Movie movie, 
                                    MovieAudioExtractionRef* extractionRefPtr, 
                                    Boolean discrete, 
                                    AudioStreamBasicDescription asbd, 
                                    AudioChannelLayout** layout, 
                                    UInt32* layoutSizePtr, 
                                    TimeRecord startTime)
{
	OSStatus	err = noErr;
	
	if (extractionRefPtr == nil)
	{
		err = paramErr;
		goto bail;
	}
	
	// Movie extraction begin: Open an extraction session
	err = MovieAudioExtractionBegin(movie, 0, extractionRefPtr);
	require(err == noErr, bail);	
	
	// If we need to extract all discrete channels, set that property
	if (discrete)
	{
            err = MovieAudioExtractionSetProperty(*extractionRefPtr,
                                                    kQTPropertyClass_MovieAudioExtraction_Movie,
                                                    kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
                                                    sizeof (discrete), 
                                                    &discrete);
            require(err == noErr, bail);	
	}
	// Set the extraction ASBD
	err = MovieAudioExtractionSetProperty(*extractionRefPtr,
                                            kQTPropertyClass_MovieAudioExtraction_Audio,
                                            kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
                                            sizeof (asbd), &asbd);
	require(err == noErr, bail);	

	// Set the output layout, if supplied
	if (*layout)
	{
		err = MovieAudioExtractionSetProperty(*extractionRefPtr,
                                                kQTPropertyClass_MovieAudioExtraction_Audio,
                                                kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
                                                *layoutSizePtr, *layout);
                require(err == noErr, bail);	
	}

	// Set the extraction start time.  The duration will be determined by how much is pulled.
	err = MovieAudioExtractionSetProperty(*extractionRefPtr,
                                            kQTPropertyClass_MovieAudioExtraction_Movie,
                                            kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
                                            sizeof(TimeRecord), &startTime);

bail:
	// If error, close the extraction session
	if (err != noErr)
	{
		if (*extractionRefPtr != nil)
			MovieAudioExtractionEnd(*extractionRefPtr);
	}	
	return err;
}
// Get the default extraction layout for this movie, expanded into individual channel descriptions.
// The channel layout returned by this routine must be deallocated by the client.
// If 'asbd' is non-NULL, fill it with the default extraction asbd, which contains the
// highest sample rate among the sound tracks that will be contributing.
//	'outLayoutSize' and 'asbd' may be nil.
OSStatus GetDefaultExtractionLayout(Movie movie, UInt32* outLayoutSize,
                            AudioChannelLayout** outLayout, AudioStreamBasicDescription *asbd)
{
	OSStatus                    err = noErr;
	AudioChannelLayout          *layout = NULL;
	UInt32                      size = 0;
	MovieAudioExtractionRef     extractionSessionRef = nil;

	if (!outLayout)
	{
		err = paramErr;
		goto bail;
	}

	// Initiate a dummy audio extraction here, in order to get the resulting default channel layout.
	err = MovieAudioExtractionBegin(movie, 0, &extractionSessionRef);
	require(err == noErr, bail);	
	
	// Get the size of the extraction output layout
	err = MovieAudioExtractionGetPropertyInfo(extractionSessionRef, kQTPropertyClass_MovieAudioExtraction_Audio,
                                                kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
                                                NULL, &size, NULL);
	require(err == noErr, bail);	

	// Allocate memory for the layout
	layout = (AudioChannelLayout *) calloc(1, size);
	if (layout == nil) 
	{
		err = memFullErr;
		goto bail;
	}

	// Get the layout for the current extraction configuration.
	// This will have already been expanded into channel descriptions.
	err = MovieAudioExtractionGetProperty(extractionSessionRef, kQTPropertyClass_MovieAudioExtraction_Audio,
										  kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
										  size, layout, nil);
	require(err == noErr, bail);	
	
	// Return the layout and size, if requested
	*outLayout = layout;
	if (outLayoutSize)	
		*outLayoutSize = size;

	// If the ASBD was requested, get that also.
	if (asbd != nil)
	{
		// Get the layout for the current extraction configuration.
		// This will have already been expanded into channel descriptions.
		size = sizeof (*asbd);
		err = MovieAudioExtractionGetProperty(extractionSessionRef,
											  kQTPropertyClass_MovieAudioExtraction_Audio,
											  kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
											  size, asbd, nil);
        require(err == noErr, bail);	
	}

bail:
	if (err != noErr)
	{
		if (layout)
			free(layout);
		if (outLayoutSize)	
			*outLayoutSize = 0;	
	}

	// Throw away the temporary audio extraction session
	if (extractionSessionRef)
	{
		MovieAudioExtractionEnd(extractionSessionRef);
	}
	
	return err;				
}
static OSStatus SecECPrivateKeyInit(SecKeyRef key,
    const uint8_t *keyData, CFIndex keyDataLength, SecKeyEncoding encoding) {
    ccec_full_ctx_t fullkey;
    fullkey.hdr = key->key;
    OSStatus err = errSecParam;

    switch (encoding) {
    case kSecKeyEncodingPkcs1:
    {
        /* TODO: DER import size (and thus cp), pub.x, pub.y and k. */
        //err = ecc_import(keyData, keyDataLength, fullkey);

        /* DER != PKCS#1, but we'll go along with it */
        ccoid_t oid;
        size_t n;
        ccec_const_cp_t cp;

        require_noerr(ccec_der_import_priv_keytype(keyDataLength, keyData, &oid, &n), abort);
        cp = ccec_cp_for_oid(oid);
        if (cp.zp == NULL) {
            cp = ccec_curve_for_length_lookup(n * 8 /* bytes -> bits */,
                ccec_cp_192(), ccec_cp_224(), ccec_cp_256(), ccec_cp_384(), ccec_cp_521(), NULL);
        }
        require_action(cp.zp != NULL, abort, err = errSecDecode);
        ccec_ctx_init(cp, fullkey);

        require_noerr(ccec_der_import_priv(cp, keyDataLength, keyData, fullkey), abort);
        err = errSecSuccess;
        break;
    }
    case kSecKeyEncodingBytes:
    {
        ccec_const_cp_t cp = getCPForPrivateSize(keyDataLength);
        require(cp.zp != NULL, abort);

        ccec_ctx_init(cp, fullkey);
        size_t pubSize = ccec_export_pub_size(fullkey);

        require(pubSize < (size_t) keyDataLength, abort);
        require_noerr_action(ccec_import_pub(cp, pubSize, keyData, fullkey),
                             abort,
                             err = errSecDecode);


        keyData += pubSize;
        keyDataLength -= pubSize;

        cc_unit *k = ccec_ctx_k(fullkey);
        require_noerr_action(ccn_read_uint(ccec_ctx_n(fullkey), k, keyDataLength, keyData),
                             abort,
                             err = errSecDecode);

        err = errSecSuccess;
        break;

    }
    case kSecGenerateKey:
    {
        CFDictionaryRef parameters = (CFDictionaryRef) keyData;

        CFTypeRef ksize = CFDictionaryGetValue(parameters, kSecAttrKeySizeInBits);
        CFIndex keyLengthInBits = getIntValue(ksize);

        ccec_const_cp_t cp = ccec_get_cp(keyLengthInBits);

        if (!cp.zp) {
            secwarning("Invalid or missing key size in: %@", parameters);
            return errSecKeySizeNotAllowed;
        }

        if (!ccec_generate_key(cp, ccrng_seckey, fullkey))
            err = errSecSuccess;
        break;
    }

    default:
        break;
    }
abort:
    return err;
}
int Effects_Buffer::max_delay() const
{
    require( sample_rate() );
    return (echo_size / stereo - max_read) * 1000L / sample_rate();
}
int Effects_Buffer::min_delay() const
{
    require( sample_rate() );
    return max_read * 1000L / sample_rate();
}
Effects_Buffer::channel_t Effects_Buffer::channel( int i )
{
    i += extra_chans;
    require( extra_chans <= i && i < (int) chans.size() );
    return chans [i].channel;
}
示例#15
0
void define_operators(py::module &m) {
    m.def("max", [](py::args args) -> Expr {
        if (args.size() < 2) {
            throw py::value_error("max() must have at least 2 arguments");
        }
        int pos = (int) args.size() - 1;
        Expr value = args[pos--].cast<Expr>();
        while (pos >= 0) {
            value = max(args[pos--].cast<Expr>(), value);
        }
        return value;
    });

    m.def("min", [](py::args args) -> Expr {
        if (args.size() < 2) {
            throw py::value_error("min() must have at least 2 arguments");
        }
        int pos = (int) args.size() - 1;
        Expr value = args[pos--].cast<Expr>();
        while (pos >= 0) {
            value = min(args[pos--].cast<Expr>(), value);
        }
        return value;
    });

    m.def("clamp", &clamp);
    m.def("abs", &abs);
    m.def("absd", &absd);

    m.def("select", [](py::args args) -> Expr {
        if (args.size() < 3) {
            throw py::value_error("select() must have at least 3 arguments");
        }
        if ((args.size() % 2) == 0) {
            throw py::value_error("select() must have an odd number of arguments");
        }
        int pos = (int) args.size() - 1;
        Expr false_value = args[pos--].cast<Expr>();
        while (pos > 0) {
            Expr true_value = args[pos--].cast<Expr>();
            Expr condition = args[pos--].cast<Expr>();
            false_value = select(condition, true_value, false_value);
        }
        return false_value;
    });

    m.def("tuple_select", [](py::args args) -> py::tuple {
        _halide_user_assert(args.size() >= 3)
            << "tuple_select() must have at least 3 arguments";
        _halide_user_assert((args.size() % 2) != 0)
            << "tuple_select() must have an odd number of arguments";

        int pos = (int) args.size() - 1;
        Tuple false_value = args[pos--].cast<Tuple>();
        bool has_tuple_cond = false, has_expr_cond = false;
        while (pos > 0) {
            Tuple true_value = args[pos--].cast<Tuple>();;
            // Note that 'condition' can be either Expr or Tuple, but must be consistent across all
            py::object py_cond = args[pos--];
            Expr expr_cond;
            Tuple tuple_cond(expr_cond);
            try {
                tuple_cond = py_cond.cast<Tuple>();
                has_tuple_cond = true;
            } catch (...) {
                expr_cond = py_cond.cast<Expr>();
                has_expr_cond = true;
            }

            if (expr_cond.defined()) {
                false_value = tuple_select(expr_cond, true_value, false_value);
            } else {
                false_value = tuple_select(tuple_cond, true_value, false_value);
            }
        }
        _halide_user_assert(!(has_tuple_cond && has_expr_cond))
            <<"tuple_select() may not mix Expr and Tuple for the condition elements.";
        return to_python_tuple(false_value);
    });

    m.def("sin", &sin);
    m.def("asin", &asin);
    m.def("cos", &cos);
    m.def("acos", &acos);
    m.def("tan", &tan);
    m.def("atan", &atan);
    m.def("atan", &atan2);
    m.def("atan2", &atan2);
    m.def("sinh", &sinh);
    m.def("asinh", &asinh);
    m.def("cosh", &cosh);
    m.def("acosh", &acosh);
    m.def("tanh", &tanh);
    m.def("atanh", &atanh);
    m.def("sqrt", &sqrt);
    m.def("hypot", &hypot);
    m.def("exp", &exp);
    m.def("log", &log);
    m.def("pow", &pow);
    m.def("erf", &erf);
    m.def("fast_log", &fast_log);
    m.def("fast_exp", &fast_exp);
    m.def("fast_pow", &fast_pow);
    m.def("fast_inverse", &fast_inverse);
    m.def("fast_inverse_sqrt", &fast_inverse_sqrt);
    m.def("floor", &floor);
    m.def("ceil", &ceil);
    m.def("round", &round);
    m.def("trunc", &trunc);
    m.def("fract", &fract);
    m.def("is_nan", &is_nan);
    m.def("reinterpret", (Expr (*)(Type, Expr)) &reinterpret);
    m.def("cast", (Expr (*)(Type, Expr)) &cast);
    m.def("print", [](py::args args) -> Expr {
        return print(args_to_vector_for_print(args));
    });
    m.def("print_when", [](Expr condition, py::args args) -> Expr {
        return print_when(condition, args_to_vector_for_print(args));
    }, py::arg("condition"));
    m.def("require", [](Expr condition, Expr value, py::args args) -> Expr {
        auto v = args_to_vector<Expr>(args);
        v.insert(v.begin(), value);
        return require(condition, v);
    }, py::arg("condition"), py::arg("value"));
    m.def("lerp", &lerp);
    m.def("popcount", &popcount);
    m.def("count_leading_zeros", &count_leading_zeros);
    m.def("count_trailing_zeros", &count_trailing_zeros);
    m.def("div_round_to_zero", &div_round_to_zero);
    m.def("mod_round_to_zero", &mod_round_to_zero);
    m.def("random_float", (Expr (*)()) &random_float);
    m.def("random_uint", (Expr (*)()) &random_uint);
    m.def("random_int", (Expr (*)()) &random_int);
    m.def("random_float", (Expr (*)(Expr)) &random_float, py::arg("seed"));
    m.def("random_uint", (Expr (*)(Expr)) &random_uint, py::arg("seed"));
    m.def("random_int", (Expr (*)(Expr)) &random_int, py::arg("seed"));
    m.def("undef", (Expr (*)(Type)) &undef);
    m.def("memoize_tag", [](Expr result, py::args cache_key_values) -> Expr {
        return Internal::memoize_tag_helper(result, args_to_vector<Expr>(cache_key_values));
    }, py::arg("result"));
    m.def("likely", &likely);
    m.def("likely_if_innermost", &likely_if_innermost);
    m.def("saturating_cast", (Expr (*)(Type, Expr))&saturating_cast);
}
示例#16
0
文件: parser.cpp 项目: Jenny-fa/lingo
Expr const*
Parser::id()
{
  Token tok = require(identifier_tok);
  return on_id(tok);
}
示例#17
0
//int main( int argc, const char * argv[] )
int manipulate_led( int which_led, int led_value )
{
#pragma unused ( argc, argv )
	IOHIDDeviceRef * tIOHIDDeviceRefs = nil;

	// create a IO HID Manager reference
	IOHIDManagerRef tIOHIDManagerRef = IOHIDManagerCreate( kCFAllocatorDefault, kIOHIDOptionsTypeNone );
	require( tIOHIDManagerRef, Oops );

	// Create a device matching dictionary
	CFDictionaryRef matchingCFDictRef = hu_CreateMatchingDictionaryUsagePageUsage( TRUE,
																				  kHIDPage_GenericDesktop,
																				  kHIDUsage_GD_Keyboard );
	require( matchingCFDictRef, Oops );

	// set the HID device matching dictionary
	IOHIDManagerSetDeviceMatching( tIOHIDManagerRef, matchingCFDictRef );

	if ( matchingCFDictRef ) {
		CFRelease( matchingCFDictRef );
	}

	// Now open the IO HID Manager reference
	IOReturn tIOReturn = IOHIDManagerOpen( tIOHIDManagerRef, kIOHIDOptionsTypeNone );
	require_noerr( tIOReturn, Oops );

	// and copy out its devices
	CFSetRef deviceCFSetRef = IOHIDManagerCopyDevices( tIOHIDManagerRef );
	require( deviceCFSetRef, Oops );

	// how many devices in the set?
	CFIndex deviceIndex, deviceCount = CFSetGetCount( deviceCFSetRef );

	// allocate a block of memory to extact the device ref's from the set into
	tIOHIDDeviceRefs = malloc( sizeof( IOHIDDeviceRef ) * deviceCount );
	if (!tIOHIDDeviceRefs) {
		CFRelease(deviceCFSetRef);
		deviceCFSetRef = NULL;
		goto Oops;
	}

	// now extract the device ref's from the set
	CFSetGetValues( deviceCFSetRef, (const void **) tIOHIDDeviceRefs );
	CFRelease(deviceCFSetRef);
	deviceCFSetRef = NULL;

	// before we get into the device loop we'll setup our element matching dictionary
	matchingCFDictRef = hu_CreateMatchingDictionaryUsagePageUsage( FALSE, kHIDPage_LEDs, 0 );
	require( matchingCFDictRef, Oops );

	int pass;	// do 256 passes
	//for ( pass = 0; pass < 256; pass++ ) {
		Boolean delayFlag = FALSE;	// if we find an LED element we'll set this to TRUE

		//printf( "pass = %d.\n", pass );
		for ( deviceIndex = 0; deviceIndex < deviceCount; deviceIndex++ ) {

			// if this isn't a keyboard device...
			if ( !IOHIDDeviceConformsTo( tIOHIDDeviceRefs[deviceIndex], kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard ) ) {
				continue;	// ...skip it
			}

			//printf( "	 device = %p.\n", tIOHIDDeviceRefs[deviceIndex] );

			// copy all the elements
			CFArrayRef elementCFArrayRef = IOHIDDeviceCopyMatchingElements( tIOHIDDeviceRefs[deviceIndex],
																		   matchingCFDictRef,
																		   kIOHIDOptionsTypeNone );
			require( elementCFArrayRef, next_device );

			// for each device on the system these values are divided by the value ranges of all LED elements found
			// for example, if the first four LED element have a range of 0-1 then the four least significant bits of
			// this value will be sent to these first four LED elements, etc.
			int device_value = pass;

			// iterate over all the elements
			CFIndex elementIndex, elementCount = CFArrayGetCount( elementCFArrayRef );
			for ( elementIndex = 0; elementIndex < elementCount; elementIndex++ ) {
				IOHIDElementRef tIOHIDElementRef = ( IOHIDElementRef ) CFArrayGetValueAtIndex( elementCFArrayRef, elementIndex );
				require( tIOHIDElementRef, next_element );

				uint32_t usagePage = IOHIDElementGetUsagePage( tIOHIDElementRef );

				// if this isn't an LED element...
				if ( kHIDPage_LEDs != usagePage ) {
					continue;	// ...skip it
				}

				uint32_t usage = IOHIDElementGetUsage( tIOHIDElementRef );
				IOHIDElementType tIOHIDElementType = IOHIDElementGetType( tIOHIDElementRef );

				//printf( "		 element = %p (page: %d, usage: %d, type: %d ).\n",
				//	   tIOHIDElementRef, usagePage, usage, tIOHIDElementType );

				// get the logical mix/max for this LED element
				CFIndex minCFIndex = IOHIDElementGetLogicalMin( tIOHIDElementRef );
				CFIndex maxCFIndex = IOHIDElementGetLogicalMax( tIOHIDElementRef );

				// calculate the range
				CFIndex modCFIndex = maxCFIndex - minCFIndex + 1;

				// compute the value for this LED element
				//CFIndex tCFIndex = minCFIndex + ( device_value % modCFIndex );
				CFIndex tCFIndex = led_value;
				device_value /= modCFIndex;

				//printf( "			 value = 0x%08lX.\n", tCFIndex );

				uint64_t timestamp = 0; // create the IO HID Value to be sent to this LED element
				IOHIDValueRef tIOHIDValueRef = IOHIDValueCreateWithIntegerValue( kCFAllocatorDefault, tIOHIDElementRef, timestamp, tCFIndex );
				if ( tIOHIDValueRef ) {
					// now set it on the device
					tIOReturn = IOHIDDeviceSetValue( tIOHIDDeviceRefs[deviceIndex], tIOHIDElementRef, tIOHIDValueRef );
					CFRelease( tIOHIDValueRef );
					require_noerr( tIOReturn, next_element );
					delayFlag = TRUE;	// set this TRUE so we'll delay before changing our LED values again
				}
			next_element:	;
				continue;
			}
			CFRelease( elementCFArrayRef );
		next_device: ;
			continue;
		}

		// if we found an LED we'll delay before continuing
		//if ( delayFlag ) {
		//	usleep( 500000 ); // sleep one half second
		//}

		// if the mouse is down…
		//if (GetCurrentButtonState()) {
		//	break;	// abort pass loop
		//}
	//}						  // next pass

	if ( matchingCFDictRef ) {
		CFRelease( matchingCFDictRef );
	}
Oops:	;
	if ( tIOHIDDeviceRefs ) {
		free(tIOHIDDeviceRefs);
	}

	if ( tIOHIDManagerRef ) {
		CFRelease( tIOHIDManagerRef );
	}
	return 0;
} /* main */
示例#18
0
json_object* ConfigCreateReportJsonMessage( mico_Context_t * const inContext )
{
  OSStatus err = kNoErr;
  config_delegate_log_trace();
  char name[50], *tempString;
  OTA_Versions_t versions;
  char rfVersion[50];
  json_object *sectors, *sector, *subMenuSectors, *subMenuSector, *mainObject = NULL;

  MicoGetRfVer( rfVersion, 50 );

  if(inContext->flashContentInRam.micoSystemConfig.configured == wLanUnConfigured){
    /*You can upload a specific menu*/
  }

  mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex);
  snprintf(name, 50, "%s(%c%c%c%c%c%c)",MODEL, 
                                        inContext->micoStatus.mac[9],  inContext->micoStatus.mac[10], 
                                        inContext->micoStatus.mac[12], inContext->micoStatus.mac[13],
                                        inContext->micoStatus.mac[15], inContext->micoStatus.mac[16]);

  versions.fwVersion = FIRMWARE_REVISION;
  versions.hdVersion = HARDWARE_REVISION;
  versions.protocol =  PROTOCOL;
  versions.rfVersion = NULL;

  sectors = json_object_new_array();
  require( sectors, exit );

  err = MICOAddTopMenu(&mainObject, name, sectors, versions);
  require_noerr(err, exit);

  /*Sector 1*/
  sector = json_object_new_array();
  require( sector, exit );
  err = MICOAddSector(sectors, "MICO SYSTEM",    sector);
  require_noerr(err, exit);

    /*name cell*/
    err = MICOAddStringCellToSector(sector, "Device Name",    inContext->flashContentInRam.micoSystemConfig.name,               "RW", NULL);
    require_noerr(err, exit);

    //Bonjour switcher cell
    err = MICOAddSwitchCellToSector(sector, "Bonjour",        inContext->flashContentInRam.micoSystemConfig.bonjourEnable,      "RW");
    require_noerr(err, exit);

    //RF power save switcher cell
    err = MICOAddSwitchCellToSector(sector, "RF power save",  inContext->flashContentInRam.micoSystemConfig.rfPowerSaveEnable,  "RW");
    require_noerr(err, exit);

    //MCU power save switcher cell
    err = MICOAddSwitchCellToSector(sector, "MCU power save", inContext->flashContentInRam.micoSystemConfig.mcuPowerSaveEnable, "RW");
    require_noerr(err, exit);

    /*sub menu*/
    subMenuSectors = json_object_new_array();
    require( subMenuSectors, exit );
    err = MICOAddMenuCellToSector(sector, "Detail", subMenuSectors);
    require_noerr(err, exit);
      
      subMenuSector = json_object_new_array();
      require( subMenuSector, exit );
      err = MICOAddSector(subMenuSectors,  "",    subMenuSector);
      require_noerr(err, exit);

        err = MICOAddStringCellToSector(subMenuSector, "Firmware Rev.",  FIRMWARE_REVISION, "RO", NULL);
        require_noerr(err, exit);
        err = MICOAddStringCellToSector(subMenuSector, "Hardware Rev.",  HARDWARE_REVISION, "RO", NULL);
        require_noerr(err, exit);
        err = MICOAddStringCellToSector(subMenuSector, "MICO OS Rev.",   MicoGetVer(),      "RO", NULL);
        require_noerr(err, exit);
        err = MICOAddStringCellToSector(subMenuSector, "RF Driver Rev.", rfVersion,         "RO", NULL);
        require_noerr(err, exit);
        err = MICOAddStringCellToSector(subMenuSector, "Model",          MODEL,             "RO", NULL);
        require_noerr(err, exit);
        err = MICOAddStringCellToSector(subMenuSector, "Manufacturer",   MANUFACTURER,      "RO", NULL);
        require_noerr(err, exit);
        err = MICOAddStringCellToSector(subMenuSector, "Protocol",       PROTOCOL,          "RO", NULL);
        require_noerr(err, exit);

      subMenuSector = json_object_new_array();
      err = MICOAddSector(subMenuSectors,  "WLAN",    subMenuSector);
      require_noerr(err, exit);
      
        tempString = DataToHexStringWithColons( (uint8_t *)inContext->flashContentInRam.micoSystemConfig.bssid, 6 );
        err = MICOAddStringCellToSector(subMenuSector, "BSSID",        tempString, "RO", NULL);
        require_noerr(err, exit);
        free(tempString);

        err = MICOAddNumberCellToSector(subMenuSector, "Channel",      inContext->flashContentInRam.micoSystemConfig.channel, "RO", NULL);
        require_noerr(err, exit);

        switch(inContext->flashContentInRam.micoSystemConfig.security){
          case SECURITY_TYPE_NONE:
            err = MICOAddStringCellToSector(subMenuSector, "Security",   "Open system", "RO", NULL); 
            break;
          case SECURITY_TYPE_WEP:
            err = MICOAddStringCellToSector(subMenuSector, "Security",   "WEP",         "RO", NULL); 
            break;
          case SECURITY_TYPE_WPA_TKIP:
            err = MICOAddStringCellToSector(subMenuSector, "Security",   "WPA TKIP",    "RO", NULL); 
            break;
          case SECURITY_TYPE_WPA_AES:
            err = MICOAddStringCellToSector(subMenuSector, "Security",   "WPA AES",     "RO", NULL); 
            break;
          case SECURITY_TYPE_WPA2_TKIP:
            err = MICOAddStringCellToSector(subMenuSector, "Security",   "WPA2 TKIP",   "RO", NULL); 
            break;
          case SECURITY_TYPE_WPA2_AES:
            err = MICOAddStringCellToSector(subMenuSector, "Security",   "WPA2 AES",    "RO", NULL); 
            break;
          case SECURITY_TYPE_WPA2_MIXED:
            err = MICOAddStringCellToSector(subMenuSector, "Security",   "WPA2 MIXED",  "RO", NULL); 
            break;
          default:
            err = MICOAddStringCellToSector(subMenuSector, "Security",   "Auto",      "RO", NULL); 
            break;
        }
        require_noerr(err, exit); 

        if(inContext->flashContentInRam.micoSystemConfig.keyLength == maxKeyLen){ /*This is a PMK key, generated by user key in WPA security type*/
          tempString = calloc(maxKeyLen+1, 1);
          require_action(tempString, exit, err=kNoMemoryErr);
          memcpy(tempString, inContext->flashContentInRam.micoSystemConfig.key, maxKeyLen);
          err = MICOAddStringCellToSector(subMenuSector, "PMK",          tempString, "RO", NULL);
          require_noerr(err, exit);
          free(tempString);
        }
        else{
          err = MICOAddStringCellToSector(subMenuSector, "KEY",          inContext->flashContentInRam.micoSystemConfig.user_key,  "RO", NULL);
          require_noerr(err, exit);
        }

  /*Sector 3*/
  sector = json_object_new_array();
  require( sector, exit );
  err = MICOAddSector(sectors, "WLAN",           sector);
  require_noerr(err, exit);
    /*SSID cell*/
    err = MICOAddStringCellToSector(sector, "Wi-Fi",        inContext->flashContentInRam.micoSystemConfig.ssid,     "RW", NULL);
    require_noerr(err, exit);
    /*PASSWORD cell*/
    err = MICOAddStringCellToSector(sector, "Password",     inContext->flashContentInRam.micoSystemConfig.user_key, "RW", NULL);
    require_noerr(err, exit);
    /*DHCP cell*/
    err = MICOAddSwitchCellToSector(sector, "DHCP",        inContext->flashContentInRam.micoSystemConfig.dhcpEnable,   "RW");
    require_noerr(err, exit);
    /*Local cell*/
    err = MICOAddStringCellToSector(sector, "IP address",  inContext->micoStatus.localIp,   "RW", NULL);
    require_noerr(err, exit);
    /*Netmask cell*/
    err = MICOAddStringCellToSector(sector, "Net Mask",    inContext->micoStatus.netMask,   "RW", NULL);
    require_noerr(err, exit);
    /*Gateway cell*/
    err = MICOAddStringCellToSector(sector, "Gateway",     inContext->micoStatus.gateWay,   "RW", NULL);
    require_noerr(err, exit);
    /*DNS server cell*/
    err = MICOAddStringCellToSector(sector, "DNS Server",  inContext->micoStatus.dnsServer, "RW", NULL);
    require_noerr(err, exit);

  mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex);
  
exit:
  if(err != kNoErr && mainObject){
    json_object_put(mainObject);
    mainObject = NULL;
  }
  return mainObject;
}
示例#19
0
//查询顶点的索引块,参数1是顶点的指针,参数2是边的目的顶点的id,参数3是顶点的块号,返回边要加入的块号,而且确保这个块肯定还能容纳边
//2 
b_type Subgraph::index_edge(Vertex* v,v_type id,t_type ts,b_type num,char is_repeat,char is_hash){
	BlockHeader<Index> *b=NULL;
	//1:获取索引块链表的第一块,然后盯住这个块
	if(v->index==INVALID_BLOCK){
		//如果顶点还没有索引块,则创建一个索引块,以后这个块一直是头块,采取分裂的方式扩容
		b_type new_num=require(3);
		//加入到顶点的索引链表中
		v->index=new_num;
		//修改了顶点的数据,则要给顶点所在的块的脏位置1
		BlockHeader<Vertex> *bv=(BlockHeader<Vertex> *)get_block(num,0,is_hash,0);//对已经占有的块,再次获取时,一定要用不加锁的方式
		bv->clean=1;
                //获取新分配的索引块
		b=(BlockHeader<Index> *)get_block(new_num,1,is_hash);
		b->init_block();
		b->next=INVALID_BLOCK;
		b->pre=INVALID_BLOCK;	
		b->clean=1;
	}else{
		//顶点有索引块,则取出第一块
		b=(BlockHeader<Index> *)get_block(v->index,0,is_hash);	
	}
	//2:查询边应该插入的索引块
	while(true){
		if((b->min==INVALID_VERTEX)||(id<b->min)){
			//如果下一块最小值为无效,或者插入的边的id小于下一块最小的id,说明该块就是要找的索引块
			uint32_t i=b->list_head;
			if(i==INVALID_INDEX){
				//只有该顶点插入第一条边的时候,list_head才会为无效值,才会主动创建边的块
				Index in;//创建一个索引项
				in.id=INVALID_VERTEX;//下一个索引项不存在,最小值就是无效的
				in.target=require(2);//获取一个边块号
				b->add_content(in);//把索引项插入索引块中
				b->clean=1;//索引块脏位置1
				BlockHeader<Edge> *insert_b=(BlockHeader<Edge>*)get_block(in.target,1,is_hash);//获取边块,这个块一直是块头,采取分裂方式扩容
				//把块加入到顶点的边链表中,作为块头,同时把顶点所在块脏位置1
				v->head=in.target;
				insert_b->pre=INVALID_BLOCK;
				insert_b->next=INVALID_BLOCK;
				insert_b->min=in.id;
				BlockHeader<Vertex> *bv=(BlockHeader<Vertex> *)get_block(num,0,is_hash,0);//记得用无锁方式
				bv->clean=1;
				//初始化该块
				insert_b->init_block();
				insert_b->clean=1;
				unlock2block(b);//释放索引块
				return in.target;	
			}else{
				while(true){
					//遍历该块的索引项,找出边要插入的块
					if((b->data[i].content.id==INVALID_VERTEX)||(id<b->data[i].content.id)){
						//如果下一个索引项的最小值无效或者大于插入边的id,则这个索引项就是要找的
						BlockHeader<Edge> *insert_b=(BlockHeader<Edge>*)get_block(b->data[i].content.target,0,is_hash);//根据索引获得边块
                       	if(is_repeat==1){
							//要根据边的时间戳去重,则要先确认这两个顶点之间的边有没有存在这个时间戳的
							if(insert_b->ts_is_in_all(id,ts,this)){
								unlock2block(insert_b);//如果存在,则释放该边块,返回无效块
								return INVALID_BLOCK;
							}
						}
						if(insert_b->size<insert_b->capacity){
							//如果该边块还没有满,则返回该块
							unlock2block(b);//释放索引块
							return insert_b->number;
						}else{
							//如果满了,则要进行边块的分裂
							b_type new_block_num=require(2);//从空闲块中释放一个新边块
							BlockHeader<Edge> *new_block=(BlockHeader<Edge> *)get_block(new_block_num,1,is_hash);//这个块不需要初始化	
							insert_b->split(new_block,this);//分裂块
							//添加新块的索引
							Index in;
							in.target=new_block_num;
							if(b->data[i].content.id==INVALID_VERTEX){
							}
							in.id=new_block->min;//新索引项的值
							b->data[i].content.id=insert_b->min;//修改旧索引项的值
							if(b->size<b->capacity){
								//如果索引块内容没满,添加新的索引项
								b->add_content(in);
							}else{
								//索引块满了,分裂索引块
								b_type new_index_num=require(3);
								BlockHeader<Index> *new_index=(BlockHeader<Index> *)get_block(new_index_num,1,is_hash);//这个块不需要初始化
								b->split(new_index,this);
								if(in.id<new_index->data[new_index->list_head].content.id){
									//如果索引项的值小于新索引块的第一项的值,则把索引插入旧块
									b->add_content(in);
									//一定要更新旧块的min
									b->min=b->data[b->list_tail].content.id;
								}else{
									//否则插入新索引块
									new_index->add_content(in);
									new_index->clean=1;
									new_index->min=new_index->data[new_index->list_tail].content.id;//这句也可以不要
								}
								unlock2block(new_index);
							}
							b->clean=1;
							unlock2block(b);
							//判断该边要插入哪个块,旧块和新块之间选择
							if(id<insert_b->min){
								//插入旧块,则释放新块的锁
                                                                unlock2block(new_block);
								return insert_b->number;
							}else{
                                                                unlock2block(insert_b);
								return new_block->number;
							}
						}
					}else{
						i=b->data[i].next;
					}
					
				}
			}	
			
		}else{
			b_type next_num=b->next;//在释放该块之前得到下一个索引块,以免在中间把该块移除出去了
                        unlock2block(b);//释放索引块
			b=(BlockHeader<Index> *)get_block(next_num,0,is_hash);
		}
	}
	
}
CFURLRef GetOpenDialogForUser(kDialogType type, char* title, char* message)
{
	NavDialogCreationOptions dialogOptions;
	NavDialogRef dialog = NULL;
	NavReplyRecord replyRecord;
	CFURLRef fileAsCFURLRef = NULL;
	FSRef fileAsFSRef;
	OSStatus status;
	
	CFAllocatorRef alloc_default = kCFAllocatorDefault;  // = NULL;

	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions(&dialogOptions);
	require_noerr( status, CantGetNavOptions );

	dialogOptions.optionFlags = kNavNoTypePopup + kNavSupportPackages + kNavAllowOpenPackages;


	if (title != NULL) {
		CFStringRef cftitle = CFStringCreateWithCString(alloc_default,title,kCFStringEncodingMacRoman);
		dialogOptions.windowTitle = cftitle;
	}

	if (message != NULL) {
		CFStringRef cfmessage = CFStringCreateWithCString(alloc_default,message,kCFStringEncodingMacRoman);
		dialogOptions.message = cfmessage;
	}


	// Make the window app-wide modal
	dialogOptions.modality = kWindowModalityAppModal;

	// Create the dialog
	if (type == kDialogFile) {
		status = NavCreateGetFileDialog(&dialogOptions, NULL, NULL, NULL, NULL, NULL, &dialog);
	} else if (type == kDialogFolder) {
		status = NavCreateChooseFolderDialog(&dialogOptions, NULL, NULL, NULL, &dialog);
	}
	require_noerr( status, CantCreateDialog );

	// Show it
	status = NavDialogRun(dialog);
	require_noerr( status, CantRunDialog );

	// Get the reply
	status = NavDialogGetReply(dialog, &replyRecord);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );

	// If the user clicked "Cancel", just bail
	if ( status == userCanceledErr ) goto UserCanceled;

	// Get the file
	status = AEGetNthPtr(&(replyRecord.selection), 1, typeFSRef, NULL, NULL, &fileAsFSRef, sizeof(FSRef), NULL);
	require_noerr( status, CantExtractFSRef );

	// Convert it to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef);

	// Cleanup
CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&replyRecord) );
CantGetReply:
CantRunDialog:
	NavDialogDispose(dialog);
CantCreateDialog:
CantGetNavOptions:
    return fileAsCFURLRef;
}
int main(int argc, char **argv)
{
    int wants_wipe = 0;
    int wants_reboot = 0;
    int wants_reboot_bootloader = 0;
    int erase_first = 1;
    void *data;
    unsigned sz;
    int status;
    int c;
    int longindex;

    const struct option longopts[] = {
        {"base", required_argument, 0, 'b'},
        {"kernel_offset", required_argument, 0, 'k'},
        {"page_size", required_argument, 0, 'n'},
        {"ramdisk_offset", required_argument, 0, 'r'},
        {"tags_offset", required_argument, 0, 't'},
        {"help", no_argument, 0, 'h'},
        {"unbuffered", no_argument, 0, 0},
        {"version", no_argument, 0, 0},
        {0, 0, 0, 0}
    };

    serial = getenv("ANDROID_SERIAL");

    while (1) {
        c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, &longindex);
        if (c < 0) {
            break;
        }
        /* Alphabetical cases */
        switch (c) {
        case 'b':
            base_addr = strtoul(optarg, 0, 16);
            break;
        case 'c':
            cmdline = optarg;
            break;
        case 'h':
            usage();
            return 1;
        case 'i': {
                char *endptr = NULL;
                unsigned long val;

                val = strtoul(optarg, &endptr, 0);
                if (!endptr || *endptr != '\0' || (val & ~0xffff))
                    die("invalid vendor id '%s'", optarg);
                vendor_id = (unsigned short)val;
                break;
            }
        case 'k':
            kernel_offset = strtoul(optarg, 0, 16);
            break;
        case 'l':
            long_listing = 1;
            break;
        case 'n':
            page_size = (unsigned)strtoul(optarg, NULL, 0);
            if (!page_size) die("invalid page size");
            break;
        case 'p':
            product = optarg;
            break;
        case 'r':
            ramdisk_offset = strtoul(optarg, 0, 16);
            break;
        case 't':
            tags_offset = strtoul(optarg, 0, 16);
            break;
        case 's':
            serial = optarg;
            break;
        case 'S':
            sparse_limit = parse_num(optarg);
            if (sparse_limit < 0) {
                    die("invalid sparse limit");
            }
            break;
        case 'u':
            erase_first = 0;
            break;
        case 'w':
            wants_wipe = 1;
            break;
        case '?':
            return 1;
        case 0:
            if (strcmp("unbuffered", longopts[longindex].name) == 0) {
                setvbuf(stdout, NULL, _IONBF, 0);
                setvbuf(stderr, NULL, _IONBF, 0);
            } else if (strcmp("version", longopts[longindex].name) == 0) {
                fprintf(stdout, "fastboot version %s\n", FASTBOOT_REVISION);
                return 0;
            }
            break;
        default:
            abort();
        }
    }

    argc -= optind;
    argv += optind;

    if (argc == 0 && !wants_wipe) {
        usage();
        return 1;
    }

    if (argc > 0 && !strcmp(*argv, "devices")) {
        skip(1);
        list_devices();
        return 0;
    }

    if (argc > 0 && !strcmp(*argv, "help")) {
        usage();
        return 0;
    }

    usb_handle* usb = open_device();

    while (argc > 0) {
        if(!strcmp(*argv, "getvar")) {
            require(2);
            fb_queue_display(argv[1], argv[1]);
            skip(2);
        } else if(!strcmp(*argv, "erase")) {
            require(2);

            if (fb_format_supported(usb, argv[1], NULL)) {
                fprintf(stderr, "******** Did you mean to fastboot format this partition?\n");
            }

            fb_queue_erase(argv[1]);
            skip(2);
        } else if(!strncmp(*argv, "format", strlen("format"))) {
            char *overrides;
            char *type_override = NULL;
            char *size_override = NULL;
            require(2);
            /*
             * Parsing for: "format[:[type][:[size]]]"
             * Some valid things:
             *  - select ontly the size, and leave default fs type:
             *    format::0x4000000 userdata
             *  - default fs type and size:
             *    format userdata
             *    format:: userdata
             */
            overrides = strchr(*argv, ':');
            if (overrides) {
                overrides++;
                size_override = strchr(overrides, ':');
                if (size_override) {
                    size_override[0] = '\0';
                    size_override++;
                }
                type_override = overrides;
            }
            if (type_override && !type_override[0]) type_override = NULL;
            if (size_override && !size_override[0]) size_override = NULL;
            if (erase_first && needs_erase(usb, argv[1])) {
                fb_queue_erase(argv[1]);
            }
            fb_perform_format(usb, argv[1], 0, type_override, size_override);
            skip(2);
        } else if(!strcmp(*argv, "signature")) {
            require(2);
            data = load_file(argv[1], &sz);
            if (data == 0) die("could not load '%s': %s", argv[1], strerror(errno));
            if (sz != 256) die("signature must be 256 bytes");
            fb_queue_download("signature", data, sz);
            fb_queue_command("signature", "installing signature");
            skip(2);
        } else if(!strcmp(*argv, "reboot")) {
            wants_reboot = 1;
            skip(1);
            if (argc > 0) {
                if (!strcmp(*argv, "bootloader")) {
                    wants_reboot = 0;
                    wants_reboot_bootloader = 1;
                    skip(1);
                }
            }
            require(0);
        } else if(!strcmp(*argv, "reboot-bootloader")) {
            wants_reboot_bootloader = 1;
            skip(1);
        } else if (!strcmp(*argv, "continue")) {
            fb_queue_command("continue", "resuming boot");
            skip(1);
        } else if(!strcmp(*argv, "boot")) {
            char *kname = 0;
            char *rname = 0;
            skip(1);
            if (argc > 0) {
                kname = argv[0];
                skip(1);
            }
            if (argc > 0) {
                rname = argv[0];
                skip(1);
            }
            data = load_bootable_image(kname, rname, &sz, cmdline);
            if (data == 0) return 1;
            fb_queue_download("boot.img", data, sz);
            fb_queue_command("boot", "booting");
        } else if(!strcmp(*argv, "flash")) {
            char *pname = argv[1];
            char *fname = 0;
            require(2);
            if (argc > 2) {
                fname = argv[2];
                skip(3);
            } else {
                fname = find_item(pname, product);
                skip(2);
            }
            if (fname == 0) die("cannot determine image filename for '%s'", pname);
            if (erase_first && needs_erase(usb, pname)) {
                fb_queue_erase(pname);
            }
            do_flash(usb, pname, fname);
        } else if(!strcmp(*argv, "flash:raw")) {
            char *pname = argv[1];
            char *kname = argv[2];
            char *rname = 0;
            require(3);
            if(argc > 3) {
                rname = argv[3];
                skip(4);
            } else {
                skip(3);
            }
            data = load_bootable_image(kname, rname, &sz, cmdline);
            if (data == 0) die("cannot load bootable image");
            fb_queue_flash(pname, data, sz);
        } else if(!strcmp(*argv, "flashall")) {
            skip(1);
            do_flashall(usb, erase_first);
            wants_reboot = 1;
        } else if(!strcmp(*argv, "update")) {
            if (argc > 1) {
                do_update(usb, argv[1], erase_first);
                skip(2);
            } else {
                do_update(usb, "update.zip", erase_first);
                skip(1);
            }
            wants_reboot = 1;
        } else if(!strcmp(*argv, "oem")) {
            argc = do_oem_command(argc, argv);
        } else if(!strcmp(*argv, "flashing") && argc == 2) {
            if(!strcmp(*(argv+1), "unlock") || !strcmp(*(argv+1), "lock")
               || !strcmp(*(argv+1), "unlock_critical")
               || !strcmp(*(argv+1), "lock_critical")
               || !strcmp(*(argv+1), "get_unlock_ability")) {
              argc = do_oem_command(argc, argv);
            } else {
              usage();
              return 1;
            }
        } else {
            usage();
            return 1;
        }
    }

    if (wants_wipe) {
        fb_queue_erase("userdata");
        fb_perform_format(usb, "userdata", 1, NULL, NULL);
        fb_queue_erase("cache");
        fb_perform_format(usb, "cache", 1, NULL, NULL);
    }
    if (wants_reboot) {
        fb_queue_reboot();
        fb_queue_wait_for_disconnect();
    } else if (wants_reboot_bootloader) {
        fb_queue_command("reboot-bootloader", "rebooting into bootloader");
        fb_queue_wait_for_disconnect();
    }

    if (fb_queue_is_empty())
        return 0;

    status = fb_execute_queue(usb);
    return (status) ? 1 : 0;
}
CFURLRef GetSaveDialogForUser(char* title, char* message)
{
	NavDialogCreationOptions dialogOptions;
	FSRef output_file;
	CFURLRef fileAsCFURLRef = NULL;
	OSStatus status;
	CFAllocatorRef alloc_default = kCFAllocatorDefault;
	
	
	AEKeyword keyword;
	DescType actual_type;
	Size actual_size;
	FSRef output_dir;
	NavReplyRecord reply;
	CFIndex len;

	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions( &dialogOptions );
	require_noerr( status, CantGetNavOptions );

	dialogOptions.optionFlags = kNavNoTypePopup + kNavSupportPackages + kNavAllowOpenPackages;

	  // = NULL;

	if (title != NULL) {
		CFStringRef cftitle = CFStringCreateWithCString(alloc_default,title,kCFStringEncodingMacRoman);
		dialogOptions.windowTitle = cftitle;
	}

	if (message != NULL) {
		CFStringRef cfmessage = CFStringCreateWithCString(alloc_default,message,kCFStringEncodingMacRoman);
		dialogOptions.message = cfmessage;
	}
	// Make the window app-wide modal
	dialogOptions.modality = kWindowModalityAppModal;

	NavDialogRef dialog;
	status = NavCreatePutFileDialog ( &dialogOptions, NULL, NULL, NULL, NULL, &dialog);
	require_noerr( status, CantCreateDialog );

	status = NavDialogRun(dialog);
	require_noerr( status, CantRunDialog );

	// get dialog reply
	status = NavDialogGetReply(dialog, &reply);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );

	//get file directory
	status = AEGetNthPtr(&(reply.selection), 1, typeFSRef, &keyword, &actual_type,
						 &output_dir, sizeof(output_file), &actual_size);
	require_noerr( status, CantExtractFSRef );

	UInt8 output_dir_name[1024];
	FSRefMakePath(&output_dir, output_dir_name, 1024 );

	// now get filename
	len = CFStringGetLength(reply.saveFileName);
	if (len > 255)
		len = 255;
	UniChar output_filename[255];
	CFStringGetCharacters(reply.saveFileName, CFRangeMake(0, len), output_filename);

	// need to unlink the old file
	if ( reply.replacing )
	{
		FSRef oldfile;

		status = FSMakeFSRefUnicode(&output_dir, len, output_filename,
								 kTextEncodingUnicodeDefault,
								 &oldfile);
		if (status == noErr) status = FSDeleteObject(&oldfile);
		//overwrite failed!
		require_noerr( status, UserCanceled );
	}

	//create fsref again to new file (NOTE: this actually makes a file...)
	status = FSCreateFileUnicode( &output_dir, len, output_filename, kFSCatInfoNone,
								 NULL, &output_file, NULL );
	require_noerr( status, CantExtractFSRef );

	// Convert it to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &output_file);

CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&reply) );
CantGetReply:
CantRunDialog:
	// cleanup dialog
	NavDialogDispose(dialog);
CantCreateDialog:
CantGetNavOptions:
    return fileAsCFURLRef;
}
示例#23
0
/*****************************************************
*
* Do_NewWindowFromAPI(outWindow) 
*
* Purpose:  called to create a new window using only API calls fron MacWindows.h, Controls.h, and HIView.h
*
* Notes:    called by Do_NewWindow()
*
* Inputs:   outWindow   - if not NULL, the address where to return the WindowRef
*                       - if not NULL, the callee will have to ShowWindow
*
* Returns:  OSStatus    - error code (0 == no error) 
*/
static OSStatus Do_NewWindowFromAPI(WindowRef * outWindow)
{
	WindowRef aWindowRef = NULL;
	CFStringRef theTitle = NULL;
	OSStatus status;
	
	// Create a window
	Rect bounds = {0, 0, 360, 480};
	status = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute | kWindowCompositingAttribute | kWindowMetalAttribute, &bounds, &aWindowRef);
	require_noerr(status, CreateNewWindow);
	require(aWindowRef != NULL, CreateNewWindow);
	
	status = RepositionWindow(aWindowRef, NULL, kWindowCascadeOnMainScreen);
	require_noerr(status, RepositionWindow);
	
	HIViewRef contentView;
	status = HIViewFindByID(HIViewGetRoot(aWindowRef), kHIViewWindowContentID, &contentView);
	require_noerr(status, HIViewFindByID);
	
	ControlRef aControlRef;
	Rect statBounds = {113, 20, 177, 460};
	ControlFontStyleRec style = {kControlUseJustMask, 0, 0, 0, 0, teJustCenter};
	status = CreateStaticTextControl(NULL, &statBounds, CFSTR("Click in the LittleArrows control above."), &style, &aControlRef);
	require_noerr(status, CreateStaticTextControl);
	HIViewID staticTextID = { 'STTC', 100 };
	HIViewSetID(aControlRef, staticTextID);
	status = HIViewAddSubview(contentView, aControlRef);
	require_noerr(status, HIViewAddSubview);
	
	Rect littleArrowBounds = {51, 234, 73, 247};
	status = CreateLittleArrowsControl(NULL, &littleArrowBounds, 0, 0, 10, 1, &aControlRef);
	require_noerr(status, CreateLittleArrowsControl);
	status = HIViewAddSubview(contentView, aControlRef);
	require_noerr(status, HIViewAddSubview);

	SetControlAction(aControlRef, LittleArrowsControlAction);

	EventTypeSpec eventTypeCVFC = {kEventClassControl, kEventControlValueFieldChanged};
	status = HIViewInstallEventHandler(aControlRef, Handle_PostLittleArrowsClick, 1, &eventTypeCVFC, (void *)aControlRef, NULL);
	require_noerr(status, CantInstallEventHandler);

	Rect buttonBounds = {320, 390, 340, 460};
	status = CreatePushButtonControl(NULL, &buttonBounds, CFSTR("OK"), &aControlRef);
	require_noerr(status, CreatePushButtonControl);
	status = SetControlCommandID(aControlRef, kHICommandOK);
	require_noerr(status, SetControlCommandID);
	status = HIViewAddSubview(contentView, aControlRef);
	require_noerr(status, HIViewAddSubview);
	status = SetWindowDefaultButton(aWindowRef, aControlRef);
	require_noerr(status, SetWindowDefaultButton);
	
	WindowDataPtr wdr = (WindowDataPtr)calloc(1, sizeof(WindowDataRec));
	require(wdr != NULL, CantAllocateWindowData);

	SetWRefCon(aWindowRef, (long)wdr);
	
	theTitle = CFStringCreateWithFormat(NULL, NULL, CFSTR("LittleArrowsShowcase Window From API #%ld"), ++gWindowCount);
	require(theTitle != NULL, CFStringCreateWithFormat);
	
	status = SetWindowTitleWithCFString(aWindowRef, theTitle);
	require_noerr(status, SetWindowTitleWithCFString);
	
	EventTypeSpec eventTypeCP = {kEventClassCommand, kEventCommandProcess};
	status = InstallWindowEventHandler(aWindowRef, Handle_WindowCommandProcess, 1, &eventTypeCP, (void *)aWindowRef, NULL);
	require_noerr(status, CantInstallEventHandler);
	
	EventTypeSpec eventTypeWC = {kEventClassWindow, kEventWindowClosed};
	status = InstallWindowEventHandler(aWindowRef, Handle_WindowIsClosing, 1, &eventTypeWC, (void *)aWindowRef, NULL);
	require_noerr(status, CantInstallEventHandler);
		
	// The window was created hidden so show it if the outWindow parameter is NULL, 
	// if it's not, it will be the responsibility of the caller to show it.
	if (outWindow == NULL)
		ShowWindow(aWindowRef);
	
	SetWindowModified(aWindowRef, false);
	
CantInstallEventHandler:
SetWindowTitleWithCFString:
CFStringCreateWithFormat:

	if (theTitle != NULL)
		CFRelease(theTitle);

CantAllocateWindowData:
SetWindowDefaultButton:
SetControlCommandID:
CreatePushButtonControl:
CreateLittleArrowsControl:
HIViewAddSubview:
CreateStaticTextControl:
HIViewFindByID:
RepositionWindow:
CreateNewWindow:
	
	if (outWindow != NULL)
		*outWindow = aWindowRef;
	
	return status;
}   // Do_NewWindowFromAPI
示例#24
0
文件: cMRC.cpp 项目: hvthaibk/ccrunch
void cMRC<T>::write(const cData3<T>& object, const std::string& fileName, cMapHeader* header)
{
    const std::string funcName("void cMRC::write(const cData3<T>& object, "
                                    "const std::string& fileName, cMapHeader* header)");

    require(object.getAddrData() != NULL, funcName + "writing an empty object");

    checkExtension(fileName);

    std::ofstream       fileHandle;

    fileHandle.open(fileName.c_str(), std::ofstream::binary);
    assure(fileHandle, fileName.c_str());

    int             map_dim[3], data_mode, origin[3], cell_grid[3], axes_order[3];
    float           cell_dim[3], cell_angle[3];
    float           density_min, density_max, density_mean;
    int             spacegroup, sym_byte = 0;
    char            mapStamp[] = "MAP ";

    // write map header
    if (header) {
        if (header->map_dim[0] == (int) object.getNrow() &&
            header->map_dim[1] == (int) object.getNcol() &&
            header->map_dim[2] == (int) object.getNsec()) {

            data_mode  = header->data_mode;
            spacegroup = header->spacegroup;

            cell_dim[0] = header->cell_dim[0];
            cell_dim[1] = header->cell_dim[1];
            cell_dim[2] = header->cell_dim[2];

            cell_angle[0] = header->cell_angle[0];
            cell_angle[1] = header->cell_angle[1];
            cell_angle[2] = header->cell_angle[2];

            map_dim[0] = header->map_dim[0];
            map_dim[1] = header->map_dim[1];
            map_dim[2] = header->map_dim[2];

            origin[0] = header->origin[0];
            origin[1] = header->origin[1];
            origin[2] = header->origin[2];

            cell_grid[0] = header->cell_grid[0];
            cell_grid[1] = header->cell_grid[1];
            cell_grid[2] = header->cell_grid[2];

            axes_order[0] = header->axes_order[0];
            axes_order[1] = header->axes_order[1];
            axes_order[2] = header->axes_order[2];
        }
        else {
            ERROR(funcName, "header information does not match in writing " + fileName);
        }
    }
    else {
        map_dim[0] = (int) object.getNrow();
        map_dim[1] = (int) object.getNcol();
        map_dim[2] = (int) object.getNsec();

        data_mode  = 2;
        spacegroup = 0;

        cell_dim[0] = (float) map_dim[0];
        cell_dim[1] = (float) map_dim[1];
        cell_dim[2] = (float) map_dim[2];

        cell_angle[0] = 90;
        cell_angle[1] = 90;
        cell_angle[2] = 90;

        origin[0] = 0;
        origin[1] = 0;
        origin[2] = 0;

        cell_grid[0] = map_dim[0];
        cell_grid[1] = map_dim[1];
        cell_grid[2] = map_dim[2];

        axes_order[0] = 1;
        axes_order[1] = 2;
        axes_order[2] = 3;
    }

    fileHandle.write((char*) map_dim,       3*sizeof(int));         // NX, NY, NZ
    fileHandle.write((char*) &data_mode,      sizeof(int));         // MODE
    fileHandle.write((char*) origin,        3*sizeof(int));         // NXSTART, NYSTART, NZSTART
    fileHandle.write((char*) cell_grid,     3*sizeof(int));         // MX, MY, MZ
    fileHandle.write((char*) cell_dim,      3*sizeof(float));       // CELLA
    fileHandle.write((char*) cell_angle,    3*sizeof(float));       // CELLB
    fileHandle.write((char*) axes_order,    3*sizeof(int));         // MAPC, MAPR, MAPS
    fileHandle.write((char*) &density_min,    sizeof(float));       // DMIN
    fileHandle.write((char*) &density_max,    sizeof(float));       // DMAX
    fileHandle.write((char*) &density_mean,   sizeof(float));       // DMEAN
    fileHandle.write((char*) &spacegroup,     sizeof(int));         // ISPG
    fileHandle.write((char*) &sym_byte,       sizeof(int));         // NSYMBT

    fileHandle.seekp(208, std::ios::beg);
    fileHandle.write((char*) mapStamp,      4*sizeof(char));        // MAP

    // write map data, assume no symmetry information
    fileHandle.seekp(CCP4_HEADER_SIZE, std::ios::beg);

    unsigned char*      bufferData   = NULL;
    size_t              bufferLength,
                        nelement     = (size_t) (map_dim[0]*map_dim[1]*map_dim[2]);

    switch (data_mode) {
        case 0:            // int8
            bufferLength = 1 * nelement;
            break;
        case 1:            // int16
            bufferLength = 2 * nelement;
            break;
        case 2:            // float32
            bufferLength = 4 * nelement;
            break;
        case 6:            // uint16
            bufferLength = 2 * nelement;
            break;
        default:
            ERROR(funcName, "unsupported data mode in reading " + fileName);
    }

    array_new(bufferData, bufferLength);

    switch (data_mode) {
        case 0:            // int8
            array_index_row2col(object.getAddrData(), (int8_t*) bufferData,
                                object.getNrow(), object.getNcol(), object.getNsec());

            break;
        case 1:            // int16
            array_index_row2col(object.getAddrData(), (int16_t*) bufferData,
                                object.getNrow(), object.getNcol(), object.getNsec());

            break;
        case 2:            // float32
            array_index_row2col(object.getAddrData(), (float*) bufferData,
                                object.getNrow(), object.getNcol(), object.getNsec());

            break;
        case 6:            // uint16
            array_index_row2col(object.getAddrData(), (uint16_t*) bufferData,
                                object.getNrow(), object.getNcol(), object.getNsec());

            break;
        default:
            ERROR(funcName, "unsupported data mode in writing " + fileName);
    }

    fileHandle.write((char*) bufferData, bufferLength);

    array_delete(bufferData);

    fileHandle.close();
}
static IOReturn
PrintSMARTDataForBSDNode ( const char * bsdNode )
{


    IOReturn error   = kIOReturnError;
    io_object_t object  = MACH_PORT_NULL;
    io_object_t parent  = MACH_PORT_NULL;
    bool found   = false;
    char *                  bsdName = NULL;
    char deviceName[MAXPATHLEN];

    sprintf ( deviceName, "%s", bsdNode );

    if ( !strncmp ( deviceName, "/dev/r", 6 ) )
    {

        // Strip off the /dev/r from /dev/rdiskX
        bsdName = &deviceName[6];

    }

    else if ( !strncmp ( deviceName, "/dev/", 5 ) )
    {

        // Strip off the /dev/r from /dev/rdiskX
        bsdName = &deviceName[5];

    }

    else
    {

        bsdName = deviceName;

    }

    require_action ( ( strncmp ( bsdName, "disk", 4 ) == 0 ), ErrorExit, PrintUsage ( ) );

    object = IOServiceGetMatchingService (  kIOMasterPortDefault,
        IOBSDNameMatching ( kIOMasterPortDefault, 0, bsdName ) );

    require ( ( object != MACH_PORT_NULL ), ErrorExit );

    parent = object;
    while ( IOObjectConformsTo ( object, kIOATABlockStorageDeviceClass ) == false )
    {

                #if DEBUG

        io_name_t className;

        error = IOObjectGetClass ( object, className );
        printf ( "Object class = %s\n", ( char * ) className );

                #endif

        error = IORegistryEntryGetParentEntry ( object, kIOServicePlane, &parent );
        require ( ( error == kIOReturnSuccess ), ReleaseObject );
        require ( ( parent != MACH_PORT_NULL ), ReleaseObject );

        IOObjectRelease ( object );
        object = parent;

    }

    if ( IOObjectConformsTo ( object, kIOATABlockStorageDeviceClass ) )
    {

        PrintSMARTDataForDevice ( object );
        found = true;

    }


ReleaseObject:


    require ( ( object != MACH_PORT_NULL ), ErrorExit );
    IOObjectRelease ( object );
    object = MACH_PORT_NULL;


ErrorExit:


    if ( found == false )
    {
        printf ( "No S.M.A.R.T. capable device at %s\n", bsdNode );
    }

    return error;

}
示例#26
0
文件: cMRC.cpp 项目: hvthaibk/ccrunch
void cMRC<T>::readHeader(const std::string& fileName, cMapHeader& header)
{
    const std::string   funcName("void cMRC::readHeader("
                                    "const std::string& fileName, "
                                    "cMapHeader& header)");

    checkExtension(fileName);

    std::ifstream       fileHandle;

    fileHandle.open(fileName.c_str(), std::ifstream::binary);
    assure(fileHandle, fileName.c_str());

    int             map_dim[3], data_mode, origin[3], cell_grid[3], axes_order[3];
    float           cell_dim[3], cell_angle[3];
    float           density_min, density_max, density_mean;
    int             spacegroup, sym_byte;
    char            mapStamp[] = "    ";

    fileHandle.read((char*) map_dim,       3*sizeof(int));         // NX, NY, NZ
    fileHandle.read((char*) &data_mode,      sizeof(int));         // MODE
    fileHandle.read((char*) origin,        3*sizeof(int));         // NXSTART, NYSTART, NZSTART
    fileHandle.read((char*) cell_grid,     3*sizeof(int));         // MX, MY, MZ
    fileHandle.read((char*) cell_dim,      3*sizeof(float));       // CELLA
    fileHandle.read((char*) cell_angle,    3*sizeof(float));       // CELLB
    fileHandle.read((char*) axes_order,    3*sizeof(int));         // MAPC, MAPR, MAPS
    fileHandle.read((char*) &density_min,    sizeof(float));       // DMIN
    fileHandle.read((char*) &density_max,    sizeof(float));       // DMAX
    fileHandle.read((char*) &density_mean,   sizeof(float));       // DMEAN
    fileHandle.read((char*) &spacegroup,     sizeof(int));         // ISPG
    fileHandle.read((char*) &sym_byte,       sizeof(int));         // NSYMBT

    fileHandle.seekg(208, std::ios::beg);
    fileHandle.read((char*) mapStamp,      4*sizeof(char));        // MAP

    // check for the need of byte swapping
    header.edian_swap = false;
    if (map_dim[0] < 0 || map_dim[0] > 100000 ||
        map_dim[1] < 0 || map_dim[1] > 100000 ||
        map_dim[2] < 0 || map_dim[2] > 100000) {
        header.edian_swap = true;
    }

    if (header.edian_swap) {
        swap4_aligned(map_dim, 3);
        swap4_aligned(&data_mode, 1);
        swap4_aligned(origin, 3);
        swap4_aligned(cell_grid, 3);
        swap4_aligned(cell_dim, 3);
        swap4_aligned(cell_angle, 3);
        swap4_aligned(axes_order, 3);
        swap4_aligned(&density_min, 1);
        swap4_aligned(&density_max, 1);
        swap4_aligned(&density_mean, 1);
        swap4_aligned(&spacegroup, 1);
        swap4_aligned(&sym_byte, 1);
        swap4_aligned(mapStamp, 1);
    }

    // check data mode and 'MAP' stamp
    require(data_mode >=0 || data_mode <= 2,
            funcName + ": non-supported data type (data_mode != 0,1,2) in" + fileName);
    if (map_dim[2] != 1) {
        require(strcmp(mapStamp, "MAP ") == 0,
                funcName + ": cannot detect the 'MAP' string in " + fileName);
    }

    // check symmetry validity
    size_t      fileSize, dataOffset,
                nelement = (size_t) map_dim[0] * (size_t) map_dim[1] * (size_t) map_dim[2];

    fileHandle.seekg(0, std::ios::end);
    fileSize   = fileHandle.tellg();

    switch (data_mode) {
        case 0:            // int8
            dataOffset = fileSize - 1 * nelement;
            break;
        case 1:            // int16
            dataOffset = fileSize - 2 * nelement;
            break;
        case 2:            // float32
            dataOffset = fileSize - 4 * nelement;
            break;
        case 6:            // uint16
            dataOffset = fileSize - 2 * nelement;
            break;
        default:
            ERROR(funcName, "unsupported data mode in reading " + fileName);
    }

    if ((int) dataOffset != (CCP4_HEADER_SIZE + sym_byte)) {
        if (dataOffset < CCP4_HEADER_SIZE) {
            ERROR(funcName, "file " + fileName + " has size smaller than expected");
        }
        else if (dataOffset == CCP4_HEADER_SIZE) {
            ERROR(funcName, "the symmetry record in " + fileName + " is bogus");
        }
        else {
            ERROR(funcName, "file " + fileName + " has size larger than expected");
        }
    }

    // save header information
    header.file_name = fileName;

    header.data_mode  = data_mode;
    header.spacegroup = spacegroup;
    header.sym_byte   = sym_byte;

    header.cell_dim[0] = cell_dim[0];
    header.cell_dim[1] = cell_dim[1];
    header.cell_dim[2] = cell_dim[2];

    header.cell_angle[0] = cell_angle[0];
    header.cell_angle[1] = cell_angle[1];
    header.cell_angle[2] = cell_angle[2];

    header.map_dim[0] = map_dim[0];
    header.map_dim[1] = map_dim[1];
    header.map_dim[2] = map_dim[2];

    header.origin[0] = origin[0];
    header.origin[1] = origin[1];
    header.origin[2] = origin[2];

    header.cell_grid[0] = cell_grid[0];
    header.cell_grid[1] = cell_grid[1];
    header.cell_grid[2] = cell_grid[2];

    header.axes_order[0] = axes_order[0];
    header.axes_order[1] = axes_order[1];
    header.axes_order[2] = axes_order[2];

    header.min  = density_min;
    header.max  = density_max;
    header.mean = density_mean;

    fileHandle.close();
}
示例#27
0
/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var ajax = require('ajax');
var UI = require('ui');
var Vector2 = require('vector2');
var Accel = require('ui/accel');

var sumx = 0;
var sumy = 0;
var sumz = 0;
var counter = 0;

var initialx = 0;
var initialy = 0;
var initialz = 0;

var finalx = 0;
var finaly = 0;
var finalz = 0;

var main = new UI.Card({
  title: 'Team BD',
  icon: 'images/menu_icon.png',
  subtitle: 'Pebble Tennis',
  body: 'Enjoy.'
});
示例#28
0
/**
 * Instantiate an application and replay a ledger history out
 * of the dump file `filename`.
 */
void
LedgerDump::loadTransactions (std::string const& filename)
{
    std::ifstream in (filename);
    require ((bool)in, "opening file");

    std::unique_ptr <Application> app (make_Application ());
    app->setup ();
    auto &lm = app->getLedgerMaster ();
    WriteLog (lsINFO, LedgerDump) << "Loading ledgers from " << filename;

    auto nTxs = 0;

    // app->setup() when called with START_UP == Config::FRESH calls
    // ApplicationImp::startNewLedger(). Unfortunately it starts the new
    // ledger at the wrong timestamp, so we call it again once we've read
    // the first ledger we're going to apply. However, it's worth
    // understanding that startNewLedger() establishes 3 ledgers:
    //
    // Ledger 0 is the genesis ledger, it's not a real ledger, just a
    //          number.
    //
    // Ledger 1 is the root-account deposit ledger, with a single pile of
    //          currency owned by a single account generated by the seed
    //          "masterpassword".
    //
    // Ledger 2 is created and closed immediately on start, not sure why.
    //
    // Ledger 3 is a new ledger chained to #2 and left open in
    //          ledgermaster.
    //
    // Ledger 3 is where replay should be starting, so (once we call
    // startNewLedger() again) we pull out ledger #2 and use it as the
    // parent of the new ledger 3 we're replaying, and throw away the #3
    // that was made by startNewLedger().

    Ledger::pointer parentLedger;

    while (in)
    {
        if ((gLedgerSeq & 0xfff) == 0) {
            Job j;
            app->doSweep (j);
        }

        Json::Value j = loadJsonRecord (in);

        Ledger::pointer deserializedLedger;
        SHAMap::pointer txSet;
        std::vector<uint256> txOrder;
        std::tie (deserializedLedger, txSet, txOrder) =
            loadLedgerAndTransactionsFromJSON (*app, j);

        if (!parentLedger)
        {
            if (getConfig ().START_LEDGER.empty ())
            {
                require (deserializedLedger->getLedgerSeq () == 3,
                         "Initial ledger isn't seq #3");

                // On first iteration, restart the app's view of the ledger
                // history at the same instant as the parent close time of the
                // first ledger (ledger #3).
                app->startNewLedger (deserializedLedger->getParentCloseTimeNC ());
                parentLedger = lm.getClosedLedger ();
                require (parentLedger->getLedgerSeq () == 2,
                         "Initial ledger parent isn't seq #2");
            }
            else
            {
                // We're being invoked with --ledger, which is where we
                // will start replay from.
                require (app->loadOldLedger (getConfig ().START_LEDGER, false),
                         "Reloading old ledger failed.");
                parentLedger = lm.getClosedLedger ();
            }

            auto const parentSeq = parentLedger->getLedgerSeq ();
            auto seq = j["seq"].asUInt ();
            while (parentSeq + 1 > seq)
            {
                // Fast-scan JSON records until we hit the right one.
                WriteLog (lsINFO, LedgerDump) << "scanning past ledger: "
                                              << seq;
                j = loadJsonRecord (in);
                seq = j["seq"].asUInt ();
                if (parentSeq + 1 <= seq)
                {
                    require (parentSeq + 1 == seq,
                             "Missing ledgers between loaded and replay-start");
                    std::tie (deserializedLedger, txSet, txOrder) =
                        loadLedgerAndTransactionsFromJSON (*app, j);
                }
            }
            gLedgerSeq = parentSeq;
            require(parentLedger->getLedgerSeq () + 1 ==
                    deserializedLedger->getLedgerSeq (),
                    "Mismatched ledger-sequence prefix.");
        }

        Ledger::pointer currentLedger =
            boost::make_shared<Ledger> (true, *parentLedger);
        currentLedger->setCloseTime (deserializedLedger->getCloseTimeNC ());
        currentLedger->setCloseFlags (deserializedLedger->getCloseFlags ());
        currentLedger->setParentHash (deserializedLedger->getParentHash ());

        WriteLog (lsINFO, LedgerDump) << "loading ledger: "
                                      << currentLedger->getLedgerSeq();

        if (ShouldLog (lsTRACE, LedgerDump))
        {
            WriteLog (lsTRACE, LedgerDump) << "expecting next ledger:";
            WriteLog (lsTRACE, LedgerDump) << deserializedLedger->getJson (0);
            WriteLog (lsTRACE, LedgerDump) << "synthetic next ledger:";
            WriteLog (lsTRACE, LedgerDump) << currentLedger->getJson (0);
        }

        gLedgerSeq++;

        // Apply transactions, transitioning from one ledger state to next.
        WriteLog (lsDEBUG, LedgerDump)
            << "Applying set of " << txOrder.size() << " transactions";
        CanonicalTXSet retriableTransactions (txSet->getHash ());
        std::set<uint256> failedTransactions;
        LedgerConsensus::applyTransactions (txSet, currentLedger, currentLedger,
                                            retriableTransactions, failedTransactions,
                                            false, txOrder);

        require (retriableTransactions.empty (), "failed retriable tx set is not empty");
        require (failedTransactions.empty (), "failed tx set is not empty");

        currentLedger->updateSkipList ();
        currentLedger->setClosed ();
        currentLedger->setCloseTime (deserializedLedger->getCloseTimeNC ());

        int asf = currentLedger->peekAccountStateMap ()->flushDirty (
            hotACCOUNT_NODE, currentLedger->getLedgerSeq());
        int tmf = currentLedger->peekTransactionMap ()->flushDirty (
            hotTRANSACTION_NODE, currentLedger->getLedgerSeq());
        nTxs += tmf;

        WriteLog (lsDEBUG, LedgerDump) << "Flushed " << asf << " account "
                                  << "and " << tmf << "transaction nodes";

        // Finalize with the LedgerMaster.
        currentLedger->setAccepted ();
        bool alreadyHadLedger = lm.storeLedger (currentLedger);
        assert (! alreadyHadLedger);
        lm.pushLedger (currentLedger);

        WriteLog (lsTRACE, LedgerDump) << "parent ledger:";
        traceLedgerContents (*parentLedger);
        WriteLog (lsTRACE, LedgerDump) << "current ledger:";
        traceLedgerContents (*currentLedger);

        try
        {
            checkLedgersEqual (*deserializedLedger, *currentLedger);
        }
        catch (...)
        {
            WriteLog (lsINFO, LedgerDump) << "bad ledger:";
            std::cerr << currentLedger->getJson (LEDGER_JSON_FULL);
            throw;
        }
        parentLedger = currentLedger;
    }

    WriteLog (lsINFO, LedgerDump) << "Loaded "
                             << gLedgerSeq << "ledgers, "
                             << nTxs << " transactions from "
                             << filename;
    exit (0);
}
示例#29
0
文件: ejs.c 项目: satanupup/appweb
MAIN(ejsMain, int argc, char **argv, char **envp)
{
    Mpr             *mpr;
    EcCompiler      *cp;
    Ejs             *ejs;
    cchar           *cmd, *className, *method, *homeDir;
    char            *argp, *searchPath, *modules, *name, *tok, *extraFiles;
    int             nextArg, err, ecFlags, stats, merge, bind, noout, debug, optimizeLevel, warnLevel, strict, i, next;

    /*  
        Initialize Multithreaded Portable Runtime (MPR)
     */
    mpr = mprCreate(argc, argv, 0);
    app = mprAllocObj(App, manageApp);
    mprAddRoot(app);
    mprAddStandardSignals();

    if (mprStart(mpr) < 0) {
        mprError("Cannot start mpr services");
        return EJS_ERR;
    }
    err = 0;
    className = 0;
    cmd = 0;
    method = 0;
    searchPath = 0;
    stats = 0;
    merge = 0;
    bind = 1;
    noout = 1;
    debug = 1;
    warnLevel = 1;
    optimizeLevel = 9;
    strict = 0;
    app->files = mprCreateList(-1, 0);
    app->iterations = 1;
    argc = mpr->argc;
    argv = (char**) mpr->argv;

    for (nextArg = 1; nextArg < argc; nextArg++) {
        argp = argv[nextArg];
        if (*argp != '-') {
            break;
        }
        if (smatch(argp, "--bind")) {
            bind = 1;

        } else if (smatch(argp, "--class")) {
            if (nextArg >= argc) {
                err++;
            } else {
                className = argv[++nextArg];
            }

        } else if (smatch(argp, "--chdir") || smatch(argp, "--home") || smatch(argp, "-C")) {
            if (nextArg >= argc) {
                err++;
            } else {
                homeDir = argv[++nextArg];
                if (chdir((char*) homeDir) < 0) {
                    mprError("Cannot change directory to %s", homeDir);
                }
            }

#if BIT_UNIX_LIKE
        } else if (smatch(argp, "--chroot")) {
            /* Not documented or supported */
            if (nextArg >= argc) {
                err++;
            } else {
                homeDir = mprGetAbsPath(argv[++nextArg]);
                if (chroot(homeDir) < 0) {
                    if (errno == EPERM) {
                        mprPrintfError("%s: Must be super user to use the --chroot option", mprGetAppName(mpr));
                    } else {
                        mprPrintfError("%s: Cannot change change root directory to %s, errno %d",
                            mprGetAppName(), homeDir, errno);
                    }
                    return 4;
                }
            }
#endif

        } else if (smatch(argp, "--cmd") || smatch(argp, "-c")) {
            if (nextArg >= argc) {
                err++;
            } else {
                cmd = argv[++nextArg];
            }

#if BIT_WIN_LIKE
        } else if (smatch(argp, "--cygroot")) {
            if (nextArg >= argc) {
                err++;
            } else {
                app->cygroot = sclone(argv[++nextArg]);
            }
#endif
        } else if (smatch(argp, "--debug")) {
            debug = 1;

        } else if (smatch(argp, "--debugger") || smatch(argp, "-D")) {
            mprSetDebugMode(1);

        } else if (smatch(argp, "--files") || smatch(argp, "-f")) {
            /* Compatibility with mozilla shell */
            if (nextArg >= argc) {
                err++;
            } else {
                extraFiles = sclone(argv[++nextArg]);
                name = stok(extraFiles, " \t", &tok);
                while (name != NULL) {
                    mprAddItem(app->files, sclone(name));
                    name = stok(NULL, " \t", &tok);
                }
            }

        } else if (smatch(argp, "--iterations") || smatch(argp, "-i")) {
            if (nextArg >= argc) {
                err++;
            } else {
                app->iterations = atoi(argv[++nextArg]);
            }

        } else if (smatch(argp, "--log")) {
            if (nextArg >= argc) {
                err++;
            } else {
                mprStartLogging(argv[++nextArg], 0);
                mprSetCmdlineLogging(1);
            }

        } else if (smatch(argp, "--method")) {
            if (nextArg >= argc) {
                err++;
            } else {
                method = argv[++nextArg];
            }

        } else if (smatch(argp, "--name")) {
            /* Just ignore. Used to tag commands with a unique command line */ 
            nextArg++;

        } else if (smatch(argp, "--nobind")) {
            bind = 0;

        } else if (smatch(argp, "--nodebug")) {
            debug = 0;

        } else if (smatch(argp, "--optimize")) {
            if (nextArg >= argc) {
                err++;
            } else {
                optimizeLevel = atoi(argv[++nextArg]);
            }

        } else if (smatch(argp, "-s")) {
            /* Compatibility with mozilla shell. Just ignore */

        } else if (smatch(argp, "--search") || smatch(argp, "--searchpath")) {
            if (nextArg >= argc) {
                err++;
            } else {
                searchPath = argv[++nextArg];
            }

        } else if (smatch(argp, "--standard")) {
            strict = 0;

        } else if (smatch(argp, "--stats")) {
            stats = 1;

        } else if (smatch(argp, "--strict")) {
            strict = 1;

        } else if (smatch(argp, "--require")) {
            if (nextArg >= argc) {
                err++;
            } else {
                if (app->modules == 0) {
                    app->modules = mprCreateList(-1, 0);
                }
                modules = sclone(argv[++nextArg]);
                name = stok(modules, " \t", &tok);
                while (name != NULL) {
                    require(name);
                    name = stok(NULL, " \t", &tok);
                }
            }

        } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) {
            mprStartLogging("stderr:2", 0);
            mprSetCmdlineLogging(1);

        } else if (smatch(argp, "--version") || smatch(argp, "-V")) {
            mprPrintf("%s-%s\n", BIT_VERSION, BIT_BUILD_NUMBER);
            return 0;

        } else if (smatch(argp, "--warn")) {
            if (nextArg >= argc) {
                err++;
            } else {
                warnLevel = atoi(argv[++nextArg]);
            }

        } else {
            err++;
            break;
        }
    }

    if (err) {
        /*  
            If --method or --class is specified, then the named class.method will be run (method defaults to "main", class
            defaults to first class with a "main").

            Examples:
                ejs
                ejs script.es arg1 arg2 arg3
                ejs --class "Customer" --method "start" --files "script1.es script2.es" main.es
         */
        mprPrintfError("Usage: %s [options] script.es [arguments] ...\n"
            "  Ejscript shell program options:\n"
            "  --class className        # Name of class containing method to run\n"
            "  --cmd ejscriptCode       # Literal ejscript statements to execute\n"
            "  --cygroot path           # Set cygwin root for resolving script paths\n"
            "  --debug                  # Use symbolic debugging information (default)\n"
            "  --debugger               # Disable timeouts to make using a debugger easier\n"
            "  --files \"files..\"        # Extra source to compile\n"
            "  --log logSpec            # Internal compiler diagnostics logging\n"
            "  --method methodName      # Name of method to run. Defaults to main\n"
            "  --nodebug                # Omit symbolic debugging information\n"
            "  --optimize level         # Set the optimization level (0-9 default is 9)\n"
            "  --require 'module,...'   # Required list of modules to pre-load\n"
            "  --search ejsPath         # Module search path\n"
            "  --standard               # Default compilation mode to standard (default)\n"
            "  --stats                  # Print memory stats on exit\n"
            "  --strict                 # Default compilation mode to strict\n"
            "  --verbose | -v           # Same as --log stderr:2 \n"
            "  --version                # Emit the compiler version information\n"
            "  --warn level             # Set the warning message level (0-9 default is 0)\n\n",
            mpr->name);
        return -1;
    }
    if ((ejs = ejsCreateVM(argc - nextArg, (cchar **) &argv[nextArg], 0)) == 0) {
        return MPR_ERR_MEMORY;
    }
    app->ejs = ejs;
    if (ejsLoadModules(ejs, searchPath, app->modules) < 0) {
        return MPR_ERR_CANT_READ;
    }

    ecFlags = 0;
    ecFlags |= (merge) ? EC_FLAGS_MERGE: 0;
    ecFlags |= (bind) ? EC_FLAGS_BIND: 0;
    ecFlags |= (noout) ? EC_FLAGS_NO_OUT: 0;
    ecFlags |= (debug) ? EC_FLAGS_DEBUG: 0;

    cp = app->compiler = ecCreateCompiler(ejs, ecFlags);
    if (cp == 0) {
        return MPR_ERR_MEMORY;
    }
    ecSetRequire(cp, app->modules);

    ecSetOptimizeLevel(cp, optimizeLevel);
    ecSetWarnLevel(cp, warnLevel);
    ecSetStrictMode(cp, strict);
    if (nextArg < argc) {
        mprAddItem(app->files, sclone(argv[nextArg]));
    }
    if (app->cygroot) {
        /*  
            When cygwin invokes a script with shebang, it passes a cygwin path to the script
            The ejs --cygroot option permits ejscript to conver this to a native path
         */
        for (next = 0; (name = mprGetNextItem(app->files, &next)) != 0; ) {
            if (*name == '/' || *name == '\\') {
                mprSetItem(app->files, next - 1, sjoin(app->cygroot, name, NULL));
            }
        }
    }
    for (i = 0; !err && i < app->iterations; i++) {
        if (cmd) {
            if (interpretCommands(cp, cmd) < 0) {
                err++;
            }
        } else if (mprGetListLength(app->files) > 0) {
            if (interpretFiles(cp, app->files, argc - nextArg, &argv[nextArg], className, method) < 0) {
                err++;
            }
        } else {
            /*  
                No args - run as an interactive shell
             */
            if (interpretCommands(cp, NULL) < 0) {
                err++;
            }
        }
    }
    if (stats) {
#if BIT_DEBUG
        mprSetLogLevel(1);
        mprPrintMem("Memory Usage", 1);
#endif
    }
    if (!err) {
        err = mpr->exitStatus;
    }
    app->ejs = 0;
    mprTerminate(MPR_EXIT_DEFAULT, err);
    ejsDestroyVM(ejs);
    mprDestroy(MPR_EXIT_DEFAULT);
    return err;
}
示例#30
0
文件: parser.cpp 项目: Jenny-fa/lingo
Var const*
Parser::var()
{
  Token tok = require(identifier_tok);
  return on_var(tok);
}