问:
Search with inequalities on string property
We are using NHibernate over SQL Server and SQLite.
The database stores records in rows rather than columns -- each row having Path|Value as columns. Path and Value are both string properties.

For certain values of Path we would like to query for inequalities -- greater-than, less-than, etc.

The trouble we are having is that because the properties are strings, the inequalities are using string comparisons -- for example, searching for Value >= 18 returns rows where Value = 5.  Unfortunately we are having trouble working around this.

1) This restriction produces incorrect results (saying 18 < 5):

Restrictions.Ge("Value", item.Value);

2) We tried casting the value to an integer, but this code produces a SqlException from NHibernate -- Error converting data type nvarchar to bigint.

Restrictions.Le(Projections.Cast(NHibernateUtil.Int64, Projections.Property("SearchString")), item.Value)

3) We were looking for a way to pad the property value with zeros (so that we would get 018 > 005), but could not find a way to do this in NHibernate.

Does anyone have any advice?

Thank you in advance!

答:
Assuming that you want to compare on integer value, with IQueryOver:

1) This restriction produces incorrect results (saying 18 < 5):

Restrictions.Ge("Value", item.Value);

```<code>Restrictions.Ge
    (
    Projections.Cast(NHibernateUtil.Int32, Projections.Property<YourEntity>(x => x.YourProperty))
        , intValue
    )
</code>```

Convert your datatype accordingly. If your C# datatype (intValue) is already numeric, no need to convert it. If your x.YourProperty is already numeric type, no need to convert it. Adjust above code accordingly.

2) We tried casting the value to an integer, but this code produces a SqlException from NHibernate -- Error converting data type nvarchar to bigint.

Restrictions.Le(Projections.Cast(NHibernateUtil.Int64, Projections.Property("SearchString")), item.Value)

Refer the above and check the datatype of item.Value.

Body:
Assuming that you want to compare on integer value, with IQueryOver:

1) This restriction produces incorrect results (saying 18 < 5):

Restrictions.Ge("Value", item.Value);

Restrictions.Ge
    (
    Projections.Cast(NHibernateUtil.Int32, Projections.Property<YourEntity>(x => x.YourProperty))
        , intValue
    )

Convert your datatype accordingly. If your C# datatype (intValue) is already numeric, no need to convert it. If your x.YourProperty is already numeric type, no need to convert it. Adjust above code accordingly.

2) We tried casting the value to an integer, but this code produces a SqlException from NHibernate -- Error converting data type nvarchar to bigint.

Restrictions.Le(Projections.Cast(NHibernateUtil.Int64, Projections.Property("SearchString")), item.Value)

Refer the above and check the datatype of item.Value.


来源: stackexchange

问:
How to print tuples of unicode strings in original language (not u'foo' form)
I have a list of tuples of unicode objects:

```<code>>>> t = [('亀',), ('犬',)]
</code>```

Printing this out, I get:

```<code>>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]
</code>```

which I guess is a list of the utf-8 byte-code representation of those strings?

but what I want to see printed out is, surprise:

```<code>[('亀',), ('犬',)]
</code>```

but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form.

答:
Python source code files are strictly ASCII, so you must use the \u escape sequences unless you specify an encoding. See PEP 0263.

```<code>#!/usr/bin/python
# coding=utf-8
t = [u'亀', u'犬']
print t
</code>```

When you pass an array to print, Python converts the object into a string using Python's rules for string conversions. The output of such conversions are designed for eval(), which is why you see those \u sequences. Here's a hack to get around that based on bobince's solution. The console must accept Unicode or this will throw an exception.

```<code>t = [(u'亀',), (u'犬',)]
print repr(t).decode('raw_unicode_escape')
</code>```

OwnerDisplayName: Daniel H

ContentLicense: CC BY-SA 2.5

Body:
I have a list of tuples of unicode objects:

>>> t = [('亀',), ('犬',)]

Printing this out, I get:

>>> print t
[('\xe4\xba\x80',), ('\xe7\x8a\xac',)]

which I guess is a list of the utf-8 byte-code representation of those strings?

but what I want to see printed out is, surprise:

[('亀',), ('犬',)]

but I'm having an inordinate amount of trouble getting the bytecode back into a human-readable form.

Body:
Python source code files are strictly ASCII, so you must use the \u escape sequences unless you specify an encoding. See PEP 0263.

#!/usr/bin/python
# coding=utf-8
t = [u'亀', u'犬']
print t

When you pass an array to print, Python converts the object into a string using Python's rules for string conversions. The output of such conversions are designed for eval(), which is why you see those \u sequences. Here's a hack to get around that based on bobince's solution. The console must accept Unicode or this will throw an exception.

t = [(u'亀',), (u'犬',)]
print repr(t).decode('raw_unicode_escape')

OwnerDisplayName: Matthew

LastEditorDisplayName: Matthew


问:
Detecting up and down swipes on a Recyclerview in a fragment how can I do that?
So I have a recyclerview loaded with Firebase Firestore Documents and I want to see if it is beeing swiped up or down. Depending on the direction I want to make the adapter.startListening(); again and stop if he swipes down. I also want to hide a button if the user scrolls down. I just need to figure out how can I see if he does that ?

This piece of code was working with left and right but for some reason won´t with up and down ?

```<code>
        new ItemTouchHelper( new ItemTouchHelper.SimpleCallback(0,
                ItemTouchHelper.UP | ItemTouchHelper.DOWN) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                if(direction == ItemTouchHelper.UP){
                    Toast.makeText(getActivity(), "You swiped up", Toast.LENGTH_LONG).show();
                }
            }
        });
</code>```

Here the complete code if it some reason interfers with smth don´t know

```<code>public class HomeFragment extends Fragment {

    View myFragment;
    private ImageButton postButton;
    CollectionReference postsRef;
    FirebaseFirestore db;
    private PostsAdapter adapter;
    FirebaseAuth mAuth;
    RecyclerView recyclerView;

    public static ProfileFragment getInstance() {
        return new ProfileFragment();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myFragment = inflater.inflate(R.layout.fragment_home, container, false);
        postButton = myFragment.findViewById( R.id.postButton);
        recyclerView = myFragment.findViewById(R.id.postlist);
        mAuth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();
        postsRef = db.collection("posts");
        SetupRecyclerView();
        postButton.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendUserToPostActivity();
            }
        });

        new ItemTouchHelper( new ItemTouchHelper.SimpleCallback(0,
                ItemTouchHelper.UP | ItemTouchHelper.DOWN) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                if(direction == ItemTouchHelper.UP){
                    Toast.makeText(getActivity(), "You swiped up", Toast.LENGTH_LONG).show();
                }
            }
        });

        adapter.setOnConfirmClickListener( new PostsAdapter.onConfirmClickListener() {
            @Override
            public void onConfirmClick(DocumentSnapshot documentSnapshot, int position) {
                Posts post = documentSnapshot.toObject(Posts.class);
                String id = documentSnapshot.getId();
                if(post.getUid().equals(mAuth.getCurrentUser().getUid())){
                    adapter.deleteItem(position);
                    Toast.makeText(getActivity(), "Post deleted", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getActivity(), "You cannot delete this", Toast.LENGTH_LONG).show();
                }
            }
        });
        return myFragment;
    }

    @Override
    public void onStart(){
        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        adapter.stopListening();
    }

    private void SetupRecyclerView() {
        Query query = postsRef.orderBy("time", Query.Direction.DESCENDING);
        FirestoreRecyclerOptions<Posts> options = new FirestoreRecyclerOptions.Builder<Posts>().setQuery(query, Posts.class).build();
        adapter = new PostsAdapter(options);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
    }

    private void SendUserToPostActivity() {
        Intent postIntent = new Intent(getActivity(), PostActivity.class);
        startActivity(postIntent);
    }
}
</code>```

答:
You're using the wrong listener. An ItemTouchHelper applies to the individual items within the recyclerview, rather than the view as whole.

What you're looking for is OnScrollListener:

```<code>recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //This is where you can track a scroll change
            }
        });
</code>```

dy in the onScrolled method refers to the change in y position on a scroll event, likewise for dx.

In that method, let's say you wanted to check if the recyclerview reached the limit of scrolling either up or down, then within that onScroll method (or wherever you're checking that), you can add a call to recyclerView.canScrollVertically(int). The int will be a value of -1 for UP, 1 for DOWN, and 0 for FALSE, i.e. cannot scroll.

Checking if the recyclerview reached the bottom:

```<code>if(!recyclerView.canScrollVertically(1)){
    //The recyclerview can no longer scroll downwards, you have reached the bottom
}
</code>```

Editing to add: Your itemTouchHelper also didn't work correctly because vertical directions are to be specified in the first parameter of the callback, and horizontal directions in the second parameter. You passed 0 for the first parameter, so it sees no vertical direction as an option

ContentLicense: CC BY-SA 4.0

Body:
So I have a recyclerview loaded with Firebase Firestore Documents and I want to see if it is beeing swiped up or down. Depending on the direction I want to make the adapter.startListening(); again and stop if he swipes down. I also want to hide a button if the user scrolls down. I just need to figure out how can I see if he does that ?

This piece of code was working with left and right but for some reason won´t with up and down ?

        new ItemTouchHelper( new ItemTouchHelper.SimpleCallback(0,
                ItemTouchHelper.UP | ItemTouchHelper.DOWN) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                if(direction == ItemTouchHelper.UP){
                    Toast.makeText(getActivity(), "You swiped up", Toast.LENGTH_LONG).show();
                }
            }
        });

Here the complete code if it some reason interfers with smth don´t know

public class HomeFragment extends Fragment {

    View myFragment;
    private ImageButton postButton;
    CollectionReference postsRef;
    FirebaseFirestore db;
    private PostsAdapter adapter;
    FirebaseAuth mAuth;
    RecyclerView recyclerView;

    public static ProfileFragment getInstance() {
        return new ProfileFragment();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myFragment = inflater.inflate(R.layout.fragment_home, container, false);
        postButton = myFragment.findViewById( R.id.postButton);
        recyclerView = myFragment.findViewById(R.id.postlist);
        mAuth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();
        postsRef = db.collection("posts");
        SetupRecyclerView();
        postButton.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendUserToPostActivity();
            }
        });

        new ItemTouchHelper( new ItemTouchHelper.SimpleCallback(0,
                ItemTouchHelper.UP | ItemTouchHelper.DOWN) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                if(direction == ItemTouchHelper.UP){
                    Toast.makeText(getActivity(), "You swiped up", Toast.LENGTH_LONG).show();
                }
            }
        });

        adapter.setOnConfirmClickListener( new PostsAdapter.onConfirmClickListener() {
            @Override
            public void onConfirmClick(DocumentSnapshot documentSnapshot, int position) {
                Posts post = documentSnapshot.toObject(Posts.class);
                String id = documentSnapshot.getId();
                if(post.getUid().equals(mAuth.getCurrentUser().getUid())){
                    adapter.deleteItem(position);
                    Toast.makeText(getActivity(), "Post deleted", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getActivity(), "You cannot delete this", Toast.LENGTH_LONG).show();
                }
            }
        });
        return myFragment;
    }

    @Override
    public void onStart(){
        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        adapter.stopListening();
    }

    private void SetupRecyclerView() {
        Query query = postsRef.orderBy("time", Query.Direction.DESCENDING);
        FirestoreRecyclerOptions<Posts> options = new FirestoreRecyclerOptions.Builder<Posts>().setQuery(query, Posts.class).build();
        adapter = new PostsAdapter(options);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
    }

    private void SendUserToPostActivity() {
        Intent postIntent = new Intent(getActivity(), PostActivity.class);
        startActivity(postIntent);
    }
}

Body:
You're using the wrong listener. An ItemTouchHelper applies to the individual items within the recyclerview, rather than the view as whole.

What you're looking for is OnScrollListener:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //This is where you can track a scroll change
            }
        });

dy in the onScrolled method refers to the change in y position on a scroll event, likewise for dx.

In that method, let's say you wanted to check if the recyclerview reached the limit of scrolling either up or down, then within that onScroll method (or wherever you're checking that), you can add a call to recyclerView.canScrollVertically(int). The int will be a value of -1 for UP, 1 for DOWN, and 0 for FALSE, i.e. cannot scroll.

Checking if the recyclerview reached the bottom:

if(!recyclerView.canScrollVertically(1)){
    //The recyclerview can no longer scroll downwards, you have reached the bottom
}

Editing to add: Your itemTouchHelper also didn't work correctly because vertical directions are to be specified in the first parameter of the callback, and horizontal directions in the second parameter. You passed 0 for the first parameter, so it sees no vertical direction as an option


问:
Javascript function scoping and hoisting
I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:

```<code>var a = 1;

function b() {
    a = 10;
    return;

    function a() {}
}
b();
alert(a);
</code>```

Using the code above, the browser will alert "1".

I'm still unsure why it returns "1". Some of the things he says come to mind like:
   All the function declarations are hoisted to the top. You can scope a variable using function.  Still doesn't click for me.

答:
ES5: function hoisting & variable hoisting

function hoisting priority is greater than variable hoisting

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2016-06-01
 * @modified
 *
 * @description function-hoisting.js
 * @augments
 * @example
 * @link
 *
 */

(function() {
  const log = console.log;

  var a = 1;
  function b() {
    a = 10;
    log(`local a`, a)
    return;
    // function hoisting priority is greater than variable hoisting
    function a() {}
  }
  b();
  log(`global a`, a);
  // local a 10
  // global a 1
})();

```

<p>which is equal to</p>

<pre class="lang-js prettyprint-override"><code>(function() {
  const log = console.log;

  // define "a" in global scope
  var a = 1;
  function b() {
    // define "a" in local scope
    var a ;
    // assign function to a
    a = function () {};
    // overwrites local variable "a"
    a = 10;
    log(`local a`, a);
    return;
  }

  b();
  // log global variable "a"
  log(`global a`, a);

  // local a 10
  // global a 1
})();

</code>```

the reason behind of hoisting

var a = 1;
//"a" is global scope
function b() {
   var a = function () {};
   //"a" is local scope
   var x = 12;
   //"x" is local scope
   a = 10;
   //global variable "a" was overwrited by the local variable "a"
   console.log("local a =" + a);
   return console.log("local x = " + x);
}
b();
// local a =10
// local x = 12
console.log("global a = " + a);
// global a = 1
console.log("can't access local x = \n");
// can't access local x =
console.log(x);
// ReferenceError: x is not defined

/**
 *  scpope & closure & hoisting (var/function)
 *
 * 1. scpope : the global var can be access in any place(the whole file scope), local var only can be accessed by the local scope(function/block scope)!
 * Note: if a local variable not using var keywords in a function, it will become a global variable!
 *
 * 2. closure : a function inner the other function, which can access local scope(parent function) & global scope, howerver it's vars can't be accessed by others! unless, your return it as return value!
 *
 * 3. hoisting : move all declare/undeclare vars/function to the scope top, than assign the value or null!
 * Note: it just move the declare, not move the value!
 *
 */

```

<h2>ES6 <code>let</code>, <code>const</code> no exist hoisting</h2>

<pre class="lang-js prettyprint-override"><code>(() => {
  const log = console.log;
  log(a)
  // Error: Uncaught ReferenceError: Cannot access 'a' before initialization
  let a = 1;
})();

</code>```

(() => {
  const log = console.log;
  log(b)
  // Error: Uncaught ReferenceError: Cannot access 'b' before initialization
  const b = 1;
})();

```

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

ContentLicense: CC BY-SA 3.0

Body:
I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:

var a = 1;

function b() {
    a = 10;
    return;

    function a() {}
}
b();
alert(a);

Using the code above, the browser will alert "1".

I'm still unsure why it returns "1". Some of the things he says come to mind like:
   All the function declarations are hoisted to the top. You can scope a variable using function.  Still doesn't click for me.

Body:
ES5: function hoisting & variable hoisting

function hoisting priority is greater than variable hoisting

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2016-06-01
 * @modified
 *
 * @description function-hoisting.js
 * @augments
 * @example
 * @link
 *
 */

(function() {
  const log = console.log;

  var a = 1;
  function b() {
    a = 10;
    log(`local a`, a)
    return;
    // function hoisting priority is greater than variable hoisting
    function a() {}
  }
  b();
  log(`global a`, a);
  // local a 10
  // global a 1
})();

which is equal to

(function() {
  const log = console.log;

  // define "a" in global scope
  var a = 1;
  function b() {
    // define "a" in local scope
    var a ;
    // assign function to a
    a = function () {};
    // overwrites local variable "a"
    a = 10;
    log(`local a`, a);
    return;
  }

  b();
  // log global variable "a"
  log(`global a`, a);

  // local a 10
  // global a 1
})();

the reason behind of hoisting

var a = 1;
//"a" is global scope
function b() {
   var a = function () {};
   //"a" is local scope
   var x = 12;
   //"x" is local scope
   a = 10;
   //global variable "a" was overwrited by the local variable "a"
   console.log("local a =" + a);
   return console.log("local x = " + x);
}
b();
// local a =10
// local x = 12
console.log("global a = " + a);
// global a = 1
console.log("can't access local x = \n");
// can't access local x =
console.log(x);
// ReferenceError: x is not defined

/**
 *  scpope & closure & hoisting (var/function)
 *
 * 1. scpope : the global var can be access in any place(the whole file scope), local var only can be accessed by the local scope(function/block scope)!
 * Note: if a local variable not using var keywords in a function, it will become a global variable!
 *
 * 2. closure : a function inner the other function, which can access local scope(parent function) & global scope, howerver it's vars can't be accessed by others! unless, your return it as return value!
 *
 * 3. hoisting : move all declare/undeclare vars/function to the scope top, than assign the value or null!
 * Note: it just move the declare, not move the value!
 *
 */

ES6 let, const no exist hoisting

(() => {
  const log = console.log;
  log(a)
  // Error: Uncaught ReferenceError: Cannot access 'a' before initialization
  let a = 1;
})();

(() => {
  const log = console.log;
  log(b)
  // Error: Uncaught ReferenceError: Cannot access 'b' before initialization
  const b = 1;
})();

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const


问:
Wrong data in query, Laravel
I try to export some data in excel using Maatwebsite\Excel. Also from front-end I pass some params ,and the problem is that in dd() I get correct data, but in excel file I get wrong data (usually nothing or all rows from db.)

My __construct():

    public function __construct($req) {
        $this->request= $req;
     }
```

<p><strong>The query:</strong> </p>

<pre class="lang-php prettyprint-override"><code>    public function query()
        {
            $direction = ($this->request->sort_direction === 'false') ? 'asc' : 'desc';

            $query = ViewData::query();

            if ($this->request->has('search_gender') && !is_null($this->request->search_gender)) {
                $query->where('gender', '=', $this->request->search_gender );
            }
            // HERE I get some strange things..
            // ($this->request->search_gender === "F")  -> if I use "F", works, if I use $this->request->search_gender , don't!
            // also if I use $this->request->search_gender, in dd($query->get()); I get correct data, in excel file I get wrong data

            if(!$this->request->sort_by){
                $this->request->sort_by = "full_name";
            }

            $query->orderBy($this->request->sort_by, $direction);

            return $query;
        }
</code>```

My controller:

    //  Export CSV data
    public function export(Request $request)
    {
        return (new DataExport($request))->download('data.xlsx');
    }
```

<p><strong>Update with actual query:</strong></p>

<pre class="lang-php prettyprint-override"><code>     array:3 [

              "query" => "select * from "view_full_data" where "gender" = ? order by "full_name" desc"
              "bindings" => array:1 [
                0 => "M"
              ]
              "time" => 34.7
            ]
</code>```

答:
EDIT 1: Following Maatwebsite\Excel documentation:

Reading the documentation, I believe that I understood your query() call. That is a implements from  InvoicesExport.

As following the official documentation, I believe that you need to create a constructor parameter to use in your where. Follow the doc example:

```<code>namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;

class InvoicesExport implements FromQuery
{
    use Exportable;

    public function __construct(int $year)
    {
        $this->year = $year;
    }

    public function query()
    {
        return Invoice::query()->whereYear('created_at', $this->year);
    }
}
</code>```

And export your data as follows:

```<code>return (new InvoicesExport(2018))->download('invoices.xlsx');
</code>```

ORIGINAL:

If I understood the problem, could be this:

The  ? is a binded value.

If you see in your dump:

```<code>"bindings" => array:1 [
    0 => "M"
]
</code>```

You think that your query will parse this value and substitute your ? with the respective value.

If you want to get your raw sql, try this:

dd($query->toSql());

And you can see if that your binding value will be parsed. And you can check if the query are built in the right way.

Title: Wrong data in query, Laravel

Body:
I try to export some data in excel using Maatwebsite\Excel. Also from front-end I pass some params ,and the problem is that in dd() I get correct data, but in excel file I get wrong data (usually nothing or all rows from db.)

My __construct():

    public function __construct($req) {
        $this->request= $req;
     }

The query:

    public function query()
        {
            $direction = ($this->request->sort_direction === 'false') ? 'asc' : 'desc';

            $query = ViewData::query();

            if ($this->request->has('search_gender') && !is_null($this->request->search_gender)) {
                $query->where('gender', '=', $this->request->search_gender );
            }
            // HERE I get some strange things..
            // ($this->request->search_gender === "F")  -> if I use "F", works, if I use $this->request->search_gender , don't!
            // also if I use $this->request->search_gender, in dd($query->get()); I get correct data, in excel file I get wrong data

            if(!$this->request->sort_by){
                $this->request->sort_by = "full_name";
            }

            $query->orderBy($this->request->sort_by, $direction);

            return $query;
        }

My controller:

    //  Export CSV data
    public function export(Request $request)
    {
        return (new DataExport($request))->download('data.xlsx');
    }

Update with actual query:

     array:3 [

              "query" => "select * from "view_full_data" where "gender" = ? order by "full_name" desc"
              "bindings" => array:1 [
                0 => "M"
              ]
              "time" => 34.7
            ]

Body:
EDIT 1: Following Maatwebsite\Excel documentation:

Reading the documentation, I believe that I understood your query() call. That is a implements from  InvoicesExport.

As following the official documentation, I believe that you need to create a constructor parameter to use in your where. Follow the doc example:

namespace App\Exports;

use App\Invoice;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;

class InvoicesExport implements FromQuery
{
    use Exportable;

    public function __construct(int $year)
    {
        $this->year = $year;
    }

    public function query()
    {
        return Invoice::query()->whereYear('created_at', $this->year);
    }
}

And export your data as follows:

return (new InvoicesExport(2018))->download('invoices.xlsx');

ORIGINAL:

If I understood the problem, could be this:

The  ? is a binded value.

If you see in your dump:

"bindings" => array:1 [
    0 => "M"
]

You think that your query will parse this value and substitute your ? with the respective value.

If you want to get your raw sql, try this:

dd($query->toSql());

And you can see if that your binding value will be parsed. And you can check if the query are built in the right way.


问:
Get the last run_at for a DelayedJob in Rails
I am using Rails Delayed Job to enqueue jobs to run at a specific time. Is it possible to know the timestamp for when a particular Delayed Job is last run?</p>

答:
You need to query for the job by some identifier. Your jobs are saved into a delayed_jobs table and the text field called 'handler' is where you can find them.
From delayed_job documenatation:

```<code> table.text :handler # YAML-encoded string of the object
</code>```

that will do work
So to query them you can do

```<code>Delayed::Job.where("handler LIKE '%name: #{name}%'")
</code>```

I don't know exactly what unique name you have there, 'name' is made up and might not work. Easiest think is to look in the database. Possibly the job's class name is saved and you can query by that.

Body:
You need to query for the job by some identifier. Your jobs are saved into a delayed_jobs table and the text field called 'handler' is where you can find them.
From delayed_job documenatation:

 table.text :handler # YAML-encoded string of the object

that will do work
So to query them you can do

Delayed::Job.where("handler LIKE '%name: #{name}%'")

I don't know exactly what unique name you have there, 'name' is made up and might not work. Easiest think is to look in the database. Possibly the job's class name is saved and you can query by that.


问:
mvn command is not recognized as an internal or external command
I am getting the mvn command not recognized as an internal or external command.

I have setup the M2_HOME, JAVA_HOME and added %M2_HOME%/bin to the path variable. All are system variables. Still getting the same problem.

Echoing the variables showing me the correct paths.

Path to Maven: C:\apache-maven-3.1.0\apache-maven-3.1.0

M2_HOME:C:\apache-maven-3.1.0\apache-maven-3.1.0

PATH: Other things,C:\Program Files (x86)\Java\jdk1.7.0_40\bin,C:\apache-maven-3.1.0\apache-maven-3.1.0\bin

and I have restarted my computer twice.

答: I have a stupid comment but someone else will have that issue.  I was getting that same error when I was trying to put in ./mvnw clean package and I found out that I had to change it a bit to .\mvnw clean packageand I lived happily ever after.


问:
I want to upload multiple files using Django
I want to upload multiple files or a folder in form , The html form uploads the multiple files successfully but when it comes to django handling it is showing me night-mares in day light .
I have created my html form like this

```<code><input type="file" name="file" multiple />
</code>```

I have created a model like this

```<code>class Report(models.Model):
    name = models.CharField(max_length=60)
    report = models.CharField(max_length=10)
    task = models.CharField(max_length=60)
    date = models.DateField(null=True)
    start_time = models.TimeField()
    end_time = models.TimeField()
    no_of_hours = models.CharField(max_length=20)
    team_lead = models.CharField(max_length=30)
    today_progress = models.CharField(max_length = 1000)
    file_input = models.FileField(upload_to='documents/')
    concern = models.CharField(max_length=1000)
    next_plan = models.CharField(max_length=1000)
    next_plan_file = models.FileField(upload_to='next/')
</code>```

And views.py like this

```<code>
def save(request):
    report_object = Report()
    report_object.name = request.POST["name"]
    report_object.report = request.POST["report"]
    report_object.task = request.POST["task"]
    report_object.date = request.POST["date"]
    report_object.start_time = request.POST["start_time"]
    report_object.end_time = request.POST["end_time"]
    report_object.no_of_hours = request.POST["no_of_hours"]
    report_object.team_lead = request.POST["team_lead"]
    report_object.today_progress = request.POST["today_progress"]
    report_object.file_input = request.FILES.["file_input"]
    report_object.concern = request.POST["concern"]
    report_object.next_plan = request.POST["next_plan"]
    report_object.next_plan_file = request.FILES.["upload_next"]
    report_object.save()
    return redirect('/')

</code>```

I pass the file into the model i have created but only the last file gets inserted and shown in Admin Panel

Now I get only last file (if I select 3 files then get 3rd file). How to get all files or folder ?
And even want to show in Django Admin Panel

答:
Try this and check out this works!!

Replace

```<code>file=request.FILES.get('file')
</code>```

with

```<code>files = request.FILES.getlist('file')
</code>```

you have to loop through each element in your view

```<code>if form.is_valid():
    name = form.cleaned_data['name']
    for f in files:
        File.objects.create(name=name, file=f)
    return HttpResponse('OK')
</code>```

Here name is your model field and saving all uploaded files in name field

Body:
I want to upload multiple files or a folder in form , The html form uploads the multiple files successfully but when it comes to django handling it is showing me night-mares in day light .
I have created my html form like this

<input type="file" name="file" multiple />

I have created a model like this

class Report(models.Model):
    name = models.CharField(max_length=60)
    report = models.CharField(max_length=10)
    task = models.CharField(max_length=60)
    date = models.DateField(null=True)
    start_time = models.TimeField()
    end_time = models.TimeField()
    no_of_hours = models.CharField(max_length=20)
    team_lead = models.CharField(max_length=30)
    today_progress = models.CharField(max_length = 1000)
    file_input = models.FileField(upload_to='documents/')
    concern = models.CharField(max_length=1000)
    next_plan = models.CharField(max_length=1000)
    next_plan_file = models.FileField(upload_to='next/')

And views.py like this

def save(request):
    report_object = Report()
    report_object.name = request.POST["name"]
    report_object.report = request.POST["report"]
    report_object.task = request.POST["task"]
    report_object.date = request.POST["date"]
    report_object.start_time = request.POST["start_time"]
    report_object.end_time = request.POST["end_time"]
    report_object.no_of_hours = request.POST["no_of_hours"]
    report_object.team_lead = request.POST["team_lead"]
    report_object.today_progress = request.POST["today_progress"]
    report_object.file_input = request.FILES.["file_input"]
    report_object.concern = request.POST["concern"]
    report_object.next_plan = request.POST["next_plan"]
    report_object.next_plan_file = request.FILES.["upload_next"]
    report_object.save()
    return redirect('/')

I pass the file into the model i have created but only the last file gets inserted and shown in Admin Panel

Now I get only last file (if I select 3 files then get 3rd file). How to get all files or folder ?
And even want to show in Django Admin Panel

Body:
Try this and check out this works!!

Replace

file=request.FILES.get('file')

with

files = request.FILES.getlist('file')

you have to loop through each element in your view

if form.is_valid():
    name = form.cleaned_data['name']
    for f in files:
        File.objects.create(name=name, file=f)
    return HttpResponse('OK')

Here name is your model field and saving all uploaded files in name field


答:
You can try nested loops like

```<code>B = []
for i in X_1:
    counts = []
    for y in X_2:
        counts.append(i.count(y))
    B.append(counts)
print(B)
</code>```

Output

```<code>[[0, 16, 3, 2], [0, 0, 21, 2], [7, 2, 6, 8], [3, 3, 4, 14]]
</code>```

Title: Is there a simple way for constructing an n by n array from two unequal arrays in python?

Body:
I have two arrays

X_1 = [[1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 3, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1],
[ 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2],
[0, 3, 3, 2, 3, 0, 0, 2, 1, 3, 2, 3, 3, 0, 2, 2, 0, 1, 0, 3, 3, 0, 2],
[3, 0, 3, 3, 1, 2, 3, 3, 0, 3, 2, 3, 2, 3, 3, 3, 1, 3, 3, 3, 3, 1, 2, 0]]

X_2 = [0,1,2,3]

I want to derive a 4 by 4 B array such that every B[i,j] element is the total number of values of X_2[i] in X_1[j]

Output:

B = [[0,16,3,2],
[0,0,21,2],
[7,2,6,7],
[3,3,4,14]]

Body:
You can try nested loops like

B = []
for i in X_1:
    counts = []
    for y in X_2:
        counts.append(i.count(y))
    B.append(counts)
print(B)

Output

[[0, 16, 3, 2], [0, 0, 21, 2], [7, 2, 6, 8], [3, 3, 4, 14]]


问:
Retrieving series rows given a condition
Consider the following series which represents the distance between location a and locations b, c, d:

```<code>   a
a  0

b  10

c  12

d  21
</code>```

Now, what I'm trying to do is retrieve all location names that are within a certain distance from a.

For example, I would like to print out all variables that are within a 15 unit distance from a, excluding a, which would be b and c.

b

c

I've tried creating an empty list and then using a for loop to append to that list but to no avail, so I'm obviously missing something.

答:
Try this:

```<code>dist = 15
val = list(df.loc[(df['a'] < dist) & (df.index != 'a')].index)
print(val)
</code>```

Output:

```<code>['b', 'c']
</code>```

Body:
Consider the following series which represents the distance between location a and locations b, c, d:

   a
a  0

b  10

c  12

d  21

Now, what I'm trying to do is retrieve all location names that are within a certain distance from a.

For example, I would like to print out all variables that are within a 15 unit distance from a, excluding a, which would be b and c.

b

c

I've tried creating an empty list and then using a for loop to append to that list but to no avail, so I'm obviously missing something.

Body:
Try this:

dist = 15
val = list(df.loc[(df['a'] < dist) & (df.index != 'a')].index)
print(val)

Output:

['b', 'c']


问:
How does AWS API Gateway charge users?
Having read the Pricing docs beforehand, we still not understand the exact pricing model of AWS API Gateway ...

We're using REST APIs (public), for the ap-south-1 / Mumbai region. The pricing page says,

'Pay only for the API calls you receive and the amount of data transferred out. There are no data transfer out charges for Private APIs.'

What does 'data transfer out' mean here? And how would I be charged for it?

Any help is appreciated!

Thanks! :)

答:
There are 2 charges:

The number of requests that you receive.

Data Transfer Out - The cumulative data size of response body content + headers sent out over the course of a month.

Title: How does AWS API Gateway charge users?


问:
Multithread performance
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

```<code>#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}
</code>```

答:
According to the Intel website, the Core i5 750 processor has 4 cores and supports 4 threads, so you shouldn't expect any more performance from 8 threads than from 4. By adding more threads to your software than you have processors (or hyperthreads) you are just adding more context switch overhead.

As to why 4 threads is no faster than 2, I would guess it is to do with the size of the working set of data. The data set is much bigger than the 8MB cache, so your test application is probably memory bandwidth limited.

To test this out, try benchmarking with a data set which fits in the cache.

Title: Multithread performance

Body:
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}


问:
Worksheet_Change function doesn't seem to work
I am checking this code, but can't make it work.
I just want to fire an event when the worksheet gets a change, any change.
I will limit the change range detection to a couple of columns, but for now I would like to see it just working.
At the moment, nothing happens when I change data on the worksheet.</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:Z50")) Is Nothing Then
        MsgBox "CHANGE DETECTED"
    End If
End Sub
</code>```

答:
The most common reason that event macros don't work is that they are installed in the wrong place.

Worksheet code is very easy to install and automatic to use:

right-click the tab name near the bottom of the Excel window

select View Code - this brings up a VBE window

paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.

If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx

To remove the macro:

bring up the VBE windows as above

clear the code out

close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!

(by the way, your code does work)

Body:
I am checking this code, but can't make it work.
I just want to fire an event when the worksheet gets a change, any change.
I will limit the change range detection to a couple of columns, but for now I would like to see it just working.
At the moment, nothing happens when I change data on the worksheet.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:Z50")) Is Nothing Then
        MsgBox "CHANGE DETECTED"
    End If
End Sub


问:
ORA-00933: SQL command not properly ended can't figure out why I am getting this error
Could I please have some help in figuring out why this isn't working? I copy and paste the same query into SQL and it works just fine?

```<code>using (OracleCommand cmd = new OracleCommand("SELECT o.load_number, p.part_number as sortpartnum, p.engineering_change as sortecl, ps.internal_part_#, ps.engineering_change, o.ship_date as custshipdate, o.ship_time as custshiptime, o.sched_ship_date as sortshipdate, o.sched_ship_time as sortshiptime, o.curr_quantity as sortcurqty, o.ship_quantity as sortshipqty, o.mr_number as sortmrnum, o.project_number as sortprojnum, o.transaction_set_id as sorttranssetid, o.id, p.id, o.rowid, o.ship_quantity, p.standard_pack_qty, o.load_number, o.row_version, o.po_number as sortponum, o.dock_code as sortdockcode, o.lot_number, o.batch_number, o.job_sequence, edi_cancellation, '', p.part_spec_id, 'N/A', '', '', o.sched_ship_date, -1 as sortload, '', '' FROM orders o, part_master p, part_specification ps WHERE o.load_number IS NULL AND o.part_id = p.id AND p.part_spec_id = ps.id AND" +

    "o.sched_ship_date <= SYSDATE + 30" +
    "UNION ALL" +
    "SELECT o.load_number, p.part_number, p.engineering_change, ps.internal_part_#, ps.engineering_change, o.ship_date, o.ship_time, o.sched_ship_date, o.sched_ship_time, o.curr_quantity, o.ship_quantity, o.mr_number, o.project_number, o.transaction_set_id, o.id, p.id, o.rowid, o.ship_quantity, p.standard_pack_qty, o.load_number, o.row_version, o.po_number, o.dock_code, o.lot_number, o.batch_number, o.job_sequence, edi_cancellation, '', p.part_spec_id, DECODE(l.inbond, 'Y', 'Yes', 'No'), '', '', o.sched_ship_date, o.load_number, '', DECODE(NVL(l.seq_quick_label, DECODE(NVL(sfx.seq_quick_label, 'N'), 'Y', 'Yes', 'No')), 'Y', 'Yes', 'No')  FROM loads l, orders o, part_master p, part_specification ps, ship_from_xref sfx WHERE o.load_number = l.load_number AND l.shipment_id IS NULL AND l.ship_from_xref_id = sfx.id AND p.id = o.part_id AND p.part_spec_id = ps.id" +
    "order by" +

        "sortload," +
        "sortpartnum," +
        "sortecl," +
        "sortshipdate," +
        "sortshiptime," +
        "sortcurqty," +
        "sortshipqty," +
        "sortmrnum," +
        "sortprojnum," +
        "sorttranssetid;", con))
</code>```

just when I launch my netcore application it gives me this error

答:
There are multiple issues:

Spacing between concatenation of the string - Spaces between two string which are used on both sides of the + must have spaces [space]" + "[space]

In the last line, You are using the ;, Just remove it.

Body:
Could I please have some help in figuring out why this isn't working? I copy and paste the same query into SQL and it works just fine?

using (OracleCommand cmd = new OracleCommand("SELECT o.load_number, p.part_number as sortpartnum, p.engineering_change as sortecl, ps.internal_part_#, ps.engineering_change, o.ship_date as custshipdate, o.ship_time as custshiptime, o.sched_ship_date as sortshipdate, o.sched_ship_time as sortshiptime, o.curr_quantity as sortcurqty, o.ship_quantity as sortshipqty, o.mr_number as sortmrnum, o.project_number as sortprojnum, o.transaction_set_id as sorttranssetid, o.id, p.id, o.rowid, o.ship_quantity, p.standard_pack_qty, o.load_number, o.row_version, o.po_number as sortponum, o.dock_code as sortdockcode, o.lot_number, o.batch_number, o.job_sequence, edi_cancellation, '', p.part_spec_id, 'N/A', '', '', o.sched_ship_date, -1 as sortload, '', '' FROM orders o, part_master p, part_specification ps WHERE o.load_number IS NULL AND o.part_id = p.id AND p.part_spec_id = ps.id AND" +

    "o.sched_ship_date <= SYSDATE + 30" +
    "UNION ALL" +
    "SELECT o.load_number, p.part_number, p.engineering_change, ps.internal_part_#, ps.engineering_change, o.ship_date, o.ship_time, o.sched_ship_date, o.sched_ship_time, o.curr_quantity, o.ship_quantity, o.mr_number, o.project_number, o.transaction_set_id, o.id, p.id, o.rowid, o.ship_quantity, p.standard_pack_qty, o.load_number, o.row_version, o.po_number, o.dock_code, o.lot_number, o.batch_number, o.job_sequence, edi_cancellation, '', p.part_spec_id, DECODE(l.inbond, 'Y', 'Yes', 'No'), '', '', o.sched_ship_date, o.load_number, '', DECODE(NVL(l.seq_quick_label, DECODE(NVL(sfx.seq_quick_label, 'N'), 'Y', 'Yes', 'No')), 'Y', 'Yes', 'No')  FROM loads l, orders o, part_master p, part_specification ps, ship_from_xref sfx WHERE o.load_number = l.load_number AND l.shipment_id IS NULL AND l.ship_from_xref_id = sfx.id AND p.id = o.part_id AND p.part_spec_id = ps.id" +
    "order by" +

        "sortload," +
        "sortpartnum," +
        "sortecl," +
        "sortshipdate," +
        "sortshiptime," +
        "sortcurqty," +
        "sortshipqty," +
        "sortmrnum," +
        "sortprojnum," +
        "sorttranssetid;", con))

just when I launch my netcore application it gives me this error


问:
How to get number's arguments(length) while passing inside back tick
I got a scenario where I'm passing number of arguments inside back tick and i need to find out the
length but every time I'm getting one. I do understand back tick do string concatenation but still i
need some way to find the length. Here Is the example</p>

```<code>var fn = (...args) => {
    console.log(args.length);
};

fn(`'mon', 'tue', 'wed'`);
</code>```

答:
You are using backticks. Just delete them and pass more strings in the function:

var fn = (...args) => {
    console.log(args.length);
};

fn('mon', 'tue', 'wed');```

Through the ...args you are telling the function that you can pass multiple parameters into the function.

Body:
I got a scenario where I'm passing number of arguments inside back tick and i need to find out the
length but every time I'm getting one. I do understand back tick do string concatenation but still i
need some way to find the length. Here Is the example

var fn = (...args) => {
    console.log(args.length);
};

fn(`'mon', 'tue', 'wed'`);

Body:
You are using backticks. Just delete them and pass more strings in the function:

var fn = (...args) => {
    console.log(args.length);
};

fn('mon', 'tue', 'wed');

Through the ...args you are telling the function that you can pass multiple parameters into the function.


问:
Objects falling in android

Just now I came accross this animation in an Android App. I was wondering which kind animation is this. Tell me name of this animation.

答: Your question is too vague but i will try to answer it. It looks like confetti and it depends on the developer how he has created it. But you can look here for this kind of animations . Lottie is pretty smooth than our regular animations. Try it once. All the best.</p>

Title: Objects falling in android


问:
Angular loading files from backend using the wrong port
My Angular frontend application is using default port 4200. My Django backend application is running on port 8000. Frontend can upload files and images to backend, a then get their links to show on page. Uploading is working fine, but then when I try to get images from backend, Angular is downloading them from frontend port 4200 and all views are breaking, because there is no such files on that path.
Briefly, I need file path in that way - http://localhost:8000/media/uploads/myfile, but I get http://localhost:4200/media/uploads/myfile.
I use proxy to get backend api:

```<code>{
  "/api": {
  "target": "http://localhost:8000",
  "secure": false
  }
}
</code>```

I do not know where the problem may be.

答:
You should add another proxy rule to proxy the media requests to django.

```<code>{
  "/api": {
  "target": "http://localhost:8000",
  "secure": false
  },

  "/media": {
  "target": "http://localhost:8000",
  "secure": false
  }
}

</code>```

Body:
My Angular frontend application is using default port 4200. My Django backend application is running on port 8000. Frontend can upload files and images to backend, a then get their links to show on page. Uploading is working fine, but then when I try to get images from backend, Angular is downloading them from frontend port 4200 and all views are breaking, because there is no such files on that path.
Briefly, I need file path in that way - http://localhost:8000/media/uploads/myfile, but I get http://localhost:4200/media/uploads/myfile.
I use proxy to get backend api:

{
  "/api": {
  "target": "http://localhost:8000",
  "secure": false
  }
}

I do not know where the problem may be.

Body:
You should add another proxy rule to proxy the media requests to django.

{
  "/api": {
  "target": "http://localhost:8000",
  "secure": false
  },

  "/media": {
  "target": "http://localhost:8000",
  "secure": false
  }
}


问:
Generic.xaml doesn't use SystemParameters set in App.xaml
To customize the look of ScrollBar I've set these:

```<code><sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">15</sys:Double>
</code>```

in App.xaml and in the Themes\Generic.xaml some of my Custom Controls have Grid.Column defined like this:

```<code><ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>
</code>```

Looks like my Custom Controls actually don't use 15 as Width. Is there any way to force Custom Controls Styles defined in Themes\Generic.xaml use these values set in App.xaml?

EDIT

Here's what I've in App.xaml now:

```<code><Application x:Class="RentManager.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:RentManager"
             xmlns:sys="clr-namespace:System;assembly=System.Runtime"
             xmlns:cc="clr-namespace:RentManager.CustomControl"
             xmlns:con="clr-namespace:RentManager.Common"
             StartupUri="Main.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
            <sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/Generic.xaml" />
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/OtherStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
</code>```

The userControl on which I'm having issue looks like this when scrollbar appears:

Look at the Misalignment in the Receivable/Payment column. Here's how it looks without scrollbar:

The custom control for Ledger is:

```<code><Style TargetType="{x:Type local:Ledger}">
        <Setter Property="Focusable" Value="False"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:Ledger}">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>
                            </Grid.ColumnDefinitions>

                            <Grid.Resources>
                                <Style TargetType="TextBlock">
                                    <Setter Property="Grid.Row" Value="1"/>
                                    <Setter Property="FontWeight" Value="Bold"/>
                                    <Setter Property="VerticalAlignment" Value="Center"/>
                                </Style>
                            </Grid.Resources>

                            <Border Grid.Row="1" Grid.ColumnSpan="5" Background="AliceBlue"/>
                            <Separator Grid.Row="0" Grid.ColumnSpan="5"/>
                            <TextBlock Text="Date" Margin="20 0 0 0"/>
                            <TextBlock Grid.Column="1" Text="Particulars"/>
                            <TextBlock Grid.Column="2" HorizontalAlignment="Right">
                    <Run Text="Receivable"/>
                    <LineBreak/>
                    <Run Text="/ Payment"/>
                            </TextBlock>
                            <TextBlock Grid.Column="3" HorizontalAlignment="Right" Text="Receipt"/>
                            <TextBlock Grid.Column="4" HorizontalAlignment="Right" Text="Balance" Margin="0 0 20 0"/>
                            <Separator Grid.Row="2" Grid.ColumnSpan="5"/>
                        </Grid>

                        <ItemsControl Grid.Row="1"
                                      ItemsSource="{TemplateBinding Source}"
                                      HorizontalContentAlignment="Stretch"
                                      VirtualizingStackPanel.IsVirtualizing="True"
                                      VirtualizingStackPanel.VirtualizationMode="Recycling"
                                      ScrollViewer.CanContentScroll="True">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <VirtualizingStackPanel/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.Template>
                                <ControlTemplate>
                                    <ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="scroll">
                                        <ItemsPresenter/>
                                    </ScrollViewer>
                                </ControlTemplate>
                            </ItemsControl.Template>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid >
                                        <Grid.RowDefinitions>
                                            <RowDefinition/>
                                            <RowDefinition/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <TextBlock Grid.Column="0" Text="{Binding Date, StringFormat='dd MMM yyyy'}" Margin="20 0 0 0"/>
                                        <ContentControl Grid.Column="1">
                                            <ContentControl.Style>
                                                <Style BasedOn="{StaticResource {x:Type ContentControl}}" TargetType="ContentControl">
                                                    <Style.Triggers>
                                                        <DataTrigger Binding="{Binding DataContext.SelectedTab.Type, RelativeSource={RelativeSource AncestorType={x:Type local:Ledger}}}" Value="Plot">
                                                            <Setter Property="Content">
                                                                <Setter.Value>
                                                                    <TextBlock TextWrapping="Wrap">
                                                                        <Run Text="{Binding SpaceName}"/>
                                                                        <Run Text=": "/>
                                                                        <Run Text="{Binding TenantName}"/>
                                                                        <Run Text=" - "/>
                                                                        <Run Text="{Binding HeadName}"/>
                                                                        <Run Text=" | "/>
                                                                        <Run Text="{Binding Narration}" FontStyle="Italic" Foreground="Blue"/>
                                                                    </TextBlock>
                                                                </Setter.Value>
                                                            </Setter>
                                                        </DataTrigger>

                                                        <DataTrigger Binding="{Binding DataContext.SelectedTab.Type, RelativeSource={RelativeSource AncestorType={x:Type local:Ledger}}}" Value="Space">
                                                            <Setter Property="Content">
                                                                <Setter.Value>
                                                                    <TextBlock TextWrapping="Wrap">
                                                                        <Run Text="{Binding PlotName}"/>
                                                                        <Run Text=": "/>
                                                                        <Run Text="{Binding TenantName}"/>
                                                                        <Run Text=" - "/>
                                                                        <Run Text="{Binding HeadName}"/>
                                                                        <Run Text=" | "/>
                                                                        <Run Text="{Binding Narration}" FontStyle="Italic" Foreground="Blue"/>
                                                                    </TextBlock>
                                                                </Setter.Value>
                                                            </Setter>
                                                        </DataTrigger>

                                                        <DataTrigger Binding="{Binding DataContext.SelectedTab.Type, RelativeSource={RelativeSource AncestorType={x:Type local:Ledger}}}" Value="Tenant">
                                                            <Setter Property="Content">
                                                                <Setter.Value>
                                                                    <TextBlock TextWrapping="Wrap">
                                                                        <Run Text="{Binding PlotName}"/>
                                                                        <Run Text=": "/>
                                                                        <Run Text="{Binding SpaceName}"/>
                                                                        <Run Text=" - "/>
                                                                        <Run Text="{Binding HeadName}"/>
                                                                        <Run Text=" | "/>
                                                                        <Run Text="{Binding Narration}" FontStyle="Italic" Foreground="Blue"/>
                                                                    </TextBlock>
                                                                </Setter.Value>
                                                            </Setter>
                                                        </DataTrigger>
                                                    </Style.Triggers>
                                                </Style>
                                            </ContentControl.Style>
                                        </ContentControl>
                                        <local:NumReport Grid.Column="2" Text="{Binding Receivable}" />
                                        <local:NumReport Grid.Column="3" Text="{Binding Receipt}" />
                                        <local:NumReport Grid.Column="4" Text="{Binding Balance}" Margin="0 0 20 0"/>
                                        <Border Grid.Column="5" Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}">
                                            <Border.Style>
                                                <Style TargetType="Border">
                                                    <Style.Triggers>
                                                        <DataTrigger Binding="{Binding ComputedVerticalScrollBarVisibility, ElementName=scroll}" Value="Visible">
                                                            <Setter Property="Visibility" Value="Collapsed" />
                                                        </DataTrigger>
                                                    </Style.Triggers>
                                                </Style>
                                            </Border.Style>
                                        </Border>
                                        <Separator Grid.Row="1" Grid.ColumnSpan="5" Background="LightBlue" Margin="0 5 0 5"/>
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>

                        <Grid Grid.Row="2">
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>
                            </Grid.ColumnDefinitions>

                            <Border Grid.Row="1" Grid.ColumnSpan="5" Background="AliceBlue"/>
                            <Separator Grid.Row="0" Grid.ColumnSpan="5"/>
                            <TextBlock Grid.Row="1" Text="Total" FontWeight="Bold" Margin="20 0 0 0"/>

                            <local:NumReport Grid.Row="1" Grid.Column="2" FontWeight="Bold" Text="{Binding TotalReceivable}"/>
                            <local:NumReport Grid.Row="1" Grid.Column="3" FontWeight="Bold" Text="{Binding TotalReceipt}"/>
                            <Separator Grid.Row="2" Grid.ColumnSpan="5"/>
                        </Grid>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Without these two lines:

```<code><sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>
</code>```

in App.xaml it works as expected! Another thing is after Adding those MergedDictionaries in App.xaml, now I've red squiggles all over my Generic.xaml.

EDIT

If I don't change those parameters in App.xaml, it looks as expected:

答:
Adding the resource to App.xaml does work.

Your way of referencing the ResourceDictionary is wrong though. You should merge it into App.xaml:

```<code><Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml"
             xmlns:sys="clr-namespace:System;assembly=System.Runtime">
    <Application.Resources>
        <ResourceDictionary>
            <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/Generic.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

    </Application.Resources>
</Application>
</code>```

Body:
To customize the look of ScrollBar I've set these:

<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">15</sys:Double>

in App.xaml and in the Themes\Generic.xaml some of my Custom Controls have Grid.Column defined like this:

<ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>

Looks like my Custom Controls actually don't use 15 as Width. Is there any way to force Custom Controls Styles defined in Themes\Generic.xaml use these values set in App.xaml?

EDIT

Here's what I've in App.xaml now:

<Application x:Class="RentManager.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:RentManager"
             xmlns:sys="clr-namespace:System;assembly=System.Runtime"
             xmlns:cc="clr-namespace:RentManager.CustomControl"
             xmlns:con="clr-namespace:RentManager.Common"
             StartupUri="Main.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
            <sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/Generic.xaml" />
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/OtherStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

The userControl on which I'm having issue looks like this when scrollbar appears:

Look at the Misalignment in the Receivable/Payment column. Here's how it looks without scrollbar:

The custom control for Ledger is:

                            </Grid.Resources>

                            <Border Grid.Row="1" Grid.ColumnSpan="5" Background="AliceBlue"/>
                            <Separator Grid.Row="0" Grid.ColumnSpan="5"/>
                            <TextBlock Text="Date" Margin="20 0 0 0"/>
                            <TextBlock Grid.Column="1" Text="Particulars"/>
                            <TextBlock Grid.Column="2" HorizontalAlignment="Right">
                    <Run Text="Receivable"/>
                    <LineBreak/>
                    <Run Text="/ Payment"/>
                            </TextBlock>
                            <TextBlock Grid.Column="3" HorizontalAlignment="Right" Text="Receipt"/>
                            <TextBlock Grid.Column="4" HorizontalAlignment="Right" Text="Balance" Margin="0 0 20 0"/>
                            <Separator Grid.Row="2" Grid.ColumnSpan="5"/>
                        </Grid>

                        <ItemsControl Grid.Row="1"
                                      ItemsSource="{TemplateBinding Source}"
                                      HorizontalContentAlignment="Stretch"
                                      VirtualizingStackPanel.IsVirtualizing="True"
                                      VirtualizingStackPanel.VirtualizationMode="Recycling"
                                      ScrollViewer.CanContentScroll="True">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <VirtualizingStackPanel/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.Template>
                                <ControlTemplate>
                                    <ScrollViewer VerticalScrollBarVisibility="Auto" x:Name="scroll">
                                        <ItemsPresenter/>
                                    </ScrollViewer>
                                </ControlTemplate>
                            </ItemsControl.Template>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid >
                                        <Grid.RowDefinitions>
                                            <RowDefinition/>
                                            <RowDefinition/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="100"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <TextBlock Grid.Column="0" Text="{Binding Date, StringFormat='dd MMM yyyy'}" Margin="20 0 0 0"/>
                                        <ContentControl Grid.Column="1">
                                            <ContentControl.Style>

                                                </Style>
                                            </ContentControl.Style>
                                        </ContentControl>
                                        <local:NumReport Grid.Column="2" Text="{Binding Receivable}" />
                                        <local:NumReport Grid.Column="3" Text="{Binding Receipt}" />
                                        <local:NumReport Grid.Column="4" Text="{Binding Balance}" Margin="0 0 20 0"/>
                                        <Border Grid.Column="5" Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}">
                                            <Border.Style>

                                                </Style>
                                            </Border.Style>
                                        </Border>
                                        <Separator Grid.Row="1" Grid.ColumnSpan="5" Background="LightBlue" Margin="0 5 0 5"/>
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>

                        <Grid Grid.Row="2">
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="{Binding Source={x:Static SystemParameters.VerticalScrollBarWidth}}"/>
                            </Grid.ColumnDefinitions>

                            <Border Grid.Row="1" Grid.ColumnSpan="5" Background="AliceBlue"/>
                            <Separator Grid.Row="0" Grid.ColumnSpan="5"/>
                            <TextBlock Grid.Row="1" Text="Total" FontWeight="Bold" Margin="20 0 0 0"/>

                            <local:NumReport Grid.Row="1" Grid.Column="2" FontWeight="Bold" Text="{Binding TotalReceivable}"/>
                            <local:NumReport Grid.Row="1" Grid.Column="3" FontWeight="Bold" Text="{Binding TotalReceipt}"/>
                            <Separator Grid.Row="2" Grid.ColumnSpan="5"/>
                        </Grid>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Without these two lines:

<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">12</sys:Double>
<sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">12</sys:Double>

in App.xaml it works as expected! Another thing is after Adding those MergedDictionaries in App.xaml, now I've red squiggles all over my Generic.xaml.

EDIT

If I don't change those parameters in App.xaml, it looks as expected:

Body:
Adding the resource to App.xaml does work.

Your way of referencing the ResourceDictionary is wrong though. You should merge it into App.xaml:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml"
             xmlns:sys="clr-namespace:System;assembly=System.Runtime">
    <Application.Resources>
        <ResourceDictionary>
            <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/RentManager;component/Themes/Generic.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

    </Application.Resources>
</Application>


问:
trying to clone a branch using git, but it doesn't work
```<code>$ git clone gitosis@tony:stylingGit2.git
Cloning into stylingGit2...
ERROR:gitosis.serve.main:Repository read access denied
fatal: The remote end hung up unexpectedly
</code>```

I'm trying to connect to a server, this happens and I wouldn't know what to do...

...does anybody knows how to solve this issue?

答:
Either gitosis is misconfigured on the server, or you actually don't have access to it.

You should check the configuration of the host "tony" (and possibly compare it to others).

Body:
$ git clone gitosis@tony:stylingGit2.git
Cloning into stylingGit2...
ERROR:gitosis.serve.main:Repository read access denied
fatal: The remote end hung up unexpectedly

I'm trying to connect to a server, this happens and I wouldn't know what to do...

...does anybody knows how to solve this issue?


答:
If the format is guaranteed to be comma-separated, you can split the first argument by comma.

```<code>var fn = (...args) => {
    console.log(args[0].split(',').length);
};

fn(`'mon', 'tue', 'wed'`); // 3
</code>```

As mentioned by other pals, it is probably not the best way to pass arguments, but just in case the function is being called by an entity that you cannot control, this should work with this specific format.

You can also remove the spread operator ... and use it like this

```<code>var fn = (args) => {
    console.log(args.split(',').length);
};

fn(`'mon', 'tue', 'wed'`); // 3
</code>```

Title: How to get number's arguments(length) while passing inside back tick

Body:
If the format is guaranteed to be comma-separated, you can split the first argument by comma.

var fn = (...args) => {
    console.log(args[0].split(',').length);
};

fn(`'mon', 'tue', 'wed'`); // 3

As mentioned by other pals, it is probably not the best way to pass arguments, but just in case the function is being called by an entity that you cannot control, this should work with this specific format.

You can also remove the spread operator ... and use it like this

var fn = (args) => {
    console.log(args.split(',').length);
};

fn(`'mon', 'tue', 'wed'`); // 3


问:
How to link source files into Eclipse based IDE
I am now at the beginning of software project for Xilinx Zynq SoC hardware platform. Xilinx company offers for software development their own Eclipse based IDE called Vitis. Due to version control reasons I need to have application source codes and custom IP peripheral drivers source codes in separate directories  (let´s say App_src and Drivers_src) and I need to link the Vitis project with the aforementioned source codes in such a manner that the source codes modification occurs in the directory which is under version control. It means that I need to prevent any copying of source codes into the workspace. Can anybody tell me how to resolve that in system manner i.e. with respect to the version control system usage? Thanks in advance for any ideas. </p>

答: I have found the solution. There is the "Link folder" option in the project Properties. This enables to link given folder without copying it into the workspace.


问:
How to create attributes on controller actions to check if user has claim
I have added a few custom claims to my user and I was wondering if I want to check if these claims exist on controller actions using attributes, I know that we can create a class and extend attribute from .Net and the general idea is to check if user has claim or not, I'm not really clear on the implementation.

Maybe something like this:

```<code>[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class ClaimRequirementAttribute : Attribute
{
    public ClaimRequirementAttribute(string claimType)
    {
        new Claim(claimType, null);
    }
}
public class ClaimRequirementFilter
{
    public void OnAuthorization(HttpContext httpContext)
    {
        var hasClaim = httpContext.User.HasClaim(x => x.Type ==
        CapabilityClaims.CanReadSpore);

        if (!hasClaim)
        {

        }
    }
}
</code>```

答:
You can get the Claims of a specific user, using the GetClaimsAsync method of UserManager.

You can use the following method:

```<code>public class TestController : Controller
{
    private readonly UserManager<AppUser> _userManager;
    public TestController(UserManager<AppUser> userManager)
    {
        _userManager = userManager;
    }

    public CheckIfClaimsExist(string email)
    {
        var user = await _userManager.FindByEmailAsync(email);
        if(user != null)
        {
            var claims = await _userManager.GetClaimsAsync(user);
        }
    }
}
</code>```

Note: AppUser class is a custom class which extends IdentityUser class from identity server.

Body:
I have added a few custom claims to my user and I was wondering if I want to check if these claims exist on controller actions using attributes, I know that we can create a class and extend attribute from .Net and the general idea is to check if user has claim or not, I'm not really clear on the implementation.

Maybe something like this:

[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class ClaimRequirementAttribute : Attribute
{
    public ClaimRequirementAttribute(string claimType)
    {
        new Claim(claimType, null);
    }
}
public class ClaimRequirementFilter
{
    public void OnAuthorization(HttpContext httpContext)
    {
        var hasClaim = httpContext.User.HasClaim(x => x.Type ==
        CapabilityClaims.CanReadSpore);

        if (!hasClaim)
        {

        }
    }
}

Body:
You can get the Claims of a specific user, using the GetClaimsAsync method of UserManager.

You can use the following method:

public class TestController : Controller
{
    private readonly UserManager<AppUser> _userManager;
    public TestController(UserManager<AppUser> userManager)
    {
        _userManager = userManager;
    }

    public CheckIfClaimsExist(string email)
    {
        var user = await _userManager.FindByEmailAsync(email);
        if(user != null)
        {
            var claims = await _userManager.GetClaimsAsync(user);
        }
    }
}

Note: AppUser class is a custom class which extends IdentityUser class from identity server.


问:
Flowable bpmn access Spring beans inside groovy script
We are setting up a flowable application to use multiple bpmns with reusable java delegates. In application.yml, we have properties set for each bpmn

e.g.

app1.mail.active: true

app2.mail.active: false

ApplicationProperties file is set with @ConfigurationProperties() to get the properties.

Created a Spring bean:

```<code>@Bean("applicationProperties")
public ApplicationProperties applicationProperties(){
    return new ApplicationProperties();
}
</code>```

I am trying to use a script task using groovy and initialize the appropriate properties. It seems Spring beans are not available inside the script.

```<code><scriptTask id="sid-C8B8BE3F-F6CB-4559-B48C-5BC14AB76494" name="Initialize Process" scriptFormat="groovy">
    <script><![CDATA[
       // I want to be able to access applicationProperties bean here
         def _properties = applicationProperties.getApp1()
         execution.setVariable("properties", _properties)
   ]]></script>
</scriptTask>
</code>```

When initializing bpmn for app1, I want to set a variable for properties related to app1 and similar to app2. I am able to use existing spring beans elsewhere in the same bpmn but not inside groovy script task.

Thank you in advance.

答:
The solution that I came up was to create a service task with java delegate to initialize application properties and common variables based on the bpmn instance and set a properties variable, then as part of the same service task I added an executionListener to set variables that are specific to that instance, using groovy script.</p>

```<code><serviceTask id="initProcess" name="Init Process" flowable:delegateExpression="${initProcessDelegate}">
   <extensionElements>
      <flowable:executionListener event="end" class="org.flowable.engine.impl.bpmn.listener.ScriptExecutionListener">
          <flowable:field name="script">
            <flowable:string><![CDATA[

               import config.ApplicationProperties;
               ApplicationProperties.Props props = (ApplicationProperties.Props) execution.getVariable("properties");
               System.out.println("properties " + properties.getUrl());

          ]]></flowable:string>
          </flowable:field>
          <flowable:field name="language">
            <flowable:string><![CDATA[groovy]]></flowable:string>
          </flowable:field>
     </flowable:executionListener>
   </extensionElements>
</serviceTask>

public class ProcessInitDelegate implements JavaDelegate {

    Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ApplicationProperties applicationProperties;

    public void execute(DelegateExecution execution) {
        log.info("<--------------- ProcessInitDelegate ------------->");
         try {
            // set up properties for current instance
            String instance = (String) execution.getVariable("processInstance");
            Object properties = applicationProperties.getInnerInstance(instance);
            if (instance.equals("<your_instance_name>")) {
              ApplicationProperties.Props instanceProperties = (ApplicationProperties.Props) properties;
              execution.setVariable("properties, instanceProperties);
            }
         } catch (Exception e) {
           log.error("Error setting up process {} ", e.getMessage());
         }
    }
}
</code>```

Body:
We are setting up a flowable application to use multiple bpmns with reusable java delegates. In application.yml, we have properties set for each bpmn

e.g.

app1.mail.active: true

app2.mail.active: false

ApplicationProperties file is set with @ConfigurationProperties() to get the properties.

Created a Spring bean:

@Bean("applicationProperties")
public ApplicationProperties applicationProperties(){
    return new ApplicationProperties();
}

I am trying to use a script task using groovy and initialize the appropriate properties. It seems Spring beans are not available inside the script.

</scriptTask>

When initializing bpmn for app1, I want to set a variable for properties related to app1 and similar to app2. I am able to use existing spring beans elsewhere in the same bpmn but not inside groovy script task.

Thank you in advance.

Body:
The solution that I came up was to create a service task with java delegate to initialize application properties and common variables based on the bpmn instance and set a properties variable, then as part of the same service task I added an executionListener to set variables that are specific to that instance, using groovy script.

<serviceTask id="initProcess" name="Init Process" flowable:delegateExpression="${initProcessDelegate}">
   <extensionElements>
      <flowable:executionListener event="end" class="org.flowable.engine.impl.bpmn.listener.ScriptExecutionListener">
          <flowable:field name="script">
            <flowable:string><![CDATA[

               import config.ApplicationProperties;
               ApplicationProperties.Props props = (ApplicationProperties.Props) execution.getVariable("properties");
               System.out.println("properties " + properties.getUrl());

          ]]></flowable:string>
          </flowable:field>
          <flowable:field name="language">
            <flowable:string><![CDATA[groovy]]></flowable:string>
          </flowable:field>
     </flowable:executionListener>
   </extensionElements>
</serviceTask>

public class ProcessInitDelegate implements JavaDelegate {

    Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ApplicationProperties applicationProperties;

    public void execute(DelegateExecution execution) {
        log.info("<--------------- ProcessInitDelegate ------------->");
         try {
            // set up properties for current instance
            String instance = (String) execution.getVariable("processInstance");
            Object properties = applicationProperties.getInnerInstance(instance);
            if (instance.equals("<your_instance_name>")) {
              ApplicationProperties.Props instanceProperties = (ApplicationProperties.Props) properties;
              execution.setVariable("properties, instanceProperties);
            }
         } catch (Exception e) {
           log.error("Error setting up process {} ", e.getMessage());
         }
    }
}


答:
As you are passing single argument, no need to use spread opearator. You can get string in single argument.

var fn = (str) => {
  const funArgs = str.split(",")
  console.log(funArgs.length);
};

fn(`'mon', 'tue', 'wed'`);```
</div>
</div>
</p>

<p>Spread operator can be used to convert arguments to an array. If you want to use spread in any way, you can do it like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var fn = (...arr) => {
  console.log(arr.length);
};

fn('mon', 'tue', 'wed');</code>```

Body:
As you are passing single argument, no need to use spread opearator. You can get string in single argument.

var fn = (str) => {
  const funArgs = str.split(",")
  console.log(funArgs.length);
};

fn(`'mon', 'tue', 'wed'`);

Spread operator can be used to convert arguments to an array. If you want to use spread in any way, you can do it like:

var fn = (...arr) => {
  console.log(arr.length);
};

fn('mon', 'tue', 'wed');