Example #1
0
static void
test_list_ops(void **state)
{
    char **list;

    list = calloc(2, sizeof(char *));
    assert_non_null(list);
    list[0] = strdup("foo");
    assert_non_null(list[0]);

    assert_int_equal(null_string_array_size(list), 1);
    free_string_list(list);

    free_string_list(NULL);
    assert_int_equal(null_string_array_size(NULL), 0);
}
Example #2
0
/****************************************************************************
 * Create a new alignment with any sequence that contains nothing but 
 * gap ('-') characters removed. Returns the new alignment.  Does not 
 * change the old alignment.
 * If there are no all-gap sequences, the returned alignment is the
 * same object as the original alignment.
 ****************************************************************************/
static ALIGNMENT_T* remove_allgap_sequences(ALIGNMENT_T* alignment)
{
  ALIGNMENT_T* new_alignment;
  int i_aln;
  int l_aln = get_num_aligned_sequences(alignment);
  STRING_LIST_T* keeper_seqs = new_string_list();

  // Identify the all-gap sequences.
  for (i_aln=0; i_aln<l_aln; i_aln++) {
    SEQ_T* sequence = get_alignment_sequence(i_aln, alignment);
    int i_seq;
    int l_seq = get_seq_length(sequence);
    // Add sequence to keepers if it contains a non-gap.
    for (i_seq=0; i_seq<l_seq; i_seq++) {
      if (get_seq_char(i_seq, sequence) != '-') {           // not gap?
	add_string(get_seq_name(sequence), keeper_seqs);    // non-gap: keeper
	break;
      }
    }
  }

  // Remove any sequences not in keeper list.
  if (get_num_strings(keeper_seqs) < l_aln) {
    new_alignment = remove_alignment_seqs(keeper_seqs, alignment);
    free_string_list(keeper_seqs);
  } else {
    new_alignment = alignment;
  }

  return(new_alignment);
} // remove_allgap_sequences
Example #3
0
void append_string_to_args( char * sin ,
                            int argc , char * argv[] ,
                            int * new_argc , char *** new_argv )
{
   int     n_argc , ii , ntok=0    ;
   char ** n_argv ,   ** stok=NULL ;
   char * cpt , * sss ;

   if( new_argc == NULL || new_argv == NULL ) return ;              /* error */

   if( sin == NULL || sin[0] == '\0' ){ *new_argv = NULL; return; } /* do nothing */

   tokenize_string( sin , &ntok , &stok ) ;
   if( stok == NULL || ntok < 1 ){ *new_argv = NULL; return; }      /* do nothing */

   /* copy input args to output */

   if( argc > 0 ){
      duplicate_string_list( argc , argv , &n_argv ) ;
      n_argc = argc ;
   } else {                                                    /* shouldn't happen */
      n_argv = NULL ;
      n_argc = 0 ;
   }

   /* append token list to output */

   appendto_string_list( &n_argc , &n_argv , ntok , stok ) ;
   free_string_list( ntok , stok ) ;

   *new_argc = n_argc ;  /* the results! */
   *new_argv = n_argv ;
   return ;
}
Example #4
0
void free_kvpair(kvpair_t* pair)
{
    if (pair) {
        free_kvpair(pair->next);
        free(pair->key);
        free_string_list(pair->values);
        free(pair);
    }
}
Example #5
0
/*******************************************************************************
 * Free TRANSFAC motif structure
 ******************************************************************************/
void free_transfac_motif(void *motif) {
    TRANSFAC_MOTIF_T *trans_motif = motif;
    myfree(trans_motif->accession);
    myfree(trans_motif->id);
    myfree(trans_motif->name);
    myfree(trans_motif->description);
    myfree(trans_motif->consensus);
    free_string_list(trans_motif->species_list);
    free_matrix(trans_motif->counts);
    myfree(trans_motif);
}
Example #6
0
void
free_record_data(void *rdata)
{
    struct record_data *r = rdata;
    switch (r->type) {
    case RECDB_INVALID: break;
    case RECDB_QSTRING: free(r->d.qstring); break;
    case RECDB_OBJECT: dict_delete(r->d.object); break;
    case RECDB_STRING_LIST: free_string_list(r->d.slist); break;
    }
    free(r);
}
Example #7
0
/**
 * Free the list of qemu options.
 */
void
qemuopts_free (struct qemuopts *qopts)
{
  size_t i;

  for (i = 0; i < qopts->nr_options; ++i) {
    free (qopts->options[i].flag);
    free (qopts->options[i].value);
    free_string_list (qopts->options[i].values);
  }
  free (qopts->options);
  free (qopts->binary);
  free (qopts);
}
Example #8
0
/* Performs filename expansion on a list of strings.  The list of strings is
 * replaced with the list of expanded strings.  0 is returned on success; -1 is
 * returned on read error in glob(). */
static int do_filename_expansion(struct list_head *string_list)
{
	struct string *s, *tmp;
	int ret = 0;

	LIST_HEAD(new_list);
	list_for_each_entry_safe(s, tmp, string_list, list)
		ret |= string_do_filename_expansion(s, &new_list);
	INIT_LIST_HEAD(string_list);
	if (ret)
		free_string_list(&new_list);
	else
		list_splice_tail(&new_list, string_list);
	return ret;
}
Example #9
0
static void free_syntax(struct syntax *syn)
{
	int i;

	for (i = 0; i < syn->states.count; i++)
		free_state(syn->states.ptrs[i]);
	free(syn->states.ptrs);

	for (i = 0; i < syn->string_lists.count; i++)
		free_string_list(syn->string_lists.ptrs[i]);
	free(syn->string_lists.ptrs);

	for (i = 0; i < syn->default_colors.count; i++)
		free_strings(syn->default_colors.ptrs[i]);
	free(syn->default_colors.ptrs);

	free(syn->name);
	free(syn);
}
Example #10
0
static kvpair_t *grok_form(xmpp_stanza_t *fields)
{
    kvpair_t *rv = NULL;

    /* walk the field peers and grab their values and stuff */
    while (fields) {
        if (xmpp_stanza_is_tag(fields)) {
            char* k = xmpp_stanza_get_attribute(fields, "var");
            char **vals = get_specific_form_values(fields, k);
            kvpair_t* thispair = mk_kvpair(k, vals);
            free_string_list(vals);
            thispair->next = rv;
            rv = thispair;
        }
        fields = xmpp_stanza_get_next(fields);
    }

    return rv;
}
Example #11
0
void prepend_string_to_args( char * sin ,
                             int argc , char * argv[] ,
                             int * new_argc , char *** new_argv )
{
   int     n_argc , ii , ntok=0    ;
   char ** n_argv ,   ** stok=NULL ;
   char * cpt , * sss ;

   if( new_argc == NULL || new_argv == NULL ) return ;              /* error */

   if( sin == NULL || sin[0] == '\0' ){ *new_argv = NULL; return; } /* do nothing */

   /*-- if no inputs after argv[0], prepend and append are identical --*/

   if( argc < 2 ){
      append_string_to_args( sin , argc , argv , new_argc , new_argv ) ;
      return ;
   }

   /*-- OK, must do it my way --*/

   tokenize_string( sin , &ntok , &stok ) ;
   if( stok == NULL || ntok < 1 ){ *new_argv = NULL; return; }      /* do nothing */

   /* copy first input arg to output */

   duplicate_string_list( 1 , argv , &n_argv ) ;
   n_argc = 1 ;

   /* append token list to output */

   appendto_string_list( &n_argc , &n_argv , ntok , stok ) ;
   free_string_list( ntok , stok ) ;

   /* append rest of input args to output */

   appendto_string_list( &n_argc , &n_argv , argc-1 , argv+1 ) ;

   *new_argc = n_argc ;  /* the results! */
   *new_argv = n_argv ;
   return ;
}
Example #12
0
File: files.c Project: h3rb/gc
/*
 * Returns a list of lines
 */
STRING_LIST *fread_file( char *filename ) {
     FILE *fp=fopen( filename, "r" );
     STRING_LIST *slist=NULL;
     STRING_LIST *last=NULL;

     if (fp == NULL) { OUTPUT("File not found: %s\n", filename); return NULL; }
     
     while( !feof(fp) && !ferror(fp) )
     {
        STRING_LIST *snode = new_string_list( );
        snode->str=fread_string_eol(fp);
        if ( snode->str == NULL ) { free_string_list(snode); break; }
        if ( last != NULL ) last->next = snode;
        else slist=snode;
        last=snode;
     }
     
     fclose(fp);
     return slist;
}
static void new_alias (gpointer data, PurpleRequestFields *fields)
{
  GtkTreeIter iter;
  GList *aliases;

  const char *alias;

  alias = purple_request_fields_get_string (fields, "alias");
  aliases = purple_prefs_get_string_list (
    "/plugins/gtk/autoprofile/components/logstat/aliases");

  aliases = g_list_append (aliases, strdup (alias));
  purple_prefs_set_string_list (
    "/plugins/gtk/autoprofile/components/logstat/aliases", aliases);
  free_string_list (aliases);

  gtk_list_store_insert (alias_list, &iter, 0);
  gtk_list_store_set (alias_list, &iter,
                      0, alias, -1);
}
static void alias_delete (GtkButton *button, gpointer data)
{
  GtkTreeSelection *selection;
  GtkTreeIter iter;
  char *alias;

  GList *aliases, *aliases_start, *new_aliases;

  selection = gtk_tree_view_get_selection (
    GTK_TREE_VIEW (alias_view));

  if (!gtk_tree_selection_get_selected (selection, NULL, &iter))
    return;

  gtk_tree_model_get (GTK_TREE_MODEL (alias_list), &iter,
                      0, &alias, -1);
  gtk_list_store_remove (alias_list, &iter);

  aliases = purple_prefs_get_string_list (
    "/plugins/gtk/autoprofile/components/logstat/aliases");
  aliases_start = aliases;

  new_aliases = NULL;

  while (aliases) {
    if (strcmp ((char *)aliases->data, alias)) {
      new_aliases = g_list_append (new_aliases, aliases->data);
    }

    aliases = aliases->next;
  }

  purple_prefs_set_string_list (
    "/plugins/gtk/autoprofile/components/logstat/aliases", new_aliases);

  free_string_list (aliases_start);
  g_list_free (new_aliases);
  free (alias);
}
Example #15
0
BOOLEAN
CreateRpcBinding(
    PVOID            *phBinding,
    RPC_BINDING_TYPE  eBindingType,
    PCWSTR            pwszHostname,
    PCWSTR            pwszBinding,
    PCREDENTIALS      pCredentials
    )
{
    PCSTR pszNtlmsspAuth = "ntlmssp";
    PCSTR pszSign = "sign";
    PCSTR pszSeal = "seal";

    BOOLEAN bRet = TRUE;
    NTSTATUS ntStatus = STATUS_SUCCESS;
    DWORD dwError = ERROR_SUCCESS;
    unsigned32 rpcStatus = RPC_S_OK;
    LSA_BINDING hBinding = NULL;
    LW_PIO_CREDS pIoCreds = NULL;
    PWSTR pwszBindingString = NULL;
    size_t sBindingStringLen = 0;
    PSTR pszBindingString = NULL;
    PSTR *ppszOptions = NULL;
    DWORD iOpt = 0;
    DWORD i = 0;
    DWORD dwNumValidOptions = 0;
    unsigned32 AuthType = 0;
    unsigned32 ProtectionLevel = 0;
    SEC_WINNT_AUTH_IDENTITY *pNtlmSspAuthInfo = NULL;
    PVOID pAuthInfo = NULL;
    unsigned char *pszUuid = NULL;
    unsigned char *pszProtSeq = NULL;
    unsigned char *pszNetworkAddr = NULL;
    unsigned char *pszEndpoint = NULL;
    unsigned char *pszOptions = NULL;
    PSTR pszHostname = NULL;

    if (phBinding == NULL)
    {
        ntStatus = STATUS_INVALID_PARAMETER;
        BAIL_ON_NT_STATUS(ntStatus);
    }

    if (pwszBinding)
    {
        dwError = LwAllocateWc16String(&pwszBindingString,
                                       pwszBinding);
        BAIL_ON_WIN_ERROR(dwError);

        dwError = LwWc16sLen(pwszBindingString, &sBindingStringLen);
        BAIL_ON_WIN_ERROR(dwError);

        dwError = LwWc16sToMbs(pwszBindingString,
                               &pszBindingString);
        BAIL_ON_WIN_ERROR(dwError);

        ppszOptions = get_string_list(pszBindingString, ':');
        if (ppszOptions == NULL)
        {
            ntStatus = STATUS_INVALID_PARAMETER;
            BAIL_ON_NT_STATUS(ntStatus);
        }

        /*
         * Find and identify valid options
         */
        while (ppszOptions[iOpt])
        {
            if (!strcasecmp(pszNtlmsspAuth, ppszOptions[iOpt]))
            {
                AuthType = rpc_c_authn_winnt;
                dwNumValidOptions++;
            }
            else if (!strcasecmp(pszSign, ppszOptions[iOpt]))
            {
                ProtectionLevel = rpc_c_authn_level_pkt_integrity;
                dwNumValidOptions++;
            }
            else if (!strcasecmp(pszSeal, ppszOptions[iOpt]))
            {
                ProtectionLevel = rpc_c_authn_level_pkt_privacy;
                dwNumValidOptions++;
            }

            iOpt++;
        }
    }

    /*
     * Cut off the options from the binding string so it can
     * be passed to rpc routines
     */
    if (dwNumValidOptions > 0)
    {
        i = sBindingStringLen;
        while (dwNumValidOptions &&
               pwszBindingString[--i])
        {
            if (pwszBindingString[i] == (WCHAR)':')
            {
                dwNumValidOptions--;
            }
        }

        pwszBindingString[i] = (WCHAR)'\0';
        pszBindingString[i] = '\0';
    }

    ntStatus = LwIoGetActiveCreds(NULL, &pIoCreds);
    BAIL_ON_NT_STATUS(ntStatus);

    if (pwszBindingString)
    {
        ntStatus = RpcInitBindingFromBindingString(
                                         (handle_t*)&hBinding,
                                         pwszBindingString,
                                         pIoCreds);
    }
    else
    {
        switch (eBindingType)
        {
        case RPC_LSA_BINDING:
            ntStatus = LsaInitBindingDefault(&hBinding,
                                             pwszHostname,
                                             pIoCreds);
            break;

        case RPC_SAMR_BINDING:
            ntStatus = SamrInitBindingDefault(&hBinding,
                                              pwszHostname,
                                              pIoCreds);
            break;

        case RPC_NETLOGON_BINDING:
            ntStatus = NetrInitBindingDefault(&hBinding,
                                              pwszHostname,
                                              pIoCreds);
            break;

        case RPC_DSSETUP_BINDING:
            ntStatus = DsrInitBindingDefault(&hBinding,
                                             pwszHostname,
                                             pIoCreds);
            break;

        case RPC_WKSSVC_BINDING:
            ntStatus = WkssInitBindingDefault(&hBinding,
                                              pwszHostname,
                                              pIoCreds);
            break;

        default:
            ntStatus = STATUS_NOT_IMPLEMENTED;
            break;
        }
    }
    BAIL_ON_NT_STATUS(ntStatus);

    switch (AuthType)
    {
    case rpc_c_authn_winnt:
        dwError = LwAllocateMemory(sizeof(*pNtlmSspAuthInfo),
                                   OUT_PPVOID(&pNtlmSspAuthInfo));
        BAIL_ON_WIN_ERROR(dwError);

        if (pCredentials->Ntlm.pwszDomain)
        {
            dwError = LwWc16sToMbs(pCredentials->Ntlm.pwszDomain,
                                   &pNtlmSspAuthInfo->Domain);
            BAIL_ON_WIN_ERROR(dwError);

            pNtlmSspAuthInfo->DomainLength = strlen(pNtlmSspAuthInfo->Domain);
        }

        dwError = LwWc16sToMbs(pCredentials->Ntlm.pwszUsername,
                               &pNtlmSspAuthInfo->User);
        BAIL_ON_WIN_ERROR(dwError);

        pNtlmSspAuthInfo->UserLength = strlen(pNtlmSspAuthInfo->User);

        dwError = LwWc16sToMbs(pCredentials->Ntlm.pwszPassword,
                               &pNtlmSspAuthInfo->Password);
        BAIL_ON_WIN_ERROR(dwError);

        pNtlmSspAuthInfo->PasswordLength = strlen(pNtlmSspAuthInfo->Password);

        pAuthInfo = (PVOID)pNtlmSspAuthInfo;
        break;

    default:
        pAuthInfo = NULL;
        break;
    }

    if (pwszHostname)
    {
        dwError = LwWc16sToMbs(pwszHostname,
                               &pszHostname);
        BAIL_ON_WIN_ERROR(dwError);
    }
    else
    {
        rpc_string_binding_parse((unsigned char*)pszBindingString,
                                 &pszUuid,
                                 &pszProtSeq,
                                 &pszNetworkAddr,
                                 &pszEndpoint,
                                 &pszOptions,
                                 &rpcStatus);
        if (rpcStatus)
        {
            ntStatus = LwRpcStatusToNtStatus(rpcStatus);
            BAIL_ON_NT_STATUS(ntStatus);
        }

        dwError = LwAllocateString((PSTR)pszNetworkAddr,
                                   &pszHostname);
        BAIL_ON_WIN_ERROR(dwError);
    }

    if (AuthType)
    {
        rpc_binding_set_auth_info(hBinding,
                                  (unsigned char*)pszHostname,
                                  ProtectionLevel,
                                  AuthType,
                                  (rpc_auth_identity_handle_t)pAuthInfo,
                                  rpc_c_authz_name, /* authz_protocol */
                                  &rpcStatus);
        if (rpcStatus)
        {
            ntStatus = LwRpcStatusToNtStatus(rpcStatus);
            BAIL_ON_NT_STATUS(ntStatus);
        }
    }

    *phBinding = hBinding;

cleanup:
    if (pIoCreds)
    {
        LwIoDeleteCreds(pIoCreds);
    }

    LW_SAFE_FREE_MEMORY(pwszBindingString);
    LW_SAFE_FREE_MEMORY(pszBindingString);
    LW_SAFE_FREE_MEMORY(pszHostname);

    rpc_string_free(&pszUuid, &rpcStatus);
    rpc_string_free(&pszProtSeq, &rpcStatus);
    rpc_string_free(&pszNetworkAddr, &rpcStatus);
    rpc_string_free(&pszEndpoint, &rpcStatus);
    rpc_string_free(&pszOptions, &rpcStatus);

    if (ppszOptions)
    {
        free_string_list(ppszOptions);
    }

    if (ntStatus == STATUS_SUCCESS &&
        dwError != ERROR_SUCCESS)
    {
        ntStatus = LwWin32ErrorToNtStatus(dwError);
    }

    if (ntStatus != STATUS_SUCCESS)
    {
        bRet = FALSE;
    }

    return bRet;

error:
    *phBinding = NULL;
    bRet       = FALSE;

    goto cleanup;
}
Example #16
0
/*************************************************************************
 * Entry point for pmp_bf
 *************************************************************************/
int main(int argc, char *argv[]) {

  char* bg_filename = NULL;
  char* motif_name = "motif"; // Use this motif name in the output.
  STRING_LIST_T* selected_motifs = NULL;
  double fg_rate = 1.0;
  double bg_rate = 1.0;
  double purine_pyrimidine = 1.0; // r
  double transition_transversion = 0.5; // R
  double pseudocount = 0.1;
  GAP_SUPPORT_T gap_support = SKIP_GAPS;
  MODEL_TYPE_T model_type = F81_MODEL;
  BOOLEAN_T use_halpern_bruno = FALSE;
  char* ustar_label = NULL;	// TLB; create uniform star tree
  int i;

  program_name = "pmp_bf";

  /**********************************************
   * COMMAND LINE PROCESSING
   **********************************************/

  // Define command line options. (FIXME: Repeated code)
  // FIXME: Note that if you add or remove options you
  // must change n_options.
  int n_options = 12;
  cmdoption const pmp_options[] = {
    {"hb", NO_VALUE},
    {"ustar", REQUIRED_VALUE},
    {"model", REQUIRED_VALUE},
    {"pur-pyr", REQUIRED_VALUE},
    {"transition-transversion", REQUIRED_VALUE},
    {"bg", REQUIRED_VALUE},
    {"fg", REQUIRED_VALUE},
    {"motif", REQUIRED_VALUE},
    {"motif-name", REQUIRED_VALUE},
    {"bgfile", REQUIRED_VALUE},
    {"pseudocount", REQUIRED_VALUE},
    {"verbosity", REQUIRED_VALUE}
  };

  int option_index = 0;

  // Define the usage message.
  char      usage[1000] = "";
  strcat(usage, "USAGE: pmp [options] <tree file> <MEME file>\n");
  strcat(usage, "\n");
  strcat(usage, "   Options:\n");

  // Evolutionary model parameters.
  strcat(usage, "     --hb\n");
  strcat(usage, "     --model single|average|jc|k2|f81|f84|hky|tn");
  strcat(usage, " (default=f81)\n");
  strcat(usage, "     --pur-pyr <float> (default=1.0)\n");
  strcat(usage, "     --transition-transversion <float> (default=0.5)\n");
  strcat(usage, "     --bg <float> (default=1.0)\n");
  strcat(usage, "     --fg <float> (default=1.0)\n");

  // Motif parameters.
  strcat(usage, "     --motif <id> (default=all)\n");
  strcat(usage, "     --motif-name <string> (default from motif file)\n");

  // Miscellaneous parameters
  strcat(usage, "     --bgfile <background> (default from motif file)\n");
  strcat(usage, "     --pseudocount <float> (default=0.1)\n");
  strcat(usage, "     --ustar <label>\n");	// TLB; create uniform star tree
  strcat(usage, "     --verbosity [1|2|3|4] (default 2)\n");
  strcat(usage, "\n    Prints the FP and FN rate at each of 10000 score values.\n");
  strcat(usage, "\n    Output format: [<motif_id> score <score> FPR <fpr> TPR <tpr>]+\n");

  // Parse the command line.
  if (simple_setopt(argc, argv, n_options, pmp_options) != NO_ERROR) {
    die("Error processing command line options: option name too long.\n");
  }

  while (TRUE) { 
    int c = 0;
    char* option_name = NULL;
    char* option_value = NULL;
    const char * message = NULL;

    // Read the next option, and break if we're done.
    c = simple_getopt(&option_name, &option_value, &option_index);
    if (c == 0) {
      break;
    } else if (c < 0) {
      (void) simple_getopterror(&message);
      die("Error processing command line options (%s)\n", message);
    }
    
    if (strcmp(option_name, "model") == 0) {
      if (strcmp(option_value, "jc") == 0) {
        model_type = JC_MODEL;
      } else if (strcmp(option_value, "k2") == 0) {
        model_type = K2_MODEL;
      } else if (strcmp(option_value, "f81") == 0) {
        model_type = F81_MODEL;
      } else if (strcmp(option_value, "f84") == 0) {
        model_type = F84_MODEL;
      } else if (strcmp(option_value, "hky") == 0) {
        model_type = HKY_MODEL;
      } else if (strcmp(option_value, "tn") == 0) {
        model_type = TAMURA_NEI_MODEL;
      } else if (strcmp(option_value, "single") == 0) {
        model_type = SINGLE_MODEL;
      } else if (strcmp(option_value, "average") == 0) {
        model_type = AVERAGE_MODEL;
      } else {
        die("Unknown model: %s\n", option_value);
      }
    } else if (strcmp(option_name, "hb") == 0){
        use_halpern_bruno = TRUE;
    } else if (strcmp(option_name, "ustar") == 0){	// TLB; create uniform star tree
        ustar_label = option_value;
    } else if (strcmp(option_name, "pur-pyr") == 0){
        purine_pyrimidine = atof(option_value);
    } else if (strcmp(option_name, "transition-transversion") == 0){
        transition_transversion = atof(option_value);
    } else if (strcmp(option_name, "bg") == 0){
      bg_rate = atof(option_value);
    } else if (strcmp(option_name, "fg") == 0){
      fg_rate = atof(option_value);
    } else if (strcmp(option_name, "motif") == 0){
        if (selected_motifs == NULL) {
          selected_motifs = new_string_list();
        }
       add_string(option_value, selected_motifs);
    } else if (strcmp(option_name, "motif-name") == 0){
        motif_name = option_value;
    } else if (strcmp(option_name, "bgfile") == 0){
      bg_filename = option_value;
    } else if (strcmp(option_name, "pseudocount") == 0){
        pseudocount = atof(option_value);
    } else if (strcmp(option_name, "verbosity") == 0){
        verbosity = atoi(option_value);
    }
  }

  // Must have tree and motif file names
  if (argc != option_index + 2) {
    fprintf(stderr, "%s", usage);
    exit(EXIT_FAILURE);
  } 

  /**********************************************
   * Read the phylogenetic tree.
   **********************************************/
  char* tree_filename = NULL;
  TREE_T* tree = NULL;
  tree_filename = argv[option_index];
  option_index++;
  tree = read_tree_from_file(tree_filename);

  // get the species names
  STRING_LIST_T* alignment_species = make_leaf_list(tree);
  char *root_label = get_label(tree);	// in case target in center
  if (strlen(root_label)>0) add_string(root_label, alignment_species);
  //write_string_list(" ", alignment_species, stderr);

  // TLB; Convert the tree to a uniform star tree with
  // the target sequence at its center.
  if (ustar_label != NULL) {
    tree = convert_to_uniform_star_tree(tree, ustar_label);
    if (tree == NULL) 
      die("Tree or alignment missing target %s\n", ustar_label);
    if (verbosity >= NORMAL_VERBOSE) {
      fprintf(stderr, 
	"Target %s placed at center of uniform (d=%.3f) star tree:\n", 
          ustar_label, get_total_length(tree) / get_num_children(tree) 
      );
      write_tree(tree, stderr);
    }
  }

  /**********************************************
   * Read the motifs.
   **********************************************/
  char* meme_filename = argv[option_index];
  option_index++;
  int num_motifs = 0; 

  MREAD_T *mread;
  ALPH_T alph;
  ARRAYLST_T *motifs;
  ARRAY_T *bg_freqs;

  mread = mread_create(meme_filename, OPEN_MFILE);
  mread_set_bg_source(mread, bg_filename);
  mread_set_pseudocount(mread, pseudocount);
  // read motifs
  motifs = mread_load(mread, NULL);
  alph = mread_get_alphabet(mread);
  bg_freqs = mread_get_background(mread);
  // check
  if (arraylst_size(motifs) == 0) die("No motifs in %s.", meme_filename);

  

  // TLB; need to resize bg_freqs array to ALPH_SIZE items
  // or copy array breaks in HB mode.  This throws away
  // the freqs for the ambiguous characters;
  int asize = alph_size(alph, ALPH_SIZE);
  resize_array(bg_freqs, asize);

  /**************************************************************
  * Compute probability distributions for each of the selected motifs.
  **************************************************************/
  int motif_index;
  for (motif_index = 0; motif_index < arraylst_size(motifs); motif_index++) {

    MOTIF_T* motif = (MOTIF_T*)arraylst_get(motif_index, motifs);
    char* motif_id = get_motif_id(motif);
    char* bare_motif_id = motif_id;

    // We may have specified on the command line that
    // only certain motifs were to be used.
    if (selected_motifs != NULL) {
      if (*bare_motif_id == '+' || *bare_motif_id == '-') {
        // The selected  motif id won't included a strand indicator.
        bare_motif_id++;
      }
      if (have_string(bare_motif_id, selected_motifs) == FALSE) {
        continue;
      }
    }

    if (verbosity >= NORMAL_VERBOSE) {
      fprintf(
        stderr, 
        "Using motif %s of width %d.\n",
        motif_id, get_motif_length(motif)
      );
    }

    // Build an array of evolutionary models for each position in the motif.
    EVOMODEL_T** models = make_motif_models(
      motif, 
      bg_freqs,
      model_type,
      fg_rate, 
      bg_rate, 
      purine_pyrimidine, 
      transition_transversion, 
      use_halpern_bruno
    );

    // Get the frequencies under the background model (row 0) 
    // and position-dependent scores (rows 1..w)
    // for each possible alignment column.
    MATRIX_T* pssm_matrix = build_alignment_pssm_matrix(
      alph,
      alignment_species,
      get_motif_length(motif) + 1, 
      models, 
      tree, 
      gap_support
    );
    ARRAY_T* alignment_col_freqs = allocate_array(get_num_cols(pssm_matrix)); 
    copy_array(get_matrix_row(0, pssm_matrix), alignment_col_freqs);
    remove_matrix_row(0, pssm_matrix);		// throw away first row
    //print_col_frequencies(alph, alignment_col_freqs);

    //
    // Get the position-dependent null model alignment column frequencies
    //
    int w = get_motif_length(motif);
    int ncols = get_num_cols(pssm_matrix); 
    MATRIX_T* pos_dep_bkg = allocate_matrix(w, ncols);
    for (i=0; i<w; i++) {
      // get the evo model corresponding to this column of the motif
      // and store it as the first evolutionary model.
      myfree(models[0]);
      // Use motif PSFM for equilibrium freqs. for model.
      ARRAY_T* site_specific_freqs = allocate_array(asize);
      int j = 0;
      for(j = 0; j < asize; j++) {
	double value = get_matrix_cell(i, j, get_motif_freqs(motif));
	set_array_item(j, value, site_specific_freqs);
      }
      if (use_halpern_bruno == FALSE) {
	models[0] = make_model(
	  model_type,
	  fg_rate,
	  transition_transversion,
	  purine_pyrimidine,
	  site_specific_freqs,
          NULL
	);
      } else {
        models[0] = make_model(
	  model_type,
	  fg_rate,
	  transition_transversion,
	  purine_pyrimidine,
	  bg_freqs,
	  site_specific_freqs
	);
      }
      // get the alignment column frequencies using this model
      MATRIX_T* tmp_pssm_matrix = build_alignment_pssm_matrix(
        alph,
	alignment_species,
	2,				// only interested in freqs under bkg
	models, 
	tree, 
	gap_support
      );
      // assemble the position-dependent background alignment column freqs.
      set_matrix_row(i, get_matrix_row(0, tmp_pssm_matrix), pos_dep_bkg);
      // chuck the pssm (not his real name)
      free_matrix(tmp_pssm_matrix);
    }

    //
    // Compute and print the score distribution under the background model
    // and under the (position-dependent) motif model.
    //
    int range = 10000;	// 10^4 gives same result as 10^5, but 10^3 differs

    // under background model
    PSSM_T* pssm = build_matrix_pssm(alph, pssm_matrix, alignment_col_freqs, range);

    // under position-dependent background (motif) model
    PSSM_T* pssm_pos_dep = build_matrix_pssm(alph, pssm_matrix, alignment_col_freqs, range);
    get_pv_lookup_pos_dep(
      pssm_pos_dep, 
      pos_dep_bkg, 
      NULL // no priors used
    );

    // print FP and FN distributions
    int num_items = get_pssm_pv_length(pssm_pos_dep);
    for (i=0; i<num_items; i++) {
      double pvf = get_pssm_pv(i, pssm);
      double pvt = get_pssm_pv(i, pssm_pos_dep);
      double fpr = pvf;
      double fnr = 1 - pvt;
      if (fpr >= 0.99999 || fnr == 0) continue;
      printf("%s score %d FPR %.3g FNR %.3g\n", motif_id, i, fpr, fnr);
    }

    // free stuff
    free_pssm(pssm);
    free_pssm(pssm_pos_dep);
    if (models != NULL) {
      int model_index;
      int num_models = get_motif_length(motif) + 1;
      for (model_index = 0; model_index < num_models; model_index++) {
        free_model(models[model_index]);
      }
      myfree(models);
    }

  } // motif

  arraylst_destroy(destroy_motif, motifs);

  /**********************************************
   * Clean up.
   **********************************************/
  // TLB may have encountered a memory corruption bug here
  // CEG has not been able to reproduce it. valgrind says all is well.
  free_array(bg_freqs);
  free_tree(TRUE, tree);
  free_string_list(selected_motifs);

  return(0);
} // main
Example #17
0
static int
_parse_line(char *s)
{
	char **semi, **comma, *star;
	int i, j, n, lasts, lastc, pri;
	struct config_rule *out;

	if (s == NULL) return -1;
	while ((*s == ' ') || (*s == '\t')) s++;
	if (*s == '#') return -1;

	semi = explode(s, "; \t");

	if (semi == NULL) return -1;
	out = (struct config_rule *)calloc(1, sizeof(struct config_rule));
	if (out == NULL) return -1;
	out->fd = -1;

	n = 0;
	lasts = -1;
	for (i = 0; semi[i] != NULL; i++)
	{
		if (semi[i][0] == '\0') continue;
		n++;
		lasts = i;
	}

	out->dst = strdup(semi[lasts]);
	if (out->dst == NULL) return -1;

	for (i = 0; i < lasts; i++)
	{
		if (semi[i][0] == '\0') continue;
		comma = explode(semi[i], ",.");
		lastc = -1;
		for (j = 0; comma[j] != NULL; j++)
		{
			if (comma[j][0] == '\0') continue;
			lastc = j;
		}

		for (j = 0; j < lastc; j++)
		{
			if (comma[j][0] == '\0') continue;
			pri = _level_for_name(comma[lastc]);
			if (pri == -1) continue;

			if (out->count == 0)
			{
				out->facility = (char **)calloc(1, sizeof(char *));
				out->fac_prefix_len = (uint32_t *)calloc(1, sizeof(uint32_t));
				out->pri = (int *)calloc(1, sizeof(int));
			}
			else
			{
				out->facility = (char **)reallocf(out->facility, (out->count + 1) * sizeof(char *));
				out->fac_prefix_len = (uint32_t *)reallocf(out->fac_prefix_len, (out->count + 1) * sizeof(uint32_t));
				out->pri = (int *)reallocf(out->pri, (out->count + 1) * sizeof(int));
			}

			if (out->facility == NULL) return -1;
			if (out->fac_prefix_len == NULL) return -1;
			if (out->pri == NULL) return -1;

			out->facility[out->count] = _clean_facility_name(comma[j]);
			if (out->facility[out->count] == NULL) return -1;

			out->fac_prefix_len[out->count] = 0;
			star = strchr(out->facility[out->count], '*');
			if (star != NULL) out->fac_prefix_len[out->count] = (uint32_t)(star - out->facility[out->count]);

			out->pri[out->count] = pri;
			out->count++;
		}

		free_string_list(comma);
	}

	free_string_list(semi);

	TAILQ_INSERT_TAIL(&bsd_out_rule, out, entries);

	return 0;
}
Example #18
0
/*************************************************************************
 * int main
 *************************************************************************/
int main(int argc, char *argv[])
{
  /* Data structures. */
  int       num_motifs;         /* The number of motifs in the model. */
  MOTIF_T   motifs[2 * MAX_MOTIFS]; /* The motifs. */
  STRING_LIST_T* motif_occurrences = NULL; /* Strings describing occurrences of
                                              motifs */
  BOOLEAN_T has_reverse_strand = FALSE;    /* MEME file contained both strands */
  ARRAY_T*  background;         /* Background probs for alphabet. */
  ORDER_T*  order_spacing;      /* Linear HMM order and spacing. */
  MATRIX_T* transp_freq = NULL; /* Matrix of inter-motif transitions freqs. */
  MATRIX_T* spacer_ave = NULL;  /* Matrix of average spacer lengths. */
  MHMM_T *  the_hmm = NULL;     /* The HMM being constructed. */

  /* Command line parameters. */
  char *    meme_filename;      /* Input file containg motifs. */
  char *    hmm_type_str;       /* HMM type. */
  HMM_T     hmm_type;
  STRING_LIST_T* requested_motifs; /* Indices of requested motifs. */
  int       request_n;          /* The user asked for the first n motifs. */
  double    e_threshold;        /* E-value threshold for motif inclusion. */
  double    complexity_threshold; // For eliminating low-complexity motifs.
  double    p_threshold;        /* p-value threshold for motif occurences. */
  char*     order_string;       /* Motif order and spacing. */
  int       spacer_states;      /* Number of states in each spacer. */
  BOOLEAN_T fim;                /* Represent spacers as free insertion
				   modules? */
  BOOLEAN_T keep_unused;        // Drop unused inter-motif transitions?
  double    trans_pseudo;       /* Transition pseudocount. */
  double    spacer_pseudo;      // Spacer (self-loop) pseudocount. */
  char*     description;        // Descriptive text to be stored in model.
  BOOLEAN_T print_header;       /* Print file header? */
  BOOLEAN_T print_params;       /* Print parameter summary? */
  BOOLEAN_T print_time;         /* Print timing data (dummy: always false). */

  /* Local variables. */
  int       i_motif;

  /**********************************************
   * COMMAND LINE PROCESSING
   **********************************************/
  // Define command line options.
  cmdoption const options[] = {
    {"type", OPTIONAL_VALUE},
    {"description", REQUIRED_VALUE},
    {"motif", REQUIRED_VALUE},
    {"nmotifs", REQUIRED_VALUE},
    {"ethresh", REQUIRED_VALUE},
    {"lowcomp", REQUIRED_VALUE},
    {"pthresh", REQUIRED_VALUE},
    {"order", REQUIRED_VALUE},
    {"nspacer", REQUIRED_VALUE},
    {"fim", NO_VALUE},
    {"keep-unused", NO_VALUE},
    {"transpseudo", REQUIRED_VALUE},
    {"spacerpseudo", REQUIRED_VALUE},
    {"verbosity", REQUIRED_VALUE},
    {"noheader", NO_VALUE},
    {"noparams", NO_VALUE},
    {"notime", NO_VALUE},
    {"quiet", NO_VALUE},
  };
  int option_count = 18;
  int option_index = 0;

  // Define the usage message.
  char      usage[1000] = "";
  strcat(usage, "USAGE: mhmm [options] <MEME file>\n");
  strcat(usage, "\n");
  strcat(usage, "   Options:\n");
  strcat(usage, "     --type [linear|complete|star] (default=linear)\n");
  strcat(usage, "     --description <string> (may be repeated)\n");
  strcat(usage, "     --motif <motif #> (may be repeated)\n");
  strcat(usage, "     --nmotifs <#>\n");
  strcat(usage, "     --ethresh <E-value>\n");
  strcat(usage, "     --lowcomp <value>\n");
  strcat(usage, "     --pthresh <p-value>\n");
  strcat(usage, "     --order <string>\n");
  strcat(usage, "     --nspacer <spacer length> (default=1)\n");
  strcat(usage, "     --fim\n");
  strcat(usage, "     --keep-unused\n");
  strcat(usage, "     --transpseudo <pseudocount>\n");
  strcat(usage, "     --spacerpseudo <pseudocount>\n");
  strcat(usage, "     --verbosity 1|2|3|4|5 (default=2)\n");
  strcat(usage, "     --noheader\n");
  strcat(usage, "     --noparams\n");
  strcat(usage, "     --notime\n");
  strcat(usage, "     --quiet\n");
  strcat(usage, "\n");

  /* Make sure various options are set to NULL or defaults. */
  meme_filename = NULL;
  hmm_type_str = NULL;
  hmm_type = INVALID_HMM;
  requested_motifs = new_string_list();
  request_n = 0;
  e_threshold = 0.0;
  complexity_threshold = 0.0;
  p_threshold = 0.0;
  order_string = NULL;
  spacer_states = DEFAULT_SPACER_STATES,
  fim = FALSE;
  keep_unused = FALSE;
  trans_pseudo = DEFAULT_TRANS_PSEUDO;
  spacer_pseudo = DEFAULT_SPACER_PSEUDO;
  description = NULL;
  print_header = TRUE;
  print_params = TRUE;
  print_time = FALSE;

	simple_setopt(argc, argv, option_count, options);

  // Parse the command line.
  while (1) { 
    int c = 0;
    char* option_name = NULL;
    char* option_value = NULL;
    const char * message = NULL;


    // Read the next option, and break if we're done.
    c = simple_getopt(&option_name, &option_value, &option_index);
    if (c == 0) {
      break;
    } else if (c < 0) {
    	simple_getopterror(&message);
      die("Error processing command line options (%s)\n", message);
    }

    if (strcmp(option_name, "type") == 0) {
			if (option_value != NULL) {
      	hmm_type_str = option_value;
			}
    } else if (strcmp(option_name, "description") == 0) {
      description = option_value;
    } else if (strcmp(option_name, "motif") == 0) {
      add_string(option_value, requested_motifs);
    } else if (strcmp(option_name, "nmotifs") == 0) {
      request_n = atoi(option_value);
    } else if (strcmp(option_name, "ethresh") == 0) {
      e_threshold = atof(option_value);
    } else if (strcmp(option_name, "lowcomp") == 0) {
      complexity_threshold = atof(option_value);
    } else if (strcmp(option_name, "pthresh") == 0) {
      p_threshold = atof(option_value);
    } else if (strcmp(option_name, "order") == 0) {
      order_string = option_value;
    } else if (strcmp(option_name, "nspacer") == 0) {
      spacer_states = atoi(option_value);
    } else if (strcmp(option_name, "fim") == 0) {
      fim = TRUE;
    } else if (strcmp(option_name, "keep-unused") == 0) {
      keep_unused = TRUE;
    } else if (strcmp(option_name, "transpseudo") == 0) {
      trans_pseudo = atof(option_value);
    } else if (strcmp(option_name, "spacerpseudo") == 0) {
      spacer_pseudo = atof(option_value);
    } else if (strcmp(option_name, "verbosity") == 0) {
      verbosity = (VERBOSE_T)atoi(option_value);
    } else if (strcmp(option_name, "noheader") == 0) {
      print_header = FALSE;
    } else if (strcmp(option_name, "noparams") == 0) {
      print_params = FALSE;
    } else if (strcmp(option_name, "notime") == 0) {
      print_time = FALSE;
    } else if (strcmp(option_name, "quiet") == 0) {
      print_header = print_params = print_time = FALSE;
      verbosity = QUIET_VERBOSE;
    }
  }

  // Read the single required argument.
  if (option_index + 1 != argc) {
    fprintf(stderr, "%s", usage);
    exit(1);
  }
  meme_filename = argv[option_index];

  // Set up motif requests. 
  if (request_n != 0) {
    if (get_num_strings(requested_motifs) != 0) {
      die("Can't combine the -motif and -nmotifs options.\n");
    } else {
      for (i_motif = 0; i_motif < request_n; i_motif++) {
        char motif_id[MAX_MOTIF_ID_LENGTH + 1];
        sprintf(motif_id, "%d", i_motif + 1);
        add_string(motif_id, requested_motifs);
      }
    }
  }

  /* Set the model type. */
  hmm_type = convert_enum_type_str(hmm_type_str, LINEAR_HMM, HMM_STRS, 
				   NUM_HMM_T);

  /* Gotta have positive spacer length. */
  if (spacer_states <= 0) {
    die("Negative spacer length (%d).\n", spacer_states);
  }

  /* Make sure motifs weren't selected redundantly. */
  // FIXME: Add tests for complexity threshold.
  if ((get_num_strings(requested_motifs) != 0) && (e_threshold != 0.0)) {
    die("Can't use -motif or -nmotifs with -ethresh.");
  }
  if ((get_num_strings(requested_motifs) != 0) && (order_string != NULL)) {
    die("Can't use -motif or -nmotifs with -order.");
  }
  if ((order_string != NULL) && (e_threshold != 0.0)) {
    die("Can't use -ethresh and -order.");
  }

  /* Prevent trying to build a complete or star model with ordering. */
  if (order_string != NULL) {
    if (hmm_type == COMPLETE_HMM) 
      die("Can't specify motif order with a completely connected model.");
    else if (hmm_type == STAR_HMM)
      die("Can't specify motif order with a star model.");
  } 

  // Parse the order string. 
  order_spacing = create_order(order_string);

  /**********************************************
   * READING THE MOTIFS
   **********************************************/

  BOOLEAN_T read_file = FALSE;
  double pseudocount = 0;

  read_meme_file(
		 meme_filename,
		 "motif-file", // Take bg freq. from motif file.
		 pseudocount,
     REQUIRE_PSPM,
		 &num_motifs,
		 motifs,
		 &motif_occurrences,
		 &has_reverse_strand,
		 &background
		 );

  process_raw_motifs_for_model(
       &num_motifs,
       motifs,
       motif_occurrences,
       requested_motifs,
       has_reverse_strand,
       keep_unused,
       p_threshold,
       e_threshold, 
       complexity_threshold, 
       &order_spacing,
       &transp_freq,
       &spacer_ave,
       trans_pseudo,
       spacer_pseudo
  );

  /**********************************************
   * BUILDING THE HMM
   **********************************************/

  /* Build the motif-based HMM. */
  if (hmm_type == LINEAR_HMM) {

    if (order_spacing != NULL) {
      reorder_motifs(order_spacing, &num_motifs, motifs);
    }
    else {
      die("No order specified for the motifs.\n"
          "For the linear model the motif file must contain motif occurence\n" 
          "data or the motif order must be specified using "
          "the --order option.");
    }

    build_linear_hmm(
      background,
		  order_spacing,
		  spacer_states,
		  motifs,
		  num_motifs, 
		  fim,
		  &the_hmm
    );

  } else if (hmm_type == COMPLETE_HMM) {

    build_complete_hmm(
      background,
		  spacer_states,
		  motifs,
		  num_motifs,
		  transp_freq,
		  spacer_ave,
		  fim,
		  &the_hmm
    );

  } else if (hmm_type == STAR_HMM) {

    build_star_hmm(
      background,
		  spacer_states,
		  motifs,
		  num_motifs,
		  fim,
		  &the_hmm
    );

  }

  // Add some global information.
  copy_string(&(the_hmm->motif_file), meme_filename);

  /**********************************************
   * WRITING THE HMM
   **********************************************/

  /* Print the header. */
  if (print_header)
    write_header(
     program, 
     "",
		 description,
		 meme_filename,
		 NULL,
		 NULL, 
		 stdout
    );

  /* Write the HMM. */
  write_mhmm(verbosity, the_hmm, stdout);

  /* Print the program parameters. */
  if (print_params) {
    printf("Program parameters for mhmm\n");
    printf("  MEME file: %s\n", meme_filename);
    printf("  Motifs:");
    write_string_list(" ", requested_motifs, stdout);
    printf("\n");
    printf("  Model topology: %s\n",
	   convert_enum_type(hmm_type, HMM_STRS, NUM_HMM_T));
    printf("  States per spacer: %d\n", spacer_states);
    printf("  Spacers are free-insertion modules: %s\n",
	   boolean_to_string(fim));
    printf("\n");
  }

  free_array(background);
  free_string_list(requested_motifs);
  free_order(order_spacing);
  free_matrix(transp_freq);
  free_matrix(spacer_ave);
  for (i_motif = 0; i_motif < num_motifs; i_motif++)
    free_motif(&(motifs[i_motif]));
  free_mhmm(the_hmm);
  return(0);
}
Example #19
0
File: main.c Project: udomsak/isync
static void
sync_chans( main_vars_t *mvars, int ent )
{
	group_conf_t *group;
	channel_conf_t *chan;
	store_t *store;
	string_list_t *mbox, *sbox, **mboxp, **sboxp;
	char *channame;
	int t;

	if (!mvars->cben)
		return;
	switch (ent) {
	case E_OPEN: goto opened;
	case E_SYNC: goto syncone;
	}
	for (;;) {
		mvars->boxlist = 0;
		if (!mvars->all) {
			if (mvars->chanptr)
				channame = mvars->chanptr->string;
			else {
				for (group = groups; group; group = group->next)
					if (!strcmp( group->name, mvars->argv[mvars->oind] )) {
						mvars->chanptr = group->channels;
						channame = mvars->chanptr->string;
						goto gotgrp;
					}
				channame = mvars->argv[mvars->oind];
			  gotgrp: ;
			}
			if ((mvars->boxlist = strchr( channame, ':' )))
				*mvars->boxlist++ = 0;
			for (chan = channels; chan; chan = chan->next)
				if (!strcmp( chan->name, channame ))
					goto gotchan;
			error( "No channel or group named '%s' defined.\n", channame );
			mvars->ret = 1;
			goto gotnone;
		  gotchan:
			mvars->chan = chan;
		}
		merge_actions( mvars->chan, mvars->ops, XOP_HAVE_TYPE, OP_MASK_TYPE, OP_MASK_TYPE );
		merge_actions( mvars->chan, mvars->ops, XOP_HAVE_CREATE, OP_CREATE, 0 );
		merge_actions( mvars->chan, mvars->ops, XOP_HAVE_EXPUNGE, OP_EXPUNGE, 0 );

		mvars->state[M] = mvars->state[S] = ST_FRESH;
		info( "Channel %s\n", mvars->chan->name );
		mvars->boxes[M] = mvars->boxes[S] = mvars->cboxes = 0;
		mvars->skip = mvars->cben = 0;
		for (t = 0; t < 2; t++) {
			mvars->drv[t] = mvars->chan->stores[t]->driver;
			if ((store = mvars->drv[t]->own_store( mvars->chan->stores[t] )))
				store_opened( store, AUX );
		}
		for (t = 0; t < 2 && !mvars->skip; t++)
			if (mvars->state[t] == ST_FRESH) {
				info( "Opening %s %s...\n", str_ms[t], mvars->chan->stores[t]->name );
				mvars->drv[t]->open_store( mvars->chan->stores[t], store_opened, AUX );
			}
		mvars->cben = 1;
	  opened:
		if (mvars->skip)
			goto next;
		if (mvars->state[M] != ST_OPEN || mvars->state[S] != ST_OPEN)
			return;

		if (mvars->boxlist)
			mvars->boxp = mvars->boxlist;
		else if (mvars->chan->patterns) {
			mvars->boxes[M] = filter_boxes( mvars->ctx[M]->boxes, mvars->chan->patterns );
			mvars->boxes[S] = filter_boxes( mvars->ctx[S]->boxes, mvars->chan->patterns );
			for (mboxp = &mvars->boxes[M]; (mbox = *mboxp); ) {
				for (sboxp = &mvars->boxes[S]; (sbox = *sboxp); sboxp = &sbox->next)
					if (!strcmp( sbox->string, mbox->string )) {
						*sboxp = sbox->next;
						free( sbox );
						*mboxp = mbox->next;
						mbox->next = mvars->cboxes;
						mvars->cboxes = mbox;
						goto gotdupe;
					}
				mboxp = &mbox->next;
			  gotdupe: ;
			}
		}

		if (mvars->list && mvars->multiple)
			printf( "%s:\n", mvars->chan->name );
	  syncml:
		mvars->done = mvars->cben = 0;
	  syncmlx:
		if (mvars->boxlist) {
			if ((mvars->names[S] = strsep( &mvars->boxp, ",\n" ))) {
				if (!*mvars->names[S])
					mvars->names[S] = 0;
				if (!mvars->list) {
					mvars->names[M] = mvars->names[S];
					sync_boxes( mvars->ctx, mvars->names, mvars->chan, done_sync, mvars );
					goto syncw;
				}
				puts( nz( mvars->names[S], "INBOX" ) );
				goto syncmlx;
			}
		} else if (mvars->chan->patterns) {
			if ((mbox = mvars->cboxes)) {
				mvars->cboxes = mbox->next;
				if (!mvars->list) {
					mvars->names[M] = mvars->names[S] = mbox->string;
					sync_boxes( mvars->ctx, mvars->names, mvars->chan, done_sync_dyn, mvars );
					goto syncw;
				}
				puts( mbox->string );
				free( mbox );
				goto syncmlx;
			}
			for (t = 0; t < 2; t++)
				if ((mbox = mvars->boxes[t])) {
					mvars->boxes[t] = mbox->next;
					if ((mvars->chan->ops[1-t] & OP_MASK_TYPE) && (mvars->chan->ops[1-t] & OP_CREATE)) {
						if (!mvars->list) {
							mvars->names[M] = mvars->names[S] = mbox->string;
							sync_boxes( mvars->ctx, mvars->names, mvars->chan, done_sync_dyn, mvars );
							goto syncw;
						}
						puts( mbox->string );
					}
					free( mbox );
					goto syncmlx;
				}
		} else {
			if (!mvars->list) {
				sync_boxes( mvars->ctx, mvars->chan->boxes, mvars->chan, done_sync, mvars );
				mvars->skip = 1;
			  syncw:
				mvars->cben = 1;
				if (!mvars->done)
					return;
			  syncone:
				if (!mvars->skip)
					goto syncml;
			} else
				printf( "%s <=> %s\n", nz( mvars->chan->boxes[M], "INBOX" ), nz( mvars->chan->boxes[S], "INBOX" ) );
		}

	  next:
		for (t = 0; t < 2; t++)
			if (mvars->state[t] == ST_OPEN) {
				mvars->drv[t]->disown_store( mvars->ctx[t] );
				mvars->state[t] = ST_CLOSED;
			}
		if (mvars->state[M] != ST_CLOSED || mvars->state[S] != ST_CLOSED) {
			mvars->skip = mvars->cben = 1;
			return;
		}
		free_string_list( mvars->cboxes );
		free_string_list( mvars->boxes[M] );
		free_string_list( mvars->boxes[S] );
		if (mvars->all) {
			if (!(mvars->chan = mvars->chan->next))
				break;
		} else {
			if (mvars->chanptr && (mvars->chanptr = mvars->chanptr->next))
				continue;
		  gotnone:
			if (!mvars->argv[++mvars->oind])
				break;
		}
	}
	for (t = 0; t < N_DRIVERS; t++)
		drivers[t]->cleanup();
}
/* The main window */
GtkWidget *logstats_prefs (struct widget *w) 
{
  GtkWidget *ret, *vbox, *hbox;
  GtkWidget *label, *button, *entry, *sw;
  
  GtkCellRenderer *renderer;
  GtkTreeSelection *selection;
  GtkTreeViewColumn *col;
  GtkTreeIter iter;
  GList *aliases, *aliases_start;

  ret = gtk_vbox_new (FALSE, 6);

  /* Checkbox for enabling/disabling */
  checkbox = gtk_check_button_new_with_mnemonic (
    "Enable statistics for logs");
  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(checkbox),
    purple_prefs_get_bool (
      "/plugins/gtk/autoprofile/components/logstat/enabled"));
  gtk_box_pack_start (GTK_BOX(ret), checkbox, FALSE, FALSE, 0);

  vbox = gtk_vbox_new (FALSE, 6);
  gtk_box_pack_start (GTK_BOX(ret), vbox, TRUE, TRUE, 0);

  /* Le format string */
  label = gtk_label_new (NULL);
  gtk_label_set_markup (GTK_LABEL(label), "<b>Format string for output</b>");
  gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
  gtk_box_pack_start (GTK_BOX(vbox), label, FALSE, FALSE, 0);

  entry = gtk_entry_new ();
  gtk_box_pack_start (GTK_BOX(vbox), entry, FALSE, FALSE, 0);
  gtk_entry_set_max_length (GTK_ENTRY(entry), 1000);
  gtk_entry_set_text (GTK_ENTRY(entry), purple_prefs_get_string (
    "/plugins/gtk/autoprofile/components/logstat/format"));
  g_signal_connect (G_OBJECT (entry), "focus-out-event",
                    G_CALLBACK (logstat_format), NULL);

  label = gtk_label_new (_(
    "%R\tTotal messages received\n"
    "%r\tTotal words received\n"
    "%S\tTotal messages sent\n"
    "%s\tTotal words sent\n"
    "%T\tTotal messages sent/received\n"
    "%t\tTotal words sent/received\n"
    "%D\tNumber of days since first logged conversation\n"
    "%d\tNumber of days with logged conversations\n"
    "%N\tNumber of logged conversations\n"
    "%n\tAverage number of conversations per day with logs\n"
    "%i\tMost conversations in a single day\n"
    "%I\tDate with most conversations\n"
    "%j\tMost messages sent in a single day\n"
    "%J\tDate with most messages sent\n"
    "%k\tMost messages received in a single day\n"
    "%K\tDate with most messages received\n"
    "%l\tMost total messages sent/received in a single day\n"
    "%L\tDate with most total messages sent/received\n"
    "%f\tDate of first logged conversation\n"
    "%u\tAverage words per message received\n"
    "%v\tAverage words per message sent\n"
    "%w\tAverage words per message sent/received\n"
    "%U\tAverage messages received per conversation\n"
    "%V\tAverage messages sent per conversation\n"
    "%W\tAverage messages sent/received per conversation\n"
    "%x\tAverage words received per day with logs\n"
    "%y\tAverage words sent per day with logs\n"
    "%z\tAverage words sent/received per day with logs\n"
    "%X\tAverage messages received per day with logs\n"
    "%Y\tAverage messages sent per day with logs\n"
    "%Z\tAverage messages sent/received per day with logs\n"
    "%p\tPercentage of days with logs\n"
    "%a\tNumber of messages received today\n"
    "%b\tNumber of messages sent today\n"
    "%c\tNumber of conversations started today\n"
    "%e\tNumber of messages sent/received today\n"
    "%A\tNumber of messages received in last week\n"
    "%B\tNumber of messages sent in last week\n"
    "%C\tNumber of conversations started in last week\n"
    "%E\tNumber of messages sent/received in last week\n"
    "%%\t%"));

  gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
  sw = gtk_scrolled_window_new (NULL,NULL);
  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
    GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
  gtk_box_pack_start (GTK_BOX (vbox), sw, TRUE, TRUE , 0);
  gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW(sw), label);

  /* Aliases */
  label = gtk_label_new (NULL);
  gtk_label_set_markup (GTK_LABEL(label), "<b>Personal aliases</b>");
  gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
  gtk_box_pack_start (GTK_BOX(vbox), label, FALSE, FALSE, 0);

  label = gtk_label_new (NULL);
  gtk_label_set_markup (GTK_LABEL(label), 
    "You need this if you have an alias for your own screen name,\n"
    "else IM's you sent will be incorrectly counted as received");
  gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
  gtk_box_pack_start (GTK_BOX(vbox), label, FALSE, FALSE, 0);

  hbox = gtk_hbox_new (FALSE, 3);
  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);

  button = gtk_button_new_with_label (_("Add alias"));
  g_signal_connect (G_OBJECT(button), "clicked",
    G_CALLBACK (alias_add), NULL);
  gtk_box_pack_start (GTK_BOX(hbox), button, TRUE, TRUE, 0); 
  button = gtk_button_new_with_label (_("Delete alias"));
  g_signal_connect (G_OBJECT(button), "clicked",
    G_CALLBACK (alias_delete), NULL);
  gtk_box_pack_start (GTK_BOX(hbox), button, TRUE, TRUE, 0); 
  button = gtk_button_new_with_label (_("?"));
  g_signal_connect (G_OBJECT(button), "clicked",
    G_CALLBACK (alias_what), NULL);
  gtk_box_pack_start (GTK_BOX(hbox), button, FALSE, FALSE, 0); 

  sw = gtk_scrolled_window_new (0, 0);
  gtk_box_pack_start (GTK_BOX(vbox), sw, FALSE, FALSE, 0);
  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW(sw),
    GTK_POLICY_NEVER, GTK_POLICY_NEVER);
  gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW(sw),
    GTK_SHADOW_IN);

  alias_list = gtk_list_store_new (1, G_TYPE_STRING);  
  alias_view = gtk_tree_view_new_with_model (GTK_TREE_MODEL (alias_list));
  gtk_container_add (GTK_CONTAINER(sw), alias_view);
 
  renderer = gtk_cell_renderer_text_new ();
  gtk_tree_view_set_headers_visible (GTK_TREE_VIEW(alias_view), FALSE);
  selection = gtk_tree_view_get_selection (
    GTK_TREE_VIEW (alias_view));
  gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);

  col = gtk_tree_view_column_new_with_attributes (
    _("Alias"), renderer, "text", 0, NULL);
  gtk_tree_view_append_column (GTK_TREE_VIEW(alias_view), col);

  aliases = purple_prefs_get_string_list (
    "/plugins/gtk/autoprofile/components/logstat/aliases");
  aliases_start = aliases;

  while (aliases) {
    gtk_list_store_append (alias_list, &iter);
    gtk_list_store_set (alias_list, &iter,
      0, (char *)aliases->data, -1);
    aliases = aliases->next;
  }
  free_string_list (aliases_start);

  /* Finish up the checkbox stuff */
  g_signal_connect (G_OBJECT(checkbox), "clicked",
    G_CALLBACK(toggle_enable), vbox);
  if (!purple_prefs_get_bool (
    "/plugins/gtk/autoprofile/components/logstat/enabled")) {
    gtk_widget_set_sensitive (vbox, FALSE);
  } else {
    gtk_widget_set_sensitive (vbox, TRUE);
  }

  return ret;
}
Example #21
0
/*
 * Used to set config parameters.
 * Line format "= name value"
 */
static void
_aslmanager_set_param(asl_out_dst_data_t *dst, char *s)
{
	char **l;
	uint32_t count;

	if (s == NULL) return;
	if (s[0] == '\0') return;

	/* skip '=' and whitespace */
	if (*s == '=') s++;
	while ((*s == ' ') || (*s == '\t')) s++;

	l = explode(s, " \t");
	if (l == NULL) return;

	for (count = 0; l[count] != NULL; count++);

	/* name is required */
	if (count == 0)
	{
		free_string_list(l);
		return;
	}

	/* value is required */
	if (count == 1)
	{
		free_string_list(l);
		return;
	}

	if (!strcasecmp(l[0], "aslmanager_debug"))
	{
		/* = debug level */
		set_debug(DEBUG_ASL, l[1]);
	}
	else if (!strcasecmp(l[0], "store_ttl"))
	{
		/* = store_ttl days */
		dst->ttl[LEVEL_ALL] = (time_t)atoll(l[1]);
	}
	else if (!strcasecmp(l[0], "module_ttl"))
	{
		/* = module_ttl days */
		module_ttl = (time_t)atoll(l[1]);
	}
	else if (!strcasecmp(l[0], "max_store_size"))
	{
		/* = max_file_size bytes */
		dst->all_max = atoi(l[1]);
	}
	else if (!strcasecmp(l[0], "archive"))
	{
		free(dst->rotate_dir);
		dst->rotate_dir = NULL;

		/* = archive {0|1} path */
		if (!strcmp(l[1], "1"))
		{
			if (l[2] == NULL) dst->rotate_dir = strdup(PATH_ASL_ARCHIVE);
			else dst->rotate_dir = strdup(l[2]);
		}
	}
	else if (!strcasecmp(l[0], "store_path"))
	{
		/* = archive path */
		free(dst->path);
		dst->path = strdup(l[1]);
	}
	else if (!strcasecmp(l[0], "archive_mode"))
	{
		dst->mode = strtol(l[1], NULL, 0);
		if ((dst->mode == 0) && (errno == EINVAL)) dst->mode = 0400;
	}

	free_string_list(l);
}