问:
Find maximum subtree in the given BST such that it has no duplicates
Given the BST which allows duplicates as separate vertices, how do I find the highest subtree such that it has no duplicates.

This is the idea:
(1) Check if the root value appears in its right subtree (inserting this way: left < root <= right). If not, tree has no duplicates. I look for it always on the left from the root's child.
(2) Traversing and doing (1) I can find all subtrees without duplicates, storing their root pointer and height.
(3) Comparing heights I can find largest seeked subtree.

I don't know how to store these information while traversing. I found programs for finding all duplicate subtrees of BST that use hash maps, but if possible I would  prefer to avoid using hash maps, as I haven't had them on my course yet.

```<code><!-- language: lang-c -->

typedef struct vertex {
    int data;
    struct vertex *left;
    struct vertex *right;
} vertex, *pvertex;

// Utility functions

int Height(pvertex t){
    if (t == NULL)
        return 0;
    if (Height(t->left) > Height(t->right))
        return Height(t->left) + 1;
    else
        return Height(t->right) + 1;
}

int DoesItOccur(pvertex t, int k){
    if(!t)
        return 0;
    if(t->data==k)
        return 1;
    if(t->data<k){
        return DoesItOccur(t->left,k);
    }
}

// My function
pvertex MaxSeeked(pvertex t){
    if(!t)
        return NULL;
    if(DoesItOccur(t->right,t->data)==0)
        return t;
    else if{
        if(t->left && t->right){
            if(Height(MaxSeeked(t->left))>Height(MaxSeeked(t->right)))
                return t->left;
            else
                return t->right;
        }
    }
    else if{
    ......
    }
}
</code>```

答:
I don't know how to store these information while traversing. I found programs for finding all duplicate subtrees of BST that use hash maps, but if possible I would prefer to avoid using hash maps, as I haven't had them on my course yet.

Note in the first place that you only need to track all the subtrees of the maximal height discovered so far.  Or maybe you can limit that to just one such, if that's all you need to discover.  For efficiency, you should also track what that maximal height actually is.

I'll suppose that you must not add members to your node structure, but if you could do, you could add a member or two wherein to record whether the tree rooted at each node contains any dupes, and how high that tree is.  You could populate those data as you go, and remember what the maximum height is, then make a second traversal to collect the nodes.

But without modifying any nodes themselves, you can still track the current candidates by other means, such as a linked list.  And you can put whatever metadata you want into the tracking data structure.  For example,

```<code>struct nondupe_subtree {
    struct vertex *root;
    int height;
    struct nondupe_subtree *next;
};
</code>```

You can then, say, perform a selective traversal of your tree in breadth first order, carrying along a linked list of struct nondupe_subtree nodes:

Start by visiting the root node.

Test the subtree rooted at each visited node to see whether it contains any dupes, according to the procedure you have described.

If so then enqueue its children for traversal.

If not then measure the subtree height and update your linked list (or not) accordingly.  Do not enqueue this node's children.

When no more nodes are enqueued for traversal, you linked list contains the roots of all the maximal height subtrees without dupes.

Note that that algorithm would in many cases be significantly sped if you could compute and store all the subtree heights in an initial DFS pass, for it is otherwise prone to performing duplicate tree-height computations.  Many of them, in some cases.

Note also that although it does simplify this particular algorithm, your rule for always putting dupes to the right works against balanced trees, which may also yield reduced performance.  In the worst case, where are vertices are duplicate, your "tree" will perforce be linear.

Body:
Given the BST which allows duplicates as separate vertices, how do I find the highest subtree such that it has no duplicates.

This is the idea:
(1) Check if the root value appears in its right subtree (inserting this way: left < root <= right). If not, tree has no duplicates. I look for it always on the left from the root's child.
(2) Traversing and doing (1) I can find all subtrees without duplicates, storing their root pointer and height.
(3) Comparing heights I can find largest seeked subtree.

I don't know how to store these information while traversing. I found programs for finding all duplicate subtrees of BST that use hash maps, but if possible I would  prefer to avoid using hash maps, as I haven't had them on my course yet.

typedef struct vertex {
    int data;
    struct vertex *left;
    struct vertex *right;
} vertex, *pvertex;

// Utility functions

int Height(pvertex t){
    if (t == NULL)
        return 0;
    if (Height(t->left) > Height(t->right))
        return Height(t->left) + 1;
    else
        return Height(t->right) + 1;
}

int DoesItOccur(pvertex t, int k){
    if(!t)
        return 0;
    if(t->data==k)
        return 1;
    if(t->data<k){
        return DoesItOccur(t->left,k);
    }
}

// My function
pvertex MaxSeeked(pvertex t){
    if(!t)
        return NULL;
    if(DoesItOccur(t->right,t->data)==0)
        return t;
    else if{
        if(t->left && t->right){
            if(Height(MaxSeeked(t->left))>Height(MaxSeeked(t->right)))
                return t->left;
            else
                return t->right;
        }
    }
    else if{
    ......
    }
}

Body:
I don't know how to store these information while traversing. I found programs for finding all duplicate subtrees of BST that use hash maps, but if possible I would prefer to avoid using hash maps, as I haven't had them on my course yet.

Note in the first place that you only need to track all the subtrees of the maximal height discovered so far.  Or maybe you can limit that to just one such, if that's all you need to discover.  For efficiency, you should also track what that maximal height actually is.

I'll suppose that you must not add members to your node structure, but if you could do, you could add a member or two wherein to record whether the tree rooted at each node contains any dupes, and how high that tree is.  You could populate those data as you go, and remember what the maximum height is, then make a second traversal to collect the nodes.

But without modifying any nodes themselves, you can still track the current candidates by other means, such as a linked list.  And you can put whatever metadata you want into the tracking data structure.  For example,

struct nondupe_subtree {
    struct vertex *root;
    int height;
    struct nondupe_subtree *next;
};

You can then, say, perform a selective traversal of your tree in breadth first order, carrying along a linked list of struct nondupe_subtree nodes:

Start by visiting the root node.

Test the subtree rooted at each visited node to see whether it contains any dupes, according to the procedure you have described.

If so then enqueue its children for traversal.

If not then measure the subtree height and update your linked list (or not) accordingly.  Do not enqueue this node's children.

When no more nodes are enqueued for traversal, you linked list contains the roots of all the maximal height subtrees without dupes.

Note that that algorithm would in many cases be significantly sped if you could compute and store all the subtree heights in an initial DFS pass, for it is otherwise prone to performing duplicate tree-height computations.  Many of them, in some cases.

Note also that although it does simplify this particular algorithm, your rule for always putting dupes to the right works against balanced trees, which may also yield reduced performance.  In the worst case, where are vertices are duplicate, your "tree" will perforce be linear.


来源: stackexchange

问:
How can I send command line arguments to a malloc array, and then send those arguments from a parent process to a child process
This is for a school assignment, and I know this is about a simple problem as there is, but for the life of me I can't figure out what I am doing wrong.

In the parent process, I need to convert cmdline arguments to integers, then store the arguments in a malloc array. I then need to send each integer to the child process one at a time. The child process will then sum all of the integers passed from the parent process. Once the summation is complete, it will return the sum to the parent process. The parent process then prints out the sum.

There are 3 things I do not understand about this code.

Taking command line arguments, converting them into integers, and storing them using a pointer to a malloc array. I do not understand why I can't just write this in my parent process:

```<code>  int* numArray = (int*) malloc (argc * sizeof(int));
  for(int i = 0; i < argc; ++i){
     numArray[i] = atoi(argv[i+1]);
  }
</code>```

How can I send individual values to child process for summation? I can read them one at a time, and then increment sum by the value in sumBuf. Then sumBuf gets overwritten with the next value, and increments sum by sumBuf again. How can I do this?

How can I access the child's return value in the parent process?

Storing the integers in the malloc array yields a segmentation fault, and I do not understand how to correct this. also, since fork returns the child's PID, if the child returns a sum, shouldn't the sum be the child's PID?

For the malloc array I have tried de-referencing numArray inside the for loop like:

```<code>   *numArray[i] = atoi(argv[i+1])
</code>```

I have tried writing individual values to the pipe within a for loop

I know that fork returns the child PID value, so if child returns sum, shouldn't sum = p, store sum into the parent's sum value?

```<code>int main(int argc, char **argv){
  int *numArray = (int*) malloc (argc * sizeof(int));
  pid_t p;
  int fd[2];
  pipe(fd);
  p = fork()
  //error checks

  if(p == 0){//child process
       int sum = 0;
       int sumBuf = 0;
       close(fd[1]);//close write end
       for(int i = 0; i < argc; ++i){
           read(fd[0], sumBuf, sizeof(int));
           sum += sumBuf;
       }
       close(fd[0]);//close read end
       return sum;//return sum from child process
   }
   else{//parent process
       int sum = 0;
       close(fd[0]);//close read end
       for(int i = 0; i < argc; ++i){
           numArray[i] = atoi(argv[i+1]);
           write(fd[1], numArray[i], sizeof(int));
       }
       close(fd[1]);//close write end of pipe
       sum = p;
       printf("Sum = %d", sum);
       return 0;
   }
   free(numArray);
   return 0;
}
</code>```

I get a segmentation fault message when I try to run this program. Please don't call me stupid, I understand the idea of what to do, but I don't understand how to implement it..

答:
Before getting to the main thing… I assume you have put #include <stdlib.h> (as well as <stdio.h> and <unistd.h>) there.

This:

```<code>int *numArray = (int*) malloc (argc * sizeof(int));
</code>```

can be replaced with a better alternative:

```<code>int *numArray = malloc(argc * sizeof *numArray);
</code>```

The cast is unnecessary. Also, using sizeof *pointer is better as if you need
to change the data type pointed by the array, you won’t need to change the
sizeof. Also, if you forget to #include <stdlib.h>, malloc() will return an int. Putting the cast basically tells the compiler to be quiet about it. If you don’t put the cast, you will get a diagnostic message.

As a matter of good habit, it’s also better to check the return value of the
malloc(), e.g.

```<code>if (!numArray) {
    return EXIT_FAILURE;
}
</code>```

Also, strtol() is better than atoi() as the former provides error checking.

Nitpick: You need to put ; after fork().

If you need to send back a value from the child to the parent, you can’t do what
you did: sum = p;. Instead, you should create another pipe if the operating
system doesn’t support bidirectional pipes (probably safer to assume this). I
leave this as an exercise for you.

Now, write() and read() need their second argument a pointer. So, for
example, the read() should be:

```<code>read(fd[0], &sumBuf, sizeof sumBuf);
</code>```

Similarly for the write().

I don’t get what you mean by why you couldn’t just write the malloc() in the
parent process. You certainly can, and it’s better as the child, as I
understand, should have no access to the allocated memory.

Now, the most likely cause of the segfault is the undefined behaviour caused by
reading past array bound. In this case, argv. This is probably easier to
explain using an example:

If you run it this way:

```<code>./a.out 1 2 3
</code>```

argc will be 4, meaning that you can only access argv[0] to argv[3]. Now,
here’s a hint: look at the loops.

ContentLicense: CC BY-SA 4.0

Body:
This is for a school assignment, and I know this is about a simple problem as there is, but for the life of me I can't figure out what I am doing wrong.

In the parent process, I need to convert cmdline arguments to integers, then store the arguments in a malloc array. I then need to send each integer to the child process one at a time. The child process will then sum all of the integers passed from the parent process. Once the summation is complete, it will return the sum to the parent process. The parent process then prints out the sum.

There are 3 things I do not understand about this code.

Taking command line arguments, converting them into integers, and storing them using a pointer to a malloc array. I do not understand why I can't just write this in my parent process:

  int* numArray = (int*) malloc (argc * sizeof(int));
  for(int i = 0; i < argc; ++i){
     numArray[i] = atoi(argv[i+1]);
  }

How can I send individual values to child process for summation? I can read them one at a time, and then increment sum by the value in sumBuf. Then sumBuf gets overwritten with the next value, and increments sum by sumBuf again. How can I do this?

How can I access the child's return value in the parent process?

Storing the integers in the malloc array yields a segmentation fault, and I do not understand how to correct this. also, since fork returns the child's PID, if the child returns a sum, shouldn't the sum be the child's PID?

For the malloc array I have tried de-referencing numArray inside the for loop like:

   *numArray[i] = atoi(argv[i+1])

I have tried writing individual values to the pipe within a for loop

I know that fork returns the child PID value, so if child returns sum, shouldn't sum = p, store sum into the parent's sum value?

int main(int argc, char **argv){
  int *numArray = (int*) malloc (argc * sizeof(int));
  pid_t p;
  int fd[2];
  pipe(fd);
  p = fork()
  //error checks

  if(p == 0){//child process
       int sum = 0;
       int sumBuf = 0;
       close(fd[1]);//close write end
       for(int i = 0; i < argc; ++i){
           read(fd[0], sumBuf, sizeof(int));
           sum += sumBuf;
       }
       close(fd[0]);//close read end
       return sum;//return sum from child process
   }
   else{//parent process
       int sum = 0;
       close(fd[0]);//close read end
       for(int i = 0; i < argc; ++i){
           numArray[i] = atoi(argv[i+1]);
           write(fd[1], numArray[i], sizeof(int));
       }
       close(fd[1]);//close write end of pipe
       sum = p;
       printf("Sum = %d", sum);
       return 0;
   }
   free(numArray);
   return 0;
}

I get a segmentation fault message when I try to run this program. Please don't call me stupid, I understand the idea of what to do, but I don't understand how to implement it..

Body:
Before getting to the main thing… I assume you have put #include <stdlib.h> (as well as <stdio.h> and <unistd.h>) there.

This:

int *numArray = (int*) malloc (argc * sizeof(int));

can be replaced with a better alternative:

int *numArray = malloc(argc * sizeof *numArray);

The cast is unnecessary. Also, using sizeof *pointer is better as if you need
to change the data type pointed by the array, you won’t need to change the
sizeof. Also, if you forget to #include <stdlib.h>, malloc() will return an int. Putting the cast basically tells the compiler to be quiet about it. If you don’t put the cast, you will get a diagnostic message.

As a matter of good habit, it’s also better to check the return value of the
malloc(), e.g.

if (!numArray) {
    return EXIT_FAILURE;
}

Also, strtol() is better than atoi() as the former provides error checking.

Nitpick: You need to put ; after fork().

If you need to send back a value from the child to the parent, you can’t do what
you did: sum = p;. Instead, you should create another pipe if the operating
system doesn’t support bidirectional pipes (probably safer to assume this). I
leave this as an exercise for you.

Now, write() and read() need their second argument a pointer. So, for
example, the read() should be:

read(fd[0], &sumBuf, sizeof sumBuf);

Similarly for the write().

I don’t get what you mean by why you couldn’t just write the malloc() in the
parent process. You certainly can, and it’s better as the child, as I
understand, should have no access to the allocated memory.

Now, the most likely cause of the segfault is the undefined behaviour caused by
reading past array bound. In this case, argv. This is probably easier to
explain using an example:

If you run it this way:

./a.out 1 2 3

argc will be 4, meaning that you can only access argv[0] to argv[3]. Now,
here’s a hint: look at the loops.


问:
Wicked PDF header not showing up
After already checking the Rails Gem repository for similar issues as well as Stack Overflow, I couldn't find an answer to my problem.

I'm trying to render a pdf using wicked_pdf within a Rails controller, but the header is not showing up, no matter what I do or which recommended solutions to similar issues I follow.

First and foremost, here is the development console output:

```<code>***************WICKED***************
  Rendering biddings/show.pdf.html.haml within layouts/pdf
  Rendered biddings/show.pdf.html.haml within layouts/pdf (0.7ms)
  Rendering biddings/header_pdf.html.haml within layouts/pdf_header
  Rendered biddings/header_pdf.html.haml within layouts/pdf_header (1.9ms)
"***************[\"/home/tommy/.rvm/gems/ruby-
 2.5.1@igalbids/bin/wkhtmltopdf\", \"-q\", \"--encoding\", \"UTF-8\",
  \"--javascript-delay\", \"500\",
  \"--disable-internal-links\", \"--disable-external-links\",
  \"--orientation\", \"Portrait\", \"--margin-top\",
  \"50\", \"--margin-bottom\", \"25\", \"--header-html\",
  \"file:////tmp/wicked_header_pdf20180801-27285-b8y5sg.html\",
  \"--footer-right\", \"Página [page] de [topage]\",
  \"file:////tmp/wicked_pdf20180801-27285-1jfgdd7.html\",
  \"/tmp/wicked_pdf_generated_file20180801-27285-1bkrvhx.pdf\"]***************"
  Rendering text template
  Rendered text template (0.1ms)
Sent data Licitación_2524.pdf (0.6ms)
Completed 200 OK in 2334ms (Views: 0.5ms | ActiveRecord: 64.4ms)
</code>```

As you can see, both the header layout and its contents are being rendered and processed, however they don't make the final output PDF, and I don't know why! Look:

So, here's my controller code:

```<code>class Api::V1::Biddings::PdfBiddingsController < PdfController
  # JWT Authentication enforced
  before_action :authenticate_user!

  # GET /biddings/:id/pdf
  def show
    @bidding = scoped_collection.find(params[:id])

    authorize [:biddings, :pdf, @bidding]
    respond_to do |format|
      format.pdf do
        render(
          pdf: "#{Bidding.model_name.human}_#{@bidding.code}",
          disposition: "inline",
          orientation: "Portrait",
          template: 'biddings/show.pdf.html.haml',
          header: {
            html: {
              template: "biddings/header_pdf.html.haml",
              handlers: [:haml],
              layout: "pdf_header",
              formats: [:haml, :html]
            }
          },
          footer: {
            html: {
              handlers: [:haml],
              layout: "pdf",
              formats: [:haml, :html],
              encoding: 'UTF-8'
            },
            right: "#{I18n.t('pdf.page')} [page] #{I18n.t('pdf.of')} [topage]"
          },
          margin: { :top => 50, :bottom => 25},
          handlers: [:haml],
          layout: "pdf",
          javascript_delay: 500,
          encoding: 'UTF-8',
          show_as_html: false,
          disable_internal_links: true,
          disable_external_links: true) and return
      end
    end
  end

  protected
  def self.model
    Bidding
  end

  private
  def scoped_collection
    policy_scope([:biddings, :pdf, Bidding]).includes(:bidding_type, :client, :payment_condition, :price_list, :real_payment_condition, :sales_man, :user)
  end

  def records_per_page
    params[:per_page] || 10
  end
end
</code>```

Nothing fancy, there you can see all the config options, pretty standard. Needless to say, the footer with the page numbering IS working fine (screenshot too long to show, but trust me). Can't say the same about the header.

Here's the PDF header layout file:

pdf_header.html.haml:

```<code>!!! 5
%html
  %head
    %meta{:content => "text/html; charset=utf-8", "http-equiv" => "content-type"}/
    = wicked_pdf_stylesheet_link_tag "bidding_pdf", media: :all
    = csrf_meta_tags
  %body.pdf
    = yield
</code>```

and here the contents for the header "contents" per se:

header_pdf.html.haml:

```<code>Test text
</code>```

Just plain text. I have a Linux 16.04 x64 OS, wicked_pdf (1.1.0), wkhtmltopdf-binary (0.12.4). How can I debug this?

答:
Upgrade wkhtmltopdf binary to at least version "0.12.4 (with patched qt)". I just spent half a day troubleshooting because my version of 0.12.1 did not support header and footer.

Ref: Wicked pdf not rendering header/footer

Title: Wicked PDF header not showing up

Body:
After already checking the Rails Gem repository for similar issues as well as Stack Overflow, I couldn't find an answer to my problem.

I'm trying to render a pdf using wicked_pdf within a Rails controller, but the header is not showing up, no matter what I do or which recommended solutions to similar issues I follow.

First and foremost, here is the development console output:

***************WICKED***************
  Rendering biddings/show.pdf.html.haml within layouts/pdf
  Rendered biddings/show.pdf.html.haml within layouts/pdf (0.7ms)
  Rendering biddings/header_pdf.html.haml within layouts/pdf_header
  Rendered biddings/header_pdf.html.haml within layouts/pdf_header (1.9ms)
"***************[\"/home/tommy/.rvm/gems/ruby-
 2.5.1@igalbids/bin/wkhtmltopdf\", \"-q\", \"--encoding\", \"UTF-8\",
  \"--javascript-delay\", \"500\",
  \"--disable-internal-links\", \"--disable-external-links\",
  \"--orientation\", \"Portrait\", \"--margin-top\",
  \"50\", \"--margin-bottom\", \"25\", \"--header-html\",
  \"file:////tmp/wicked_header_pdf20180801-27285-b8y5sg.html\",
  \"--footer-right\", \"Página [page] de [topage]\",
  \"file:////tmp/wicked_pdf20180801-27285-1jfgdd7.html\",
  \"/tmp/wicked_pdf_generated_file20180801-27285-1bkrvhx.pdf\"]***************"
  Rendering text template
  Rendered text template (0.1ms)
Sent data Licitación_2524.pdf (0.6ms)
Completed 200 OK in 2334ms (Views: 0.5ms | ActiveRecord: 64.4ms)

As you can see, both the header layout and its contents are being rendered and processed, however they don't make the final output PDF, and I don't know why! Look:

So, here's my controller code:

class Api::V1::Biddings::PdfBiddingsController < PdfController
  # JWT Authentication enforced
  before_action :authenticate_user!

  # GET /biddings/:id/pdf
  def show
    @bidding = scoped_collection.find(params[:id])

    authorize [:biddings, :pdf, @bidding]
    respond_to do |format|
      format.pdf do
        render(
          pdf: "#{Bidding.model_name.human}_#{@bidding.code}",
          disposition: "inline",
          orientation: "Portrait",
          template: 'biddings/show.pdf.html.haml',
          header: {
            html: {
              template: "biddings/header_pdf.html.haml",
              handlers: [:haml],
              layout: "pdf_header",
              formats: [:haml, :html]
            }
          },
          footer: {
            html: {
              handlers: [:haml],
              layout: "pdf",
              formats: [:haml, :html],
              encoding: 'UTF-8'
            },
            right: "#{I18n.t('pdf.page')} [page] #{I18n.t('pdf.of')} [topage]"
          },
          margin: { :top => 50, :bottom => 25},
          handlers: [:haml],
          layout: "pdf",
          javascript_delay: 500,
          encoding: 'UTF-8',
          show_as_html: false,
          disable_internal_links: true,
          disable_external_links: true) and return
      end
    end
  end

  protected
  def self.model
    Bidding
  end

  private
  def scoped_collection
    policy_scope([:biddings, :pdf, Bidding]).includes(:bidding_type, :client, :payment_condition, :price_list, :real_payment_condition, :sales_man, :user)
  end

  def records_per_page
    params[:per_page] || 10
  end
end

Nothing fancy, there you can see all the config options, pretty standard. Needless to say, the footer with the page numbering IS working fine (screenshot too long to show, but trust me). Can't say the same about the header.

Here's the PDF header layout file:

pdf_header.html.haml:

!!! 5
%html
  %head
    %meta{:content => "text/html; charset=utf-8", "http-equiv" => "content-type"}/
    = wicked_pdf_stylesheet_link_tag "bidding_pdf", media: :all
    = csrf_meta_tags
  %body.pdf
    = yield

and here the contents for the header "contents" per se:

header_pdf.html.haml:

Test text

Just plain text. I have a Linux 16.04 x64 OS, wicked_pdf (1.1.0), wkhtmltopdf-binary (0.12.4). How can I debug this?


问:
Duplicate entries in the list
Having to enter 8 unique entries, logic should detect if any entry is duplicate otherwise continue until all 8 entries are entered.

I've played around with the For loop but it seems to not give me desired output, i want to go back to last entry if duplicate entry is scanned instead it will give a message "Duplicate SCAN, please rescan" but also the counter moves on.

sorry, i'm new to this i thought i've included code. Hoping it goes through this time.

```<code>x=1
mac_list = []
while (x <=8):
    MAC1 = input("SCAN MAC"+str(x)+":")

for place in mac_list:

    print (mac_list)
    if place==MAC1:
        print ("place"+place)
        print ("Duplicate SCAN, please rescan")
else:
    mac_list.append(MAC1)
    x+=1
</code>```

答:
Would something like this not work?

Sets can only hold unique elements and thus remove any duplicates by default - that should solve a lot of your worries. This should work better for larger datasets over elementwise comparison.

```<code>entries = set()

while len(entries)<8:
    entries = entries ^ set([input("You do not have enough unique items yet, add another")])
</code>```

To detect a change you can have an old list and a new one:

```<code>entries = set()
new=set()

while True:

    latest = input("You do not have enough unique items yet, add another")
    new = entries ^ set([latest])
    if len(new) == len(entries):
        print("you entered a duplicate:",latest, " Please rescan")
    else:
        entries = new
        if len(entries) == 8 : break

</code>```

Title: Duplicate entries in the list

Body:
Having to enter 8 unique entries, logic should detect if any entry is duplicate otherwise continue until all 8 entries are entered.

I've played around with the For loop but it seems to not give me desired output, i want to go back to last entry if duplicate entry is scanned instead it will give a message "Duplicate SCAN, please rescan" but also the counter moves on.

sorry, i'm new to this i thought i've included code. Hoping it goes through this time.

x=1
mac_list = []
while (x <=8):
    MAC1 = input("SCAN MAC"+str(x)+":")

for place in mac_list:

    print (mac_list)
    if place==MAC1:
        print ("place"+place)
        print ("Duplicate SCAN, please rescan")
else:
    mac_list.append(MAC1)
    x+=1

Body:
Would something like this not work?

Sets can only hold unique elements and thus remove any duplicates by default - that should solve a lot of your worries. This should work better for larger datasets over elementwise comparison.

entries = set()

while len(entries)<8:
    entries = entries ^ set([input("You do not have enough unique items yet, add another")])

To detect a change you can have an old list and a new one:

entries = set()
new=set()

while True:

    latest = input("You do not have enough unique items yet, add another")
    new = entries ^ set([latest])
    if len(new) == len(entries):
        print("you entered a duplicate:",latest, " Please rescan")
    else:
        entries = new
        if len(entries) == 8 : break


问:
No password for Azure sandbox supplied in Python tutorial
I am using the Intro to Python docs
In Unit 3, when I click Activate sandbox, I get a message

Microsoft Learn needs your permission to create Azure resources

When I click

Review Permissions

I get an Azure login screen with a new user name. I have not been told the password, so I can't sign in.

答: You have to create a Microsoft Account first (https://account.microsoft.com/account?lang=en-us), then grant Microsoft Learn access via Review Permissions to begin allocating Azure resources.</p>


问:
Partition column disappears in result set dataframe Spark
I tried to split Spark data frame by the timestamp column update_database_time and write it into HDFS with defined Avro schema. However, after calling the repartition method  I get this exception:

```<code>Caused by: org.apache.spark.sql.avro.IncompatibleSchemaException: Cannot convert Catalyst type StructType(StructField(random_pk,DecimalType(38,0),true), StructField(random_string,StringType,true), StructField(code,StringType,true), StructField(random_bool,BooleanType,true), StructField(random_int,IntegerType,true), StructField(random_float,DoubleType,true), StructField(random_double,DoubleType,true), StructField(random_enum,StringType,true), StructField(random_date,DateType,true), StructField(random_decimal,DecimalType(4,2),true), StructField(update_database_time_tz,TimestampType,true), StructField(random_money,DecimalType(19,4),true)) to Avro type {"type":"record","name":"TestData","namespace":"DWH","fields":[{"name":"random_pk","type":["null",{"type":"bytes","logicalType":"decimal","precision":38,"scale":0}]},{"name":"random_string","type":["string","null"]},{"name":"code","type":["string","null"]},{"name":"random_bool","type":["boolean","null"]},{"name":"random_int","type":["int","null"]},{"name":"random_float","type":["double","null"]},{"name":"random_double","type":["double","null"]},{"name":"random_enum","type":["null",{"type":"enum","name":"enumType","symbols":["VAL_1","VAL_2","VAL_3"]}]},{"name":"random_date","type":["null",{"type":"int","logicalType":"date"}]},{"name":"random_decimal","type":["null",{"type":"bytes","logicalType":"decimal","precision":4,"scale":2}]},{"name":"update_database_time","type":["null",{"type":"long","logicalType":"timestamp-millis"}]},{"name":"update_database_time_tz","type":["null",{"type":"long","logicalType":"timestamp-millis"}]},{"name":"random_money","type":["null",{"type":"bytes","logicalType":"decimal","precision":19,"scale":4}]}]}.
</code>```

I assume that the column for partitioning disappears in the result. How can I redefine the operation so it would not happen?

Here is the code I use:

```<code>    dataDF.write
      .partitionBy("update_database_time")
      .format("avro")
      .option(
        "avroSchema",
        SchemaRegistry.getSchema(
          schemaRegistryConfig.url,
          schemaRegistryConfig.dataSchemaSubject,
          schemaRegistryConfig.dataSchemaVersion))
  .save(s"${hdfsURL}${pathToSave}")
</code>```

答:
By the exception you have provided, the error seems to stem from incompatible schemas between the fetched AVRO schema and Spark's schema. Taking a quick look, the most worrisome parts are probably these ones:

(Possibly catalyst doesn't know how to transform string into enumType)

Spark schema:

```<code>StructField(random_enum,StringType,true)
</code>```

AVRO schema:

```<code>{
      "name": "random_enum",
      "type": [
        "null",
        {
          "type": "enum",
          "name": "enumType",
          "symbols": [
            "VAL_1",
            "VAL_2",
            "VAL_3"
          ]
        }
      ]
    }
</code>```

(update_databse_time_tz appears only once in the dataframe's schema, but twice in the AVRO schema)

Spark schema:

```<code>StructField(update_database_time_tz,TimestampType,true)
</code>```

AVRO schema:

```<code>{
      "name": "update_database_time",
      "type": [
        "null",
        {
          "type": "long",
          "logicalType": "timestamp-millis"
        }
      ]
    },
    {
      "name": "update_database_time_tz",
      "type": [
        "null",
        {
          "type": "long",
          "logicalType": "timestamp-millis"
        }
      ]
    }
</code>```

I'd suggest to consolidate schemas first and get rid of that exception before going inside other possible partitioning problems.

EDIT: In regards to number 2 I've missed the face that there are different names in the AVRO schema, which leads to a problem of missing a column update_database_time in the Dataframe.

Body:
I tried to split Spark data frame by the timestamp column update_database_time and write it into HDFS with defined Avro schema. However, after calling the repartition method  I get this exception:

Caused by: org.apache.spark.sql.avro.IncompatibleSchemaException: Cannot convert Catalyst type StructType(StructField(random_pk,DecimalType(38,0),true), StructField(random_string,StringType,true), StructField(code,StringType,true), StructField(random_bool,BooleanType,true), StructField(random_int,IntegerType,true), StructField(random_float,DoubleType,true), StructField(random_double,DoubleType,true), StructField(random_enum,StringType,true), StructField(random_date,DateType,true), StructField(random_decimal,DecimalType(4,2),true), StructField(update_database_time_tz,TimestampType,true), StructField(random_money,DecimalType(19,4),true)) to Avro type {"type":"record","name":"TestData","namespace":"DWH","fields":[{"name":"random_pk","type":["null",{"type":"bytes","logicalType":"decimal","precision":38,"scale":0}]},{"name":"random_string","type":["string","null"]},{"name":"code","type":["string","null"]},{"name":"random_bool","type":["boolean","null"]},{"name":"random_int","type":["int","null"]},{"name":"random_float","type":["double","null"]},{"name":"random_double","type":["double","null"]},{"name":"random_enum","type":["null",{"type":"enum","name":"enumType","symbols":["VAL_1","VAL_2","VAL_3"]}]},{"name":"random_date","type":["null",{"type":"int","logicalType":"date"}]},{"name":"random_decimal","type":["null",{"type":"bytes","logicalType":"decimal","precision":4,"scale":2}]},{"name":"update_database_time","type":["null",{"type":"long","logicalType":"timestamp-millis"}]},{"name":"update_database_time_tz","type":["null",{"type":"long","logicalType":"timestamp-millis"}]},{"name":"random_money","type":["null",{"type":"bytes","logicalType":"decimal","precision":19,"scale":4}]}]}.

I assume that the column for partitioning disappears in the result. How can I redefine the operation so it would not happen?

Here is the code I use:

    dataDF.write
      .partitionBy("update_database_time")
      .format("avro")
      .option(
        "avroSchema",
        SchemaRegistry.getSchema(
          schemaRegistryConfig.url,
          schemaRegistryConfig.dataSchemaSubject,
          schemaRegistryConfig.dataSchemaVersion))
  .save(s"${hdfsURL}${pathToSave}")

Body:
By the exception you have provided, the error seems to stem from incompatible schemas between the fetched AVRO schema and Spark's schema. Taking a quick look, the most worrisome parts are probably these ones:

(Possibly catalyst doesn't know how to transform string into enumType)

Spark schema:

StructField(random_enum,StringType,true)

AVRO schema:

{
      "name": "random_enum",
      "type": [
        "null",
        {
          "type": "enum",
          "name": "enumType",
          "symbols": [
            "VAL_1",
            "VAL_2",
            "VAL_3"
          ]
        }
      ]
    }

(update_databse_time_tz appears only once in the dataframe's schema, but twice in the AVRO schema)

Spark schema:

StructField(update_database_time_tz,TimestampType,true)

AVRO schema:

{
      "name": "update_database_time",
      "type": [
        "null",
        {
          "type": "long",
          "logicalType": "timestamp-millis"
        }
      ]
    },
    {
      "name": "update_database_time_tz",
      "type": [
        "null",
        {
          "type": "long",
          "logicalType": "timestamp-millis"
        }
      ]
    }

I'd suggest to consolidate schemas first and get rid of that exception before going inside other possible partitioning problems.

EDIT: In regards to number 2 I've missed the face that there are different names in the AVRO schema, which leads to a problem of missing a column update_database_time in the Dataframe.


问:
How update/remove conda-forge channel from Anaconda?
I want to install Orange3 through conda. So I type in Anaconda Prompt

```<code>conda config --add channels confa-forge
</code>```

After that I try to install Orange3

```<code>conda install orange3
</code>```

But the Anaconda prompt show this error message

```<code>CondaHTTPEErroR: HTTP 404 NOT FOUND for url <https://conda.anaconda.org/confa-forge/noarch/repodata.json>
</code>```

So I realize that I write confa-forge instead conda-forge.

How can I delete the channel confa-forge? Or Can I update the channel to conda-forge?

答:
Also you can also check

http://conda-forge.org/docs/user/tipsandtricks.html#using-multiple-channels

To see your channels' priorities $conda config --describe channel_priority

Body:
I want to install Orange3 through conda. So I type in Anaconda Prompt

conda config --add channels confa-forge

After that I try to install Orange3

conda install orange3

But the Anaconda prompt show this error message

CondaHTTPEErroR: HTTP 404 NOT FOUND for url <https://conda.anaconda.org/confa-forge/noarch/repodata.json>

So I realize that I write confa-forge instead conda-forge.

How can I delete the channel confa-forge? Or Can I update the channel to conda-forge?


问:
IF condition expression evaluation in TSQL
In programming language like C#, java if a condition has multiple expressions with AND(&&) operator then the second expression is only evaluated if first expression is true.

What about in TSQL? To be specific this is a condition in a Stored procedure in Microsoft Sql server.

```<code>IF (exprA AND exprB)
</code>```

In the above condition if exprA is false then will the exprB is evaluated or not?

答: You can't rely on SQL Server not evaluating the second expression if the first one is false. See my answer to the question linked by Martin in his comment.</p>

ContentLicense: CC BY-SA 3.0

Body:
In programming language like C#, java if a condition has multiple expressions with AND(&&) operator then the second expression is only evaluated if first expression is true.

What about in TSQL? To be specific this is a condition in a Stored procedure in Microsoft Sql server.

IF (exprA AND exprB)

In the above condition if exprA is false then will the exprB is evaluated or not?


问:
Pyinstaller command not found (MacOS)
I've been trying to use PyInstaller on my program, scratch_1.py. The PyCharm project folder is called "idigen", which is saved in my desktop. So, I changed the director like so:

```<code>cd /Users/joelsaarinen/Desktop/idigen
</code>```

then, moved on to use pyinstaller, and I get this error:

```<code>pyinstaller scratch_1.py
-bash: pyinstaller: command not found
</code>```

I'm confused because when I use:

```<code>pip show pyinstaller
</code>```

to verify that I have pyinstaller installed, it returns a positive result.

Is there an additional command I should be putting in when using Pyinstaller on one of my files? Might this be an issue with this specific program or the operating system in general? Thanks in advance.

答:
This is a common problem due to the fact that you might install a different version of python and keep using an old version that is preinstalled in the machine. Here is the best solution.

First, check the version of the python that you installed. In my case, i installed python 3.5 and the machine had python2.7. If you run python on the terminal, most likely the preinstalled one is the one that will run.

Second, check the directory of your desired python version. watch -a python3 is the command to run to see your directory.

Third, set the directory as the main one to run your python commands.
alias python=/usr/local/bin/python3 does the whole trick

Lastly, reinstall pip. Download the get-pip.py file and run sudo /usr/local/bin/python3 get-pip.py * I used the path to show the reason we updated the alias*

Now you can run pyinstaller without problems

Title: Pyinstaller command not found (MacOS)

Body:
I've been trying to use PyInstaller on my program, scratch_1.py. The PyCharm project folder is called "idigen", which is saved in my desktop. So, I changed the director like so:

cd /Users/joelsaarinen/Desktop/idigen

then, moved on to use pyinstaller, and I get this error:

pyinstaller scratch_1.py
-bash: pyinstaller: command not found

I'm confused because when I use:

pip show pyinstaller

to verify that I have pyinstaller installed, it returns a positive result.

Is there an additional command I should be putting in when using Pyinstaller on one of my files? Might this be an issue with this specific program or the operating system in general? Thanks in advance.


问:
Backend return html but frontend does not redirect
I hit an api endpoint and I checked the network call responses with an html response with status code of 302. However, I don't see the redirect happening on the UI. The redirect is to another application (a different url)

```<code>export function callThis(payload) {
  const url = "some-path";
  const headers = getHeaders();
  return fetch(url, { method: 'POST', headers: headers, body:
      JSON.stringify(payload) })
  .then((response) => response.json());
}
</code>```

Is there something I'm missing?

答: try to help but with this snippet, you didn't show your "redirect part" if you are using reactjs you should have a look at DOM Router and using Redirect or push history. </p>

Body:
I hit an api endpoint and I checked the network call responses with an html response with status code of 302. However, I don't see the redirect happening on the UI. The redirect is to another application (a different url)

export function callThis(payload) {
  const url = "some-path";
  const headers = getHeaders();
  return fetch(url, { method: 'POST', headers: headers, body:
      JSON.stringify(payload) })
  .then((response) => response.json());
}

Is there something I'm missing?


问:
Is there a way to tell if a release is fired by a schedule in octopus
We have a project in Octopus that has been configured to release to an environment on a schedule.

In the process definition we use a step template for Slack to send the team a notification when a release takes place. We would like to avoid sending this Slack message if the release was fired by the schedule - rather than user initiated.

I was hoping there would be a system variable that we could check before running the Slack step - but I can't seem to find anything documented as such, and google didn't turn anything up.

TIA

答:
If you are using Octopus 2019.5.0 or later, there are two variables that will be populated if the deployment was created by a trigger.

Octopus.Deployment.Trigger.Id

Octopus.Deployment.Trigger.Name

You can see the details at https://github.com/OctopusDeploy/Issues/issues/5462

For your Slack step, you can use this run condition to skip it if the trigger ID is populated.

```<code>#{unless Octopus.Deployment.Trigger.Id}True#{/unless}
</code>```

I hope that helps!

Body:
If you are using Octopus 2019.5.0 or later, there are two variables that will be populated if the deployment was created by a trigger.

Octopus.Deployment.Trigger.Id

Octopus.Deployment.Trigger.Name

You can see the details at https://github.com/OctopusDeploy/Issues/issues/5462

For your Slack step, you can use this run condition to skip it if the trigger ID is populated.

#{unless Octopus.Deployment.Trigger.Id}True#{/unless}

I hope that helps!


问:
How to merge JSON segments in Dataweave 1.0
I have some dataweave 1.0 code that outputs this JSON.
I am specifically interested in the 4 fields which I have prefixed with "xxx_" for clarity

```<code>{
    "list_of_orders": {
        "order": [{
                "order_hdr": {
                    "HDR": "C",
                    "xxx_cust_long_text_2": "FREIGHT CHARGE APPLIES",
                    "customer_po_nbr": "55555",
                    "order_nbr": "99999",
                    "dest_dept_nbr": "12345",
                    "shipto_name": "BOB",
                    "shipto_addr3": "",
                    "shipto_addr": "VICTORIA STREET",
                    "shipto_addr2": "",
                    "shipto_city": "HAMILTON",
                    "cust_nbr": "13245",
                    "cust_name": "ROB",
                    "cust_addr3": "",
                    "cust_addr": "PO BOX 11111",
                    "cust_addr2": "MANUKAU CITY",
                    "cust_city": "AUCKLAND",
                    "ord_date": "2019-05-02",
                    "ship_via": "",
                    "xxx_cust_decimal_1": "",
                    "cust_decimal_3": 205.00,
                    "cust_decimal_4": 30.75,
                    "cust_decimal_5": 235.75,
                    "customer_po_type": "Y",
                    "facility_code": null,
                    "start_ship_date": "",
                    "stop_ship_date": "",
                    "company_code": null,
                    "order_type": "SBS",
                    "action_code": "CREATE"
                }
            },
            {
                "order_hdr": {
                    "HDR": "S",
                    "xxx_cust_long_text_2": "",
                    "customer_po_nbr": "55555",
                    "order_nbr": "99999",
                    "dest_dept_nbr": "12345",
                    "shipto_name": "BOB",
                    "shipto_addr3": "",
                    "shipto_addr": "VICTORIA STREET",
                    "shipto_addr2": "",
                    "shipto_city": "HAMILTON",
                    "cust_nbr": "13245",
                    "cust_name": "ROB",
                    "cust_addr3": "",
                    "cust_addr": "PO BOX 11111",
                    "cust_addr2": "MANUKAU CITY",
                    "cust_city": "AUCKLAND",
                    "ord_date": "2019-05-02",
                    "ship_via": "",
                    "xxx_cust_decimal_1": "10.00",
                    "cust_decimal_3": 205.00,
                    "cust_decimal_4": 30.75,
                    "cust_decimal_5": 235.75,
                    "customer_po_type": "Y",
                    "facility_code": null,
                    "start_ship_date": "",
                    "stop_ship_date": "",
                    "company_code": null,
                    "order_type": "SBS",
                    "action_code": "CREATE"
                }
            }
        ]
    }
}
</code>```

(Please note that the HDR tag is just added here so that I can see where the data comes from - it will not be in the final output)

So I am being asked to merge the two headers together using this logic

Take the xxx_cust_long_text_2 from HDR C

Take the xxx_cust_decimal_1 from HDR S

Merge them into a single order_hdr that looks like this

```<code>        "order_hdr": {
          "xxx_cust_long_text_2": "FREIGHT CHARGE APPLIES",
          "customer_po_nbr": "55555",
          "order_nbr": "99999",
          "dest_dept_nbr": "12345",
          "shipto_name": "BOB",
          "shipto_addr3": "",
          "shipto_addr": "VICTORIA STREET",
          "shipto_addr2": "",
          "shipto_city": "HAMILTON",
          "cust_nbr": "13245",
          "cust_name": "ROB",
          "cust_addr3": "",
          "cust_addr": "PO BOX 11111",
          "cust_addr2": "MANUKAU CITY",
          "cust_city": "AUCKLAND",
          "ord_date": "2019-05-02",
          "ship_via": "",
          "xxx_cust_decimal_1": "10.00",
          "cust_decimal_3": 205.00,
          "cust_decimal_4": 30.75,
          "cust_decimal_5": 235.75,
          "customer_po_type": "Y",
          "facility_code": null,
          "start_ship_date": "",
          "stop_ship_date": "",
          "company_code": null,
          "order_type": "SBS",
          "action_code": "CREATE"
        }

</code>```

Any help would be appreciated

Thanks

答:
```<code>%dw 1.0
%output application/json
%var headerS = payload.list_of_orders.order.order_hdr filter ($.HDR == "S")
%var headerC  = payload.list_of_orders.order.order_hdr filter ($.HDR == "C")
---
{
    header: payload.list_of_orders.order[0].order_hdr
        - "HDR"
        - "xxx_cust_decimal_1"
        - "xxx_cust_long_text_2"
        ++ { xxx_cust_decimal_1: headerS[0].xxx_cust_decimal_1}
        ++ { xxx_cust_long_text_2: headerC[0].xxx_cust_long_text_2}
}
</code>```

Body:
I have some dataweave 1.0 code that outputs this JSON.
I am specifically interested in the 4 fields which I have prefixed with "xxx_" for clarity

{
    "list_of_orders": {
        "order": [{
                "order_hdr": {
                    "HDR": "C",
                    "xxx_cust_long_text_2": "FREIGHT CHARGE APPLIES",
                    "customer_po_nbr": "55555",
                    "order_nbr": "99999",
                    "dest_dept_nbr": "12345",
                    "shipto_name": "BOB",
                    "shipto_addr3": "",
                    "shipto_addr": "VICTORIA STREET",
                    "shipto_addr2": "",
                    "shipto_city": "HAMILTON",
                    "cust_nbr": "13245",
                    "cust_name": "ROB",
                    "cust_addr3": "",
                    "cust_addr": "PO BOX 11111",
                    "cust_addr2": "MANUKAU CITY",
                    "cust_city": "AUCKLAND",
                    "ord_date": "2019-05-02",
                    "ship_via": "",
                    "xxx_cust_decimal_1": "",
                    "cust_decimal_3": 205.00,
                    "cust_decimal_4": 30.75,
                    "cust_decimal_5": 235.75,
                    "customer_po_type": "Y",
                    "facility_code": null,
                    "start_ship_date": "",
                    "stop_ship_date": "",
                    "company_code": null,
                    "order_type": "SBS",
                    "action_code": "CREATE"
                }
            },
            {
                "order_hdr": {
                    "HDR": "S",
                    "xxx_cust_long_text_2": "",
                    "customer_po_nbr": "55555",
                    "order_nbr": "99999",
                    "dest_dept_nbr": "12345",
                    "shipto_name": "BOB",
                    "shipto_addr3": "",
                    "shipto_addr": "VICTORIA STREET",
                    "shipto_addr2": "",
                    "shipto_city": "HAMILTON",
                    "cust_nbr": "13245",
                    "cust_name": "ROB",
                    "cust_addr3": "",
                    "cust_addr": "PO BOX 11111",
                    "cust_addr2": "MANUKAU CITY",
                    "cust_city": "AUCKLAND",
                    "ord_date": "2019-05-02",
                    "ship_via": "",
                    "xxx_cust_decimal_1": "10.00",
                    "cust_decimal_3": 205.00,
                    "cust_decimal_4": 30.75,
                    "cust_decimal_5": 235.75,
                    "customer_po_type": "Y",
                    "facility_code": null,
                    "start_ship_date": "",
                    "stop_ship_date": "",
                    "company_code": null,
                    "order_type": "SBS",
                    "action_code": "CREATE"
                }
            }
        ]
    }
}

(Please note that the HDR tag is just added here so that I can see where the data comes from - it will not be in the final output)

So I am being asked to merge the two headers together using this logic

Take the xxx_cust_long_text_2 from HDR C

Take the xxx_cust_decimal_1 from HDR S

Merge them into a single order_hdr that looks like this

        "order_hdr": {
          "xxx_cust_long_text_2": "FREIGHT CHARGE APPLIES",
          "customer_po_nbr": "55555",
          "order_nbr": "99999",
          "dest_dept_nbr": "12345",
          "shipto_name": "BOB",
          "shipto_addr3": "",
          "shipto_addr": "VICTORIA STREET",
          "shipto_addr2": "",
          "shipto_city": "HAMILTON",
          "cust_nbr": "13245",
          "cust_name": "ROB",
          "cust_addr3": "",
          "cust_addr": "PO BOX 11111",
          "cust_addr2": "MANUKAU CITY",
          "cust_city": "AUCKLAND",
          "ord_date": "2019-05-02",
          "ship_via": "",
          "xxx_cust_decimal_1": "10.00",
          "cust_decimal_3": 205.00,
          "cust_decimal_4": 30.75,
          "cust_decimal_5": 235.75,
          "customer_po_type": "Y",
          "facility_code": null,
          "start_ship_date": "",
          "stop_ship_date": "",
          "company_code": null,
          "order_type": "SBS",
          "action_code": "CREATE"
        }

Any help would be appreciated

Thanks


问:
exchange first and last characters in a word or a string
I have a code snippet that does a job of replacing first and last character from a given string, which works correctly:

```<code>def front_back(s1):
if len(s1) == 1:
    return s1
else:
    convert_to_list = list(s1)
    temp_list = convert_to_list[0], convert_to_list[-1]
    convert_to_list[-1] = temp_list[0]
    convert_to_list[0] = temp_list[1]
    s1 = ''.join(convert_to_list)
    return s1

inpt1 = input('Enter string :')
print(front_back(inpt1))
</code>```

Output I get is :

```<code>front_back('code') -- 'eodc'
</code>```

In the above code what modifications I can make, to make it more effective, since I know you can achieve it using slicing function.
Also, how can i make this code work for a string with two words:

```<code>input: 'hello world'

output should be: 'oellh dorlw'
</code>```

since currently it just replaces the first character i.e. 'ello worlh'

Thanks in advance.

答:
edit:</p>

```<code>def front_back(s1):
    if len(s1) == 1:
        return s1
    else:
        newlist = []
        convert_to_list = s1.split()
        for each in convert_to_list:
            each_list = list(each)
            firstC, lastC = each_list[0], each_list[-1]

            each_list[0] = lastC
            each_list[-1] = firstC

            newword = ''.join(each_list)
            newlist.append(newword)

    return ' '.join(newlist)

inpt1 = input('Enter string :')
print(front_back(inpt1))
</code>```

Body:
I have a code snippet that does a job of replacing first and last character from a given string, which works correctly:

def front_back(s1):
if len(s1) == 1:
    return s1
else:
    convert_to_list = list(s1)
    temp_list = convert_to_list[0], convert_to_list[-1]
    convert_to_list[-1] = temp_list[0]
    convert_to_list[0] = temp_list[1]
    s1 = ''.join(convert_to_list)
    return s1

inpt1 = input('Enter string :')
print(front_back(inpt1))

Output I get is :

front_back('code') -- 'eodc'

In the above code what modifications I can make, to make it more effective, since I know you can achieve it using slicing function.
Also, how can i make this code work for a string with two words:

input: 'hello world'

output should be: 'oellh dorlw'

since currently it just replaces the first character i.e. 'ello worlh'

Thanks in advance.

Body:
edit:

def front_back(s1):
    if len(s1) == 1:
        return s1
    else:
        newlist = []
        convert_to_list = s1.split()
        for each in convert_to_list:
            each_list = list(each)
            firstC, lastC = each_list[0], each_list[-1]

            each_list[0] = lastC
            each_list[-1] = firstC

            newword = ''.join(each_list)
            newlist.append(newword)

    return ' '.join(newlist)

inpt1 = input('Enter string :')
print(front_back(inpt1))


问:
How can I override shared library in LD_LIBRARY_PATH with clang++?
I'm trying to compile a shared library I wrote in C++ to use a specific version of another shared library in the current directory, however it seems to be ignoring that and it uses the (older and incompatible) .so file in my LD_LIBRARY_PATH at runtime. How would I go about overriding the .so file it uses to use my own? I also need to retain the older version for another use on the same system.

Here's my command I'm using to compile: clang++ /data/openpilot/selfdrive/df/libs/libSNPE.so -lsymphony-cpu -lsymphonypower -I/data/openpilot/phonelibs/snpe/include -std=c++14 -lstdc++ -fPIC -o d_f.so dynamic_follow.cc -shared

/data/openpilot/selfdrive/df/libs/libSNPE.so being the library I want to use.

I also tried to use the -l flag before my library file, however it returns cannot find -l/data/openpilot/selfdrive/df/libs/libSNPE.so

Confirmed to still use the library in LD_LIBRARY_PATH with this command as well: clang++ -Wl,-rpath,/data/openpilot/selfdrive/df/libs -L/data/openpilot/selfdrive/df/libs -lSNPE -lsymphony-cpu -lsymphonypower -I/data/openpilot/phonelibs/snpe/include -std=c++14 -stdlib=libc++ -fPIC -o d_f.so dynamic_follow.cc -shared

答:
The -L flag tells where to look for libraries at link time, while LD_LIBRARY_PATH tells where to look for libraries at run-time. So whatever path you set at link-time, this will be ignored when running the executable.

You need to have LD_LIBRARY_PATH include the directory of your dynamic library at run-time for your executable to find it. So you may run your executable like this:

```<code>LD_LIBRARY_PATH=/data/openpilot/selfdrive/df/libs:"$LD_LIBRARY_PATH" ./your-exec
</code>```

Body:
The -L flag tells where to look for libraries at link time, while LD_LIBRARY_PATH tells where to look for libraries at run-time. So whatever path you set at link-time, this will be ignored when running the executable.

You need to have LD_LIBRARY_PATH include the directory of your dynamic library at run-time for your executable to find it. So you may run your executable like this:

LD_LIBRARY_PATH=/data/openpilot/selfdrive/df/libs:"$LD_LIBRARY_PATH" ./your-exec


问:
Put svg inside class
I would like to know how to put a svg created by me inside a css or scss class to assign only the class in the icon as in this w3 example:</p>

```<code><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<i class="fa fa-home"></i>
</code>```

答:
If you want to display a custom SVG via CSS you can do it in two steps:

Turn the SVG into a Data Image

Use the Data Image SVG as a CSS Background

Working Example:

div {
display: inline-block;
width: 40px;
height: 40px;
margin-right: 1px;
background-color: rgb(255, 0, 0);
}

.svg-background {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><rect x="2" y="3" width="36" height="5" fill="rgb(255, 255, 255)" /><rect x="2" y="11" width="36" height="5" fill="rgb(255, 255, 255)" /><rect x="2" y="19" width="36" height="5" fill="rgb(255, 255, 255)" /></svg>');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div>
<div class="svg-background"></div></code>```

Title: Put svg inside class

Body:
I would like to know how to put a svg created by me inside a css or scss class to assign only the class in the icon as in this w3 example:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Body:
If you want to display a custom SVG via CSS you can do it in two steps:

Turn the SVG into a Data Image

Use the Data Image SVG as a CSS Background

Working Example:

div {
display: inline-block;
width: 40px;
height: 40px;
margin-right: 1px;
background-color: rgb(255, 0, 0);
}

.svg-background {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><rect x="2" y="3" width="36" height="5" fill="rgb(255, 255, 255)" /><rect x="2" y="11" width="36" height="5" fill="rgb(255, 255, 255)" /><rect x="2" y="19" width="36" height="5" fill="rgb(255, 255, 255)" /></svg>');
}

<div></div>
<div class="svg-background"></div>


问:
Multiple text files inside two loop
I want to create some file inside two loops and fill out them without closing the file inside the first and second loop.

Here you can find what I mean of this question by looking at this part of a code, and it doesn't work ... of course, it creates 100 files but the problem is that each file just holds the last iteration of the first loop while I want each file to write the whole iteration of the first loop.

```<code>ofstream fout;
for(int t = 0; t < N; t++){
    for(int e = 0; e < 100; e++){
        fout.open("myfile_"+strcpp(e)+".txt");
        fout << t << psi[e] << endl;
    }
}
fout.close();
</code>```

where the function strcpp(e) is given by

```<code>template <class T>
string  strcpp(T value){
        ostringstream out;
        out << value;
        return out.str();
}
</code>```

答:
Every time you call:

```<code>fout.open(...);
</code>```

The whole contents of the file before opening it are erased. Since you open each file many times you are constantly erasing anything that you had written to it before you write the next line. This is why the last write of your outer for loop is the only thing in each file.
We can fix this by specifying we want to append to the file we are opening. std::ofstream::open() takes a second optional argument that specifies the mode. You can set the mode to append whatever you write in the file to the end of what is already in there instead of erasing the original file contents.
Ex:

```<code>fout.open(my_file_name, ios::app);
</code>```

Although a better solution might be to just switch in your inner and outer for loop. Then you open each file before the start of the inner for loop, do all the writes to that one file, then close that file and move on to the next one. This way you don't have to open each file many, many times.

Title: Multiple text files inside two loop

Body:
I want to create some file inside two loops and fill out them without closing the file inside the first and second loop.

Here you can find what I mean of this question by looking at this part of a code, and it doesn't work ... of course, it creates 100 files but the problem is that each file just holds the last iteration of the first loop while I want each file to write the whole iteration of the first loop.

ofstream fout;
for(int t = 0; t < N; t++){
    for(int e = 0; e < 100; e++){
        fout.open("myfile_"+strcpp(e)+".txt");
        fout << t << psi[e] << endl;
    }
}
fout.close();

where the function strcpp(e) is given by

template <class T>
string  strcpp(T value){
        ostringstream out;
        out << value;
        return out.str();
}

Body:
Every time you call:

fout.open(...);

The whole contents of the file before opening it are erased. Since you open each file many times you are constantly erasing anything that you had written to it before you write the next line. This is why the last write of your outer for loop is the only thing in each file.
We can fix this by specifying we want to append to the file we are opening. std::ofstream::open() takes a second optional argument that specifies the mode. You can set the mode to append whatever you write in the file to the end of what is already in there instead of erasing the original file contents.
Ex:

fout.open(my_file_name, ios::app);

Although a better solution might be to just switch in your inner and outer for loop. Then you open each file before the start of the inner for loop, do all the writes to that one file, then close that file and move on to the next one. This way you don't have to open each file many, many times.


问:
How to implement Django users referred by other users relationship?
I want to implement a way to keep track of referrals in my django application.  I am using the default Users table.  A user can 'refer' multiple people, but a referred user can only be referred by one user.

I have tried adding this to my models.py but it is causing errors.

```<code>class Referral(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    referredBy = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

this causes the below error:

```<code>ERRORS:
RateManager.Referral.referredBy: (fields.E305) Reverse query name for 'Referral.referredBy' clashes with reverse query name for 'Referral.user'.
    HINT: Add or change a related_name argument to the definition for 'Referral.referredBy' or 'Referral.user'.
</code>```

How do I go about implementing this?

答:
Simply omit the referredBy = models.ForeignKey(User, on_delete=models.CASCADE) since the OneToOneField already references the Users table.

If for some reason you need to have both columns (I can't see why though), you can change your model's related_name attributes:

```<code>class Referral(models.Model):
    user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE)
    referredBy = models.ForeignKey(User, related_name='referredBy', on_delete=models.CASCADE)
</code>```

Body:
I want to implement a way to keep track of referrals in my django application.  I am using the default Users table.  A user can 'refer' multiple people, but a referred user can only be referred by one user.

I have tried adding this to my models.py but it is causing errors.

class Referral(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    referredBy = models.ForeignKey(User, on_delete=models.CASCADE)

this causes the below error:

ERRORS:
RateManager.Referral.referredBy: (fields.E305) Reverse query name for 'Referral.referredBy' clashes with reverse query name for 'Referral.user'.
    HINT: Add or change a related_name argument to the definition for 'Referral.referredBy' or 'Referral.user'.

How do I go about implementing this?

Body:
Simply omit the referredBy = models.ForeignKey(User, on_delete=models.CASCADE) since the OneToOneField already references the Users table.

If for some reason you need to have both columns (I can't see why though), you can change your model's related_name attributes:

class Referral(models.Model):
    user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE)
    referredBy = models.ForeignKey(User, related_name='referredBy', on_delete=models.CASCADE)


问:
No Elements Found When Parsing?
I am new to iPhone programming, however, I have been researching my problem for some time now and have not been able to find a solution...

Basically, I am trying to parse a URL that I do not control, which has the following desired info in its Page Source:

```<code><tr style=" ">

<td valign="top" style="  ">
<p style="  ">
4/10/2011
</p>
</td>
<td valign="top" style="  ">
<p style="  ">
-18
</p>
</td>
<td valign="top" style="  ">
<p style="  ">
21%
</p>
</td>
<td valign="top" style="  ">
<p style="  ">
39%
</p>
</td>
<td valign="top" style="  ">
<p style="  ">
45%
</p>
</td>
<td valign="top" style="  ">
<p style="  ">
54%
</p>
</td>
</tr>`
</code>```

After properly creating a connection with the site, I put my data together and attempt to parse:

```<code>//This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[xmlData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
/*
//We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[[NSString alloc] initWithData:xmlDat encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"xmlCheck = %@", xmlCheck);
//Check was Successful!
*/

//Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
[parser setDelegate:self];
//Tell it to start parsing - the document will be parsed and the delegate of NSXMLParser will get all of
//its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
//The parser is done (it blocks until done), you can release it immediately
[parser release];
}

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *) qName
attributes:(NSDictionary *) attributeDict
{
NSLog(@"StartedParsing");

//if ([elementName isEqualToString:@"tr"]) {
if (elementName) {
NSLog(@"found element!");
titleString = [[NSMutableString alloc] init];
}
}
</code>```

You will notice that at first I attempted to search for the element, 'tr', but then switched to looking for any element in the URL.  Nothing is printed to my Console Window, which makes me think my parser is not finding any elements.

Now, if I attempt the same code on the following website: http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml, a number of different elements are found.  This leads me to believe the URL may need to be in a certain format.  Can someone help me??

Thanks in Advance!

P.S. - I have also implemented the 'foundCharacters' and 'didEndElement' Parser Functions, but have not been able to use them as my parser doesn't appear to be finding any elements...

答:
The html isn't valid XML, but I think that's an easy fix, add the xml start tag like:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<tr style=" ">
snipped for space...
</tr>`
</code>```

Title: No Elements Found When Parsing?

Body:
I am new to iPhone programming, however, I have been researching my problem for some time now and have not been able to find a solution...

Basically, I am trying to parse a URL that I do not control, which has the following desired info in its Page Source:

4/10/2011

-18

21%

39%

45%

54%

`

After properly creating a connection with the site, I put my data together and attempt to parse:

//This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[xmlData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
/*
//We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[[NSString alloc] initWithData:xmlDat encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"xmlCheck = %@", xmlCheck);
//Check was Successful!
*/

//Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
[parser setDelegate:self];
//Tell it to start parsing - the document will be parsed and the delegate of NSXMLParser will get all of
//its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
//The parser is done (it blocks until done), you can release it immediately
[parser release];
}

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *) qName
attributes:(NSDictionary *) attributeDict
{
NSLog(@"StartedParsing");

//if ([elementName isEqualToString:@"tr"]) {
if (elementName) {
NSLog(@"found element!");
titleString = [[NSMutableString alloc] init];
}
}

You will notice that at first I attempted to search for the element, 'tr', but then switched to looking for any element in the URL.  Nothing is printed to my Console Window, which makes me think my parser is not finding any elements.

Now, if I attempt the same code on the following website: http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml, a number of different elements are found.  This leads me to believe the URL may need to be in a certain format.  Can someone help me??

Thanks in Advance!

P.S. - I have also implemented the 'foundCharacters' and 'didEndElement' Parser Functions, but have not been able to use them as my parser doesn't appear to be finding any elements...

Body:
The html isn't valid XML, but I think that's an easy fix, add the xml start tag like:

<?xml version="1.0" encoding="utf-8"?>
<tr style=" ">
snipped for space...
</tr>`


问:
Create and include new file into python package
I want to use version for my package base on git describe command. For this, I created setup.py with function get_version(). This function retrieves version from .version file if it exists, else computes new package version and writes it to a new .version file. However, when I call python setup.py sdist, .version is not copying inside .tar archive. This causes error when I'm trying to install package from PyPi repo. How to properly include my .version file "on the fly" into package?

setup.py:

import pathlib
from subprocess import check_output
from setuptools import find_packages, setup

_VERSION_FILE = pathlib.Path(".version")  # Add it to .gitignore!
_GIT_COMMAND = "git describe --tags --long --dirty"
_VERSION_FORMAT = "{tag}.dev{commit_count}+{commit_hash}"

def get_version() -> str:
    """ Return version from git, write commit to file
    """
    if _VERSION_FILE.is_file():
        with _VERSION_FILE.open() as f:
            return f.readline().strip()
    output = check_output(_GIT_COMMAND.split()).decode("utf-8").strip().split("-")

    tag, count, commit = output[:3]
    dirty = len(output) == 4

    if count == "0" and not dirty:
        return tag

    version = _VERSION_FORMAT.format(tag=tag, commit_count=count, commit_hash=commit)

    with _VERSION_FILE.open("w") as f:
        print(version, file=f, end="")

    return version

_version = get_version()

setup(
    name="mypackage",
    package_data={
        "": [str(_VERSION_FILE)]
    },
    version=_version,
    packages=find_packages(exclude=["tests"]),
)
```

答: If you include a file called MANIFEST.in in the same directory as setup.py with include .version inside, this should get the file picked up.


问:
RegEx for matching lines starting with [ and ending with ]
I am trying to find the lines that start with [ and ends with ] in a file. I am using regex, but not able to get the result.

I have tried regex with various options, e.g., \s, \S, \w and \W.

import re
infile=open("C:\\Users\\Downloads\\Files\\processed.csv","r")
myregex = re.compile(r'(^\[)(\]$)')
list=[]
for groups in myregex.findall(infile.read()):
    item=''.join(groups)
    cleanitem=item.replace('\n','')
    list.append(cleanitem)
print (list)
infile.close()
```

It should print all the lines that start with [ and ends with ].

How do I solve this problem?

答:
Here, we can find a simple expression with a capturing group, if we like, something similar to:

```<code>^(\[.+\])$
</code>```

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"^(\[.+\])$"

test_str = ("[ and ends with ]\n"
    " [ and ends with ]")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

DEMO

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I am trying to find the lines that start with [ and ends with ] in a file. I am using regex, but not able to get the result.

I have tried regex with various options, e.g., \s, \S, \w and \W.

import re
infile=open("C:\\Users\\Downloads\\Files\\processed.csv","r")
myregex = re.compile(r'(^\[)(\]$)')
list=[]
for groups in myregex.findall(infile.read()):
    item=''.join(groups)
    cleanitem=item.replace('\n','')
    list.append(cleanitem)
print (list)
infile.close()

It should print all the lines that start with [ and ends with ].

How do I solve this problem?

Body:
Here, we can find a simple expression with a capturing group, if we like, something similar to:

^(\[.+\])$

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"^(\[.+\])$"

test_str = ("[ and ends with ]\n"
    " [ and ends with ]")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

DEMO

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
Even vanilla Azure function will not publish from VS
I created an Azure function tonight in Visual Studio and had errors publishing it.  So I created a vanilla HTTP triggered one, and tried to publish it, no code changes.  Same errors.  I am logged in to my Azure account, I've downloaded a publish profile, and reset it and tried again.  I've done it by selecting the function app in the IDE.  I've tried figuring out how to FTP the function app, but I pushed files up and nothing appeared in the portal (I copied the build folder into the wwwroot folder on the server).  In FTP, I can see in the deployment folder some files are there, that denote that an attempted deployment failed, so it's talking to Azure, and deciding it hasn't worked.

The error log is not very helpful:

30/05/2019 8:46:11 PM
System.AggregateException: One or more errors occurred. ---> System.Exception: Publishing failed.
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at Microsoft.Publish.Framework.Model.DefaultPublishSteps.<>c__DisplayClass26_0.b__2()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Publish.Framework.Model.DefaultPublishSteps.d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Publish.Framework.ViewModel.ProfileSelectorViewModel.d__176.MoveNext()
---> (Inner Exception #0) System.Exception: Publishing failed.<---

===================

I'd be quite happy to do it via FTP if there was a guide on what to put where.

答:
I'm not sure about the Visual Studio issue. I ran into something similar once, and it required me to log out of my Azure subscription and log back in before it got resolved. You may want to give that a try if you haven't already.

Regarding alternate deployment strategies, I suggest you take a look at the Run from Package deployment feature. It allows you to publish your app as a zip file and run it that way. Other MS-specific tools (VS Code, Azure Pipelines, etc.) are moving towards using this mechanism rather than the legacy "MSDeploy" mechanism that Visual Studio uses today.


问:
Javascript to remove bb_quotes ([quote..] [/quote]) from text
The goal is to use Javascript (vanilla) to remove all text (inclusive) that is between: [quote][/quote] and [quote=something][/quote] (case insensitive). It would be best to also remove double spaces, if they exist after removing the quotes. I tried this Javascript as below, ie:

```<code>t.replace(/\[quote.*\](.*?)\[\/quote\]/gi,'')
</code>```

, but I don't get the correct results. What is the correct way?

var t='Starting [QUOTE]this should be ignored hello[/quote] it. This is not quote and [quote=frank]HELLO quotes[/quote] Marky Mark 84WD. Last [quote=irene]try.[/quote]';

console.log(t.replace(/\[quote.*\](.*?)\[\/quote\]/gi,''));

//Current result: Starting.
//Expected result: Starting it. This is not quote and Marky Mark 84WD. Last

var t='[Quote]this should be ignored hello[/quote]. This is not quote and [quote=frank]HELLO quote[/quote] Marky Mark 84WD.';

console.log(t.replace(/\[quote.*\](.*?)\[\/quote\]/gi,''));

//Current result: Marky Mark 84WD.
//Expected result: . This is not quote and Marky Mark 84WD.```

答:
You can use /\[(quote)[^\]]*](.*?)\[\/\1\]/gi to achieve the filtering:

var t='Starting [QUOTE]this should be ignored hello[/quote] it. This is not quote and [quote=frank]HELLO quotes[/quote] Marky Mark 84WD. Last [quote=irene]try.[/quote]';

console.log(t.replace(/\[(quote)[^\]]*](.*?)\[\/\1\]/gi,''));

var t='[Quote]this should be ignored hello[/quote]. This is not quote and [quote=frank]HELLO quote[/quote] Marky Mark 84WD.';

console.log(t.replace(/\[(quote)[^\]]*](.*?)\[\/\1\]/gi,''));```

Body:
The goal is to use Javascript (vanilla) to remove all text (inclusive) that is between: [quote][/quote] and [quote=something][/quote] (case insensitive). It would be best to also remove double spaces, if they exist after removing the quotes. I tried this Javascript as below, ie:

t.replace(/\[quote.*\](.*?)\[\/quote\]/gi,'')

, but I don't get the correct results. What is the correct way?

var t='Starting [QUOTE]this should be ignored hello[/quote] it. This is not quote and [quote=frank]HELLO quotes[/quote] Marky Mark 84WD. Last [quote=irene]try.[/quote]';

console.log(t.replace(/\[quote.*\](.*?)\[\/quote\]/gi,''));

//Current result: Starting.
//Expected result: Starting it. This is not quote and Marky Mark 84WD. Last

var t='[Quote]this should be ignored hello[/quote]. This is not quote and [quote=frank]HELLO quote[/quote] Marky Mark 84WD.';

console.log(t.replace(/\[quote.*\](.*?)\[\/quote\]/gi,''));

//Current result: Marky Mark 84WD.
//Expected result: . This is not quote and Marky Mark 84WD.


问:
Material-UI checkbox backrground color
I am using material ui checkbox, i wanted it to have its own background color over my div which has colored background. I have set the root to have a backgroundColor as white but the svgicon is a round shape which is not the look i intend to have. Can i shape the checkbox ?

Already have tried many things but not able to figure out how to change the icon

```<code>const styles = {
    root : {
        padding : '0px',
        display : 'inline-block',
        backgroundColor : 'white'
    },
    formLabelRoot : {
        margin : '0'
    }
}
.
.
.
render () {
        const { classes } = this.props
        return(
            <div style={customStyles.divStyle}>
                <div style={customStyles.div1}>
                    <FormControlLabel
                        classes={{root: classes.formLabelRoot}}
                        control={
                            <Checkbox
                                classes={{root : classes.root }}
                                color='primary'
                            />
                            }
                        label={''}
                    />
                </div>
</code>```

The background white is making a spherical rounded checkbox apparent

Image of what is happening now

答:
You might have to make a compromise here if you don't want to go making your own icons.
Something like this is possible without changing the icons. If you're looking for a solid white box with a grey outline as the unchecked box, you might have to provide that svg yourself because I don't see anything like it in @material-ui/icons.

If this IS something you're ok with then target the svg, and give it a fill: "white".

Title: Material-UI checkbox backrground color

Body:
I am using material ui checkbox, i wanted it to have its own background color over my div which has colored background. I have set the root to have a backgroundColor as white but the svgicon is a round shape which is not the look i intend to have. Can i shape the checkbox ?

Already have tried many things but not able to figure out how to change the icon

const styles = {
    root : {
        padding : '0px',
        display : 'inline-block',
        backgroundColor : 'white'
    },
    formLabelRoot : {
        margin : '0'
    }
}
.
.
.
render () {
        const { classes } = this.props
        return(

                    <FormControlLabel
                        classes={{root: classes.formLabelRoot}}
                        control={
                            <Checkbox
                                classes={{root : classes.root }}
                                color='primary'
                            />
                            }
                        label={''}
                    />

The background white is making a spherical rounded checkbox apparent

Image of what is happening now


问:
Skip login screen in case user is already logged in
I'm using firebase to authenticate my user. I created some activities and have login screen which I want to show if user is not logged in already. I defined most of activities in manifest as default, and login screen activity as main. Am I doing it properly? Which of screens should be defined in manifest as main? Login screen or screen with most of informations (right main)?</p>

答: Define your main screen as the default. Make sure your query if the user is logged in before requesting data that may lead to failure due to the fact that the user is not logged in. The reason for this case is in most scenarios, users will log in and you don't want to be running two activities every time your app starts.</p>


问:
Get image preview before uploading in React
Many examples of this on here but can't seem to find any for react. I have managed to convert the vanilla js to react but getting an error.

The answer looks simple enough so here I go in react:

```<code>getInitialState: function(){
  return{file: []}
},

_onChange: function(){
  // Assuming only image
  var file = this.refs.file.files[0];
  var reader = new FileReader();
  var url = reader.readAsDataURL(file);
  console.log(url) // Would see a path?
  // TODO: concat files for setState
},

render: function(){
 return(
  <div>
    <form>
      <input
        ref="file"
        type="file"
        name="user[image]"
        multiple="true"
        onChange={this._onChange}/>
     </form>
    {/* Only show first image, for now. */}
    <img src={this.state.file[0} />
  </div>
 )
};
</code>```

Basically all answers I have seen show something like what I have. Any difference in React app?

Regarding answer:

答:
I had a crazy time trying to get this to work with multiple files, so if anyone else is having this problem, here you go:

```<code>const onFileChange = e => {
e.preventDefault();
const filesList = e.target.files;

if (filesList.length === 0) return;
//Spread array to current state preview URLs
let arr = [...data.imagePreviewUrls];
for (let i = 0; i < filesList.length; i++) {
  const file = filesList[i];

  const reader = new FileReader();
  reader.onload = upload => {
    //push new image to the end of arr
    arr.push(upload.target.result);
    //Set state to arr
    setData({
      ...data,
      imagePreviewUrls: arr
    });
  };
  reader.readAsDataURL(file);
}
};
</code>```

Essentially the for loop resolves before even the first onload event fires, resetting the state every time it iterates. To resolve this just make an array outside of the for loop and push the new item to it onload. This will handle multiple files even if the user closes the file dialog and later chooses to upload more, as long as state hasn't been reset.

Body:
Many examples of this on here but can't seem to find any for react. I have managed to convert the vanilla js to react but getting an error.

The answer looks simple enough so here I go in react:

getInitialState: function(){
  return{file: []}
},

_onChange: function(){
  // Assuming only image
  var file = this.refs.file.files[0];
  var reader = new FileReader();
  var url = reader.readAsDataURL(file);
  console.log(url) // Would see a path?
  // TODO: concat files for setState
},

render: function(){
 return(

    <form>
      <input
        ref="file"
        type="file"
        name="user[image]"
        multiple="true"
        onChange={this._onChange}/>
     </form>
    {/* Only show first image, for now. */}

 )
};

Basically all answers I have seen show something like what I have. Any difference in React app?

Regarding answer:

Body:
I had a crazy time trying to get this to work with multiple files, so if anyone else is having this problem, here you go:

const onFileChange = e => {
e.preventDefault();
const filesList = e.target.files;

if (filesList.length === 0) return;
//Spread array to current state preview URLs
let arr = [...data.imagePreviewUrls];
for (let i = 0; i < filesList.length; i++) {
  const file = filesList[i];

  const reader = new FileReader();
  reader.onload = upload => {
    //push new image to the end of arr
    arr.push(upload.target.result);
    //Set state to arr
    setData({
      ...data,
      imagePreviewUrls: arr
    });
  };
  reader.readAsDataURL(file);
}
};

Essentially the for loop resolves before even the first onload event fires, resetting the state every time it iterates. To resolve this just make an array outside of the for loop and push the new item to it onload. This will handle multiple files even if the user closes the file dialog and later chooses to upload more, as long as state hasn't been reset.


问:
Return instance of generic type
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.

```<code>public class Parameter<T> : IParameter<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public bool IsValid()
    {
        if (String.IsNullOrEmpty(Name))
            return false;

        return (typeof(T) == typeof(String)) ||
               typeof(T) == typeof(bool) ||
               typeof(T) == typeof(int) ||
               typeof(T) == typeof(double);
    }

    public XElement ToXml()
    {
        if (!IsValid())
            throw new InvalidParameterException();

        var xElement = new XElement("Parameter", Value,
                                    new XAttribute("Type", typeof (T)),
                                    new XAttribute("Name", Name));
        return xElement;
    }

    public static Parameter<T> FromXml(XElement xElement)
    {
        var sType = xElement.Attributes()
                    .Where(attribute => attribute.Name == "Type")
                    .Single().Name.ToString();
        var name = xElement.Attributes()
                                .Where(attribute => attribute.Name == "Name")
                                .Single().Name.ToString();
        var sValue = xElement.Value;//need to use this
        var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>

        //I need somehow set T equal to typeVar here and Set
        return new Parameter<T>() {Name = name};//this is wrong.
        //I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
        //basing on typeVar
    }
}
</code>```

I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!

UPD: I'm using .NET 4.0. Does it make any difference? :)

UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.

答:
Make a non-generic base class and inherit the generic class from it (they can have the same name and only differ by the generic type). On the non-generic base class, create generic instances in your static method (which returns the non-generic base class as result). You can then cast this to the generic type you expect.

```<code>public abstract class Parameter {
  public static Parameter FromXml(XElement xElement) {
    ...
  }

  public string Name { get; set; }

  public abstract XElement ToXml();
}

public class Parameter<T>: Parameter {
  public T Value { get; set; }

  public override XElement ToXml() {
    ...
  }
}
</code>```

There isn't really another way of doing this, since in your sample the type for T is specified before the static method runs.

Title: Return instance of generic type

Body:
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.

public class Parameter<T> : IParameter<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public bool IsValid()
    {
        if (String.IsNullOrEmpty(Name))
            return false;

        return (typeof(T) == typeof(String)) ||
               typeof(T) == typeof(bool) ||
               typeof(T) == typeof(int) ||
               typeof(T) == typeof(double);
    }

    public XElement ToXml()
    {
        if (!IsValid())
            throw new InvalidParameterException();

        var xElement = new XElement("Parameter", Value,
                                    new XAttribute("Type", typeof (T)),
                                    new XAttribute("Name", Name));
        return xElement;
    }

    public static Parameter<T> FromXml(XElement xElement)
    {
        var sType = xElement.Attributes()
                    .Where(attribute => attribute.Name == "Type")
                    .Single().Name.ToString();
        var name = xElement.Attributes()
                                .Where(attribute => attribute.Name == "Name")
                                .Single().Name.ToString();
        var sValue = xElement.Value;//need to use this
        var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>

        //I need somehow set T equal to typeVar here and Set
        return new Parameter<T>() {Name = name};//this is wrong.
        //I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
        //basing on typeVar
    }
}

I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!

UPD: I'm using .NET 4.0. Does it make any difference? :)

UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.

Body:
Make a non-generic base class and inherit the generic class from it (they can have the same name and only differ by the generic type). On the non-generic base class, create generic instances in your static method (which returns the non-generic base class as result). You can then cast this to the generic type you expect.

public abstract class Parameter {
  public static Parameter FromXml(XElement xElement) {
    ...
  }

  public string Name { get; set; }

  public abstract XElement ToXml();
}

public class Parameter<T>: Parameter {
  public T Value { get; set; }

  public override XElement ToXml() {
    ...
  }
}

There isn't really another way of doing this, since in your sample the type for T is specified before the static method runs.


问:
PyInstaller Convert to macOS
I wrote some python code for a friend of mine and used pyinstall to package it up for him.  The problem is I use windows and he uses a Mac. Is there anyway I can convert my script to run on his computer? Or is he going to need to install python himself?  How do people with two different OSes usually work together? </p>

答:
I found your question while solving this issue.
The sad thing is you will need a mac to build the program for the mac os.
I took a while doing this as my program was a bit bulky but in the end, the hustle is worth it.

Some of the issues you might face regarding pyinstaller can be addressed on this answer here.

Title: PyInstaller Convert to macOS


答:
it means run the command called "wallet" which is to be found in the current directory "./" and provide it with a single parameter "balance".

I use the term "command" above, but in linux it could be lots of thins, for example it could be an excutable script such as a shell script, a compiled program (e.g. C) an alias etc.

Title: what does "./wallet balance" mean?

Body:
I am a beginner with bash and I'm using an open source file which have this sentence ./wallet balance at the end of the file , Could any body tell me what dose it mean ?! here's the code inside the opensource file :

#!/usr/bin/env bash
C_RED="\033[31;01m"
C_GREEN="\033[32;01m"
C_YELLOW="\033[33;01m"
C_BLUE="\033[34;01m"
C_PINK="\033[35;01m"
C_CYAN="\033[36;01m"
C_NO="\033[0m"

################################################################################
### MAIN #######################################################################
################################################################################

if [[ ${#} -gt 0 ]]; then
    printf "${C_RED}balance does not require any argument.\n"
    printf "${C_YELLOW}usage: ${C_NO}%s\n" "balance"
    exit 1
fi
./wallet balance