问:
Why is wire variable causing illegal left-hand side in continuous assignment?
I have read through all similar posts, but none address the issue I'm having, namely that line 41 assign Y[b]=~Y[b]; causes error "Illegal left-hand side in continuous assignment."

I haven't assigned any regs so I don't see what the issue is. If I replace b with an actual number (say, 3) it works fine. But I need b as a variable here.

```<code>// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  wire b;        // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  assign b=(S[1]!=P[1])? b:b+1; // if parity of 2^0 not the same, add 1 to b
  assign b=(S[2]!=P[2])? b:b+2; // if parity of 2^1 not the same, add 2 to b
  assign b=(S[3]!=P[3])? b:b+4; // if parity of 2^2 not the same, add 4 to b

  assign Y[b]=~Y[b]; // correct the incorrect bit
  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule
</code>```

答:
Verilog standard lists legal lhs values for the continuous assignment as the following (Table 10-1):

Net or variable (vector or scalar)

Constant bit-select of a vector net or packed variable

Constant part-select of a vector net or packed variable

Concatenation or nested concatenation of any of the above left-hand sides

in your case Y[b] is not a constant selection, because b is not a constant. Therefore syntactically your lhs is illegal and you get this message from the compiler.

On a side note you have a zero-delay loop here. See other answers for explanation.

Body:
I have read through all similar posts, but none address the issue I'm having, namely that line 41 assign Y[b]=~Y[b]; causes error "Illegal left-hand side in continuous assignment."

I haven't assigned any regs so I don't see what the issue is. If I replace b with an actual number (say, 3) it works fine. But I need b as a variable here.

// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  wire b;        // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  assign b=(S[1]!=P[1])? b:b+1; // if parity of 2^0 not the same, add 1 to b
  assign b=(S[2]!=P[2])? b:b+2; // if parity of 2^1 not the same, add 2 to b
  assign b=(S[3]!=P[3])? b:b+4; // if parity of 2^2 not the same, add 4 to b

  assign Y[b]=~Y[b]; // correct the incorrect bit
  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule


来源: stackexchange

问:
Build with PyInstaller skipping libraries
i'm trying to build an app for windows using PyInstaller, but skipping libraries (ex django). I'm will run requirements.txt to use the installed libaries on local system python.
The intention is to compile (protect) the code and keep the libraries on system.

Saw about changing the python path on runtime using hook, but not found nothing.

Thanks for the help!

答:
You can exclude modules on the command line like this:</p>

```<code>pyinstaller --exclude-module django
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can exclude modules on the command line like this:

pyinstaller --exclude-module django


问:
cant get my dropdown list to close when I click outside
cant get my dropdown list to close when I click outside the button the function above renders the dropdown button to work completly. The function at the bottom of the page is the on Im trying to get to work at the moment it renders the other function inside the script impossible to use, the work if I remove it. The dropwdown html thats in the code below is just an  example.</p>

```<code>        //this is how the dropdown looks like got it from //http://www.w3schools.com/w3css/w3css_dropdowns.asp
         <div class="w3-dropdown-click">
           <button onclick="myFunction()" class="w3-btn">ClickMe</button>
            <div id="Demo" class="w3-dropdown-content w3-card">
   /*some example links*/
            <a href="#">Link 1</a>
            <a href="#">Link 2</a>
            <a href="#">Link 3</a>
           </div>
         </div>
    // I use two of these on my page

    <script>
    //this functions open and closes my dropdown when clicked
       function myFunction(event) {
     //opens the selected dropdownlist
         document.getElementById("Demo").classList.toggle("w3-show");
     //closes the other dropdownlist
          document.getElementById("Demo2").classList.remove("w3-show");
          event.stopPropagation();
       }

          //this functions open and closes my other dropdown when clicked
      function myFunction2(event) {
                 //opens the selected dropdownlist
         document.getElementById("Demo2").classList.toggle("w3-show");
                 //closes the other dropdownlist
         document.getElementById("Demo").classList.remove("w3-show");
         event.stopPropagation();
       }

    // the funtion im trying to get to work it should close the dropdown when Im clicking outsid of the dropdown buttons
             $(":not(#Demo2)").click( function(){
               document.getElementById("Demo").classList.remove("w3-show");
               document.getElementById("Demo2").classList.remove("w3-show");
              });
              </script>
</code>```

答:
window.addEventListener('mouseup',function(event){
        var pol = document.getElementById('Demo1');
        if(event.target != pol && event.target.parentNode != pol){
            document.getElementById("Demo").classList.remove("w3-show");
            document.getElementById("Demo2").classList.remove("w3-show");

        }
  });  ```

ContentLicense: CC BY-SA 3.0

Body:
cant get my dropdown list to close when I click outside the button the function above renders the dropdown button to work completly. The function at the bottom of the page is the on Im trying to get to work at the moment it renders the other function inside the script impossible to use, the work if I remove it. The dropwdown html thats in the code below is just an  example.

        //this is how the dropdown looks like got it from //http://www.w3schools.com/w3css/w3css_dropdowns.asp

           <button onclick="myFunction()" class="w3-btn">ClickMe</button>

   /*some example links*/
            Link 1
            Link 2
            Link 3

    // I use two of these on my page


问:
How to handle nightly build in Jenkins declarative pipeline
I have a multibranch pipeline with a Jenkinsfile in my repo and I am able to have my CI workflow (build & unit tests -> deploy-dev -> approval -> deploy-QA -> approval -> deploy-prod) on every commit.
What I would like to do is add SonarQube Analysis on nightly builds in the first phase build & unit tests.
Since my build is triggerd by Gitlab I have defined my pipeline triggers as follow :

```<code>pipeline {
    ...
    triggers {
        gitlab(triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: 'All')
    }
    ...
}
</code>```

To setup my nightly build I have added

```<code>triggers {
    ...
    cron('H H * * *')
}
</code>```

But now, how to execute analysis step if we are only building the job triggered by the cron expression at night ?

My simplified build stage looks as follow :

```<code>stage('Build & Tests & Analysis') {
    // HERE THE BEGIN SONAR ANALYSIS  (to be executed on nightly builds)
    bat 'msbuild.exe ...'
    bat 'mstest.exe ...'
    // HERE THE END SONAR ANALYSIS (to be executed on nightly builds)
}
</code>```

答:
This works in declarative pipeline</p>

```<code>when {
    triggeredBy 'TimerTrigger'
}
</code>```

Body:
I have a multibranch pipeline with a Jenkinsfile in my repo and I am able to have my CI workflow (build & unit tests -> deploy-dev -> approval -> deploy-QA -> approval -> deploy-prod) on every commit.
What I would like to do is add SonarQube Analysis on nightly builds in the first phase build & unit tests.
Since my build is triggerd by Gitlab I have defined my pipeline triggers as follow :

pipeline {
    ...
    triggers {
        gitlab(triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: 'All')
    }
    ...
}

To setup my nightly build I have added

triggers {
    ...
    cron('H H * * *')
}

But now, how to execute analysis step if we are only building the job triggered by the cron expression at night ?

My simplified build stage looks as follow :

stage('Build & Tests & Analysis') {
    // HERE THE BEGIN SONAR ANALYSIS  (to be executed on nightly builds)
    bat 'msbuild.exe ...'
    bat 'mstest.exe ...'
    // HERE THE END SONAR ANALYSIS (to be executed on nightly builds)
}

Body:
This works in declarative pipeline

when {
    triggeredBy 'TimerTrigger'
}


问:
Preact class attribute is empty
Today I am trying to use CSS in preact with webpack.
It is almost working for me.

This is target code. In browser class attribute is empty. I tried className with same result, but CSS code is included in bundle.

```<code>import css from './todo-list.css';

export class C extends Component {
  render() {
    return <h1 class={css.bordered}>title</h1>;
  }
}

</code>```

If I just import css and don't reference it anywhere from the code
then CSS code is skipped.

So as for now my workaround is to reference css somewhere and hardcode CSS classes as string literals.

```<code>import css from './styles.css';

export class C extends Component {
  render() {
    return <h1 class='bordered'><span class={css}>title</span></h1>;
  }
}

</code>```

I wasn't able to spot any issue with className for preact. It looks like it supported out of the box without.
Any ideas about debugging class attribute are appreciated.

Versions:

```<code>    "css-loader": "^2.1.1",
    "preact": "^8.4.2",
    "webpack": "^4.28.1"

</code>```

Loader configuration:

```<code>      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader']
      },

</code>```

In browser css is a function and it returns empty object:

```<code>_todo_list_css__WEBPACK_IMPORTED_MODULE_5___default
ƒ getModuleExports() { return module; }
</code>```

答:
Solution came after discovering the way how to configure webpack plugins when they are piped.

This configuration worked out for me:

```<code>      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          }
        ]
      }
</code>```

Title: Preact class attribute is empty

Body:
Today I am trying to use CSS in preact with webpack.
It is almost working for me.

This is target code. In browser class attribute is empty. I tried className with same result, but CSS code is included in bundle.

import css from './todo-list.css';

export class C extends Component {
  render() {
    return
title
;
  }
}

If I just import css and don't reference it anywhere from the code
then CSS code is skipped.

So as for now my workaround is to reference css somewhere and hardcode CSS classes as string literals.

import css from './styles.css';

export class C extends Component {
  render() {
    return
title
;
  }
}

I wasn't able to spot any issue with className for preact. It looks like it supported out of the box without.
Any ideas about debugging class attribute are appreciated.

Versions:

    "css-loader": "^2.1.1",
    "preact": "^8.4.2",
    "webpack": "^4.28.1"

Loader configuration:

      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader']
      },

In browser css is a function and it returns empty object:

_todo_list_css__WEBPACK_IMPORTED_MODULE_5___default
ƒ getModuleExports() { return module; }

Body:
Solution came after discovering the way how to configure webpack plugins when they are piped.

This configuration worked out for me:

      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          }
        ]
      }


问:
Unable to create record via nested attributes Rails API
I'm currently trying to create an Order instance. There is an association of the model Order with Items. The association is as follows. Order has many Items. I try following the documentation https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

```<code>class Order < ApplicationRecord
  has_many :items
  accepts_nested_attributes_for :items
end

class OrdersController < ApplicationController
  ##
  private

  def order_params
    params.require(:order).permit(:description,
                                  items_attributes: [:id, :quantity])
  end
end
</code>```

From the following post, it shows that the id has to be pass in the params. Rails 5 Api create new object from json with nested resource

```<code>params = {order: {description: "this is a test"}, items_attributes: [{id: 3, quantity: 3, description: 'within order -> item'}]}
=> {:order=>{:description=>"this is a test"}, :items_attributes=>[{:id=>3, :quantity=>3, :description=>"within order -> item"}]}
[7] pry(main)> order_test = Order.create!(params[:order])
   (0.4ms)  BEGIN
  Order Create (62.9ms)  INSERT INTO "orders" ("description", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["description", "this is a test"], ["created_at", "2019-05-30 23:31:39.409528"], ["updated_at", "2019-05-30 23:31:39.409528"]]
   (4.6ms)  COMMIT
=> #<Order:0x00007ff91556e4b8 id: 14, description: "this is a test", created_at: Thu, 30 May 2019 23:31:39 UTC +00:00, updated_at: Thu, 30 May 2019 23:31:39 UTC +00:00>
</code>```

I create an order however when I check for the items it returns an empty array.

```<code>=> #<Order:0x00007ff9142da590 id: 14, description: "this is a test", created_at: Thu, 30 May 2019 23:31:39 UTC +00:00, updated_at: Thu, 30 May 2019 23:31:39 UTC +00:00>
[11] pry(main)> Order.last.items
  Order Load (0.4ms)  SELECT  "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT $1  [["LIMIT", 1]]
  Item Load (0.3ms)  SELECT "items".* FROM "items" WHERE "items"."order_id" = $1  [["order_id", 14]]
=> []
</code>```

Here is the table for items:

```<code>class CreateItems < ActiveRecord::Migration[5.2]
  def change
    create_table :items do |t|
      t.references :order, foreign_key: true
      t.integer :quantity
      t.string :description

      t.timestamps
    end
  end
end
</code>```

What is wrong?

答:
The mistake was in the order the parameters were being passed.

```<code>{:order=>{:id=>22, :description=>"this is a test", :items_attributes=>[{:order_id=>22, :quantity=>3, :description=>"within order -> item"}]}}
</code>```

This solved it:

```<code>order = Order.create!(params[:order])

<Order:0x00007ff918039ee0 id: 22, description: "this is a test", created_at: Fri, 31 May 2019 01:39:23 UTC +00:00, updated_at: Fri, 31 May 2019 01:39:23 UTC +00:00>
[39] pry(main)> order.items
  Item Load (114.8ms)  SELECT "items".* FROM "items" WHERE "items"."order_id" = $1  [["order_id", 22]]
=> [#<Item:0x00007ff9180394b8
  id: 4,
  order_id: 22,
  quantity: 3,
  description: "within order -> item",
  created_at: Fri, 31 May 2019 01:39:23 UTC +00:00,
  updated_at: Fri, 31 May 2019 01:39:23 UTC +00:00>]
</code>```

Body:
I'm currently trying to create an Order instance. There is an association of the model Order with Items. The association is as follows. Order has many Items. I try following the documentation https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

class Order < ApplicationRecord
  has_many :items
  accepts_nested_attributes_for :items
end

class OrdersController < ApplicationController
  ##
  private

  def order_params
    params.require(:order).permit(:description,
                                  items_attributes: [:id, :quantity])
  end
end

From the following post, it shows that the id has to be pass in the params. Rails 5 Api create new object from json with nested resource

params = {order: {description: "this is a test"}, items_attributes: [{id: 3, quantity: 3, description: 'within order -> item'}]}
=> {:order=>{:description=>"this is a test"}, :items_attributes=>[{:id=>3, :quantity=>3, :description=>"within order -> item"}]}
[7] pry(main)> order_test = Order.create!(params[:order])
   (0.4ms)  BEGIN
  Order Create (62.9ms)  INSERT INTO "orders" ("description", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["description", "this is a test"], ["created_at", "2019-05-30 23:31:39.409528"], ["updated_at", "2019-05-30 23:31:39.409528"]]
   (4.6ms)  COMMIT
=> #<Order:0x00007ff91556e4b8 id: 14, description: "this is a test", created_at: Thu, 30 May 2019 23:31:39 UTC +00:00, updated_at: Thu, 30 May 2019 23:31:39 UTC +00:00>

I create an order however when I check for the items it returns an empty array.

=> #<Order:0x00007ff9142da590 id: 14, description: "this is a test", created_at: Thu, 30 May 2019 23:31:39 UTC +00:00, updated_at: Thu, 30 May 2019 23:31:39 UTC +00:00>
[11] pry(main)> Order.last.items
  Order Load (0.4ms)  SELECT  "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT $1  [["LIMIT", 1]]
  Item Load (0.3ms)  SELECT "items".* FROM "items" WHERE "items"."order_id" = $1  [["order_id", 14]]
=> []

Here is the table for items:

class CreateItems < ActiveRecord::Migration[5.2]
  def change
    create_table :items do |t|
      t.references :order, foreign_key: true
      t.integer :quantity
      t.string :description

      t.timestamps
    end
  end
end

What is wrong?

Body:
The mistake was in the order the parameters were being passed.

{:order=>{:id=>22, :description=>"this is a test", :items_attributes=>[{:order_id=>22, :quantity=>3, :description=>"within order -> item"}]}}

This solved it:

order = Order.create!(params[:order])

<Order:0x00007ff918039ee0 id: 22, description: "this is a test", created_at: Fri, 31 May 2019 01:39:23 UTC +00:00, updated_at: Fri, 31 May 2019 01:39:23 UTC +00:00>
[39] pry(main)> order.items
  Item Load (114.8ms)  SELECT "items".* FROM "items" WHERE "items"."order_id" = $1  [["order_id", 22]]
=> [#<Item:0x00007ff9180394b8
  id: 4,
  order_id: 22,
  quantity: 3,
  description: "within order -> item",
  created_at: Fri, 31 May 2019 01:39:23 UTC +00:00,
  updated_at: Fri, 31 May 2019 01:39:23 UTC +00:00>]


问:
virtual function with user-defined-type vector
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

```<code>class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};
</code>```

but when I write the derived class:

```<code>#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};
</code>```

I get this error:

```<code>invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’
</code>```

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?

答: The two myStruct types are totally unrelated. This means that you're trying to override TestFather::get_myStructVect() and have it return a completely different type. This is not allowed.

Body:
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};

but when I write the derived class:

#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};

I get this error:

invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?


问:
How is this for loop terminated?
Found as a user submission on leetcode for the problem Plus One.

```<code>vector<int> plusOne(vector<int>& digits) {
  for (int i=digits.size(); i--; digits[i] = 0)
      if (digits[i]++ < 9)
          return digits;
  digits[0]++;
  digits.push_back(0);
  return digits;
}
</code>```

Normally there's something in the conditional like i >= 0; How is this for loop terminating and not accesing some -i element?

答:
A for loop terminates when the second expression is false or when contextually converted to a bool value produces false. In C++, 0 is contextually converted to false; all other integers convert to true in a bool context. (Thanks to M.M.for the link.)

So at the beginning of each loop the expression i-- is evaluated. It's just an expression, so it will produce a result. If the result it produces is zero, the loop will end. If you haven't seen this expression before, here is how it works:

It both decrements i and returns the original value of i before it was decremented. So if i were 5, evaluating i-- will have the "result" 5, but as a side effect, i will be 4 after the evaluation.

The big picture: i is decremented by 1 each time, so assuming it starts off positive, it will get down to 0, at which time evaluating i-- will produce 0.

Title: How is this for loop terminated?

Body:
Found as a user submission on leetcode for the problem Plus One.

vector<int> plusOne(vector<int>& digits) {
  for (int i=digits.size(); i--; digits[i] = 0)
      if (digits[i]++ < 9)
          return digits;
  digits[0]++;
  digits.push_back(0);
  return digits;
}

Normally there's something in the conditional like i >= 0; How is this for loop terminating and not accesing some -i element?


问:
I get error 500 when i request with a anon user and not error 401, using "rest_framework.permissions.IsAuthenticated" , in Django rest framework
I'm building an api where users have to be logged in to see the content with django, and django rest framework.

Using 'rest_framework.permissions.IsAuthenticated' and rest_framework.authentication.TokenAuthentication as it says in the documentation.

Settings.py

```<code>REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
}
</code>```

and it works perfectly, it does not allow to anonymous users see  the contents (endpoints, views etc... ), but the problem is that it responds with an error 500 and not 401 Unauthorized as it should.

i get this exeption when I make a request without any token:

```<code>TypeError: int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser'
</code>```

Does anyone know what can be done for the IsAuthenticated and TokenAuthentication permissions to return 401 and not 500?

full error stack:

```<code>File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
web_1  |     return view_func(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
web_1  |     return self.dispatch(request, *args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
web_1  |     response = self.handle_exception(exc)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
web_1  |     self.raise_uncaught_exception(exc)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 482, in dispatch
web_1  |     self.initial(request, *args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 400, in initial
web_1  |     self.check_permissions(request)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 333, in check_permissions
web_1  |     if not permission.has_permission(request, self):
web_1  |   File "/qr/qr/permissions.py", line 39, in has_permission
web_1  |     user_company = str(CustomUser.objects.get(user=request.user).seat.company.id)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
web_1  |     return getattr(self.get_queryset(), name)(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 370, in get
web_1  |     clone = self.filter(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 781, in filter
web_1  |     return self._filter_or_exclude(False, *args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 799, in _filter_or_exclude
web_1  |     clone.query.add_q(Q(*args, **kwargs))
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1260, in add_q
web_1  |     clause, _ = self._add_q(q_object, self.used_aliases)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1286, in _add_q
web_1  |     allow_joins=allow_joins, split_subq=split_subq,
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1216, in build_filter
web_1  |     condition = lookup_class(lhs, value)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
web_1  |     self.rhs = self.get_prep_lookup()
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 110, in get_prep_lookup
web_1  |     self.rhs = target_field.get_prep_value(self.rhs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 962, in get_prep_value
web_1  |     return int(value)
web_1  | TypeError: int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser'
</code>```

答:
The error is being raised from within your permissions class.

When you check the CustomUser model with user_company = str(CustomUser.objects.get(user=request.user).seat.company.id), the request.user is an instance of AnonymousUser and not User, hence why it is failing.  You should add some code to your permissions to check for an anonymous user with:

```<code>if request.user.is_anonymous:
    raise AuthenticationFailed() # You could also use PermissionDenied to return 403

# Unauthenticated users will receive an unauthorized (401) response

user_company = str(CustomUser.objects.get(user=request.user).seat.company.id)
</code>```

is_anonymous is a property of the User and AnonymousUser classes intended to be used by developers to check if the user is actually authenticated or not.

Body:
I'm building an api where users have to be logged in to see the content with django, and django rest framework.

Using 'rest_framework.permissions.IsAuthenticated' and rest_framework.authentication.TokenAuthentication as it says in the documentation.

Settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
}

and it works perfectly, it does not allow to anonymous users see  the contents (endpoints, views etc... ), but the problem is that it responds with an error 500 and not 401 Unauthorized as it should.

i get this exeption when I make a request without any token:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser'

Does anyone know what can be done for the IsAuthenticated and TokenAuthentication permissions to return 401 and not 500?

full error stack:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
web_1  |     return view_func(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
web_1  |     return self.dispatch(request, *args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
web_1  |     response = self.handle_exception(exc)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
web_1  |     self.raise_uncaught_exception(exc)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 482, in dispatch
web_1  |     self.initial(request, *args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 400, in initial
web_1  |     self.check_permissions(request)
web_1  |   File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 333, in check_permissions
web_1  |     if not permission.has_permission(request, self):
web_1  |   File "/qr/qr/permissions.py", line 39, in has_permission
web_1  |     user_company = str(CustomUser.objects.get(user=request.user).seat.company.id)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
web_1  |     return getattr(self.get_queryset(), name)(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 370, in get
web_1  |     clone = self.filter(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 781, in filter
web_1  |     return self._filter_or_exclude(False, *args, **kwargs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 799, in _filter_or_exclude
web_1  |     clone.query.add_q(Q(*args, **kwargs))
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1260, in add_q
web_1  |     clause, _ = self._add_q(q_object, self.used_aliases)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1286, in _add_q
web_1  |     allow_joins=allow_joins, split_subq=split_subq,
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1216, in build_filter
web_1  |     condition = lookup_class(lhs, value)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
web_1  |     self.rhs = self.get_prep_lookup()
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 110, in get_prep_lookup
web_1  |     self.rhs = target_field.get_prep_value(self.rhs)
web_1  |   File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 962, in get_prep_value
web_1  |     return int(value)
web_1  | TypeError: int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser'

Body:
The error is being raised from within your permissions class.

When you check the CustomUser model with user_company = str(CustomUser.objects.get(user=request.user).seat.company.id), the request.user is an instance of AnonymousUser and not User, hence why it is failing.  You should add some code to your permissions to check for an anonymous user with:

if request.user.is_anonymous:
    raise AuthenticationFailed() # You could also use PermissionDenied to return 403

# Unauthenticated users will receive an unauthorized (401) response

user_company = str(CustomUser.objects.get(user=request.user).seat.company.id)

is_anonymous is a property of the User and AnonymousUser classes intended to be used by developers to check if the user is actually authenticated or not.


问:
Ray cluster configuration file_mounts section not allowing worker nodes to launch
I am trying to distribute a small number of files to each node in a Ray cluster on AWS EC2, using the file_mounts block in the configuration file:-

file_mounts: {
    "./": "./run_files"
}

The cluster launches with only a master node, onto which the contents of the run_files directory have been correctly copied. However, the two worker nodes that were requested do not launch. If I omit the file_mounts section, the workers launch. The Ray monitor indicates that there is a problem locating the file libtcl.so in the matplotlib sub-directory of the Anaconda3 installation.  This file is on the correct path on the master node so it appears that the setup on worker nodes is not working properly:-

```<code>$ ray exec ray_conf.yaml  'tail -n 100 -f /tmp/ray/session_*/logs/monitor*'
2019-05-29 19:36:14,019 INFO updater.py:95 -- NodeUpdater: Waiting for IP of i-073950262949fe9a8...
2019-05-29 19:36:14,019 INFO log_timer.py:21 -- NodeUpdater: i-073950262949fe9a8: Got IP [LogTimer=362ms]
2019-05-29 19:36:14,025 INFO updater.py:272 -- NodeUpdater: Running tail -n 100 -f /tmp/ray/session_*/logs/monitor* on 54.175.173.233...
==> /tmp/ray/session_2019-05-29_23-35-49_842129_4407/logs/monitor.err <==
Traceback (most recent call last):
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/monitor.py", line 376, in <module>
redis_password=args.redis_password)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/monitor.py", line 54, in __init__
self.load_metrics)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 349, in __init__
self.reload_config(errors_fatal=True)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 523, in reload_config
raise e
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 516, in reload_config
new_config["worker_start_ray_commands"]
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 790, in hash_runtime_conf
add_content_hashes(local_path)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 778, in add_content_hashes
add_hash_of_file(fpath)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 764, in add_hash_of_file
with open(fpath, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: './anaconda3/pkgs/matplotlib-2.1.0-py36hba5de38_0/lib/libtcl.so'

==> /tmp/ray/session_2019-05-29_23-35-49_842129_4407/logs/monitor.out <==
</code>```

(Note that this problem follows on from the question "Workers not being launched on EC2 by ray", I have continued in a new question because the source of the error is now more specifically identified.)

答:
I think that the libtcl.so error message is very misleading.  The problem is that the file_mounts remote path cannot be the home directory on the workers (neither ./ nor ~/ works); it has to be a sub-directory. So the following was successful:-</p>

```<code>file_mounts: {"~/run_files": "./run_files"}
</code>```

Body:
I am trying to distribute a small number of files to each node in a Ray cluster on AWS EC2, using the file_mounts block in the configuration file:-

file_mounts: {
    "./": "./run_files"
}

The cluster launches with only a master node, onto which the contents of the run_files directory have been correctly copied. However, the two worker nodes that were requested do not launch. If I omit the file_mounts section, the workers launch. The Ray monitor indicates that there is a problem locating the file libtcl.so in the matplotlib sub-directory of the Anaconda3 installation.  This file is on the correct path on the master node so it appears that the setup on worker nodes is not working properly:-

$ ray exec ray_conf.yaml  'tail -n 100 -f /tmp/ray/session_*/logs/monitor*'
2019-05-29 19:36:14,019 INFO updater.py:95 -- NodeUpdater: Waiting for IP of i-073950262949fe9a8...
2019-05-29 19:36:14,019 INFO log_timer.py:21 -- NodeUpdater: i-073950262949fe9a8: Got IP [LogTimer=362ms]
2019-05-29 19:36:14,025 INFO updater.py:272 -- NodeUpdater: Running tail -n 100 -f /tmp/ray/session_*/logs/monitor* on 54.175.173.233...
==> /tmp/ray/session_2019-05-29_23-35-49_842129_4407/logs/monitor.err <==
Traceback (most recent call last):
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/monitor.py", line 376, in <module>
redis_password=args.redis_password)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/monitor.py", line 54, in __init__
self.load_metrics)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 349, in __init__
self.reload_config(errors_fatal=True)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 523, in reload_config
raise e
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 516, in reload_config
new_config["worker_start_ray_commands"]
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 790, in hash_runtime_conf
add_content_hashes(local_path)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 778, in add_content_hashes
add_hash_of_file(fpath)
  File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/autoscaler/autoscaler.py", line 764, in add_hash_of_file
with open(fpath, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: './anaconda3/pkgs/matplotlib-2.1.0-py36hba5de38_0/lib/libtcl.so'

==> /tmp/ray/session_2019-05-29_23-35-49_842129_4407/logs/monitor.out <==

(Note that this problem follows on from the question "Workers not being launched on EC2 by ray", I have continued in a new question because the source of the error is now more specifically identified.)

Body:
I think that the libtcl.so error message is very misleading.  The problem is that the file_mounts remote path cannot be the home directory on the workers (neither ./ nor ~/ works); it has to be a sub-directory. So the following was successful:-

file_mounts: {"~/run_files": "./run_files"}


问:
using values instead of pointers as function arguments
I have this function "cost_compare" that I would like to offload on FPGA for some experimental purposes. This function, how it is called and its arguments are as follows.

The synthesis tool doesn't accept double pointers as arguments for HW functions (in fact it is very picky about using pointers especially to data structures).

How do I get rid of the pointers in the function argument list? In other words, how do I convert pointers in this example to values? How does this possible solution affect the call by reference performed by spec_qsort?

Thanks in advance
Hooman

```<code>typedef struct arc *arc_p;
typedef LONG cost_t;

typedef struct basket
{
    arc_t *a;
    cost_t cost;
    cost_t abs_cost;
    LONG number;
} BASKET;
/* ... */
typedef struct arc
{
    int id;
    cost_t cost;
    node_p tail, head;
    short ident;
    arc_p nextout, nextin;
    flow_t flow;
    cost_t org_cost;
} arc;
/* ... */
extern int cost_compare( BASKET **b1, BASKET **b2 );
/* ... */
int cost_compare( BASKET **b1, BASKET **b2 )
{
    if( (*b1)->abs_cost < (*b2)->abs_cost )
        return 1;
    if( (*b1)->abs_cost > (*b2)->abs_cost )
        return -1;
    if( (*b1)->a->id > (*b2)->a->id )
        return 1;
    else
        return -1;
}
/* ... */
spec_qsort(perm + 1, basket_sizes[thread], sizeof(BASKET*),
           (int (*)(const void *, const void *))cost_compare);
/* ... */
BASKET* max, *act;
for (j = 1; j < num_threads; j++) {
    act = *perm_p[j];
    if (act->number >= 0) {
        if (!max || cost_compare(&act, &max) < 0) {
            max = act;
            max_pos = j;
        }
    }
    /* ... */
    BASKET*     max_basket;
    static BASKET    **opt_basket;

    for (i = 0; i< num_threads; i++) {
        if ((!max_basket && opt_basket[i]) || (opt_basket[i] &&
                                               cost_compare(&opt_basket[i], &max_basket) < 0)) {
            max_basket = opt_basket[i];
        }
    }
/* ... */
</code>```

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

Thanks @Gerardo Zinno. When I run in SW, your approach (in the last paragraph) works fine. However, when I synthesis 'cost_compare' on FPGA using Xilinx SDSoC, it only works for

```<code>if(b1->abs_cost < b2->abs_cost)
</code>```

but not for

```<code>if( b1->a->id > b2->a->id )
</code>```

and the tools gives me this error:

```<code>ERROR: [SYNCHK 200-61] /home/a1083898/Xilinx_examples/original_routeplanning/src/pbeampp.c:85: unsupported memory access on variable 'x' which is (or contains) an array with unknown size at compile time.

ERROR: [SYNCHK 200-41] /home/a1083898/Xilinx_examples/original_routeplanning/src/pbeampp.c:89: unsupported pointer reinterpretation from type 'i8*' to type '%struct.arc.1.4.6 = type { i32, i64, %struct.node.0.3.5*, %s...' on variable 'x'.

ERROR: [SYNCHK 200-11] /home/a1083898/Xilinx_examples/original_routeplanning/src/pbeampp.c:89: Argument 'x' has an unsynthesizable type 'i8*' (possible cause(s): pointer to pointer or global pointer).

ERROR: [SYNCHK 200-11] /home/a1083898/Xilinx_examples/original_routeplanning/src/pbeampp.c:89: Argument 'x' has an unsynthesizable type 'i8*' (possible cause(s): structure variable cannot be decomposed due to (1) unsupported type conversion; (2) memory copy operation; (3) function pointer used in struct; (4) unsupported pointer comparison).'
</code>```

Also when called by 'qsort' as

```<code>qsort(perm + 1, basket_sizes[thread], sizeof(BASKET*), cost_compare);
</code>```

I receive this warning:

```<code>warning: incompatible pointer types passing 'int (void *, void *)' to parameter of type '__compar_fn_t' (aka 'int (*)(const void *, const void *)') [-Wincompatible-pointer-types]
</code>```

I know this error has nothing to do with C programming but if there is any way to get rid of 'b1->a->id' and 'b2->a->id', I believe the problem could be solved with the HW synthesis tool.

Kind regards
Hooman

答:
In the int cost_compare( BASKET **b1, BASKET **b2 ) you don't need double pointers since you are just comparing elements and not swapping anything. (In fact notice that you aren't using b1 directly, but you're always dereferencing it)

Just change the function signature to int cost_compare( BASKET *b1, BASKET *b2 ). In the function's body  change every (*b1)->abs_const to b1->abs_const.

Also, since spec_qsort expects a function with signature int compare (void *, void *), you could get rid of this cast "(int (*)(const void *, const void *)) cost_compare)" , change the signature of cost_compare to an appropriate one and cast the arguments inside the function, like this:

```<code>int cost_compare( void *a, void *b ){
 BASKET *b1 = a;
 BASKET *b2 = b;
 if(b1->abs_cost < b2->abs_cost){
   return 1;
 }
 ...
 else return -1;
}
</code>```

and then call spec_qsort(perm + 1, basket_sizes[thread], sizeof(BASKET*), cost_compare), in this way everything is easier to read.

EDIT: To answer to one point of the last edit you made, change cost_compare to :

```<code>int cost_compare( const void *a, const void *b ){
     BASKET b1 = *(BASKET *)a;
     BASKET b2 = *(BASKET *)b;
     if(b1.abs_cost < b2.abs_cost){
       return 1;
     }
     ...
     if(*(b1.a).id > *(b2.a).id)
         return 1;
     else return -1;
    }
</code>```

Body:
I have this function "cost_compare" that I would like to offload on FPGA for some experimental purposes. This function, how it is called and its arguments are as follows.

The synthesis tool doesn't accept double pointers as arguments for HW functions (in fact it is very picky about using pointers especially to data structures).

How do I get rid of the pointers in the function argument list? In other words, how do I convert pointers in this example to values? How does this possible solution affect the call by reference performed by spec_qsort?

Thanks in advance
Hooman

typedef struct arc *arc_p;
typedef LONG cost_t;

typedef struct basket
{
    arc_t *a;
    cost_t cost;
    cost_t abs_cost;
    LONG number;
} BASKET;
/* ... */
typedef struct arc
{
    int id;
    cost_t cost;
    node_p tail, head;
    short ident;
    arc_p nextout, nextin;
    flow_t flow;
    cost_t org_cost;
} arc;
/* ... */
extern int cost_compare( BASKET **b1, BASKET **b2 );
/* ... */
int cost_compare( BASKET **b1, BASKET **b2 )
{
    if( (*b1)->abs_cost < (*b2)->abs_cost )
        return 1;
    if( (*b1)->abs_cost > (*b2)->abs_cost )
        return -1;
    if( (*b1)->a->id > (*b2)->a->id )
        return 1;
    else
        return -1;
}
/* ... */
spec_qsort(perm + 1, basket_sizes[thread], sizeof(BASKET*),
           (int (*)(const void *, const void *))cost_compare);
/* ... */
BASKET* max, *act;
for (j = 1; j < num_threads; j++) {
    act = *perm_p[j];
    if (act->number >= 0) {
        if (!max || cost_compare(&act, &max) < 0) {
            max = act;
            max_pos = j;
        }
    }
    /* ... */
    BASKET*     max_basket;
    static BASKET    **opt_basket;

    for (i = 0; i< num_threads; i++) {
        if ((!max_basket && opt_basket[i]) || (opt_basket[i] &&
                                               cost_compare(&opt_basket[i], &max_basket) < 0)) {
            max_basket = opt_basket[i];
        }
    }
/* ... */

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

Thanks @Gerardo Zinno. When I run in SW, your approach (in the last paragraph) works fine. However, when I synthesis 'cost_compare' on FPGA using Xilinx SDSoC, it only works for

if(b1->abs_cost < b2->abs_cost)

but not for

if( b1->a->id > b2->a->id )

and the tools gives me this error:

ERROR: [SYNCHK 200-61] /home/a1083898/Xilinx_examples/original_routeplanning/src/pbeampp.c:85: unsupported memory access on variable 'x' which is (or contains) an array with unknown size at compile time.

ERROR: [SYNCHK 200-41] /home/a1083898/Xilinx_examples/original_routeplanning/src/pbeampp.c:89: unsupported pointer reinterpretation from type 'i8*' to type '%struct.arc.1.4.6 = type { i32, i64, %struct.node.0.3.5*, %s...' on variable 'x'.

ERROR: [SYNCHK 200-11] /home/a1083898/Xilinx_examples/original_routeplanning/src/pbeampp.c:89: Argument 'x' has an unsynthesizable type 'i8*' (possible cause(s): pointer to pointer or global pointer).

ERROR: [SYNCHK 200-11] /home/a1083898/Xilinx_examples/original_routeplanning/src/pbeampp.c:89: Argument 'x' has an unsynthesizable type 'i8*' (possible cause(s): structure variable cannot be decomposed due to (1) unsupported type conversion; (2) memory copy operation; (3) function pointer used in struct; (4) unsupported pointer comparison).'

Also when called by 'qsort' as

qsort(perm + 1, basket_sizes[thread], sizeof(BASKET*), cost_compare);

I receive this warning:

warning: incompatible pointer types passing 'int (void *, void *)' to parameter of type '__compar_fn_t' (aka 'int (*)(const void *, const void *)') [-Wincompatible-pointer-types]

I know this error has nothing to do with C programming but if there is any way to get rid of 'b1->a->id' and 'b2->a->id', I believe the problem could be solved with the HW synthesis tool.

Kind regards
Hooman

Body:
In the int cost_compare( BASKET **b1, BASKET **b2 ) you don't need double pointers since you are just comparing elements and not swapping anything. (In fact notice that you aren't using b1 directly, but you're always dereferencing it)

Just change the function signature to int cost_compare( BASKET *b1, BASKET *b2 ). In the function's body  change every (*b1)->abs_const to b1->abs_const.

Also, since spec_qsort expects a function with signature int compare (void *, void *), you could get rid of this cast "(int (*)(const void *, const void *)) cost_compare)" , change the signature of cost_compare to an appropriate one and cast the arguments inside the function, like this:

int cost_compare( void *a, void *b ){
 BASKET *b1 = a;
 BASKET *b2 = b;
 if(b1->abs_cost < b2->abs_cost){
   return 1;
 }
 ...
 else return -1;
}

and then call spec_qsort(perm + 1, basket_sizes[thread], sizeof(BASKET*), cost_compare), in this way everything is easier to read.

EDIT: To answer to one point of the last edit you made, change cost_compare to :

int cost_compare( const void *a, const void *b ){
     BASKET b1 = *(BASKET *)a;
     BASKET b2 = *(BASKET *)b;
     if(b1.abs_cost < b2.abs_cost){
       return 1;
     }
     ...
     if(*(b1.a).id > *(b2.a).id)
         return 1;
     else return -1;
    }


问:
Export a single worksheet to a new workbook using VBA and a button
I have a worksheet that has a button, once clicked it will export that sheet into a new workbook and allow the user to save the new workbook to their specified location.

Before upgrading to excel 2016 this code worked fine, but now it's hitting my error handler.  I am fairly new to VBA and did not create this code to begin with, so I am not sure if there is an easier way or if I just need to enter a new case for 2016 users and what that new code should say.

Here is the current code:

```<code>Private Sub SaveIt(SaveName As String)
Dim Fullname As String
Dim FileName As String
Dim Result As String
On Error GoTo ErrHandler

SaveName = SaveName & "\Premium Comparison"
Select Case Int(Application.Version)
  Case 11
   Application.Dialogs(xlDialogSaveAs).Show arg1:=SaveName ', arg2:=56, no arg2 is used in 2003,arg2 is to save 2003 in excel 2010
  Case 14
   Application.DisplayAlerts = False
   Result = Application.Dialogs(xlDialogSaveAs).Show(arg1:=SaveName, arg2:=51)   'xlsx format in 2010
   If Result Then
    Fullname = ActiveWorkbook.Fullname
    FileName = ActiveWorkbook.Name
    Application.Workbooks(FileName).Close SaveChanges:=False
    Application.Workbooks.Open FileName:=Fullname, UpdateLinks:=False
    Application.DisplayAlerts = True
   Else
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
   End If
  Case 15
   Application.DisplayAlerts = False
   Result = Application.Dialogs(xlDialogSaveAs).Show(arg1:=SaveName, arg2:=51)   'xlsx format in 2010
   If Result Then
    Fullname = ActiveWorkbook.Fullname
    FileName = ActiveWorkbook.Name
    Application.Workbooks(FileName).Close SaveChanges:=False
    Application.Workbooks.Open FileName:=Fullname, UpdateLinks:=False
    Application.DisplayAlerts = True
   Else
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
   End If
  Case Else
   MsgBox "Invalid excel version - " & Application.Version
End Select
Workbooks(CWName).Worksheets("Premium Comparison").Protect "Racers"
Exit Sub
ErrHandler:
'User pressed the Cancel button
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
Workbooks(CWName).Worksheets("Premium Comparison").Protect "Racers"
Exit Sub
End Sub
</code>```

We haven't all been upgraded yet, so I still need 2010 users to be able to export/save but also allow 2016 users to do so.  Currently they are just getting the Invalid excel version message.

答:
Untested just FYI, but I would combine your identical "Case Statements" by using Case X To Y and increment 15 to 16 which equals Office 2016.

Sources:

https://www.ozgrid.com/VBA/select-case.htm

https://www.rondebruin.nl/win/s9/win012.htm

Code:

```<code>Private Sub SaveIt(SaveName As String)
Dim Fullname As String
Dim FileName As String
Dim Result As String
On Error GoTo ErrHandler

SaveName = SaveName & "\Premium Comparison"
Select Case Int(Application.Version)
  Case 11 ' Office 2003
   Application.Dialogs(xlDialogSaveAs).Show arg1:=SaveName ', arg2:=56, no arg2 is used in 2003,arg2 is to save 2003 in excel 2010
  Case 14 to 16 ' Office 2010 --> Office 2016
   Application.DisplayAlerts = False
   Result = Application.Dialogs(xlDialogSaveAs).Show(arg1:=SaveName, arg2:=51)   'xlsx format in 2010
   If Result Then
    Fullname = ActiveWorkbook.Fullname
    FileName = ActiveWorkbook.Name
    Application.Workbooks(FileName).Close SaveChanges:=False
    Application.Workbooks.Open FileName:=Fullname, UpdateLinks:=False
    Application.DisplayAlerts = True
   Else
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
   End If
  Case Else
   MsgBox "Invalid excel version - " & Application.Version
End Select
Workbooks(CWName).Worksheets("Premium Comparison").Protect "Racers"
Exit Sub
ErrHandler:
'User pressed the Cancel button
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
Workbooks(CWName).Worksheets("Premium Comparison").Protect "Racers"
Exit Sub
End Sub
</code>```

Body:
I have a worksheet that has a button, once clicked it will export that sheet into a new workbook and allow the user to save the new workbook to their specified location.

Before upgrading to excel 2016 this code worked fine, but now it's hitting my error handler.  I am fairly new to VBA and did not create this code to begin with, so I am not sure if there is an easier way or if I just need to enter a new case for 2016 users and what that new code should say.

Here is the current code:

Private Sub SaveIt(SaveName As String)
Dim Fullname As String
Dim FileName As String
Dim Result As String
On Error GoTo ErrHandler

SaveName = SaveName & "\Premium Comparison"
Select Case Int(Application.Version)
  Case 11
   Application.Dialogs(xlDialogSaveAs).Show arg1:=SaveName ', arg2:=56, no arg2 is used in 2003,arg2 is to save 2003 in excel 2010
  Case 14
   Application.DisplayAlerts = False
   Result = Application.Dialogs(xlDialogSaveAs).Show(arg1:=SaveName, arg2:=51)   'xlsx format in 2010
   If Result Then
    Fullname = ActiveWorkbook.Fullname
    FileName = ActiveWorkbook.Name
    Application.Workbooks(FileName).Close SaveChanges:=False
    Application.Workbooks.Open FileName:=Fullname, UpdateLinks:=False
    Application.DisplayAlerts = True
   Else
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
   End If
  Case 15
   Application.DisplayAlerts = False
   Result = Application.Dialogs(xlDialogSaveAs).Show(arg1:=SaveName, arg2:=51)   'xlsx format in 2010
   If Result Then
    Fullname = ActiveWorkbook.Fullname
    FileName = ActiveWorkbook.Name
    Application.Workbooks(FileName).Close SaveChanges:=False
    Application.Workbooks.Open FileName:=Fullname, UpdateLinks:=False
    Application.DisplayAlerts = True
   Else
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
   End If
  Case Else
   MsgBox "Invalid excel version - " & Application.Version
End Select
Workbooks(CWName).Worksheets("Premium Comparison").Protect "Racers"
Exit Sub
ErrHandler:
'User pressed the Cancel button
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
Workbooks(CWName).Worksheets("Premium Comparison").Protect "Racers"
Exit Sub
End Sub

We haven't all been upgraded yet, so I still need 2010 users to be able to export/save but also allow 2016 users to do so.  Currently they are just getting the Invalid excel version message.

Body:
Untested just FYI, but I would combine your identical "Case Statements" by using Case X To Y and increment 15 to 16 which equals Office 2016.

Sources:

https://www.ozgrid.com/VBA/select-case.htm

https://www.rondebruin.nl/win/s9/win012.htm

Code:

Private Sub SaveIt(SaveName As String)
Dim Fullname As String
Dim FileName As String
Dim Result As String
On Error GoTo ErrHandler

SaveName = SaveName & "\Premium Comparison"
Select Case Int(Application.Version)
  Case 11 ' Office 2003
   Application.Dialogs(xlDialogSaveAs).Show arg1:=SaveName ', arg2:=56, no arg2 is used in 2003,arg2 is to save 2003 in excel 2010
  Case 14 to 16 ' Office 2010 --> Office 2016
   Application.DisplayAlerts = False
   Result = Application.Dialogs(xlDialogSaveAs).Show(arg1:=SaveName, arg2:=51)   'xlsx format in 2010
   If Result Then
    Fullname = ActiveWorkbook.Fullname
    FileName = ActiveWorkbook.Name
    Application.Workbooks(FileName).Close SaveChanges:=False
    Application.Workbooks.Open FileName:=Fullname, UpdateLinks:=False
    Application.DisplayAlerts = True
   Else
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
   End If
  Case Else
   MsgBox "Invalid excel version - " & Application.Version
End Select
Workbooks(CWName).Worksheets("Premium Comparison").Protect "Racers"
Exit Sub
ErrHandler:
'User pressed the Cancel button
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
Workbooks(CWName).Worksheets("Premium Comparison").Protect "Racers"
Exit Sub
End Sub


问:
Screenshots made on an iPhone XR are not accepted for 6.5 inch screenshots on App Store Connect
I just bought a new iPhone XR so I could make the screenshots for my App Store app. Starting March 27th 2019, you need to provide 6.5" (new phone models) screenshots:

However, App Store Connect is not accepting my screenshots made with this device. After further research, I found out that iPhone XR is actually 6.1":

I am not from the iOS world (I mainly work with Google and Android), so I am wondering if I am missing something, or are the docs wrong?

答:
Although iPhone XR and XS Max screens has the same size in terms of POINTS, they are not the same in terms of PIXELS (and inches).

```<code>XR:     6.1in, 828x1792 @2x
XS Max: 6.5in, 1242x2688 @3x  <--- you want this one.
</code>```

There is confusion for required size because the spec says to use 6.5in screen for both XR and XS Max, implying they're both the same size.

Just use the XS Max simulator to take screenshots and you should be good.  I tried it just now, got the needed size.

Body:
Although iPhone XR and XS Max screens has the same size in terms of POINTS, they are not the same in terms of PIXELS (and inches).

XR:     6.1in, 828x1792 @2x
XS Max: 6.5in, 1242x2688 @3x  <--- you want this one.

There is confusion for required size because the spec says to use 6.5in screen for both XR and XS Max, implying they're both the same size.

Just use the XS Max simulator to take screenshots and you should be good.  I tried it just now, got the needed size.


问:
Cutting a database down to size
Say you have a database that has served a company for 10 years. It is 500GB in size, it has myriad tables, stored procedures and triggers.

Now say you wish to create a cut down version of the database to use as a test bed for use in integration testing and for individual testers and developers to spin up instances of to play around with.

In broad terms how would you set about this task?

In case it matters, the database I have in mind is SQL Server 2008.

Edit: removed "unit testing" because of course unit tests should not test db integration

答: I would under no circumstances allow developers to develop against a smaller database when it will have to run on on one this size. You will have problems that only arise when things go to prod and this is a foolish idea. The queries that work well on small datasets are not the queries that work well on large datasets. The time wasted writing queries that cannot not run on production is one reason why it is foolish to allow developers to work with a small set of data. </p>

Title: Cutting a database down to size


问:
Default expanded in lazy loaded mode Element UI Tree - Vue
I am using element ui tree with lazy load.

I am trying to set default nodes expanded.

But seems lazy loading and expanded are not working together.

```<code><el-tree :data="DocumentField" class="fullHeight" lazy :load="loadNode" :default-expanded-keys="[0]">
</code>```

Following is the reproduction of the same.

https://codepen.io/anon/pen/oRQXxQ?editors=1010

So is it possible to keep default node expanded and lazy loading work only with non expanded nodes?

答:
You need to set node-key to make it work

```<code><el-tree
  :props="props"
  :load="loadNode"
         :default-expanded-keys="[2, 3]"
  lazy
  node-key="id"
  show-checkbox>
</el-tree>
</code>```

Demo on codepen

Body:
I am using element ui tree with lazy load.

I am trying to set default nodes expanded.

But seems lazy loading and expanded are not working together.

<el-tree :data="DocumentField" class="fullHeight" lazy :load="loadNode" :default-expanded-keys="[0]">

Following is the reproduction of the same.

https://codepen.io/anon/pen/oRQXxQ?editors=1010

So is it possible to keep default node expanded and lazy loading work only with non expanded nodes?

Body:
You need to set node-key to make it work

<el-tree
  :props="props"
  :load="loadNode"
         :default-expanded-keys="[2, 3]"
  lazy
  node-key="id"
  show-checkbox>
</el-tree>

Demo on codepen


问:
Discrepancy between Explain Analyze Actual Row Scanned vs. Total Row in Table
Recently we experienced a performance problem in Production Aurora PG cluster. This is an EXPLAIN ANALYZE of the query.

The majority of the time is spent on ```Bitmap Index Scan on job_stage  (cost=0.00..172.93 rows=9666 width=0) (actual time=238.410..238.410 rows=2019444 loops=1)``` where 2019444 are scanned. However, what troubles me is that there are only 70k rows in this table. Autovacuum is turned on, but the RDS was overloaded recently from another issue. We suspect that the autovacuum was running behind. If that is the case, would it explain our observation the scanned row exceeds actual row in table?

```
Nested Loop  (cost=229.16..265.28 rows=1 width=464) (actual time=239.815..239.815 rows=0 loops=1)
  ->  Nested Loop  (cost=228.62..252.71 rows=1 width=540) (actual time=239.814..239.814 rows=0 loops=1)
        Join Filter: (job.scanner_uuid = scanner_resource_pool.resource_uuid)
        Rows Removed by Join Filter: 1
        ->  Index Scan using scanner_resource_pool_scanner_index on scanner_resource_pool  (cost=0.41..8.43 rows=1 width=115) (actual time=0.017..0.019 rows=1 loops=1)
              Index Cond: ((box_uuid = '5d8a7e0c-23ff-4853-bb6d-ffff6a38afa7'::text) AND (scanner_uuid = '9be9ac50-de05-4ddd-9545-ddddc484dce'::text))
        ->  Bitmap Heap Scan on job  (cost=228.22..244.23 rows=4 width=464) (actual time=239.790..239.791 rows=1 loops=1)
              Recheck Cond: ((box_uuid = '5d8a7e0c-23ff-4853-bb6d-ffff6a38afa7'::text) AND (stage = 'active'::text))
              Rows Removed by Index Recheck: 6
              Heap Blocks: exact=791
              ->  BitmapAnd  (cost=228.22..228.22 rows=4 width=0) (actual time=238.913..238.913 rows=0 loops=1)
                    ->  Bitmap Index Scan on job_box_status  (cost=0.00..55.04 rows=1398 width=0) (actual time=0.183..0.183 rows=899 loops=1)
                          Index Cond: (box_uuid = '5d8a7e0c-23ff-4853-bb6d-ffff6a38afa7'::text)
                    ->  Bitmap Index Scan on job_stage  (cost=0.00..172.93 rows=9666 width=0) (actual time=238.410..238.410 rows=2019444 loops=1)
                          Index Cond: (stage = 'active'::text)
  ->  Index Only Scan using uc_box_uuid on scanner  (cost=0.54..12.56 rows=1 width=87) (never executed)
        Index Cond: ((box_uuid = '5d8a7e0c-23ff-4853-bb6d-ffff6a38afa7'::text) AND (uuid = '9be9ac50-de05-4ddd-9545-ddddc484dce'::text))
        Heap Fetches: 0
Planning time: 1.274 ms
Execution time: 239.876 ms
```

答: I found my answer by confirming with AWS. If autovacuum was running behind, the EXPLAIN ANALYZE result may show this discrepancy.</p>

Body:
Recently we experienced a performance problem in Production Aurora PG cluster. This is an EXPLAIN ANALYZE of the query.

The majority of the time is spent on
Bitmap Index Scan on job_stage  (cost=0.00..172.93 rows=9666 width=0) (actual time=238.410..238.410 rows=2019444 loops=1)
 where 2019444 are scanned. However, what troubles me is that there are only 70k rows in this table. Autovacuum is turned on, but the RDS was overloaded recently from another issue. We suspect that the autovacuum was running behind. If that is the case, would it explain our observation the scanned row exceeds actual row in table?

Nested Loop  (cost=229.16..265.28 rows=1 width=464) (actual time=239.815..239.815 rows=0 loops=1)
  ->  Nested Loop  (cost=228.62..252.71 rows=1 width=540) (actual time=239.814..239.814 rows=0 loops=1)
        Join Filter: (job.scanner_uuid = scanner_resource_pool.resource_uuid)
        Rows Removed by Join Filter: 1
        ->  Index Scan using scanner_resource_pool_scanner_index on scanner_resource_pool  (cost=0.41..8.43 rows=1 width=115) (actual time=0.017..0.019 rows=1 loops=1)
              Index Cond: ((box_uuid = '5d8a7e0c-23ff-4853-bb6d-ffff6a38afa7'::text) AND (scanner_uuid = '9be9ac50-de05-4ddd-9545-ddddc484dce'::text))
        ->  Bitmap Heap Scan on job  (cost=228.22..244.23 rows=4 width=464) (actual time=239.790..239.791 rows=1 loops=1)
              Recheck Cond: ((box_uuid = '5d8a7e0c-23ff-4853-bb6d-ffff6a38afa7'::text) AND (stage = 'active'::text))
              Rows Removed by Index Recheck: 6
              Heap Blocks: exact=791
              ->  BitmapAnd  (cost=228.22..228.22 rows=4 width=0) (actual time=238.913..238.913 rows=0 loops=1)
                    ->  Bitmap Index Scan on job_box_status  (cost=0.00..55.04 rows=1398 width=0) (actual time=0.183..0.183 rows=899 loops=1)
                          Index Cond: (box_uuid = '5d8a7e0c-23ff-4853-bb6d-ffff6a38afa7'::text)
                    ->  Bitmap Index Scan on job_stage  (cost=0.00..172.93 rows=9666 width=0) (actual time=238.410..238.410 rows=2019444 loops=1)
                          Index Cond: (stage = 'active'::text)
  ->  Index Only Scan using uc_box_uuid on scanner  (cost=0.54..12.56 rows=1 width=87) (never executed)
        Index Cond: ((box_uuid = '5d8a7e0c-23ff-4853-bb6d-ffff6a38afa7'::text) AND (uuid = '9be9ac50-de05-4ddd-9545-ddddc484dce'::text))
        Heap Fetches: 0
Planning time: 1.274 ms
Execution time: 239.876 ms


问:
MouseClick and MoveTo event is not working on the 2nd Part that spawned
I'm working on a project that the player clicks on an object and it walks over to it, wait a second, then the object is removed from the game and points update on the leaderboard. The problem is it only works on the first round. The 2nd time, the new part spawned and it does have the ClickDetector as its child, but it does not function.

```<code>local flowers = game.ReplicatedStorage.Flowers.level1:GetChildren()
local selection = math.random(1,#flowers)
local Clone = flowers[selection]:Clone()

local ClickDetector = Instance.new("ClickDetector")
ClickDetector.Parent = Clone
ClickDetector.MaxActivationDistance = 500

local spawners = workspace.Spawners.level1:GetChildren()
local spawnSelection = math.random(1,#spawners)
local spawner = spawners[spawnSelection]

while true do

    wait(1)
    if Clone.Parent == nil then
        Clone.Parent = workspace.Flowers.level1
        Clone.CFrame = spawner.CFrame + Vector3.new(math.random(-5,5),1,math.random(-5,5))
        print("Clone added")

        ClickDetector.MouseClick:Connect(function(playerWhoClicked)
            playerWhoClicked.Character.Humanoid:MoveTo(Clone.Position,Clone)
            print("clicked")

            wait(1)

            Clone:Remove()
            print("Clone removed")

            local flowerValue = playerWhoClicked.leaderstats.Flowers
            local coinsValue = playerWhoClicked.leaderstats.Coins
            flowerValue.Value = flowerValue.Value + 1
            coinsValue.Value = coinsValue.Value + 5
        end)
    end

end
</code>```

There are no error messages on output. Just that on the new spawned part, "clicked" is not printing.

答:
Your problem is that the function in the ClickDetector is using a reference to Clone, and when Clone is destroyed, it doesn't exist anymore. Your code would work if it simply unparented the object from the world rather than destroyed it.

```<code>-- choose a random flower and clone it
local flowers = game.ReplicatedStorage.Flowers.level1:GetChildren()
local selection = math.random(1,#flowers)
local Clone = flowers[selection]:Clone()

-- configure a click detector into the cloned flower
local ClickDetector = Instance.new("ClickDetector")
ClickDetector.Parent = Clone
ClickDetector.MaxActivationDistance = 500
ClickDetector.MouseClick:Connect(function(playerWhoClicked)
    -- when a player clicks on the flower, move the player over to it
    playerWhoClicked.Character.Humanoid:MoveTo(Clone.Position,Clone)
    print("clicked")

    -- remove the cloned flower from the workspace, but don't destroy it
    wait(1)
    Clone.Parent = nil -- << simply hide it from the world

    -- award the player with some points
    local flowerValue = playerWhoClicked.leaderstats.Flowers
    local coinsValue = playerWhoClicked.leaderstats.Coins
    flowerValue.Value = flowerValue.Value + 1
    coinsValue.Value = coinsValue.Value + 5
end)

-- choose a random spawn location
local spawners = workspace.Spawners.level1:GetChildren()
local spawnSelection = math.random(1,#spawners)
local spawner = spawners[spawnSelection]

-- begin a loop to place the flower into the world
while true do

    wait(1)
    -- if the flower isn't visible, place it near a specific location
    if Clone.Parent == nil then
        Clone.Parent = workspace.Flowers.level1
        Clone.CFrame = spawner.CFrame + Vector3.new(math.random(-5,5),1,math.random(-5,5))
        print("Clone added into the world")

        -- now wait for a player to click on it and unparent it.
        -- this case will come back around a second later, and it will be added back in.
    end

end
</code>```

This way, you don't have to worry about the second or third spawning of the flower, because there will only ever be one flower.

Body:
I'm working on a project that the player clicks on an object and it walks over to it, wait a second, then the object is removed from the game and points update on the leaderboard. The problem is it only works on the first round. The 2nd time, the new part spawned and it does have the ClickDetector as its child, but it does not function.

local flowers = game.ReplicatedStorage.Flowers.level1:GetChildren()
local selection = math.random(1,#flowers)
local Clone = flowers[selection]:Clone()

local ClickDetector = Instance.new("ClickDetector")
ClickDetector.Parent = Clone
ClickDetector.MaxActivationDistance = 500

local spawners = workspace.Spawners.level1:GetChildren()
local spawnSelection = math.random(1,#spawners)
local spawner = spawners[spawnSelection]

while true do

    wait(1)
    if Clone.Parent == nil then
        Clone.Parent = workspace.Flowers.level1
        Clone.CFrame = spawner.CFrame + Vector3.new(math.random(-5,5),1,math.random(-5,5))
        print("Clone added")

        ClickDetector.MouseClick:Connect(function(playerWhoClicked)
            playerWhoClicked.Character.Humanoid:MoveTo(Clone.Position,Clone)
            print("clicked")

            wait(1)

            Clone:Remove()
            print("Clone removed")

            local flowerValue = playerWhoClicked.leaderstats.Flowers
            local coinsValue = playerWhoClicked.leaderstats.Coins
            flowerValue.Value = flowerValue.Value + 1
            coinsValue.Value = coinsValue.Value + 5
        end)
    end

end

There are no error messages on output. Just that on the new spawned part, "clicked" is not printing.

Body:
Your problem is that the function in the ClickDetector is using a reference to Clone, and when Clone is destroyed, it doesn't exist anymore. Your code would work if it simply unparented the object from the world rather than destroyed it.

-- choose a random flower and clone it
local flowers = game.ReplicatedStorage.Flowers.level1:GetChildren()
local selection = math.random(1,#flowers)
local Clone = flowers[selection]:Clone()

-- configure a click detector into the cloned flower
local ClickDetector = Instance.new("ClickDetector")
ClickDetector.Parent = Clone
ClickDetector.MaxActivationDistance = 500
ClickDetector.MouseClick:Connect(function(playerWhoClicked)
    -- when a player clicks on the flower, move the player over to it
    playerWhoClicked.Character.Humanoid:MoveTo(Clone.Position,Clone)
    print("clicked")

    -- remove the cloned flower from the workspace, but don't destroy it
    wait(1)
    Clone.Parent = nil -- << simply hide it from the world

    -- award the player with some points
    local flowerValue = playerWhoClicked.leaderstats.Flowers
    local coinsValue = playerWhoClicked.leaderstats.Coins
    flowerValue.Value = flowerValue.Value + 1
    coinsValue.Value = coinsValue.Value + 5
end)

-- choose a random spawn location
local spawners = workspace.Spawners.level1:GetChildren()
local spawnSelection = math.random(1,#spawners)
local spawner = spawners[spawnSelection]

-- begin a loop to place the flower into the world
while true do

    wait(1)
    -- if the flower isn't visible, place it near a specific location
    if Clone.Parent == nil then
        Clone.Parent = workspace.Flowers.level1
        Clone.CFrame = spawner.CFrame + Vector3.new(math.random(-5,5),1,math.random(-5,5))
        print("Clone added into the world")

        -- now wait for a player to click on it and unparent it.
        -- this case will come back around a second later, and it will be added back in.
    end

end

This way, you don't have to worry about the second or third spawning of the flower, because there will only ever be one flower.


问:
How do you detect a string within a file name in batch?
I am trying to sort a series of folders containing thousands of company documents into an alphabetically sorted list of individual folders with the naming scheme "last name, first name".

The documents I am trying to sort have the name of their subject in the file's name. For example, one file could be called "Baggins_Frodo_Resume" or "Snow, Jon - Resume". I need to sort those files into folders called "Snow, John" and "Baggins, Frodo" respectively.

I have the name of each folder on a text file called "list of names.txt" in the format:

```<code>Last First
Baggins Frodo
Snow Jon
</code>```

Written out in plain English, I would like to have the batch file follow the steps outlined below. I used brackets around terms that should be variables.

Read the first line in the file "list of names.txt"

Assign the last name from the list to the variable [last name] and the first name to the variable [first name]

Within directory [C:\folder that needs sorting]...

if [file name] contains the text [last name] AND [first name] then...

Copy [file] to a folder called [last name, first name]

Repeat until no more files containing the name exist

Move on to the next line on "list of names.txt" and repeat.

I apologize in advance for my erroneous code, I am usually just barely able to figure out the basics of batch when I need it but this time I'm really struggling.

I had some trouble formatting the code below so here is a link to what I have with adjusted spacing and highlights.

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
rem Read the first name on the list and assign it to a variable
for /f "tokens=*" %%f in ("list of names.txt") do (
    for /f "tokens=*" %%F in ('dir /S /B /A:-D "%%f"') do (
        for %%N in ("%%F") do (
            set name=%%~NN
            set dest="%%~NN"
            set the directory
            cd /d %userprofile%\desktop\"folder to sort"
            rem find each file within the directory that contains the current name from the list
            find /I . -name "*%%~NN*" ! -name "*:*" -print if errorlevel 0 then(
                rem copy matching files to their respective folder
                copy "%%F" "%%~NN"\!name!!ext!"
            ) else (
echo No additional matches found
pause
end
            )
        )
    )
)
</code>```

There are a couple of issues here that I would really appreciate help fixing.

As my question suggests I'm not sure how to search just the name of each file for matches and not the entire contents of the file.

Additionally, I'm not sure how to separate the first/last names from "list of names.txt" to assign them to separate variables.

This is my first post on stackoverflow and in the future, I would like to be able to adjust the color of my code properly. I see in the help section that " In many cases, the syntax highlighting language will be inferred from the question's tags," but that didn't occur in my case. Is there anything obvious I'm missing?

Thanks in advance for your time, I really appreciate it!

答:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q56380365.txt"
SET /a maxwords=0
rem for each line in the names file...to %%a
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 rem analyse line
 CALL :words %%a
 IF !wordcount! lss 0 GOTO :EOF
 IF !wordcount! gtr !maxwords! SET /a maxwords=!wordcount!
)

:: Now have max # words in maxwords

:scandir
rem for each line in the names file...to %%a
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 REM how many words IN this line?
 CALL :words %%a
 IF !wordcount! equ %maxwords% (
  rem read entire source directory using first word found as a filter
  FOR /f "delims=" %%h IN ('dir /b /a-d "%sourcedir%\!#1!*" 2^>nul') DO (
   CALL :matchname "%%h"
  )
 )
)
SET /a maxwords-=1
IF %maxwords% gtr 0 GOTO scandir

GOTO :EOF

:: Establish "Wordcount" and words as #*; subdir
:words
CALL :clear#
SET /a wordcount=0
SET "allwords=%~1 %~2"
SET "subdir=%~1"
SET "subdir2=%~2"
:: error if more than 2 "words" provided
IF "%~3" neq "" ECHO error IN line %*&SET /a wordcount=-1&GOTO :EOF
:wordloop
SET /a wordcount+=1
CALL :atom %allwords%
SET "#%wordcount%=%car%"
IF DEFINED cdr SET "allwords=%cdr%"&GOTO wordloop
GOTO :EOF

:: First word to car, remainder to cdr
:atom
SET "car=%1"
SET "cdr="
:atomlp
SHIFT
IF "%1" neq "" SET "cdr=%cdr% %1"&GOTO atomlp
IF DEFINED cdr SET "cdr=%cdr:~1%"
GOTO :EOF

:: remove variables starting #
:clear#
For %%b IN (#) DO FOR  /F "delims==" %%a In ('set %%b 2^>Nul') DO SET "%%a="
GOTO :EOF

:: match filename in %1 to %maxwords% words in #* and move if matched
:matchname
SET "file=%~1"
SET /a match=1
:: replace commas, underscores [etc] with spaces
SET "file=%file:,= %"
SET "file=%file:_= %"

:matchloop
CALL :atom %file%
IF /i "%car%" neq "!#%match%!" GOTO :EOF
SET "file=%cdr%"
IF %match% neq %maxwords% SET /a match +=1&GOTO matchloop
:: all matched - move
MD "%destdir%\%subdir%, %subdir2%" 2>NUL >nul
ECHO MOVE "%sourcedir%\%~1" "%destdir%\%subdir%, %subdir2%"
GOTO :eof
```

Landed up a little more complex than I'd anticipated. Since this used delayedexpansion, the usual warnings about special characters like ! and & and other non-alphanumerics should be carefully processed. Normal alphanumerics and commas should be fine.

This approach first examines the names file - q56380365.txt on my system. Rather than simply two names, it allows a quoted string also, so a line like "van der Waals" Johannes can be used. Each line is passed to the :words routine which establishes subdir and subdir2 for the subdirectory construction and also counts the individual words and places them in environment variables #1, #2..#n. If more than 2 strings are passed to :words then it returns wordcount as -1 to flag an error, having reported the line-contents. This ensures the two parts of the name are recognised correctly.

:words itself calls :atom which returns car as the first string in the list and cdr as the remaining strings. The reason for their being so named, I'll leave for someone else to ekthplain.

Having established the maximum number of words in the names file, we then scan the names file in reverse-order of the number of words - simply by reading the names file repeatedly, and matching against a reducing count. Where we have a match, we match the filenames using the first word as a filter. :matchname accepts the filename as %1 and replaces any commas or underscores with spaces to the variable file. We then match the strings in turn against #1...#n until we reach the required number of matched words. If any words fail to match (I used /i to make the match case-insensitive) then the processing of this filename is abandoned. Having matched the required number of words, the required directory is created (2>nul suppresses the error message presuming the problem is "directory already exists") and the file is moved to the required subdirectory.

Note that the md is live, so the directories will be created, but the move command is simply echoed for safety's sake. Remove the echo keyword here to actually move the file...

Note : fix - Comment 'how many words..' should be conventional REM, not :: as labels are not allowed within a for loop (except in circumstances that have been published by others after commendable extensive research, but I have no intention of arranging since a blanket "always use rem" always works)

Body:
I am trying to sort a series of folders containing thousands of company documents into an alphabetically sorted list of individual folders with the naming scheme "last name, first name".

The documents I am trying to sort have the name of their subject in the file's name. For example, one file could be called "Baggins_Frodo_Resume" or "Snow, Jon - Resume". I need to sort those files into folders called "Snow, John" and "Baggins, Frodo" respectively.

I have the name of each folder on a text file called "list of names.txt" in the format:

Last First
Baggins Frodo
Snow Jon

Written out in plain English, I would like to have the batch file follow the steps outlined below. I used brackets around terms that should be variables.

Read the first line in the file "list of names.txt"

Assign the last name from the list to the variable [last name] and the first name to the variable [first name]

Within directory [C:\folder that needs sorting]...

if [file name] contains the text [last name] AND [first name] then...

Copy [file] to a folder called [last name, first name]

Repeat until no more files containing the name exist

Move on to the next line on "list of names.txt" and repeat.

I apologize in advance for my erroneous code, I am usually just barely able to figure out the basics of batch when I need it but this time I'm really struggling.

I had some trouble formatting the code below so here is a link to what I have with adjusted spacing and highlights.

SETLOCAL ENABLEDELAYEDEXPANSION
rem Read the first name on the list and assign it to a variable
for /f "tokens=*" %%f in ("list of names.txt") do (
    for /f "tokens=*" %%F in ('dir /S /B /A:-D "%%f"') do (
        for %%N in ("%%F") do (
            set name=%%~NN
            set dest="%%~NN"
            set the directory
            cd /d %userprofile%\desktop\"folder to sort"
            rem find each file within the directory that contains the current name from the list
            find /I . -name "*%%~NN*" ! -name "*:*" -print if errorlevel 0 then(
                rem copy matching files to their respective folder
                copy "%%F" "%%~NN"\!name!!ext!"
            ) else (
echo No additional matches found
pause
end
            )
        )
    )
)

There are a couple of issues here that I would really appreciate help fixing.

As my question suggests I'm not sure how to search just the name of each file for matches and not the entire contents of the file.

Additionally, I'm not sure how to separate the first/last names from "list of names.txt" to assign them to separate variables.

This is my first post on stackoverflow and in the future, I would like to be able to adjust the color of my code properly. I see in the help section that " In many cases, the syntax highlighting language will be inferred from the question's tags," but that didn't occur in my case. Is there anything obvious I'm missing?

Thanks in advance for your time, I really appreciate it!

Body:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q56380365.txt"
SET /a maxwords=0
rem for each line in the names file...to %%a
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 rem analyse line
 CALL :words %%a
 IF !wordcount! lss 0 GOTO :EOF
 IF !wordcount! gtr !maxwords! SET /a maxwords=!wordcount!
)

:: Now have max # words in maxwords

:scandir
rem for each line in the names file...to %%a
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 REM how many words IN this line?
 CALL :words %%a
 IF !wordcount! equ %maxwords% (
  rem read entire source directory using first word found as a filter
  FOR /f "delims=" %%h IN ('dir /b /a-d "%sourcedir%\!#1!*" 2^>nul') DO (
   CALL :matchname "%%h"
  )
 )
)
SET /a maxwords-=1
IF %maxwords% gtr 0 GOTO scandir

GOTO :EOF

:: Establish "Wordcount" and words as #*; subdir
:words
CALL :clear#
SET /a wordcount=0
SET "allwords=%~1 %~2"
SET "subdir=%~1"
SET "subdir2=%~2"
:: error if more than 2 "words" provided
IF "%~3" neq "" ECHO error IN line %*&SET /a wordcount=-1&GOTO :EOF
:wordloop
SET /a wordcount+=1
CALL :atom %allwords%
SET "#%wordcount%=%car%"
IF DEFINED cdr SET "allwords=%cdr%"&GOTO wordloop
GOTO :EOF

:: First word to car, remainder to cdr
:atom
SET "car=%1"
SET "cdr="
:atomlp
SHIFT
IF "%1" neq "" SET "cdr=%cdr% %1"&GOTO atomlp
IF DEFINED cdr SET "cdr=%cdr:~1%"
GOTO :EOF

:: remove variables starting #
:clear#
For %%b IN (#) DO FOR  /F "delims==" %%a In ('set %%b 2^>Nul') DO SET "%%a="
GOTO :EOF

:: match filename in %1 to %maxwords% words in #* and move if matched
:matchname
SET "file=%~1"
SET /a match=1
:: replace commas, underscores [etc] with spaces
SET "file=%file:,= %"
SET "file=%file:_= %"

:matchloop
CALL :atom %file%
IF /i "%car%" neq "!#%match%!" GOTO :EOF
SET "file=%cdr%"
IF %match% neq %maxwords% SET /a match +=1&GOTO matchloop
:: all matched - move
MD "%destdir%\%subdir%, %subdir2%" 2>NUL >nul
ECHO MOVE "%sourcedir%\%~1" "%destdir%\%subdir%, %subdir2%"
GOTO :eof

Landed up a little more complex than I'd anticipated. Since this used delayedexpansion, the usual warnings about special characters like ! and & and other non-alphanumerics should be carefully processed. Normal alphanumerics and commas should be fine.

This approach first examines the names file - q56380365.txt on my system. Rather than simply two names, it allows a quoted string also, so a line like "van der Waals" Johannes can be used. Each line is passed to the :words routine which establishes subdir and subdir2 for the subdirectory construction and also counts the individual words and places them in environment variables #1, #2..#n. If more than 2 strings are passed to :words then it returns wordcount as -1 to flag an error, having reported the line-contents. This ensures the two parts of the name are recognised correctly.

:words itself calls :atom which returns car as the first string in the list and cdr as the remaining strings. The reason for their being so named, I'll leave for someone else to ekthplain.

Having established the maximum number of words in the names file, we then scan the names file in reverse-order of the number of words - simply by reading the names file repeatedly, and matching against a reducing count. Where we have a match, we match the filenames using the first word as a filter. :matchname accepts the filename as %1 and replaces any commas or underscores with spaces to the variable file. We then match the strings in turn against #1...#n until we reach the required number of matched words. If any words fail to match (I used /i to make the match case-insensitive) then the processing of this filename is abandoned. Having matched the required number of words, the required directory is created (2>nul suppresses the error message presuming the problem is "directory already exists") and the file is moved to the required subdirectory.

Note that the md is live, so the directories will be created, but the move command is simply echoed for safety's sake. Remove the echo keyword here to actually move the file...

Note : fix - Comment 'how many words..' should be conventional REM, not :: as labels are not allowed within a for loop (except in circumstances that have been published by others after commendable extensive research, but I have no intention of arranging since a blanket "always use rem" always works)


问:
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.

答:
So, I found the issue.  If you create a function inside Azure and download it, it will use csx files, which is not what I wanted, but, the local.settings.json contains a ton of settings that are not in the VS generated file.  Copying those into my project made it all work.  You should use your own download, so the settings are correct for you, but, it was settings like this:

```<code>"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"WEBSITE_SLOT_NAME": "Production",
"FUNCTIONS_EXTENSION_VERSION": "~2",
"ScmType": "None",
"WEBSITE_AUTH_ENABLED": "False",
"APPINSIGHTS_INSTRUMENTATIONKEY": "xxxxxx",
"WEBSITE_NODE_DEFAULT_VERSION": "10.14.1",
"WEBSITE_CONTENTAZUREFILECONNECTIONSTRING": "DefaultEndpointsProtocol=xsxxxxxx",
"WEBSITE_CONTENTSHARE": "xxxx",
"WEBSITE_SITE_NAME": "xxxxxx",
"AzureWebJobsStorage": "DefaultEndpointsProtocol=xxxxxxxx"
</code>```

Deploying also caused my project to download missing DLLs, so it seems the wizard in Visual Studio is a complete wash.

Body:
So, I found the issue.  If you create a function inside Azure and download it, it will use csx files, which is not what I wanted, but, the local.settings.json contains a ton of settings that are not in the VS generated file.  Copying those into my project made it all work.  You should use your own download, so the settings are correct for you, but, it was settings like this:

"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"WEBSITE_SLOT_NAME": "Production",
"FUNCTIONS_EXTENSION_VERSION": "~2",
"ScmType": "None",
"WEBSITE_AUTH_ENABLED": "False",
"APPINSIGHTS_INSTRUMENTATIONKEY": "xxxxxx",
"WEBSITE_NODE_DEFAULT_VERSION": "10.14.1",
"WEBSITE_CONTENTAZUREFILECONNECTIONSTRING": "DefaultEndpointsProtocol=xsxxxxxx",
"WEBSITE_CONTENTSHARE": "xxxx",
"WEBSITE_SITE_NAME": "xxxxxx",
"AzureWebJobsStorage": "DefaultEndpointsProtocol=xxxxxxxx"

Deploying also caused my project to download missing DLLs, so it seems the wizard in Visual Studio is a complete wash.