Пример #1
0
void
transfer_window_files (gftp_window_data * fromwdata, gftp_window_data * towdata)
{
  gftp_file * tempfle, * newfle;
  GList * templist, * filelist;
  gftp_transfer * transfer;
  int num, ret, disconnect;

  if (!check_status (_("Transfer Files"), fromwdata, 1, 0, 1,
       towdata->request->put_file != NULL && fromwdata->request->get_file != NULL))
    return;

  if (!GFTP_IS_CONNECTED (fromwdata->request) || 
      !GFTP_IS_CONNECTED (towdata->request))
    {
      ftp_log (gftp_logging_error, NULL,
               _("Retrieve Files: Not connected to a remote site\n"));
      return;
    }

  if (check_reconnect (fromwdata) < 0 || check_reconnect (towdata) < 0)
    return;

  transfer = g_malloc0 (sizeof (*transfer));
  transfer->fromreq = gftp_copy_request (fromwdata->request);
  transfer->toreq = gftp_copy_request (towdata->request);
  transfer->fromwdata = fromwdata;
  transfer->towdata = towdata;

  num = 0;
  templist = gftp_gtk_get_list_selection (fromwdata);
  filelist = fromwdata->files;
  while (templist != NULL)
    {
      templist = get_next_selection (templist, &filelist, &num);
      tempfle = filelist->data;
      if (strcmp (tempfle->file, "..") != 0)
        {
          newfle = copy_fdata (tempfle);
          transfer->files = g_list_append (transfer->files, newfle);
        }
    }

  if (transfer->files != NULL)
    {
      gftp_swap_socks (transfer->fromreq, fromwdata->request);
      gftp_swap_socks (transfer->toreq, towdata->request);

      ret = gftp_gtk_get_subdirs (transfer);
      if (ret < 0)
        disconnect = 1;
      else
        disconnect = 0;

      if (!GFTP_IS_CONNECTED (transfer->fromreq))
        {
          gftpui_disconnect (fromwdata);
          disconnect = 1;
        } 

      if (!GFTP_IS_CONNECTED (transfer->toreq))
        {
          gftpui_disconnect (towdata);
          disconnect = 1;
        } 

      if (disconnect)
        {
          free_tdata (transfer);
          return;
        }

      gftp_swap_socks (fromwdata->request, transfer->fromreq);
      gftp_swap_socks (towdata->request, transfer->toreq);
    }

  if (transfer->files != NULL)
    {
      gftpui_common_add_file_transfer (transfer->fromreq, transfer->toreq, 
                                       transfer->fromwdata, transfer->towdata, 
                                       transfer->files);
      g_free (transfer);
    }
  else
    free_tdata (transfer);
}
Пример #2
0
void
process_outgoing_tun (struct context *c)
{
  struct gc_arena gc = gc_new ();

  /*
   * Set up for write() call to TUN/TAP
   * device.
   */
  if (c->c2.to_tun.len <= 0)
    return;

  perf_push (PERF_PROC_OUT_TUN);

  /*
   * The --mssfix option requires
   * us to examine the IP header (IPv4 or IPv6).
   */
  process_ip_header (c, PIP_MSSFIX|PIPV4_EXTRACT_DHCP_ROUTER|PIPV4_CLIENT_NAT|PIPV4_OUTGOING, &c->c2.to_tun);

  if (c->c2.to_tun.len <= MAX_RW_SIZE_TUN (&c->c2.frame))
    {
      /*
       * Write to TUN/TAP device.
       */
      int size;

#ifdef LOG_RW
      if (c->c2.log_rw)
	fprintf (stderr, "w");
#endif
      dmsg (D_TUN_RW, "TUN WRITE [%d]", BLEN (&c->c2.to_tun));

#ifdef PACKET_TRUNCATION_CHECK
      ipv4_packet_size_verify (BPTR (&c->c2.to_tun),
			       BLEN (&c->c2.to_tun),
			       TUNNEL_TYPE (c->c1.tuntap),
			       "WRITE_TUN",
			       &c->c2.n_trunc_tun_write);
#endif

#ifdef TUN_PASS_BUFFER
      size = write_tun_buffered (c->c1.tuntap, &c->c2.to_tun);
#else
      size = write_tun (c->c1.tuntap, BPTR (&c->c2.to_tun), BLEN (&c->c2.to_tun));
#endif

      if (size > 0)
	c->c2.tun_write_bytes += size;
      check_status (size, "write to TUN/TAP", NULL, c->c1.tuntap);

      /* check written packet size */
      if (size > 0)
	{
	  /* Did we write a different size packet than we intended? */
	  if (size != BLEN (&c->c2.to_tun))
	    msg (D_LINK_ERRORS,
		 "TUN/TAP packet was destructively fragmented on write to %s (tried=%d,actual=%d)",
		 c->c1.tuntap->actual_name,
		 BLEN (&c->c2.to_tun),
		 size);

	  /* indicate activity regarding --inactive parameter */
	  register_activity (c, size);
	}
    }
  else
    {
      /*
       * This should never happen, probably indicates some kind
       * of MTU mismatch.
       */
      msg (D_LINK_ERRORS, "tun packet too large on write (tried=%d,max=%d)",
	   c->c2.to_tun.len,
	   MAX_RW_SIZE_TUN (&c->c2.frame));
    }

  buf_reset (&c->c2.to_tun);

  perf_pop ();
  gc_free (&gc);
}
Пример #3
0
void
read_incoming_link (struct context *c)
{
  /*
   * Set up for recvfrom call to read datagram
   * sent to our TCP/UDP port.
   */
  int status;

  /*ASSERT (!c->c2.to_tun.len);*/

  perf_push (PERF_READ_IN_LINK);

  c->c2.buf = c->c2.buffers->read_link_buf;
  ASSERT (buf_init (&c->c2.buf, FRAME_HEADROOM_ADJ (&c->c2.frame, FRAME_HEADROOM_MARKER_READ_LINK)));

  status = link_socket_read (c->c2.link_socket,
			     &c->c2.buf,
			     MAX_RW_SIZE_LINK (&c->c2.frame),
			     &c->c2.from);

  if (socket_connection_reset (c->c2.link_socket, status))
    {
#if PORT_SHARE
      if (port_share && socket_foreign_protocol_detected (c->c2.link_socket))
	{
	  const struct buffer *fbuf = socket_foreign_protocol_head (c->c2.link_socket);
	  const int sd = socket_foreign_protocol_sd (c->c2.link_socket);
	  port_share_redirect (port_share, fbuf, sd);
	  register_signal (c, SIGTERM, "port-share-redirect");
	}
      else
#endif
      {
	/* received a disconnect from a connection-oriented protocol */
	if (c->options.inetd)
	  {
	    register_signal (c, SIGTERM, "connection-reset-inetd");
	    msg (D_STREAM_ERRORS, "Connection reset, inetd/xinetd exit [%d]", status);
	  }
	else
	  {
#ifdef ENABLE_OCC
	    if (event_timeout_defined(&c->c2.explicit_exit_notification_interval))
	      {
		msg (D_STREAM_ERRORS, "Connection reset during exit notification period, ignoring [%d]", status);
		openvpn_sleep(1);
	      }
	    else
#endif
	      {
		register_signal (c, SIGUSR1, "connection-reset"); /* SOFT-SIGUSR1 -- TCP connection reset */
		msg (D_STREAM_ERRORS, "Connection reset, restarting [%d]", status);
	      }
	  }
      }
      perf_pop ();
      return;
    }

  /* check recvfrom status */
  check_status (status, "read", c->c2.link_socket, NULL);

  /* Remove socks header if applicable */
  socks_postprocess_incoming_link (c);

  perf_pop ();
}
Пример #4
0
bool redis_string::mset(const std::vector<string>& keys,
	const std::vector<string>& values)
{
	build("MSET", NULL, keys, values);
	return check_status();
}
Пример #5
0
/*
 * Counts occurrences of four-node functional motifs in a binary graph.
 */
VECTOR_T* BCT_NAMESPACE::motif4funct_bin(const MATRIX_T* W, MATRIX_T** F) {
	if (safe_mode) check_status(W, SQUARE | BINARY, "motif4funct_bin");
	
	// load motif34lib M4 ID4 N4
	VECTOR_T* ID4;
	VECTOR_T* N4;
	MATRIX_T* M4 = motif4generate(&ID4, &N4);
	
	// n=length(W);
	int n = length(W);
	
	// f=zeros(199,1);
	VECTOR_T* f = zeros_vector(199);
	
	// F=zeros(199,n);
	if (F != NULL) {
		*F = zeros(199, n);
	}
	
	// A=1*(W~=0);
	MATRIX_T* A = compare_elements(W, fp_not_equal, 0.0);
	
	// As=A|A.';
	MATRIX_T* A_transpose = MATRIX_ID(alloc)(A->size2, A->size1);
	MATRIX_ID(transpose_memcpy)(A_transpose, A);
	MATRIX_T* As = logical_or(A, A_transpose);
	MATRIX_ID(free)(A_transpose);
	
	// for u=1:n-3
	for (int u = 0; u < n - 3; u++) {
		
		// V1=[false(1,u) As(u,u+1:n)];
		VECTOR_T* V1 = VECTOR_ID(alloc)(n);
		MATRIX_ID(get_row)(V1, As, u);
		for (int i = 0; i <= u; i++) {
			VECTOR_ID(set)(V1, i, 0.0);
		}
		
		// for v1=find(V1)
		VECTOR_T* find_V1 = find(V1);
		if (find_V1 != NULL) {
			for (int i_find_V1 = 0; i_find_V1 < (int)find_V1->size; i_find_V1++) {
				int v1 = (int)VECTOR_ID(get)(find_V1, i_find_V1);
				
				// V2=[false(1,u) As(v1,u+1:n)];
				VECTOR_T* V2 = VECTOR_ID(alloc)(n);
				MATRIX_ID(get_row)(V2, As, v1);
				for (int i = 0; i <= u; i++) {
					VECTOR_ID(set)(V2, i, 0.0);
				}
				
				// V2(V1)=0;
				logical_index_assign(V2, V1, 0.0);
				
				// V2=V2|([false(1,v1) As(u,v1+1:n)]);
				VECTOR_T* V2_1 = V2;
				VECTOR_T* V2_2 = VECTOR_ID(alloc)(n);
				MATRIX_ID(get_row)(V2_2, As, u);
				for (int i = 0; i <= v1; i++) {
					VECTOR_ID(set)(V2_2, i, 0.0);
				}
				V2 = logical_or(V2_1, V2_2);
				VECTOR_ID(free)(V2_1);
				VECTOR_ID(free)(V2_2);
				
				// for v2=find(V2)
				VECTOR_T* find_V2 = find(V2);
				if (find_V2 != NULL) {
					for (int i_find_V2 = 0; i_find_V2 < (int)find_V2->size; i_find_V2++) {
						int v2 = (int)VECTOR_ID(get)(find_V2, i_find_V2);
						
						// vz=max(v1,v2);
						int vz = (v1 > v2) ? v1 : v2;
						
						// V3=([false(1,u) As(v2,u+1:n)]);
						VECTOR_T* V3 = VECTOR_ID(alloc)(n);
						MATRIX_ID(get_row)(V3, As, v2);
						for (int i = 0; i <= u; i++) {
							VECTOR_ID(set)(V3, i, 0.0);
						}
						
						// V3(V2)=0;
						logical_index_assign(V3, V2, 0.0);
						
						// V3=V3|([false(1,v2) As(v1,v2+1:n)]);
						VECTOR_T* V3_1 = V3;
						VECTOR_T* V3_2 = VECTOR_ID(alloc)(n);
						MATRIX_ID(get_row)(V3_2, As, v1);
						for (int i = 0; i <= v2; i++) {
							VECTOR_ID(set)(V3_2, i, 0.0);
						}
						V3 = logical_or(V3_1, V3_2);
						VECTOR_ID(free)(V3_1);
						VECTOR_ID(free)(V3_2);
						
						// V3(V1)=0;
						logical_index_assign(V3, V1, 0.0);
						
						// V3=V3|([false(1,vz) As(u,vz+1:n)]);
						V3_1 = V3;
						V3_2 = VECTOR_ID(alloc)(n);
						MATRIX_ID(get_row)(V3_2, As, u);
						for (int i = 0; i <= vz; i++) {
							VECTOR_ID(set)(V3_2, i, 0.0);
						}
						V3 = logical_or(V3_1, V3_2);
						VECTOR_ID(free)(V3_1);
						VECTOR_ID(free)(V3_2);
						
						// for v3=find(V3)
						VECTOR_T* find_V3 = find(V3);
						if (find_V3 != NULL ) {
							for (int i_find_V3 = 0; i_find_V3 < (int)find_V3->size; i_find_V3++) {
								int v3 = (int)VECTOR_ID(get)(find_V3, i_find_V3);
								
								// a=[A(v1,u);A(v2,u);A(v3,u);A(u,v1);A(v2,v1);A(v3,v1);A(u,v2);A(v1,v2);A(v3,v2);A(u,v3);A(v1,v3);A(v2,v3)];
								int A_rows[] = { v1, v2, v3, u, v2, v3, u, v1, v3, u, v1, v2 };
								int A_cols[] = { u, u, u, v1, v1, v1, v2, v2, v2, v3, v3, v3 };
								MATRIX_T* a = MATRIX_ID(alloc)(12, 1);
								for (int i = 0; i < 12; i++) {
									MATRIX_ID(set)(a, i, 0, MATRIX_ID(get)(A, A_rows[i], A_cols[i]));
								}
								
								// ind=(M4*a)==N4;
								MATRIX_T* M4_mul_a_m = mul(M4, a);
								MATRIX_ID(free)(a);
								VECTOR_T* M4_mul_a = to_vector(M4_mul_a_m);
								MATRIX_ID(free)(M4_mul_a_m);
								VECTOR_T* ind = compare_elements(M4_mul_a, fp_equal, N4);
								VECTOR_ID(free)(M4_mul_a);
								
								// id=ID4(ind);
								VECTOR_T* id = logical_index(ID4, ind);
								VECTOR_ID(free)(ind);
								if (id != NULL) {
									VECTOR_ID(add_constant)(id, -1.0);
								
									// [idu j]=unique(id);
									VECTOR_T* j;
									VECTOR_T* idu = unique(id, "last", &j);
									VECTOR_ID(free)(id);
									
									// j=[0;j];
									VECTOR_T* temp = VECTOR_ID(alloc)(j->size + 1);
									VECTOR_ID(set)(temp, 0, -1.0);
									VECTOR_ID(view) temp_subv = VECTOR_ID(subvector)(temp, 1, j->size);
									VECTOR_ID(memcpy)(&temp_subv.vector, j);
									VECTOR_ID(free)(j);
									j = temp;
									
									// mu=length(idu);
									int mu = length(idu);
									
									// f2=zeros(mu,1);
									VECTOR_T* f2 = zeros_vector(mu);
									
									// for h=1:mu
									for (int h = 0; h < mu; h++) {
										
										// f2(h)=j(h+1)-j(h);
										FP_T j_h_add_1 = VECTOR_ID(get)(j, h + 1);
										FP_T j_h = VECTOR_ID(get)(j, h);
										VECTOR_ID(set)(f2, h, j_h_add_1 - j_h);
									}
									VECTOR_ID(free)(j);
									
									// f(idu)=f(idu)+f2;
									VECTOR_T* f_idu_add_f2 = ordinal_index(f, idu);
									VECTOR_ID(add)(f_idu_add_f2, f2);
									ordinal_index_assign(f, idu, f_idu_add_f2);
									VECTOR_ID(free)(f_idu_add_f2);
									
									// if nargout==2; F(idu,[u v1 v2 v3])=F(idu,[u v1 v2 v3])+[f2 f2 f2 f2]; end
									if (F != NULL) {
										FP_T F_cols[] = { (FP_T)u, (FP_T)v1, (FP_T)v2, (FP_T)v3 };
										VECTOR_ID(view) F_cols_vv = VECTOR_ID(view_array)(F_cols, 4);
										MATRIX_T* F_idx = ordinal_index(*F, idu, &F_cols_vv.vector);
										for (int i = 0; i < 4; i++) {
											VECTOR_ID(view) F_idx_col_i = MATRIX_ID(column)(F_idx, i);
											VECTOR_ID(add)(&F_idx_col_i.vector, f2);
										}
										ordinal_index_assign(*F, idu, &F_cols_vv.vector, F_idx);
										MATRIX_ID(free)(F_idx);
									}
									
									VECTOR_ID(free)(idu);
									VECTOR_ID(free)(f2);
								}
							}
							
							VECTOR_ID(free)(find_V3);
						}
						
						VECTOR_ID(free)(V3);
					}
					
					VECTOR_ID(free)(find_V2);
				}
				
				VECTOR_ID(free)(V2);
			}
			
			VECTOR_ID(free)(find_V1);
		}
		
		VECTOR_ID(free)(V1);
	}
	
	VECTOR_ID(free)(ID4);
	VECTOR_ID(free)(N4);
	MATRIX_ID(free)(M4);
	MATRIX_ID(free)(A);
	MATRIX_ID(free)(As);
	return f;
}
Пример #6
0
int tune_it(int fd_frontend, unsigned int freq, unsigned int srate, char pol, int tone, fe_spectral_inversion_t specInv, unsigned char diseqc,fe_modulation_t modulation,fe_code_rate_t HP_CodeRate,fe_transmit_mode_t TransmissionMode,fe_guard_interval_t guardInterval, fe_bandwidth_t bandwidth, fe_code_rate_t LP_CodeRate, fe_hierarchy_t hier) {
  int res, hi_lo, dfd;
  unsigned int base;
  struct dvb_frontend_parameters feparams;
  struct dvb_frontend_info fe_info;

  if ( (res = ioctl(fd_frontend,FE_GET_INFO, &fe_info) < 0)){
     perror("FE_GET_INFO: ");
     return -1;
  }
  
  fprintf(stderr,"Using DVB card \"%s\", freq=%d\n",fe_info.name, freq);

  if (freq < 1000000) freq*=1000UL;
  switch(fe_info.type) {
    case FE_OFDM:
      feparams.frequency=freq;
      feparams.inversion=INVERSION_OFF;
      feparams.u.ofdm.bandwidth=bandwidth;
      feparams.u.ofdm.code_rate_HP=HP_CodeRate;
      feparams.u.ofdm.code_rate_LP=LP_CodeRate;
      feparams.u.ofdm.constellation=modulation;
      feparams.u.ofdm.transmission_mode=TransmissionMode;
      feparams.u.ofdm.guard_interval=guardInterval;
      feparams.u.ofdm.hierarchy_information=hier;
      fprintf(stderr,"tuning DVB-T (%s) to %d Hz, Bandwidth: %d\n",DVB_T_LOCATION,freq, 
	bandwidth==BANDWIDTH_8_MHZ ? 8 : (bandwidth==BANDWIDTH_7_MHZ ? 7 : 6));
      break;
    case FE_QPSK:
    	pol = toupper(pol);
	if (freq > 2200000) {
        if (freq < SLOF) {
          feparams.frequency=(freq-LOF1);
	  hi_lo = 0;
	  base = LOF1;
        } else {
          feparams.frequency=(freq-LOF2);
	  hi_lo = 1;
	  base = LOF2;
      } 
      } else {
          feparams.frequency=freq;
	  base = 0;
      }

      fprintf(stderr,"tuning DVB-S to Freq: %u, Pol:%c Srate=%d, 22kHz tone=%s, LNB: %d\n",feparams.frequency,pol,srate,tone == SEC_TONE_ON ? "on" : "off", diseqc);
      feparams.inversion=specInv;
      feparams.u.qpsk.symbol_rate=srate;
      feparams.u.qpsk.fec_inner=FEC_AUTO;
      dfd = fd_frontend;

   if(do_diseqc(dfd, diseqc, (pol == 'V' ? 1 : 0), hi_lo) == 0)
	fprintf(stderr, "DISEQC SETTING SUCCEDED\n");
   else  {
	fprintf(stderr, "DISEQC SETTING FAILED\n");
          return -1;
        }
      break;
    case FE_QAM:
      fprintf(stderr,"tuning DVB-C to %d, srate=%d\n",freq,srate);
      feparams.frequency=freq;
      feparams.inversion=INVERSION_OFF;
      feparams.u.qam.symbol_rate = srate;
      feparams.u.qam.fec_inner = FEC_AUTO;
      feparams.u.qam.modulation = modulation;
      break;
#ifdef DVB_ATSC
    case FE_ATSC:
      fprintf(stderr, "tuning ATSC to %d, modulation=%d\n",freq,modulation);
      feparams.frequency=freq;
      feparams.u.vsb.modulation = modulation;
      break;
#endif
    default:
      fprintf(stderr,"Unknown FE type. Aborting\n");
      exit(-1);
  }
  usleep(100000);

  return(check_status(fd_frontend,fe_info.type,&feparams,base));
}
Пример #7
0
/*!
  \brief Get number of layers in category index
  
  \param Map pointer to Map_info structure
  
  \return number of layers
 */
int Vect_cidx_get_num_fields(const struct Map_info *Map)
{
    check_status(Map);

    return Map->plus.n_cidx;
}
Пример #8
0
int read_dsk(spi_t *spi)
{
    int result = start_floppy(spi);
    if(result < 0) {
        return result;
    }

    int num_tracks = config.end_track - config.begin_track + 1;
    int side;
    switch(config.sides) {
        case SIDES_TOP:
            side = 1;
            break;
        case SIDES_BOTTOM:
            side = 0;
            break;
        case SIDES_ALL:
            side = 0; 
            num_tracks *= 2;
            break;
    }

    int i;
    int t = config.begin_track;
    int error = 0;
    for(i=0;i<num_tracks;i++) {
        // determine file name
        const char *output_file = config.args[0];
        char name[256];
        snprintf(name,255,"%s_%02d_%d",output_file,t,side);

        printf("reading track %02d.%d to '%s'\r", t, side, name);
        fflush(stdout);
        
        // receive SPI raw blocks with track samples
        if(config.verbose>0) {
            printf("\n  [waiting for raw blocks... wait_blocks=%d max_blocks=%d]\n", config.wait_blocks, config.max_blocks);
        }
        uint8_t *raw_blocks;
        uint32_t num_blocks;
        error = spi_bulk_read_raw_blocks(spi, config.wait_blocks, config.max_blocks, &raw_blocks, &num_blocks);

        // reading from SPI failed!
        if(error < 0) {
            printf("READ ERROR: %s (got %d blocks)\n", spi_bulk_proto_error_string(error), num_blocks);
            if(raw_blocks != NULL) {

            	/* write error dump */
            	FILE *fh = fopen("error.dump","w");
                if(fh != NULL) {
                     if(config.verbose) {
                         printf("  [writing 'error.dump']\n");
                     }
                     fwrite(raw_blocks, num_blocks * SPI_BLOCK_SIZE,1,fh);
                     fclose(fh);
                 }

            	free(raw_blocks);
            }
            error = -1;
            break;
        }
        
        // decode blocks
        uint8_t *data;
        uint32_t max_frame_size;
        int size = spi_bulk_decode_raw_blocks(raw_blocks, config.max_blocks, &data, &max_frame_size);
        if(size <= 0) {
            printf("DECODE ERROR: %s\n", spi_bulk_proto_error_string(size));
            error = -2;
            break;
        }
        if(config.verbose) {
            printf("  [decoded %d/%x bytes, max frame size: %d]\n", size, size, max_frame_size);
        }
        free(raw_blocks);

        // get status
        if(check_status(spi, size)<0) {
        	printf("SAMPLER FAILED!\n");
        	error = -3;
        	break;
        }

        // write raw track data
        FILE *fh = fopen(name,"w");
        if(fh != NULL) {
            if(config.verbose) {
                printf("  [writing track to file '%s']\n", name);
            }
            fwrite(data,size,1,fh);
            fclose(fh);
        } else {
            printf("ERROR writing to '%s'\n", name);
            error = -3;
            break;
        }
        free(data);
        
        // ready?
        if(i == (num_tracks-1))
            break;
        
        // next track
        if(config.sides == SIDES_ALL) {
            // toggle side
            if(i % 2 == 0) {
                error = (control_floppy(spi,"t") != 1) ? -1 : 0;
                side = 1;
            } else {
                error = (control_floppy(spi,"b+01") != 2) ? -1 : 0;
                side = 0;
                t++;
            }
        } else {
            error = (control_floppy(spi,"+01") != 1) ? -1 : 0;
            t++;
        }
        if(error<0) {
            break;
        }
    }
    
    result = stop_floppy(spi);
    if(result < 0) {
        return result;
    }
    
    if(error==0) {
        printf("\nwrote %d tracks successfully.\n", num_tracks);
    } else {
        printf("\nFAILED in track %02d.%d!\n",t, side);
    }
    return 0;
}
Пример #9
0
int read_trk(spi_t *spi)
{
    int result;

    result = start_floppy(spi);
    if(result < 0) {
        return result;
    }

    printf("reading track %d side %c\n", config.begin_track, config.sides);
    
    if(config.verbose>0) {
        printf("  [waiting for raw blocks... wait_blocks=%d max_blocks=%d]\n", config.wait_blocks, config.max_blocks);
    }
    uint8_t *raw_blocks;
    uint32_t num_blocks;
    result = spi_bulk_read_raw_blocks(spi, config.wait_blocks, config.max_blocks, &raw_blocks, &num_blocks);

    result = stop_floppy(spi);
    if(result < 0) {
        return result;
    }

    if(num_blocks <= 0) {
        printf("READ ERROR: %s\n", spi_bulk_proto_error_string(num_blocks));
        return num_blocks;
    }

    printf("track data: received %d blocks, %d bytes\n", num_blocks, num_blocks * 4096);
    
    // write raw (debug) data
    if(config.num_args>1) {
        const char *raw_output = config.args[1];
        FILE *fh = fopen(raw_output,"w");
        if(fh != NULL) {
            printf("writing to raw data to '%s'\n", raw_output);
            fwrite(raw_blocks,num_blocks * 4096,1,fh);
            fclose(fh);
        } else {
            printf("ERROR writing to '%s'\n", raw_output);
        }
    }

    // decode blocks
    uint8_t *data;
    uint32_t max_frame_size;
    int size = spi_bulk_decode_raw_blocks(raw_blocks, config.max_blocks, &data, &max_frame_size);
    if(size <= 0) {
        printf("DECODE ERROR: %s\n", spi_bulk_proto_error_string(size));
        return -2;
    }
    if(config.verbose) {
        printf("  [decoded %d/%x bytes, max frame size: %d]\n", size, size, max_frame_size);
    }
    free(raw_blocks);

    // check status
    if(check_status(spi, size)<0) {
    	printf("SAMPLER FAILED\n");
    	return -3;
    }

    // write data
    const char *output_file = config.args[0];
    FILE *fh = fopen(output_file,"w");
    if(fh != NULL) {
        if(config.verbose) {
            printf("writing to track to '%s'\n", output_file);
        }
        fwrite(data,size,1,fh);
        fclose(fh);
    } else {
        printf("ERROR writing to '%s'\n", output_file);
    }
    
    free(data);
    return 0;
}
Пример #10
0
static int
mp750_fill_buffer (pixma_t * s, pixma_imagebuf_t * ib)
{
  mp750_t *mp = (mp750_t *) s->subdriver;
  int error;
  uint8_t info;
  unsigned block_size, bytes_received, n;
  int shift[3], base_shift;
  int c;

  c = ((is_ccd_grayscale (s)) ? 3 : s->param->channels) * s->param->depth / 8; /* single-byte or double-byte data */

  if (mp->state == state_warmup)
    {
      int tmo = 60;

      query_status (s);
      check_status (s);
 /*SIM*/ while (!is_calibrated (s) && --tmo >= 0)
        {
          if (s->cancel)
            return PIXMA_ECANCELED;
          if (handle_interrupt (s, 1000) > 0)
            {
              block_size = 0;
              error = request_image_block (s, &block_size, &info);
               /*SIM*/ if (error < 0)
          return error;
            }
        }
      if (tmo < 0)
        {
          PDBG (pixma_dbg (1, "WARNING: Timed out waiting for calibration\n"));
          return PIXMA_ETIMEDOUT;
        }
      pixma_sleep (100000);
      query_status (s);
      if (is_warming_up (s) || !is_calibrated (s))
        {
          PDBG (pixma_dbg (1, "WARNING: Wrong status: wup=%d cal=%d\n",
               is_warming_up (s), is_calibrated (s)));
          return PIXMA_EPROTO;
        }
      block_size = 0;
      request_image_block (s, &block_size, &info);
       /*SIM*/ mp->state = state_scanning;
      mp->last_block = 0;
    }

  /* TODO: Move to other place, values are constant. */
  base_shift = calc_component_shifting (s) * mp->line_size;
  if (s->param->source == PIXMA_SOURCE_ADF)
    {
      shift[0] = 0;
      shift[1] = -base_shift;
      shift[2] = -2 * base_shift;
    }
  else
    {
      shift[0] = -2 * base_shift;
      shift[1] = -base_shift;
      shift[2] = 0;
    }

  do
    {
      if (mp->last_block_size > 0)
        {
          block_size = mp->imgbuf_len - mp->last_block_size;
          memcpy (mp->img, mp->img + mp->last_block_size, block_size);
        }

      do
        {
          if (s->cancel)
            return PIXMA_ECANCELED;
          if (mp->last_block)
            {
              /* end of image */
              info = mp->last_block;
              if (info != 0x38)
                {
                  query_status (s);
                   /*SIM*/ while ((info & 0x28) != 0x28)
                    {
                      pixma_sleep (10000);
                      error = request_image_block2 (s, &info);
                      if (s->cancel)
                        return PIXMA_ECANCELED;	/* FIXME: Is it safe to cancel here? */
                      if (error < 0)
                        return error;
                    }
                }
              mp->needs_abort = (info != 0x38);
              mp->last_block = info;
              mp->state = state_finished;
              return 0;
            }

          check_status (s);
           /*SIM*/ while (handle_interrupt (s, 1) > 0);
           /*SIM*/ block_size = IMAGE_BLOCK_SIZE;
          error = request_image_block (s, &block_size, &info);
          if (error < 0)
            {
              if (error == PIXMA_ECANCELED)
                read_error_info (s, NULL, 0);
              return error;
            }
          mp->last_block = info;
          if ((info & ~0x38) != 0)
            {
              PDBG (pixma_dbg (1, "WARNING: Unknown info byte %x\n", info));
            }
          if (block_size == 0)
            {
              /* no image data at this moment. */
              pixma_sleep (10000);
            }
        }
      while (block_size == 0);

      error = read_image_block (s, mp->rawimg + mp->rawimg_left);
      if (error < 0)
	{
	  mp->state = state_transfering;
	  return error;
	}
      bytes_received = error;
      PASSERT (bytes_received == block_size);

      /* TODO: simplify! */
      mp->rawimg_left += bytes_received;
      n = mp->rawimg_left / 3;
      /* n = number of pixels in the buffer? */

      /* Color to Grayscale converion for CCD sensor */
      if (is_ccd_grayscale (s)) {
	shift_rgb (mp->rawimg, n, shift[0], shift[1], shift[2], mp->stripe_shift, mp->line_size, 
		   mp->imgcol + mp->imgbuf_ofs); 
	/* dst: img, src: imgcol */
	rgb_to_gray (mp->img, mp->imgcol, n, c); /* cropping occurs later? */  
	PDBG (pixma_dbg (4, "*fill_buffer: did grayscale conversion \n"));
      }
      /* Color image processing */
      else {
	shift_rgb (mp->rawimg, n, shift[0], shift[1], shift[2], mp->stripe_shift, mp->line_size, 
		   mp->img + mp->imgbuf_ofs);
	PDBG (pixma_dbg (4, "*fill_buffer: no grayscale conversion---keep color \n")); 
      }

      /* entering remaining unprocessed bytes after last complete pixel into mp->rawimg buffer -- no influence on mp->img */
      n *= 3;
      mp->shifted_bytes += n;
      mp->rawimg_left -= n;	/* rawimg_left = 0, 1 or 2 bytes left in the buffer. */
      mp->last_block_size = n;
      memcpy (mp->rawimg, mp->rawimg + n, mp->rawimg_left);

    }
  while (mp->shifted_bytes <= 0);

  if ((unsigned) mp->shifted_bytes < mp->last_block_size) 
    {
      if (is_ccd_grayscale (s))
	ib->rptr = mp->img + mp->last_block_size/3 - mp->shifted_bytes/3; /* testing---works OK */
      else
	ib->rptr = mp->img + mp->last_block_size - mp->shifted_bytes;
    }
  else
    ib->rptr = mp->img;
  if (is_ccd_grayscale (s))
    ib->rend = mp->img + mp->last_block_size/3; /* testing---works OK */
  else
    ib->rend = mp->img + mp->last_block_size; 
  return ib->rend - ib->rptr;
}
Пример #11
0
int main() {

    MPI_Init( NULL, NULL );
    FTI_Init( "config.fti", MPI_COMM_WORLD );
    MPI_Comm_rank( FTI_COMM_WORLD, &rank );
    MPI_Comm_size( FTI_COMM_WORLD, &size );

    // total number of staged files
    num_files = ((unsigned long)size)*FILES_PER_ITER*NUM_ITER;

    // request ID array
    int *reqID = (int*) malloc( FILES_PER_ITER*NUM_ITER * sizeof(int) );

    // set stage and remote directory
    char ldir[F_BUFF];
    char rdir[] = REMOTE_DIR;
    if ( FTI_GetStageDir( ldir, F_BUFF ) != FTI_SCES ) {
        EXIT_FAIL( "Failed to get the local directory." );
    }
    
    // create remote directory
    errno = 0;
    if ( mkdir( rdir, (mode_t) 0700 ) != 0 ) {
        if ( errno != EEXIST ) {
            char msg[F_BUFF];
            snprintf( msg, F_BUFF ,"unable to create remote directory ('%s').", rdir ); 
            EXIT_FAIL( msg );
        }
    }

    // allocate filename arrays
    char *lfile[FILES_PER_ITER];
    char *rfile[FILES_PER_ITER];
    char *filename[FILES_PER_ITER];
    unsigned long i;
    for(i=0; i<FILES_PER_ITER; ++i) {
        lfile[i] = (char*) malloc( F_BUFF );
        rfile[i] = (char*) malloc( F_BUFF );
        filename[i] = (char*) malloc( F_BUFF );
    }

    // perform staging
    unsigned long request_counter = 0;
    for(i=0; i<NUM_ITER; ++i) {
        unsigned long j = 0;
        for(; j<FILES_PER_ITER; ++j) {
            snprintf( filename[j], F_BUFF, F_FORM, rank, i, j );
            snprintf( lfile[j], F_BUFF, "%s/%s", ldir, filename[j] );
            snprintf( rfile[j], F_BUFF, "%s/%s", rdir, filename[j] );
            createFile( lfile[j] );
            if ( (reqID[i*FILES_PER_ITER+j] = FTI_SendFile( lfile[j], rfile[j] )) == FTI_NSCS ) {
                char msg[F_BUFF];
                snprintf( msg, F_BUFF, "Failed to stage %s.", filename[j] );
                EXIT_FAIL( msg );
            }
            request_counter++;
        }
        if ( i%CLEAN_FREQ == 0 ) {
            check_status( request_counter, reqID, true ); 
        }

    }
    
    while( check_status( request_counter, reqID, true ) ) { sleep(2); }
    
    FTI_Finalize();

    // remove files
    for(i=0; i<NUM_ITER; ++i) {
        unsigned long j = 0;
        for(; j<FILES_PER_ITER; ++j) {
            snprintf( filename[j], F_BUFF, F_FORM, rank, i, j );
            snprintf( rfile[j], F_BUFF, "%s/%s", rdir, filename[j] );
            errno = 0;
            if ( remove( rfile[j] ) != 0 ) {
                if ( errno != ENOENT ) {
                    char msg[F_BUFF];
                    snprintf( msg, F_BUFF, "Failed to remove %s ('%s').", filename[j], strerror(errno) );
                    EXIT_FAIL( msg );
                }
            }
        }
    }
    
    MPI_Finalize();

    return EXIT_SUCCESS;

}
Пример #12
0
static int
calibrate_cs (pixma_t * s)
{
   /*SIM*/ check_status (s);
  return calibrate (s);
}
Пример #13
0
static int
activate_cs (pixma_t * s, uint8_t x)
{
   /*SIM*/ check_status (s);
  return activate (s, x);
}
Пример #14
0
/*ARGSUSED1*/
static int
get_neighbors(dev_info_t *di, int flag)
{
	register int nid, snid, cnid;
	dev_info_t *parent;
	char buf[OBP_MAXPROPNAME];

	if (di == NULL)
		return (DDI_WALK_CONTINUE);

	nid = ddi_get_nodeid(di);

	snid = cnid = 0;
	switch (flag) {
		case DDI_WALK_PRUNESIB:
			cnid = (int)prom_childnode((pnode_t)nid);
			break;
		case DDI_WALK_PRUNECHILD:
			snid = (int)prom_nextnode((pnode_t)nid);
			break;
		case 0:
			snid = (int)prom_nextnode((pnode_t)nid);
			cnid = (int)prom_childnode((pnode_t)nid);
			break;
		default:
			return (DDI_WALK_TERMINATE);
	}


	if (snid && (snid != -1) && ((parent = ddi_get_parent(di)) != NULL)) {
		/*
		 * add the first sibling that passes check_status()
		 */
		for (; snid && (snid != -1);
		    snid = (int)prom_nextnode((pnode_t)snid)) {
			if (getlongprop_buf(snid, OBP_NAME, buf,
			    sizeof (buf)) > 0) {
				if (check_status(snid, buf, parent) ==
				    DDI_SUCCESS) {
					(void) ddi_add_child(parent, buf,
					    snid, -1);
					break;
				}
			}
		}
	}

	if (cnid && (cnid != -1)) {
		/*
		 * add the first child that passes check_status()
		 */
		if (getlongprop_buf(cnid, OBP_NAME, buf, sizeof (buf)) > 0) {
			if (check_status(cnid, buf, di) == DDI_SUCCESS) {
				(void) ddi_add_child(di, buf, cnid, -1);
			} else {
				for (cnid = (int)prom_nextnode((pnode_t)cnid);
				    cnid && (cnid != -1);
				    cnid = (int)prom_nextnode((pnode_t)cnid)) {
					if (getlongprop_buf(cnid, OBP_NAME,
					    buf, sizeof (buf)) > 0) {
						if (check_status(cnid, buf, di)
						    == DDI_SUCCESS) {
							(void) ddi_add_child(
							    di, buf, cnid, -1);
							break;
						}
					}
				}
			}
		}
	}

	return (DDI_WALK_CONTINUE);
}
Пример #15
0
static int tune_it(int fd_frontend, int fd_sec, unsigned int freq, unsigned int srate, char pol, int tone,
	fe_spectral_inversion_t specInv, unsigned int diseqc, fe_modulation_t modulation, fe_code_rate_t HP_CodeRate,
	fe_transmit_mode_t TransmissionMode, fe_guard_interval_t guardInterval, fe_bandwidth_t bandwidth,
	fe_code_rate_t LP_CodeRate, fe_hierarchy_t hier, int timeout)
{
  int hi_lo = 0, dfd;
  struct dvb_frontend_parameters feparams;
  struct dvb_frontend_info fe_info;

  mp_msg(MSGT_DEMUX, MSGL_V,  "TUNE_IT, fd_frontend %d, fd_sec %d\nfreq %lu, srate %lu, pol %c, tone %i, specInv, diseqc %u, fe_modulation_t modulation,fe_code_rate_t HP_CodeRate, fe_transmit_mode_t TransmissionMode,fe_guard_interval_t guardInterval, fe_bandwidth_t bandwidth\n",
    fd_frontend, fd_sec, (long unsigned int)freq, (long unsigned int)srate, pol, tone, diseqc);


  memset(&feparams, 0, sizeof(feparams));
  if ( ioctl(fd_frontend,FE_GET_INFO, &fe_info) < 0)
  {
        mp_msg(MSGT_DEMUX, MSGL_FATAL, "FE_GET_INFO FAILED\n");
        return -1;
  }

  mp_msg(MSGT_DEMUX, MSGL_V, "Using DVB card \"%s\"\n", fe_info.name);

  switch(fe_info.type)
  {
    case FE_OFDM:
      if (freq < 1000000) freq*=1000UL;
      feparams.frequency=freq;
      feparams.inversion=specInv;
      feparams.u.ofdm.bandwidth=bandwidth;
      feparams.u.ofdm.code_rate_HP=HP_CodeRate;
      feparams.u.ofdm.code_rate_LP=LP_CodeRate;
      feparams.u.ofdm.constellation=modulation;
      feparams.u.ofdm.transmission_mode=TransmissionMode;
      feparams.u.ofdm.guard_interval=guardInterval;
      feparams.u.ofdm.hierarchy_information=hier;
      mp_msg(MSGT_DEMUX, MSGL_V, "tuning DVB-T to %d Hz, bandwidth: %d\n",freq, bandwidth);
      break;
    case FE_QPSK:
      if (freq > 2200000)
      {
        // this must be an absolute frequency
        if (freq < SLOF)
        {
          freq = feparams.frequency=(freq-LOF1);
          hi_lo = 0;
        }
        else
        {
          freq = feparams.frequency=(freq-LOF2);
          hi_lo = 1;
        }
      }
      else
      {
        // this is an L-Band frequency
       feparams.frequency=freq;
      }

      feparams.inversion=specInv;
      feparams.u.qpsk.symbol_rate=srate;
      feparams.u.qpsk.fec_inner=HP_CodeRate;
      dfd = fd_frontend;

      mp_msg(MSGT_DEMUX, MSGL_V, "tuning DVB-S to Freq: %u, Pol: %c Srate: %d, 22kHz: %s, LNB:  %d\n",freq,pol,srate,hi_lo ? "on" : "off", diseqc);

      if(do_diseqc(dfd, diseqc, (pol == 'V' ? 1 : 0), hi_lo) == 0)
          mp_msg(MSGT_DEMUX, MSGL_V, "DISEQC SETTING SUCCEDED\n");
      else
      {
          mp_msg(MSGT_DEMUX, MSGL_ERR, "DISEQC SETTING FAILED\n");
          return -1;
      }
      break;
    case FE_QAM:
      mp_msg(MSGT_DEMUX, MSGL_V, "tuning DVB-C to %d, srate=%d\n",freq,srate);
      feparams.frequency=freq;
      feparams.inversion=specInv;
      feparams.u.qam.symbol_rate = srate;
      feparams.u.qam.fec_inner = HP_CodeRate;
      feparams.u.qam.modulation = modulation;
      break;
#ifdef DVB_ATSC
    case FE_ATSC:
      mp_msg(MSGT_DEMUX, MSGL_V, "tuning ATSC to %d, modulation=%d\n",freq,modulation);
      feparams.frequency=freq;
      feparams.u.vsb.modulation = modulation;
      break;
#endif
    default:
      mp_msg(MSGT_DEMUX, MSGL_V, "Unknown FE type. Aborting\n");
      return 0;
  }
  usleep(100000);

  if(ioctl(fd_frontend,FE_SET_FRONTEND,&feparams) < 0)
  {
    mp_msg(MSGT_DEMUX, MSGL_ERR, "ERROR tuning channel\n");
    return -1;
  }

  return check_status(fd_frontend, timeout);
}
Пример #16
0
static void reentry_tls_init() {
    // value for reentry_flag_key will default to NULL (false)
    check_status(pthread_key_create(&reentry_flag_key, NULL));
}
Пример #17
0
/*
 * Counts occurrences of three-node structural motifs in a binary graph.
 */
VECTOR_T* BCT_NAMESPACE::motif3struct_bin(const MATRIX_T* A, MATRIX_T** F) {
    if (safe_mode) check_status(A, SQUARE | BINARY, "motif3struct_bin");

    // load motif34lib M3n ID3
    VECTOR_T* ID3;
    MATRIX_T* M3 = motif3generate(&ID3);

    // n=length(A);
    int n = length(A);

    // F=zeros(13,n);
    if (F != NULL) {
        *F = zeros(13, n);
    }

    // f=zeros(13,1);
    VECTOR_T* f = zeros_vector(13);

    // As=A|A.';
    MATRIX_T* A_transpose = MATRIX_ID(alloc)(A->size2, A->size1);
    MATRIX_ID(transpose_memcpy)(A_transpose, A);
    MATRIX_T* As = logical_or(A, A_transpose);
    MATRIX_ID(free)(A_transpose);

    // for u=1:n-2
    for (int u = 0; u < n - 2; u++) {

        // V1=[false(1,u) As(u,u+1:n)];
        VECTOR_T* V1 = VECTOR_ID(alloc)(n);
        MATRIX_ID(get_row)(V1, As, u);
        for (int i = 0; i <= u; i++) {
            VECTOR_ID(set)(V1, i, 0.0);
        }

        // for v1=find(V1)
        VECTOR_T* find_V1 = find(V1);
        if (find_V1 != NULL) {
            for (int i_find_V1 = 0; i_find_V1 < (int)find_V1->size; i_find_V1++) {
                int v1 = (int)VECTOR_ID(get)(find_V1, i_find_V1);

                // V2=[false(1,u) As(v1,u+1:n)];
                VECTOR_T* V2 = VECTOR_ID(alloc)(n);
                MATRIX_ID(get_row)(V2, As, v1);
                for (int i = 0; i <= u; i++) {
                    VECTOR_ID(set)(V2, i, 0.0);
                }

                // V2(V1)=0;
                logical_index_assign(V2, V1, 0.0);

                // V2=([false(1,v1) As(u,v1+1:n)])|V2;
                VECTOR_T* V2_1 = VECTOR_ID(alloc)(n);
                MATRIX_ID(get_row)(V2_1, As, u);
                for (int i = 0; i <= v1; i++) {
                    VECTOR_ID(set)(V2_1, i, 0.0);
                }
                VECTOR_T* V2_2 = V2;
                V2 = logical_or(V2_1, V2_2);
                VECTOR_ID(free)(V2_1);
                VECTOR_ID(free)(V2_2);

                // for v2=find(V2)
                VECTOR_T* find_V2 = find(V2);
                if (find_V2 != NULL) {
                    for (int i_find_V2 = 0; i_find_V2 < (int)find_V2->size; i_find_V2++) {
                        int v2 = (int)VECTOR_ID(get)(find_V2, i_find_V2);

                        // s=uint32(sum(10.^(5:-1:0).*[A(v1,u) A(v2,u) A(u,v1) A(v2,v1) A(u,v2) A(v1,v2)]));
                        int A_rows[] = { v1, v2, u, v2, u, v1 };
                        int A_cols[] = { u, u, v1, v1, v2, v2 };
                        VECTOR_T* s = VECTOR_ID(alloc)(6);
                        for (int i = 0; i < 6; i++) {
                            VECTOR_ID(set)(s, i, MATRIX_ID(get)(A, A_rows[i], A_cols[i]));
                        }

                        // ind=ID3(s==M3n);
                        int i_M3 = 0;
                        for ( ; i_M3 < (int)M3->size1; i_M3++) {
                            VECTOR_ID(view) M3_row_i_M3 = MATRIX_ID(row)(M3, i_M3);
                            if (compare_vectors(s, &M3_row_i_M3.vector) == 0) {
                                break;
                            }
                        }
                        VECTOR_ID(free)(s);
                        if (i_M3 < (int)M3->size1) {
                            int ind = (int)VECTOR_ID(get)(ID3, i_M3) - 1;

                            // if nargout==2; F(ind,[u v1 v2])=F(ind,[u v1 v2])+1; end
                            if (F != NULL) {
                                int F_cols[] = { u, v1, v2 };
                                for (int i = 0; i < 3; i++) {
                                    MATRIX_ID(set)(*F, ind, F_cols[i], MATRIX_ID(get)(*F, ind, F_cols[i]) + 1.0);
                                }
                            }

                            // f(ind)=f(ind)+1;
                            VECTOR_ID(set)(f, ind, VECTOR_ID(get)(f, ind) + 1.0);
                        }
                    }

                    VECTOR_ID(free)(find_V2);
                }

                VECTOR_ID(free)(V2);
            }

            VECTOR_ID(free)(find_V1);
        }

        VECTOR_ID(free)(V1);
    }

    VECTOR_ID(free)(ID3);
    MATRIX_ID(free)(M3);
    MATRIX_ID(free)(As);
    return f;
}
Пример #18
0
bool redis_hash::hmset(const char* key, const std::map<string, const char*>& attrs)
{
	hash_slot(key);
	build("HMSET", key, attrs);
	return check_status();
}
Пример #19
0
int
main(int argc, char *argv[]) {
  cipher_t *c = NULL;
  err_status_t status;
  unsigned char test_key[20] = {
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
    0x10, 0x11, 0x12, 0x13
  };
  int q;
  unsigned do_timing_test = 0;
  unsigned do_validation = 0;
  unsigned do_array_timing_test = 0;

  /* process input arguments */
  while (1) {
    q = getopt(argc, argv, "tva");
    if (q == -1) 
      break;
    switch (q) {
    case 't':
      do_timing_test = 1;
      break;
    case 'v':
      do_validation = 1;
      break;
    case 'a':
      do_array_timing_test = 1;
      break;
    default:
      usage(argv[0]);
    }    
  }
   
  printf("cipher test driver\n"
	 "David A. McGrew\n"
	 "Cisco Systems, Inc.\n");

  if (!do_validation && !do_timing_test && !do_array_timing_test)
    usage(argv[0]);

   /* arry timing (cache thrash) test */
  if (do_array_timing_test) {
    int max_num_cipher = 1 << 16;   /* number of ciphers in cipher_array */
    int num_cipher;
    
    for (num_cipher=1; num_cipher < max_num_cipher; num_cipher *=8)
      cipher_driver_test_array_throughput(&null_cipher, 0, num_cipher); 

    for (num_cipher=1; num_cipher < max_num_cipher; num_cipher *=8)
      cipher_driver_test_array_throughput(&aes_icm, 30, num_cipher); 

    for (num_cipher=1; num_cipher < max_num_cipher; num_cipher *=8)
      cipher_driver_test_array_throughput(&aes_cbc, 16, num_cipher); 
 
  }

  if (do_validation) {
    cipher_driver_self_test(&null_cipher);
    cipher_driver_self_test(&aes_icm);
    cipher_driver_self_test(&aes_cbc);
  }

  /* do timing and/or buffer_test on null_cipher */
  status = cipher_type_alloc(&null_cipher, &c, 0); 
  check_status(status);

  status = cipher_init(c, NULL, direction_encrypt);
  check_status(status);

  if (do_timing_test) 
    cipher_driver_test_throughput(c);
  if (do_validation) {
    status = cipher_driver_test_buffering(c);
    check_status(status);
  }
  status = cipher_dealloc(c);
  check_status(status);
  

  /* run the throughput test on the aes_icm cipher */
    status = cipher_type_alloc(&aes_icm, &c, 30);  
    if (status) {
      fprintf(stderr, "error: can't allocate cipher\n");
      exit(status);
    }

    status = cipher_init(c, test_key, direction_encrypt);
    check_status(status);

    if (do_timing_test)
      cipher_driver_test_throughput(c);
    
    if (do_validation) {
      status = cipher_driver_test_buffering(c);
      check_status(status);
    }
    
    status = cipher_dealloc(c);
    check_status(status);
  
  return 0;
}
Пример #20
0
CAMLprim value mmdb_ml_lookup_path(value ip, value query_list, value mmdb)
{
  CAMLparam3(ip, query_list, mmdb);
  CAMLlocal3(iter_count, caml_clean_result, query_r);

  int total_len = 0, copy_count = 0, gai_error = 0, mmdb_error = 0;
  char *clean_result;
  long int int_result;

  iter_count = query_list;

  unsigned int len = caml_string_length(ip);
  char *as_string = caml_strdup(String_val(ip));
  if (strlen(as_string) != (size_t)len) {
    caml_failwith("Could not copy IP address properly");
  }

  MMDB_s *as_mmdb = (MMDB_s*)Data_custom_val(mmdb);
  MMDB_lookup_result_s *result = caml_stat_alloc(sizeof(*result));
  *result = MMDB_lookup_string(as_mmdb, as_string, &gai_error, &mmdb_error);
  check_error(gai_error, mmdb_error);
  caml_stat_free(as_string);

  while (iter_count != Val_emptylist) {
    total_len++;
    iter_count = Field(iter_count, 1);
  }

  char **query = caml_stat_alloc(sizeof(char *) * (total_len + 1));

  while (query_list != Val_emptylist) {
    query[copy_count] = caml_strdup(String_val(Field(query_list, 0)));
    copy_count++;
    query_list = Field(query_list, 1);
  }
  query[total_len] = NULL;
  MMDB_entry_data_s entry_data;

  int status = MMDB_aget_value(&result->entry,
			       &entry_data,
			       (const char *const *const)query);
  check_status(status);
  check_data(entry_data);
  caml_stat_free(result);
  for (int i = 0; i < copy_count; caml_stat_free(query[i]), i++);
  caml_stat_free(query);
  query_r = caml_alloc(2, 0);
  as_mmdb = NULL;
  switch (entry_data.type) {
  case MMDB_DATA_TYPE_BYTES:
    clean_result = caml_stat_alloc(entry_data.data_size + 1);
    memcpy(clean_result, entry_data.bytes, entry_data.data_size);
    caml_clean_result = caml_copy_string(clean_result);
    caml_stat_free(clean_result);
    goto string_finish;

  case MMDB_DATA_TYPE_UTF8_STRING:
    clean_result = strndup(entry_data.utf8_string, entry_data.data_size);
    caml_clean_result = caml_copy_string(clean_result);
    free(clean_result);
    goto string_finish;

  case MMDB_DATA_TYPE_FLOAT:
    Store_field(query_r, 0, polymorphic_variants.poly_float);
    Store_field(query_r, 1, caml_copy_double(entry_data.float_value));
    goto finish;

  case MMDB_DATA_TYPE_BOOLEAN:
    Store_field(query_r, 0, polymorphic_variants.poly_bool);
    Store_field(query_r, 1, Val_true ? entry_data.boolean : Val_false);
    goto finish;

  case MMDB_DATA_TYPE_DOUBLE:
    Store_field(query_r, 0, polymorphic_variants.poly_float);
    Store_field(query_r, 1, caml_copy_double(entry_data.double_value));
    goto finish;

  case MMDB_DATA_TYPE_UINT16:
    Store_field(query_r, 0, polymorphic_variants.poly_int);
    int_result = Val_long(entry_data.uint16);
    goto int_finish;

  case MMDB_DATA_TYPE_UINT32:
    Store_field(query_r, 0, polymorphic_variants.poly_int);
    int_result = Val_long(entry_data.uint32);
    goto int_finish;

  case MMDB_DATA_TYPE_UINT64:
    Store_field(query_r, 0, polymorphic_variants.poly_int);
    int_result = Val_long(entry_data.uint32);
    goto int_finish;

    // look at /usr/bin/sed -n 1380,1430p src/maxminddb.c
  case MMDB_DATA_TYPE_ARRAY:
  case MMDB_DATA_TYPE_MAP:
    caml_failwith("Can't return a Map or Array yet");
  }

 string_finish:
  Store_field(query_r, 0, polymorphic_variants.poly_string);
  Store_field(query_r, 1, caml_clean_result);
  CAMLreturn(query_r);

 int_finish:
  Store_field(query_r, 1, int_result);
  CAMLreturn(query_r);

 finish:
  CAMLreturn(query_r);
}
Пример #21
0
bool redis_string::mset(const std::map<string, string>& objs)
{
	build("MSET", NULL, objs);
	return check_status();
}
Пример #22
0
void
ShaderAPITest::check_compile_status(GLuint id)
{
	check_status(id, GL_COMPILE_STATUS, glGetShaderiv,
		     glGetShaderInfoLog);
}
Пример #23
0
bool redis_string::mset(const char* keys[], const size_t keys_len[],
	const char* values[], const size_t values_len[], size_t argc)
{
	build("MSET", NULL, keys, keys_len, values, values_len, argc);
	return check_status();
}
Пример #24
0
void
ShaderAPITest::check_link_status(GLuint id)
{
	check_status(id, GL_LINK_STATUS, glGetProgramiv,
		     glGetProgramInfoLog);
}
Пример #25
0
void
process_outgoing_link (struct context *c)
{
  struct gc_arena gc = gc_new ();

  perf_push (PERF_PROC_OUT_LINK);

  if (c->c2.to_link.len > 0 && c->c2.to_link.len <= EXPANDED_SIZE (&c->c2.frame))
    {
      /*
       * Setup for call to send/sendto which will send
       * packet to remote over the TCP/UDP port.
       */
      int size = 0;
      ASSERT (link_socket_actual_defined (c->c2.to_link_addr));

#ifdef ENABLE_DEBUG
      /* In gremlin-test mode, we may choose to drop this packet */
      if (!c->options.gremlin || ask_gremlin (c->options.gremlin))
#endif
	{
	  /*
	   * Let the traffic shaper know how many bytes
	   * we wrote.
	   */
#ifdef ENABLE_FEATURE_SHAPER
	  if (c->options.shaper)
	    shaper_wrote_bytes (&c->c2.shaper, BLEN (&c->c2.to_link)
				+ datagram_overhead (c->options.ce.proto));
#endif
	  /*
	   * Let the pinger know that we sent a packet.
	   */
	  if (c->options.ping_send_timeout)
	    event_timeout_reset (&c->c2.ping_send_interval);

#if PASSTOS_CAPABILITY
	  /* Set TOS */
	  link_socket_set_tos (c->c2.link_socket);
#endif

	  /* Log packet send */
#ifdef LOG_RW
	  if (c->c2.log_rw)
	    fprintf (stderr, "W");
#endif
	  msg (D_LINK_RW, "%s WRITE [%d] to %s: %s",
	       proto2ascii (c->c2.link_socket->info.proto, c->c2.link_socket->info.af, true),
	       BLEN (&c->c2.to_link),
	       print_link_socket_actual (c->c2.to_link_addr, &gc),
	       PROTO_DUMP (&c->c2.to_link, &gc));

	  /* Packet send complexified by possible Socks5 usage */
	  {
	    struct link_socket_actual *to_addr = c->c2.to_link_addr;
	    int size_delta = 0;

	    /* If Socks5 over UDP, prepend header */
	    socks_preprocess_outgoing_link (c, &to_addr, &size_delta);

	    /* Send packet */
	    size = link_socket_write (c->c2.link_socket,
				      &c->c2.to_link,
				      to_addr);

	    /* Undo effect of prepend */
	    link_socket_write_post_size_adjust (&size, size_delta, &c->c2.to_link);
	  }

	  if (size > 0)
	    {
	      c->c2.max_send_size_local = max_int (size, c->c2.max_send_size_local);
	      c->c2.link_write_bytes += size;
	      link_write_bytes_global += size;
#ifdef ENABLE_MEMSTATS
	      if (mmap_stats)
		mmap_stats->link_write_bytes = link_write_bytes_global;
#endif
#ifdef ENABLE_MANAGEMENT
	      if (management)
		{
		  management_bytes_out (management, size);
#ifdef MANAGEMENT_DEF_AUTH
		  management_bytes_server (management, &c->c2.link_read_bytes, &c->c2.link_write_bytes, &c->c2.mda_context);
#endif
		}
#endif
	    }
	}

      /* Check return status */
      check_status (size, "write", c->c2.link_socket, NULL);

      if (size > 0)
	{
	  /* Did we write a different size packet than we intended? */
	  if (size != BLEN (&c->c2.to_link))
	    msg (D_LINK_ERRORS,
		 "TCP/UDP packet was truncated/expanded on write to %s (tried=%d,actual=%d)",
		 print_link_socket_actual (c->c2.to_link_addr, &gc),
		 BLEN (&c->c2.to_link),
		 size);
	}

      /* if not a ping/control message, indicate activity regarding --inactive parameter */
      if (c->c2.buf.len > 0 )
        register_activity (c, size);
    }
  else
    {
      if (c->c2.to_link.len > 0)
	msg (D_LINK_ERRORS, "TCP/UDP packet too large on write to %s (tried=%d,max=%d)",
	     print_link_socket_actual (c->c2.to_link_addr, &gc),
	     c->c2.to_link.len,
	     EXPANDED_SIZE (&c->c2.frame));
    }

  buf_reset (&c->c2.to_link);

  perf_pop ();
  gc_free (&gc);
}
Пример #26
0
z_status zp_parser::_process_group(zp_flags flags,zp_mode mode)
{
	//ZTF;
	zp_group_type group_type=zp_group_single;
	z_status group_status=zs_no_match;
	z_status status=zs_no_match;



	zp_text_parser& tmpl=context_get_current_template_parser();
	if(mode.skip_test)
		group_status=zs_skipped;

	zp_mode local_mode=mode;
	bool end_of_group=false;//reached end of template
	bool complete=false;//done processing, but need to skip to end

	//AND group stuff
	bool satisfied=true;
	bool at_least_one=false;
	U64 and_group_bitmask_satisfied=0;
	U64 and_group_bitmask_done=0;
	int current_stage=0;
	ctext tpl_start=tmpl.get_index();
	ctext tpl_random=0;

	while(!end_of_group)
	{

		zp_flags stage_flags=flags; //pass inherited flags
		ctext stage_start=tmpl.get_index();
		U64 stage_bit_mask=(1<<current_stage);
		if(zp_group_and==group_type)
		{
			if(and_group_bitmask_done&stage_bit_mask)
				local_mode.skip_test=1;
			if(mode.output)
				if(and_group_bitmask_satisfied&stage_bit_mask)
					local_mode.skip_test=1;

		}
		/*
		if((mode.output)&&(tpl_random))
		{
			tmpl.set_index(tpl_random);
			zp_flags dummy_flags;
			status=_process_stage(local_mode,&dummy_flags);
			tmpl.set_index(stage_start);
		}*/

		status=_process_stage(local_mode,&stage_flags);
		if(status>zs_fatal_error)
			return check_status(status);

		if(status==zs_no_match)
		{
			if(tpl_random)
			{

				ctext current_index=tmpl.get_index();
				ctext current_index_under_test=tmpl.get_index_under_test();
				tmpl.set_index(tpl_random);
				zp_flags dummy_flags;
				status=_process_stage(local_mode,&dummy_flags);
				tmpl.set_index_under_test(current_index_under_test);
				if(status==zs_matched)
				{
					tmpl.set_index(stage_start);
					continue; //try the stage again
				}
				tmpl.set_index(current_index);
			}
		}		
		if(stage_flags.random)
		{
			tpl_random=stage_start;
		}


		//--------------------------------------
		//	Advance to next stage, check group
		//--------------------------------------
		char next_char=tmpl.current_ch();
		if(tmpl.eob())
		{
			end_of_group=true;
		}		
		else
		{
			switch(next_char)
			{
			case '&':
			case '|':
			case ':':
				{
					if(group_type==zp_group_single)
					{
						group_type=(zp_group_type)next_char;
						if(group_type==zp_group_stage)
							group_status=zs_matched;
						if(group_type==zp_group_or)
							mode.or_group=1;

					}
					if(next_char!=group_type)
					{
						Z_ERROR_MSG(zs_template_syntax_error,"Mixed group types!");
						return check_status(zs_template_syntax_error);
					}
					tmpl.inc(); //Advance
					break;
				}
			case ')':
				end_of_group=true;
				break;
			default:
				return check_status(zs_template_syntax_error);
			}
		}
		//--------------------------------------
		//	Process result based on group type
		//--------------------------------------

		switch(group_type)
		{
		case zp_group_single:
			{
				group_status=status;
			}
			break;
		case zp_group_or:
			{
				switch(status)
				{
				case zs_matched:
					group_status= zs_matched;
					complete=true;
					break;
				case zs_no_match:
				case zs_skipped:
					break;
				case zs_eof:
					//this is an eof for one item. it will rewind and try the next in the OR group
					//complete=true;
					//group_status= zs_eof;
					break;
				default:
					return  status;
					
				}
			}
			break;
		case zp_group_stage:
			{
				switch(status)
				{
				case zs_matched:
				case zs_skipped:
					break;
				case zs_eof:
					/*even if we got an end of buffer error,
					we need to keep going. We only stop if the stage is required
					*/
					//complete=true;
				case zs_no_match:
					if(stage_flags.required)
					{
						group_status=zs_no_match;
						group_status= status;
						complete=true;
					}
					break;
				default:
					return  status;
					break;
				}
			}
			break;
		case zp_group_and:
			{
				// AND groups have to match all stages, BUT
				// in any order, so if any match, the template gets reset and scans again
				
				local_mode=mode;
				
				switch(status)
				{
				case zs_matched:
					at_least_one=true;
					if(!stage_flags.multi)
						and_group_bitmask_done|=stage_bit_mask;
					and_group_bitmask_satisfied|=stage_bit_mask;
					break;
				case zs_eof: 
					//complete=true;
				case zs_no_match:
					if((stage_flags.required)&&
						(!(and_group_bitmask_satisfied&stage_bit_mask)))
							satisfied=false;
					break;

				case zs_skipped: 
					break;
				default:
					return status;
				}
				current_stage++; //only used by AND groups
				if(end_of_group)
				{
					if(at_least_one)
					{
						satisfied=true;//by default, satisfied. 
						at_least_one=false;

						tmpl.set_index(tpl_start);
						current_stage=0;
						end_of_group=false;
						continue;
					}
					complete=true;
					if(satisfied)
					{
						group_status=zs_matched;
						break;
					}
					group_status=zs_no_match;
					
					break;
				}
			}
			break;
		}//Switch for group type
		if(complete)
		{
			if(local_mode.nested_group)
				local_mode.skip_test=1;
			else
				break;
		}
	}
	if(mode.skip_test)
		return zs_skipped;
	return group_status;
}
Пример #27
0
void
io_wait_dowork (struct context *c, const unsigned int flags)
{
  unsigned int socket = 0;
  unsigned int tuntap = 0;
  struct event_set_return esr[4];

  /* These shifts all depend on EVENT_READ and EVENT_WRITE */
  static int socket_shift = 0;     /* depends on SOCKET_READ and SOCKET_WRITE */
  static int tun_shift = 2;        /* depends on TUN_READ and TUN_WRITE */
  static int err_shift = 4;        /* depends on ES_ERROR */
#ifdef ENABLE_MANAGEMENT
  static int management_shift = 6; /* depends on MANAGEMENT_READ and MANAGEMENT_WRITE */
#endif

  /*
   * Decide what kind of events we want to wait for.
   */
  event_reset (c->c2.event_set);

  /*
   * On win32 we use the keyboard or an event object as a source
   * of asynchronous signals.
   */
  if (flags & IOW_WAIT_SIGNAL)
    wait_signal (c->c2.event_set, (void*)&err_shift);

  /*
   * If outgoing data (for TCP/UDP port) pending, wait for ready-to-send
   * status from TCP/UDP port. Otherwise, wait for incoming data on
   * TUN/TAP device.
   */
  if (flags & IOW_TO_LINK)
    {
      if (flags & IOW_SHAPER)
	{
	  /*
	   * If sending this packet would put us over our traffic shaping
	   * quota, don't send -- instead compute the delay we must wait
	   * until it will be OK to send the packet.
	   */
#ifdef ENABLE_FEATURE_SHAPER
	  int delay = 0;

	  /* set traffic shaping delay in microseconds */
	  if (c->options.shaper)
	    delay = max_int (delay, shaper_delay (&c->c2.shaper));
	  
	  if (delay < 1000)
	    {
	      socket |= EVENT_WRITE;
	    }
	  else
	    {
	      shaper_soonest_event (&c->c2.timeval, delay);
	    }
#else /* ENABLE_FEATURE_SHAPER */
	  socket |= EVENT_WRITE;
#endif /* ENABLE_FEATURE_SHAPER */
	}
      else
	{
	  socket |= EVENT_WRITE;
	}
    }
  else if (!((flags & IOW_FRAG) && TO_LINK_FRAG (c)))
    {
      if (flags & IOW_READ_TUN)
	tuntap |= EVENT_READ;
    }

  /*
   * If outgoing data (for TUN/TAP device) pending, wait for ready-to-send status
   * from device.  Otherwise, wait for incoming data on TCP/UDP port.
   */
  if (flags & IOW_TO_TUN)
    {
      tuntap |= EVENT_WRITE;
    }
  else
    {
      if (flags & IOW_READ_LINK)
	socket |= EVENT_READ;
    }

  /*
   * outgoing bcast buffer waiting to be sent?
   */
  if (flags & IOW_MBUF)
    socket |= EVENT_WRITE;

  /*
   * Force wait on TUN input, even if also waiting on TCP/UDP output
   */
  if (flags & IOW_READ_TUN_FORCE)
    tuntap |= EVENT_READ;

  /*
   * Configure event wait based on socket, tuntap flags.
   */
  socket_set (c->c2.link_socket, c->c2.event_set, socket, (void*)&socket_shift, NULL);
  tun_set (c->c1.tuntap, c->c2.event_set, tuntap, (void*)&tun_shift, NULL);

#ifdef ENABLE_MANAGEMENT
  if (management)
    management_socket_set (management, c->c2.event_set, (void*)&management_shift, NULL);
#endif

  /*
   * Possible scenarios:
   *  (1) tcp/udp port has data available to read
   *  (2) tcp/udp port is ready to accept more data to write
   *  (3) tun dev has data available to read
   *  (4) tun dev is ready to accept more data to write
   *  (5) we received a signal (handler sets signal_received)
   *  (6) timeout (tv) expired
   */

  c->c2.event_set_status = ES_ERROR;

  if (!c->sig->signal_received)
    {
      if (!(flags & IOW_CHECK_RESIDUAL) || !socket_read_residual (c->c2.link_socket))
	{
	  int status;

#ifdef ENABLE_DEBUG
	  if (check_debug_level (D_EVENT_WAIT))
	    show_wait_status (c);
#endif

	  /*
	   * Wait for something to happen.
	   */
	  status = event_wait (c->c2.event_set, &c->c2.timeval, esr, SIZE(esr));

	  check_status (status, "event_wait", NULL, NULL);

	  if (status > 0)
	    {
	      int i;
	      c->c2.event_set_status = 0;
	      for (i = 0; i < status; ++i)
		{
		  const struct event_set_return *e = &esr[i];
		  c->c2.event_set_status |= ((e->rwflags & 3) << *((int*)e->arg));
		}
	    }
	  else if (status == 0)
	    {
	      c->c2.event_set_status = ES_TIMEOUT;
	    }
	}
      else
	{
	  c->c2.event_set_status = SOCKET_READ;
	}
    }

  /* 'now' should always be a reasonably up-to-date timestamp */
  update_time ();

  /* set signal_received if a signal was received */
  if (c->c2.event_set_status & ES_ERROR)
    get_signal (&c->sig->signal_received);

  dmsg (D_EVENT_WAIT, "I/O WAIT status=0x%04x", c->c2.event_set_status);
}
Пример #28
0
z_status zp_parser::get_flags(zp_flags& flags)
{
	//zp_flags& flags=_ctx_current->_flags;
	zp_text_parser& tmpl=context_get_current_template_parser();

	flags.as_u32=0;
	flags.required=1;
	char c=0;
	while(1)
	{
		c=tmpl.current_ch();
		if(tmpl.eob())
		{
			return check_status(zs_template_syntax_error);
		}
		switch(c)
		{


		case '#':
			flags.create_default=1;
			flags.required=0;
			break;
			
		case '%':
			flags.random=1;
			flags.required=0;
			flags.multi=1;

			break;
			
		case '@':
			flags.this_obj=1;
			break;
		case '{':
			tmpl.inc();
			flags.parent_data=1;

			if(tmpl.test_any_identifier()!=zs_matched) 
				return check_status(zs_template_syntax_error);
			tmpl.get_match( _ctx_current->_member_var_name);
			if(tmpl.current_ch()!='}')
				return check_status(zs_template_syntax_error);
			break;


		case '+':
			flags.multi=1;
			break;
		case '!':
			flags.commited=1;
			break;
		case '*':
			flags.multi=1;
			flags.required=0;
			break;
		case '?':
			flags.required=0;
			break;
		case ' ': //skip white space
			break;
		case '-': //skip dash
			break;
		default:
			return zs_matched;
		}
		tmpl.inc();
	}

}
Пример #29
0
/*
 * Counts occurrences of three-node functional motifs in a weighted graph.
 * Returns intensity and (optionally) coherence and motif counts.
 */
MATRIX_T* BCT_NAMESPACE::motif3funct_wei(const MATRIX_T* W, MATRIX_T** Q, MATRIX_T** F) {
	if (safe_mode) check_status(W, SQUARE | WEIGHTED, "motif3funct_wei");
	
	// load motif34lib M3 M3n ID3 N3
	VECTOR_T* ID3;
	VECTOR_T* N3;
	MATRIX_T* M3 = motif3generate(&ID3, &N3);
	
	// n=length(W);
	int n = length(W);
	
	// I=zeros(13,n);
	MATRIX_T* I = zeros(13, n);
	
	// Q=zeros(13,n);
	if (Q != NULL) {
		*Q = zeros(13, n);
	}
	
	// F=zeros(13,n);
	if (F != NULL) {
		*F = zeros(13, n);
	}
	
	// A=1*(W~=0);
	MATRIX_T* A = compare_elements(W, fp_not_equal, 0.0);
	
	// As=A|A.';
	MATRIX_T* A_transpose = MATRIX_ID(alloc)(A->size2, A->size1);
	MATRIX_ID(transpose_memcpy)(A_transpose, A);
	MATRIX_T* As = logical_or(A, A_transpose);
	MATRIX_ID(free)(A_transpose);
	
	// for u=1:n-2
	for (int u = 0; u < n - 2; u++) {
		
		// V1=[false(1,u) As(u,u+1:n)];
		VECTOR_T* V1 = VECTOR_ID(alloc)(n);
		MATRIX_ID(get_row)(V1, As, u);
		for (int i = 0; i <= u; i++) {
			VECTOR_ID(set)(V1, i, 0.0);
		}
		
		// for v1=find(V1)
		VECTOR_T* find_V1 = find(V1);
		if (find_V1 != NULL) {
			for (int i_find_V1 = 0; i_find_V1 < (int)find_V1->size; i_find_V1++) {
				int v1 = (int)VECTOR_ID(get)(find_V1, i_find_V1);
				
				// V2=[false(1,u) As(v1,u+1:n)];
				VECTOR_T* V2 = VECTOR_ID(alloc)(n);
				MATRIX_ID(get_row)(V2, As, v1);
				for (int i = 0; i <= u; i++) {
					VECTOR_ID(set)(V2, i, 0.0);
				}
				
				// V2(V1)=0;
				logical_index_assign(V2, V1, 0.0);
				
				// V2=([false(1,v1) As(u,v1+1:n)])|V2;
				VECTOR_T* V2_1 = VECTOR_ID(alloc)(n);
				MATRIX_ID(get_row)(V2_1, As, u);
				for (int i = 0; i <= v1; i++) {
					VECTOR_ID(set)(V2_1, i, 0.0);
				}
				VECTOR_T* V2_2 = V2;
				V2 = logical_or(V2_1, V2_2);
				VECTOR_ID(free)(V2_1);
				VECTOR_ID(free)(V2_2);
				
				// for v2=find(V2)
				VECTOR_T* find_V2 = find(V2);
				if (find_V2 != NULL) {
					for (int i_find_V2 = 0; i_find_V2 < (int)find_V2->size; i_find_V2++) {
						int v2 = (int)VECTOR_ID(get)(find_V2, i_find_V2);
						
						// w=[W(v1,u) W(v2,u) W(u,v1) W(v2,v1) W(u,v2) W(v1,v2)];
						int WA_rows[] = { v1, v2, u, v2, u, v1 };
						int WA_cols[] = { u, u, v1, v1, v2, v2 };
						VECTOR_T* w = VECTOR_ID(alloc)(6);
						for (int i = 0; i < 6; i++) {
							VECTOR_ID(set)(w, i, MATRIX_ID(get)(W, WA_rows[i], WA_cols[i]));
						}
						
						// a=[A(v1,u);A(v2,u);A(u,v1);A(v2,v1);A(u,v2);A(v1,v2)];
						MATRIX_T* a = MATRIX_ID(alloc)(6, 1);
						for (int i = 0; i < 6; i++) {
							MATRIX_ID(set)(a, i, 0, MATRIX_ID(get)(A, WA_rows[i], WA_cols[i]));
						}
						
						// ind=(M3*a)==N3;
						MATRIX_T* M3_mul_a_m = mul(M3, a);
						MATRIX_ID(free)(a);
						VECTOR_T* M3_mul_a = to_vector(M3_mul_a_m);
						MATRIX_ID(free)(M3_mul_a_m);
						VECTOR_T* ind = compare_elements(M3_mul_a, fp_equal, N3);
						VECTOR_ID(free)(M3_mul_a);
						
						// m=sum(ind);
						int m = (int)sum(ind);
						if (m > 0) {
							
							// M=M3(ind,:).*repmat(w,m,1);
							VECTOR_T* M3_cols = sequence(0, M3->size2 - 1);
							MATRIX_T* M = log_ord_index(M3, ind, M3_cols);
							VECTOR_ID(free)(M3_cols);
							for (int i = 0; i < (int)M->size1; i++) {
								VECTOR_ID(view) M_row_i = MATRIX_ID(row)(M, i);
								VECTOR_ID(mul)(&M_row_i.vector, w);
							}
							
							// id=ID3(ind);
							VECTOR_T* id = logical_index(ID3, ind);
							VECTOR_ID(add_constant)(id, -1.0);
							
							// l=N3(ind);
							VECTOR_T* l = logical_index(N3, ind);
							
							// x=sum(M,2)./l;
							VECTOR_T* x = sum(M, 2);
							VECTOR_ID(div)(x, l);
							
							// M(M==0)=1;
							MATRIX_T* M_eq_0 = compare_elements(M, fp_equal, 0.0);
							logical_index_assign(M, M_eq_0, 1.0);
							MATRIX_ID(free)(M_eq_0);
							
							// i=prod(M,2).^(1./l);
							VECTOR_T* prod_M = prod(M, 2);
							MATRIX_ID(free)(M);
							VECTOR_T* l_pow_neg_1 = pow_elements(l, -1.0);
							VECTOR_ID(free)(l);
							VECTOR_T* i = pow_elements(prod_M, l_pow_neg_1);
							VECTOR_ID(free)(prod_M);
							VECTOR_ID(free)(l_pow_neg_1);
							
							// q = i./x;
							VECTOR_T* q = copy(i);
							VECTOR_ID(div)(q, x);
							VECTOR_ID(free)(x);
							
							// [idu j]=unique(id);
							VECTOR_T* j;
							VECTOR_T* idu = unique(id, "last", &j);
							VECTOR_ID(free)(id);
							
							// j=[0;j];
							VECTOR_T* temp = VECTOR_ID(alloc)(j->size + 1);
							VECTOR_ID(set)(temp, 0, -1.0);
							VECTOR_ID(view) temp_subv = VECTOR_ID(subvector)(temp, 1, j->size);
							VECTOR_ID(memcpy)(&temp_subv.vector, j);
							VECTOR_ID(free)(j);
							j = temp;
							
							// mu=length(idu);
							int mu = length(idu);
							
							// i2=zeros(mu,1);
							VECTOR_T* i2 = zeros_vector(mu);
							
							// q2=i2; f2=i2;
							VECTOR_T* q2 = copy(i2);
							VECTOR_T* f2 = copy(i2);
							
							// for h=1:mu
							for (int h = 0; h < mu; h++) {
								
								// i2(h)=sum(i(j(h)+1:j(h+1)));
								int j_h = (int)VECTOR_ID(get)(j, h);
								int j_h_add_1 = (int)VECTOR_ID(get)(j, h + 1);
								VECTOR_T* iq_indices = sequence(j_h + 1, j_h_add_1);
								VECTOR_T* i_idx = ordinal_index(i, iq_indices);
								VECTOR_ID(set)(i2, h, sum(i_idx));
								VECTOR_ID(free)(i_idx);
								
								// q2(h)=sum(q(j(h)+1:j(h+1)));
								VECTOR_T* q_idx = ordinal_index(q, iq_indices);
								VECTOR_ID(free)(iq_indices);
								VECTOR_ID(set)(q2, h, sum(q_idx));
								VECTOR_ID(free)(q_idx);
								
								// f2(h)=j(h+1)-j(h);
								VECTOR_ID(set)(f2, h, (FP_T)(j_h_add_1 - j_h));
							}
							VECTOR_ID(free)(i);
							VECTOR_ID(free)(q);
							VECTOR_ID(free)(j);
							
							// I(idu,[u v1 v2])=I(idu,[u v1 v2])+[i2 i2 i2];
							// Q(idu,[u v1 v2])=Q(idu,[u v1 v2])+[q2 q2 q2];
							// F(idu,[u v1 v2])=F(idu,[u v1 v2])+[f2 f2 f2];
							FP_T IQF_cols[] = { (FP_T)u, (FP_T)v1, (FP_T)v2 };
							VECTOR_ID(view) IQF_cols_vv = VECTOR_ID(view_array)(IQF_cols, 3);
							MATRIX_T* I_idx = ordinal_index(I, idu, &IQF_cols_vv.vector);
							MATRIX_T* Q_idx = NULL;
							MATRIX_T* F_idx = NULL;
							if (Q != NULL) {
								Q_idx = ordinal_index(*Q, idu, &IQF_cols_vv.vector);
							}
							if (F != NULL) {
								F_idx = ordinal_index(*F, idu, &IQF_cols_vv.vector);
							}
							for (int j = 0; j < 3; j++) {
								VECTOR_ID(view) I_idx_col_j = MATRIX_ID(column)(I_idx, j);
								VECTOR_ID(add)(&I_idx_col_j.vector, i2);
								if (Q != NULL) {
									VECTOR_ID(view) Q_idx_col_j = MATRIX_ID(column)(Q_idx, j);
									VECTOR_ID(add)(&Q_idx_col_j.vector, q2);
								}
								if (F != NULL) {
									VECTOR_ID(view) F_idx_col_j = MATRIX_ID(column)(F_idx, j);
									VECTOR_ID(add)(&F_idx_col_j.vector, f2);
								}
							}
							VECTOR_ID(free)(i2);
							VECTOR_ID(free)(q2);
							VECTOR_ID(free)(f2);
							ordinal_index_assign(I, idu, &IQF_cols_vv.vector, I_idx);
							MATRIX_ID(free)(I_idx);
							if (Q != NULL) {
								ordinal_index_assign(*Q, idu, &IQF_cols_vv.vector, Q_idx);
								MATRIX_ID(free)(Q_idx);
							}
							if (F != NULL) {
								ordinal_index_assign(*F, idu, &IQF_cols_vv.vector, F_idx);
								MATRIX_ID(free)(F_idx);
							}
							VECTOR_ID(free)(idu);
						}
						
						VECTOR_ID(free)(w);
						VECTOR_ID(free)(ind);
					}
					
					VECTOR_ID(free)(find_V2);
				}
				
				VECTOR_ID(free)(V2);
			}
			
			VECTOR_ID(free)(find_V1);
		}
		
		VECTOR_ID(free)(V1);
	}
	
	VECTOR_ID(free)(ID3);
	VECTOR_ID(free)(N3);
	MATRIX_ID(free)(M3);
	MATRIX_ID(free)(A);
	MATRIX_ID(free)(As);
	return I;
}
Пример #30
0
/*
 * Counts occurrences of four-node structural motifs in a binary graph.
 */
VECTOR_T* BCT_NAMESPACE::motif4struct_bin(const MATRIX_T* A, MATRIX_T** F) {
	if (safe_mode) check_status(A, SQUARE | BINARY, "motif4struct_bin");
	
	// load motif34lib M4n ID4
	VECTOR_T* ID4;
	MATRIX_T* M4 = motif4generate(&ID4);
	
	// n=length(A);
	int n = length(A);
	
	// F=zeros(199,n);
	if (F != NULL) {
		*F = zeros(199, n);
	}
	
	// f=zeros(199,1);
	VECTOR_T* f = zeros_vector(199);
	
	// As=A|A.';
	MATRIX_T* A_transpose = MATRIX_ID(alloc)(A->size2, A->size1);
	MATRIX_ID(transpose_memcpy)(A_transpose, A);
	MATRIX_T* As = logical_or(A, A_transpose);
	MATRIX_ID(free)(A_transpose);
	
	// for u=1:n-3
	for (int u = 0; u < n - 3; u++) {
		
		// V1=[false(1,u) As(u,u+1:n)];
		VECTOR_T* V1 = VECTOR_ID(alloc)(n);
		MATRIX_ID(get_row)(V1, As, u);
		for (int i = 0; i <= u; i++) {
			VECTOR_ID(set)(V1, i, 0.0);
		}
		
		// for v1=find(V1)
		VECTOR_T* find_V1 = find(V1);
		if (find_V1 != NULL) {
			for (int i_find_V1 = 0; i_find_V1 < (int)find_V1->size; i_find_V1++) {
				int v1 = (int)VECTOR_ID(get)(find_V1, i_find_V1);
				
				// V2=[false(1,u) As(v1,u+1:n)];
				VECTOR_T* V2 = VECTOR_ID(alloc)(n);
				MATRIX_ID(get_row)(V2, As, v1);
				for (int i = 0; i <= u; i++) {
					VECTOR_ID(set)(V2, i, 0.0);
				}
				
				// V2(V1)=0;
				logical_index_assign(V2, V1, 0.0);
				
				// V2=V2|([false(1,v1) As(u,v1+1:n)]);
				VECTOR_T* V2_1 = V2;
				VECTOR_T* V2_2 = VECTOR_ID(alloc)(n);
				MATRIX_ID(get_row)(V2_2, As, u);
				for (int i = 0; i <= v1; i++) {
					VECTOR_ID(set)(V2_2, i, 0.0);
				}
				V2 = logical_or(V2_1, V2_2);
				VECTOR_ID(free)(V2_1);
				VECTOR_ID(free)(V2_2);
				
				// for v2=find(V2)
				VECTOR_T* find_V2 = find(V2);
				if (find_V2 != NULL) {
					for (int i_find_V2 = 0; i_find_V2 < (int)find_V2->size; i_find_V2++) {
						int v2 = (int)VECTOR_ID(get)(find_V2, i_find_V2);
						
						// vz=max(v1,v2);
						int vz = (v1 > v2) ? v1 : v2;
						
						// V3=([false(1,u) As(v2,u+1:n)]);
						VECTOR_T* V3 = VECTOR_ID(alloc)(n);
						MATRIX_ID(get_row)(V3, As, v2);
						for (int i = 0; i <= u; i++) {
							VECTOR_ID(set)(V3, i, 0.0);
						}
						
						// V3(V2)=0;
						logical_index_assign(V3, V2, 0.0);
						
						// V3=V3|([false(1,v2) As(v1,v2+1:n)]);
						VECTOR_T* V3_1 = V3;
						VECTOR_T* V3_2 = VECTOR_ID(alloc)(n);
						MATRIX_ID(get_row)(V3_2, As, v1);
						for (int i = 0; i <= v2; i++) {
							VECTOR_ID(set)(V3_2, i, 0.0);
						}
						V3 = logical_or(V3_1, V3_2);
						VECTOR_ID(free)(V3_1);
						VECTOR_ID(free)(V3_2);
						
						// V3(V1)=0;
						logical_index_assign(V3, V1, 0.0);
						
						// V3=V3|([false(1,vz) As(u,vz+1:n)]);
						V3_1 = V3;
						V3_2 = VECTOR_ID(alloc)(n);
						MATRIX_ID(get_row)(V3_2, As, u);
						for (int i = 0; i <= vz; i++) {
							VECTOR_ID(set)(V3_2, i, 0.0);
						}
						V3 = logical_or(V3_1, V3_2);
						VECTOR_ID(free)(V3_1);
						VECTOR_ID(free)(V3_2);
						
						// for v3=find(V3)
						VECTOR_T* find_V3 = find(V3);
						if (find_V3 != NULL ) {
							for (int i_find_V3 = 0; i_find_V3 < (int)find_V3->size; i_find_V3++) {
								int v3 = (int)VECTOR_ID(get)(find_V3, i_find_V3);
								
								// s=uint32(sum(10.^(11:-1:0).*[A(v1,u) A(v2,u) A(v3,u) A(u,v1) A(v2,v1) A(v3,v1) A(u,v2) A(v1,v2) A(v3,v2) A(u,v3) A(v1,v3) A(v2,v3)]));
								int A_rows[] = { v1, v2, v3, u, v2, v3, u, v1, v3, u, v1, v2 };
								int A_cols[] = { u, u, u, v1, v1, v1, v2, v2, v2, v3, v3, v3 };
								VECTOR_T* s = VECTOR_ID(alloc)(12);
								for (int i = 0; i < 12; i++) {
									VECTOR_ID(set)(s, i, MATRIX_ID(get)(A, A_rows[i], A_cols[i]));
								}
								
								// ind=ID4(s==M4n);
								int i_M4 = 0;
								for ( ; i_M4 < (int)M4->size1; i_M4++) {
									VECTOR_ID(view) M4_row_i_M4 = MATRIX_ID(row)(M4, i_M4);
									if (compare_vectors(s, &M4_row_i_M4.vector) == 0) {
										break;
									}
								}
								VECTOR_ID(free)(s);
								if (i_M4 < (int)M4->size1) {
									int ind = (int)VECTOR_ID(get)(ID4, i_M4) - 1;
									
									// if nargout==2; F(ind,[u v1 v2 v3])=F(ind,[u v1 v2 v3])+1; end
									if (F != NULL) {
										int F_cols[] = { u, v1, v2, v3 };
										for (int i = 0; i < 4; i++) {
											MATRIX_ID(set)(*F, ind, F_cols[i], MATRIX_ID(get)(*F, ind, F_cols[i]) + 1.0);
										}
									}
									
									// f(ind)=f(ind)+1;
									VECTOR_ID(set)(f, ind, VECTOR_ID(get)(f, ind) + 1.0);
								}
							}
							
							VECTOR_ID(free)(find_V3);
						}
						
						VECTOR_ID(free)(V3);
					}
					
					VECTOR_ID(free)(find_V2);
				}
				
				VECTOR_ID(free)(V2);
			}
			
			VECTOR_ID(free)(find_V1);
		}
		
		VECTOR_ID(free)(V1);
	}
	
	VECTOR_ID(free)(ID4);
	MATRIX_ID(free)(M4);
	MATRIX_ID(free)(As);
	return f;
}