问:
Jenkins assigning true to boolean variable and false to def variable
Very simple and straightforward question:

Let's say we have this pipeline (I don't think there is a simpler example):

```<code>node {
    env.someEnvVariable = false

    boolean asBoolean = env.someEnvVariable ?: false
    def asDef         = env.someEnvVariable ?: false

    echo "asBoolean: $asBoolean"   // prints true because of Jenkins
    echo "asDef: $asDef"           // prints false
}
</code>```

Why????

Defining a variable as boolean makes Jenkins assign it a true value but defining it as def assign it the real false value

Where is taking Jenkins that true value from?

edit: another example:

```<code>node {
    env.someEnvVariable = false
    boolean someBoolean = false
    def someVar = false

    echo "envVar: ${env.someEnvVariable}"     // prints false
    echo "someBoolean: ${someBoolean}"        // prints false
    echo "someVar: ${someVar}"                // prints false
    if (env.someEnvVariable != null) {
        someBoolean = env.someEnvVariable
        someVar = env.someEnvVariable
    }
    echo "envVar: ${env.someEnvVariable}"     // prints false
    echo "someBoolean: ${someBoolean}"        // prints true because of hack
    echo "someVar: ${someVar}"                // prints false
}
</code>```

答:
This is due to "groovy truth": a non-empty string asserts as true.

https://docs.groovy-lang.org/latest/html/documentation/core-semantics.html#Groovy-Truth

Body:
Very simple and straightforward question:

Let's say we have this pipeline (I don't think there is a simpler example):

node {
    env.someEnvVariable = false

    boolean asBoolean = env.someEnvVariable ?: false
    def asDef         = env.someEnvVariable ?: false

    echo "asBoolean: $asBoolean"   // prints true because of Jenkins
    echo "asDef: $asDef"           // prints false
}

Why????

Defining a variable as boolean makes Jenkins assign it a true value but defining it as def assign it the real false value

Where is taking Jenkins that true value from?

edit: another example:

node {
    env.someEnvVariable = false
    boolean someBoolean = false
    def someVar = false

    echo "envVar: ${env.someEnvVariable}"     // prints false
    echo "someBoolean: ${someBoolean}"        // prints false
    echo "someVar: ${someVar}"                // prints false
    if (env.someEnvVariable != null) {
        someBoolean = env.someEnvVariable
        someVar = env.someEnvVariable
    }
    echo "envVar: ${env.someEnvVariable}"     // prints false
    echo "someBoolean: ${someBoolean}"        // prints true because of hack
    echo "someVar: ${someVar}"                // prints false
}


来源: stackexchange

问:
Can I auto-collapse OpenUI5 side navigation depending on the screen width?
I am currently using toolPage control with sideNavigation to display my navigation. By default, its displayed and can be collapsed if I click the "hamburger" icon at the top.

Now, I would like it to collapse not only by icon-click, but also if the browser width is decreased (or when a user opens it on the phone). Is there a way to achieve it? I know boolean properties 'sideExpanded' on 'toolPage' control and 'expanded' on sideNavigation control, but how can I set their value automatically depending on the width of the screen?

Can I see somewhere in the this.getView() structure the actual width of the window? I assume that then I could tie this expanded value to the function/formatter which determines if the control should be expanded or not. Or should I tie t the devide model somehow? In my manifest.json, I have desktop, tablet and phone deviceTypes defined. What is the correct way to do it? Thanks a lot!

答:
You can achieve this using sap.ui.Device.resize.attachHandler(myFunction, oListener?) method, callback function returns parameters height and width based on your requirement you can expand or collapse thesideNavigation.

other way is to check the device sap.ui.Device.media.attachHandler(myFunction, null, sap.ui.Device.media.RANGESETS.SAP_STANDARD); using this you can access the callback to with parameters type of device:
Do initialization: myFunction(sap.ui.Device.media.getCurrentRange(sap.ui.Device.media.RANGESETS.SAP_STANDARD));

```<code>function myFunction(mParams) {
switch(mParams.name) {
    case "Phone":
        // Do what is needed for a little screen
        break;
    case "Tablet":
        // Do what is needed for a medium sized screen
        break;
    case "Desktop":
        // Do what is needed for a large screen
}}
</code>```

Regards,
Saddam

ContentLicense: CC BY-SA 4.0

Body:
You can achieve this using sap.ui.Device.resize.attachHandler(myFunction, oListener?) method, callback function returns parameters height and width based on your requirement you can expand or collapse thesideNavigation.

other way is to check the device sap.ui.Device.media.attachHandler(myFunction, null, sap.ui.Device.media.RANGESETS.SAP_STANDARD); using this you can access the callback to with parameters type of device:
Do initialization: myFunction(sap.ui.Device.media.getCurrentRange(sap.ui.Device.media.RANGESETS.SAP_STANDARD));

function myFunction(mParams) {
switch(mParams.name) {
    case "Phone":
        // Do what is needed for a little screen
        break;
    case "Tablet":
        // Do what is needed for a medium sized screen
        break;
    case "Desktop":
        // Do what is needed for a large screen
}}

Regards,
Saddam


问:
Partials w.r.t a single array where two different parts of the array are used in compute?
I have an array, a, of (x,y) coordinate pairs. This array is the only input to the component.

To generate an array of the angle of each coordinate pair, I use np.arctan2(a[1,:], a[0,:])

I'm not sure how to declare the partials, now. If I used two inputs (i.e x_coordinates, y_coordinates) it'd be quite easy to define the partials as per SymPy: Can I safely differentiate atan2()?.

However, since I only have the one array, I'm not sure how to go about this. My first idea was to do:

```<code>y = a[1, :]
x = a[0, :]
partials['angles', 'a'] = x/(x**2 + y**2) - y/(x**2 + y**2)
</code>```

but I suspect this isn't correct, since I'm missing the dx and dy parts of the total derivative of arctan2.

What's the best way to go about this, without having to split the input array?

答:
Here a and theta are both vector valued.  When OpenMDAO computes partials, it flattens the outputs and inputs in C-order (row-major).

Lets assume we compute atan2 at 5 points.

So in this case we have a single scalar output at 5 points (5 rows in the jacobian) and two inputs at each point (10 columns in the jacobian).

Furthermore, each atan2 calculation only depends on the corresponding (y, x) in a.  So we'd expect that only the first two elements of the first row of the jacobian will be nonzero.  In the second row, it will be the 3rd and 4th elements, etc.  This is a banded structure.

Sometimes in situations like this it's useful to see the structure of the partial derivatives Jacobian obtained by approximating the derivatives:

```<code>    import openmdao.api as om
    import numpy as np

    class Atan2Comp(om.ExplicitComponent):

        def initialize(self):
            self.options.declare('num_points', default=5, desc='number of points at which atan2 is computed')

        def setup(self):
            n = self.options['num_points']
            self.add_input('a', shape=(n, 2))
            self.add_output('theta', shape=(n,))

            self.declare_partials(of='theta', wrt='a')

        def compute(self, inputs, outputs):
            a = inputs['a']
            y = a[:, 0]
            x = a[:, 1]
            outputs['theta'] = np.arctan2(y, x)

        def compute_partials(self, inputs, partials, discrete_inputs=None):
                partials['theta', 'a'] = 1.0

    n = 5
    p = om.Problem(model=om.Group())
    ivc = p.model.add_subsystem('ivc', om.IndepVarComp(), promotes_outputs=['a'])
    ivc.add_output('a', shape=(n, 2))
    p.model.add_subsystem('atan2', Atan2Comp(num_points=n), promotes_inputs=['a'])

    p.setup()

    p.set_val('a', np.random.rand(n, 2))

    p.setup()
    p.run_model()

    with np.printoptions(linewidth=1024):
        p.check_partials()
</code>```

This shows the structure of the Jacobian as being:

```<code>----------------------------
Component: Atan2Comp 'atan2'
----------------------------
  atan2: 'theta' wrt 'a'
    Forward Magnitude : 7.071068e+00
         Fd Magnitude : 3.177623e+00 (fd:forward)
    Absolute Error (Jfor  - Jfd) : 7.503866e+00 *

    Relative Error (Jfor  - Jfd) : 2.361472e+00 *

    Raw Forward Derivative (Jfor)
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]

    Raw FD Derivative (Jfd)
[[ 0.93986629 -0.35863362  0.          0.          0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.72103352 -0.80351616  0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          2.06027062 -0.73005685  0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.48842487 -0.71201471  0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.          0.          1.22969926 -0.9404304 ]]
</code>```

So the FD result has the expected value.  We just crammed 1's into the matrix, so clearly the analytic form has the wrong value. Let's fix that.

First, lets declare this partial as being sparse, since it can make a significant difference in performance.

The column of each nonzero element is just [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], in our example with 5 points.
The row of each nonzero element is repetitive [0, 0, 1, 1, 2, 2, 3, 3, 4, 4].
The declare_partials call thus becomes:

```<code>cs = np.arange(2 * n, dtype=int)
rs = np.repeat(np.arange(n, dtype=int), 2)
self.declare_partials(of='theta', wrt='a', rows=rs, cols=cs)
</code>```

Now, in compute_partials, we need to put the partials of y on the diagonal (based on the way I ordered y, x in a).  Since it was declared as a sparse derivative, this is equivalent to putting the partials of y on the even-indexed elements of the partial.

```<code>            def compute_partials(self, inputs, partials, discrete_inputs=None):
                a = inputs['a']
                y = a[:, 0]
                x = a[:, 1]

                # The partials wrt y go on the even-index elements of the sparse partial.
                partials['theta', 'a'][::2] = x / (x**2 + y**2)

                # The partials wrt x go on the odd-index elements of the sparse partial.
                partials['theta', 'a'][1::2] = -y / (x**2 + y**2)
</code>```

With those changes implemented, the result of check_partials shows

```<code>----------------------------
Component: Atan2Comp 'atan2'
----------------------------
  atan2: 'theta' wrt 'a'
    Forward Magnitude : 3.326988e+00
         Fd Magnitude : 3.326985e+00 (fd:forward)
    Absolute Error (Jfor  - Jfd) : 3.489868e-06 *

    Relative Error (Jfor  - Jfd) : 1.048958e-06 *

    Raw Forward Derivative (Jfor)
[[ 1.55572771 -1.03761371  0.          0.          0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          1.05925649 -0.05293248  0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          1.71871308 -1.07781134  0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.99912434 -0.1373792   0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.          0.          1.13627733 -0.15229154]]

    Raw FD Derivative (Jfd)
[[ 1.5557261  -1.03761209  0.          0.          0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          1.05925643 -0.05293242  0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          1.71871122 -1.07780948  0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.9991242  -0.13737906  0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.          0.          1.13627715 -0.15229136]]
</code>```

Just note that if your "vector" dimension of 'a' is not the first axis, you're going to have a different sparsity pattern, but the same process applies.

Body:
I have an array, a, of (x,y) coordinate pairs. This array is the only input to the component.

To generate an array of the angle of each coordinate pair, I use np.arctan2(a[1,:], a[0,:])

I'm not sure how to declare the partials, now. If I used two inputs (i.e x_coordinates, y_coordinates) it'd be quite easy to define the partials as per SymPy: Can I safely differentiate atan2()?.

However, since I only have the one array, I'm not sure how to go about this. My first idea was to do:

y = a[1, :]
x = a[0, :]
partials['angles', 'a'] = x/(x**2 + y**2) - y/(x**2 + y**2)

but I suspect this isn't correct, since I'm missing the dx and dy parts of the total derivative of arctan2.

What's the best way to go about this, without having to split the input array?

Body:
Here a and theta are both vector valued.  When OpenMDAO computes partials, it flattens the outputs and inputs in C-order (row-major).

Lets assume we compute atan2 at 5 points.

So in this case we have a single scalar output at 5 points (5 rows in the jacobian) and two inputs at each point (10 columns in the jacobian).

Furthermore, each atan2 calculation only depends on the corresponding (y, x) in a.  So we'd expect that only the first two elements of the first row of the jacobian will be nonzero.  In the second row, it will be the 3rd and 4th elements, etc.  This is a banded structure.

Sometimes in situations like this it's useful to see the structure of the partial derivatives Jacobian obtained by approximating the derivatives:

    import openmdao.api as om
    import numpy as np

    class Atan2Comp(om.ExplicitComponent):

        def initialize(self):
            self.options.declare('num_points', default=5, desc='number of points at which atan2 is computed')

        def setup(self):
            n = self.options['num_points']
            self.add_input('a', shape=(n, 2))
            self.add_output('theta', shape=(n,))

            self.declare_partials(of='theta', wrt='a')

        def compute(self, inputs, outputs):
            a = inputs['a']
            y = a[:, 0]
            x = a[:, 1]
            outputs['theta'] = np.arctan2(y, x)

        def compute_partials(self, inputs, partials, discrete_inputs=None):
                partials['theta', 'a'] = 1.0

    n = 5
    p = om.Problem(model=om.Group())
    ivc = p.model.add_subsystem('ivc', om.IndepVarComp(), promotes_outputs=['a'])
    ivc.add_output('a', shape=(n, 2))
    p.model.add_subsystem('atan2', Atan2Comp(num_points=n), promotes_inputs=['a'])

    p.setup()

    p.set_val('a', np.random.rand(n, 2))

    p.setup()
    p.run_model()

    with np.printoptions(linewidth=1024):
        p.check_partials()

This shows the structure of the Jacobian as being:

----------------------------
Component: Atan2Comp 'atan2'
----------------------------
  atan2: 'theta' wrt 'a'
    Forward Magnitude : 7.071068e+00
         Fd Magnitude : 3.177623e+00 (fd:forward)
    Absolute Error (Jfor  - Jfd) : 7.503866e+00 *

    Relative Error (Jfor  - Jfd) : 2.361472e+00 *

    Raw Forward Derivative (Jfor)
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]

    Raw FD Derivative (Jfd)
[[ 0.93986629 -0.35863362  0.          0.          0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.72103352 -0.80351616  0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          2.06027062 -0.73005685  0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.48842487 -0.71201471  0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.          0.          1.22969926 -0.9404304 ]]

So the FD result has the expected value.  We just crammed 1's into the matrix, so clearly the analytic form has the wrong value. Let's fix that.

First, lets declare this partial as being sparse, since it can make a significant difference in performance.

The column of each nonzero element is just [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], in our example with 5 points.
The row of each nonzero element is repetitive [0, 0, 1, 1, 2, 2, 3, 3, 4, 4].
The declare_partials call thus becomes:

cs = np.arange(2 * n, dtype=int)
rs = np.repeat(np.arange(n, dtype=int), 2)
self.declare_partials(of='theta', wrt='a', rows=rs, cols=cs)

Now, in compute_partials, we need to put the partials of y on the diagonal (based on the way I ordered y, x in a).  Since it was declared as a sparse derivative, this is equivalent to putting the partials of y on the even-indexed elements of the partial.

            def compute_partials(self, inputs, partials, discrete_inputs=None):
                a = inputs['a']
                y = a[:, 0]
                x = a[:, 1]

                # The partials wrt y go on the even-index elements of the sparse partial.
                partials['theta', 'a'][::2] = x / (x**2 + y**2)

                # The partials wrt x go on the odd-index elements of the sparse partial.
                partials['theta', 'a'][1::2] = -y / (x**2 + y**2)

With those changes implemented, the result of check_partials shows

----------------------------
Component: Atan2Comp 'atan2'
----------------------------
  atan2: 'theta' wrt 'a'
    Forward Magnitude : 3.326988e+00
         Fd Magnitude : 3.326985e+00 (fd:forward)
    Absolute Error (Jfor  - Jfd) : 3.489868e-06 *

    Relative Error (Jfor  - Jfd) : 1.048958e-06 *

    Raw Forward Derivative (Jfor)
[[ 1.55572771 -1.03761371  0.          0.          0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          1.05925649 -0.05293248  0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          1.71871308 -1.07781134  0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.99912434 -0.1373792   0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.          0.          1.13627733 -0.15229154]]

    Raw FD Derivative (Jfd)
[[ 1.5557261  -1.03761209  0.          0.          0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          1.05925643 -0.05293242  0.          0.          0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          1.71871122 -1.07780948  0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.9991242  -0.13737906  0.          0.        ]
 [ 0.          0.          0.          0.          0.          0.          0.          0.          1.13627715 -0.15229136]]

Just note that if your "vector" dimension of 'a' is not the first axis, you're going to have a different sparsity pattern, but the same process applies.


问:
Dynamic query in LINQ
How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

```<code>string name
string address
int phoneno
</code>```

I have to query based on information given similar to

```<code>query = string.Empty;

if(!string.IsNullorEmpty(name))
{
   query += "@name = name";
}

if(!string.IsNullorEmpty(address))
{
   query += "@address = address";
}

if(!string.IsNullorEmpty(phoneno))
{
   query += "@phoneno = phoneno";
}

var result = from condition in customer
    where(query)
    select condition;
</code>```

Edit #1:

the items are changeable at run time like

```<code>private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
   here the attribute may be, name alone, or name and address, or name address and phoneno

      foreach(string field in attributes.key)
      {
           query += field == attributes[key];

      }

         Customers[] =ExecuteQuery(query);

}
</code>```

Is this kind of query supported by LINQ?

Edit #2:

Hi Mouk,

As I am new to C#, I am still struggling, this is not working for me.

```<code>var query = _ConfigFile.ConnectionMasterSection;

for(int i = 0; i < filter.count; i++)
{
    query = result.Where(p => typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value);
}
</code>```

This yeilds Empty, where as i used this

```<code>var query = _ConfigFile.ConnectionMasterSection;

//Hard coded
res.Where(q => q.category == filter[0].Value);
</code>```

And it worked as I expected.

Hi Bryan Watts,

I tried your code also and I getting this error: "Lambda Parameter not in scope".

```<code>for(int i = 0; i < filter.count; i++)
{
    Field item = filter[i];

    MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute));

    MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value"));
}

try
{
    var myquery = Queryable.Where(coll, Expression.Lambda<Func<Connection, bool>>(
    Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p")));
}
</code>```

What is the mistake here?

答:
It sounds like you need to dynamically compose queries.

See my answer to this question.

It explains how queries against an IQueryable<T> are composed by the compiler, and what you can do to add dynamic elements.

Edit

Here is an example of how you would dynamically build a set of Where conditions on top of an IQueryable<Customer>:

```<code>// This method ANDs equality expressions for each property, like so:
//
// customers.Where(c => c.Property1 == value1 && c.Property2 == value2 && ...);

private IQueryable<Customer> FilterQuery(IQueryable<Customer> customers, IDictionary<string, string> filter)
{
    var parameter = Expression.Parameter(typeof(Customer), "c");
    Expression filterExpression = null;

    foreach(var filterItem in filter)
    {
        var property = typeof(Customer).GetProperty(filterItem.Key);
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var equality = Expression.Equal(propertyAccess, Expression.Constant(filterItem.Value));

        if(filterExpression == null)
        {
            filterExpression = equality;
        }
        else
        {
            filterExpression = Expression.And(filterExpression, equality);
        }
    }

    if(filterExpression != null)
    {
        var whereBody = Expression.Lambda<Func<Customer, bool>>(filterExpression, parameter);

        customers = customers.Where(whereBody);
    }

    return customers;
}
</code>```

OwnerDisplayName: Mohanavel

LastEditorDisplayName: Quintin Robinson

ContentLicense: CC BY-SA 2.5

Title: Dynamic query in LINQ

Body:
How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

string name
string address
int phoneno

I have to query based on information given similar to

query = string.Empty;

if(!string.IsNullorEmpty(name))
{
   query += "@name = name";
}

if(!string.IsNullorEmpty(address))
{
   query += "@address = address";
}

if(!string.IsNullorEmpty(phoneno))
{
   query += "@phoneno = phoneno";
}

var result = from condition in customer
    where(query)
    select condition;

Edit #1:

the items are changeable at run time like

private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
   here the attribute may be, name alone, or name and address, or name address and phoneno

      foreach(string field in attributes.key)
      {
           query += field == attributes[key];

      }

         Customers[] =ExecuteQuery(query);

}

Is this kind of query supported by LINQ?

Edit #2:

Hi Mouk,

As I am new to C#, I am still struggling, this is not working for me.

var query = _ConfigFile.ConnectionMasterSection;

for(int i = 0; i < filter.count; i++)
{
    query = result.Where(p => typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value);
}

This yeilds Empty, where as i used this

var query = _ConfigFile.ConnectionMasterSection;

//Hard coded
res.Where(q => q.category == filter[0].Value);

And it worked as I expected.

Hi Bryan Watts,

I tried your code also and I getting this error: "Lambda Parameter not in scope".

for(int i = 0; i < filter.count; i++)
{
    Field item = filter[i];

    MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute));

    MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value"));
}

try
{
    var myquery = Queryable.Where(coll, Expression.Lambda<Func<Connection, bool>>(
    Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p")));
}

What is the mistake here?

Body:
It sounds like you need to dynamically compose queries.

See my answer to this question.

It explains how queries against an IQueryable<T> are composed by the compiler, and what you can do to add dynamic elements.

Edit

Here is an example of how you would dynamically build a set of Where conditions on top of an IQueryable<Customer>:

// This method ANDs equality expressions for each property, like so:
//
// customers.Where(c => c.Property1 == value1 && c.Property2 == value2 && ...);

private IQueryable<Customer> FilterQuery(IQueryable<Customer> customers, IDictionary<string, string> filter)
{
    var parameter = Expression.Parameter(typeof(Customer), "c");
    Expression filterExpression = null;

    foreach(var filterItem in filter)
    {
        var property = typeof(Customer).GetProperty(filterItem.Key);
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var equality = Expression.Equal(propertyAccess, Expression.Constant(filterItem.Value));

        if(filterExpression == null)
        {
            filterExpression = equality;
        }
        else
        {
            filterExpression = Expression.And(filterExpression, equality);
        }
    }

    if(filterExpression != null)
    {
        var whereBody = Expression.Lambda<Func<Customer, bool>>(filterExpression, parameter);

        customers = customers.Where(whereBody);
    }

    return customers;
}

OwnerDisplayName: Bryan Watts

LastEditorDisplayName: Bryan Watts


问:
How do you get around generic functions not respecting associated types as derivable?
Here is the actual code, that I want to improve.

In cell, I want to enforce that Cell is a subclass of Self.Cell, which we know will derive from UIView, meaning that it itself is a class.

```<code>import UIKit

// Conforming types will have a function called `cell`
// which returns a subclass of `Cell`
protocol cell {
   typealias Cell: UIView
}

extension UICollectionView: cell {
   typealias Cell = UICollectionViewCell
}
extension UITableView: cell {
   typealias Cell = UITableViewCell
}

extension cell {
   // Error, because Self.Cell is not a protocol
   func cell<Cell: Self.Cell>() -> Cell! {
      // The real function shouldn't return
      // an implicitly unwrapped optional
      // but getting this to compile will solve my problem.
      return nil
   }
}
</code>```

答:
Since you want to ensure that the returned cell is a subclass of the type provided by the conforming type, it makes more sense to add this to the protocol requirement instead of trying to return a view for each Cell type with a single method in an extension of the protocol

```<code>// Written in Swift 5.2
protocol cell {
    associatedtype Cell: UIView
    func cell() -> Cell!
}

extension UICollectionView: cell {
    typealias Cell = UICollectionViewCell

    func cell() -> UICollectionViewCell! {
        UICollectionViewCell()
    }
}
extension UITableView: cell {
    typealias Cell = UITableViewCell

    func cell() -> UITableViewCell! {
        UITableViewCell()
    }
}
</code>```

The conforming types are free to return whatever subclass they want, and the cell() method will return a UIView that inherits from the cell class specified by the type. Note, however, that extending these classes prevents subclasses from overriding the protocol's methods and specifying cells of their own.

This is an old thread and you are probably already aware of this now. Hopefully this helped regardless.

ContentLicense: CC BY-SA 3.0

Body:
Here is the actual code, that I want to improve.

In cell, I want to enforce that Cell is a subclass of Self.Cell, which we know will derive from UIView, meaning that it itself is a class.

import UIKit

// Conforming types will have a function called `cell`
// which returns a subclass of `Cell`
protocol cell {
   typealias Cell: UIView
}

extension UICollectionView: cell {
   typealias Cell = UICollectionViewCell
}
extension UITableView: cell {
   typealias Cell = UITableViewCell
}

extension cell {
   // Error, because Self.Cell is not a protocol
   func cell<Cell: Self.Cell>() -> Cell! {
      // The real function shouldn't return
      // an implicitly unwrapped optional
      // but getting this to compile will solve my problem.
      return nil
   }
}

Body:
Since you want to ensure that the returned cell is a subclass of the type provided by the conforming type, it makes more sense to add this to the protocol requirement instead of trying to return a view for each Cell type with a single method in an extension of the protocol

// Written in Swift 5.2
protocol cell {
    associatedtype Cell: UIView
    func cell() -> Cell!
}

extension UICollectionView: cell {
    typealias Cell = UICollectionViewCell

    func cell() -> UICollectionViewCell! {
        UICollectionViewCell()
    }
}
extension UITableView: cell {
    typealias Cell = UITableViewCell

    func cell() -> UITableViewCell! {
        UITableViewCell()
    }
}

The conforming types are free to return whatever subclass they want, and the cell() method will return a UIView that inherits from the cell class specified by the type. Note, however, that extending these classes prevents subclasses from overriding the protocol's methods and specifying cells of their own.

This is an old thread and you are probably already aware of this now. Hopefully this helped regardless.


问:
Using dplyr mutate function to create new variable conditionally based on current row
I am working on creating conditional averages for a large data set that involves # of flu cases seen during the week for several years. The data is organized as such:

What I want to do is create a new column that tabulates that average number of cases for that same week in previous years. For instance, for the row where Week.Number is 1 and Flu.Year is 2017, I would like the new row to give the average count for any year with Week.Number==1 & Flu.Year<2017. Normally, I would use the case_when() function to conditionally tabulate something like this. For instance, when calculating the average weekly volume I used this code:

```<code>   mutate(average = case_when(
    Flu.Year==2016 ~ mean(chcc$count[chcc$Flu.Year==2016]),
    Flu.Year==2017 ~ mean(chcc$count[chcc$Flu.Year==2017]),
    Flu.Year==2018 ~ mean(chcc$count[chcc$Flu.Year==2018]),
    Flu.Year==2019 ~ mean(chcc$count[chcc$Flu.Year==2019]),
  ),
</code>```

However, since there are four years of data * 52 weeks which is a lot of iterations to spell out the conditions for. Is there a way to elegantly code this in dplyr? The problem I keep running into is that I want to call values in counts column based on Week.Number and Flu.Year values in other rows conditioned on the current value of Week.Number and Flu.Year, and I am not sure how to accomplish that. Please let me know if there is further information / detail I can provide.

Thanks,
Steven

dat <- tibble( Flu.Year = rep(2016:2019,each = 52), Week.Number = rep(1:52,4), count = sample(1000, size=52*4, replace=TRUE) )
```

答:
We can use aggregate from base R

```<code>aggregate(count ~ Flu.Year, data, FUN = mean)
</code>```

Body:
I am working on creating conditional averages for a large data set that involves # of flu cases seen during the week for several years. The data is organized as such:

What I want to do is create a new column that tabulates that average number of cases for that same week in previous years. For instance, for the row where Week.Number is 1 and Flu.Year is 2017, I would like the new row to give the average count for any year with Week.Number==1 & Flu.Year<2017. Normally, I would use the case_when() function to conditionally tabulate something like this. For instance, when calculating the average weekly volume I used this code:

   mutate(average = case_when(
    Flu.Year==2016 ~ mean(chcc$count[chcc$Flu.Year==2016]),
    Flu.Year==2017 ~ mean(chcc$count[chcc$Flu.Year==2017]),
    Flu.Year==2018 ~ mean(chcc$count[chcc$Flu.Year==2018]),
    Flu.Year==2019 ~ mean(chcc$count[chcc$Flu.Year==2019]),
  ),

However, since there are four years of data * 52 weeks which is a lot of iterations to spell out the conditions for. Is there a way to elegantly code this in dplyr? The problem I keep running into is that I want to call values in counts column based on Week.Number and Flu.Year values in other rows conditioned on the current value of Week.Number and Flu.Year, and I am not sure how to accomplish that. Please let me know if there is further information / detail I can provide.

Thanks,
Steven

dat <- tibble( Flu.Year = rep(2016:2019,each = 52), Week.Number = rep(1:52,4), count = sample(1000, size=52*4, replace=TRUE) )

Body:
We can use aggregate from base R

aggregate(count ~ Flu.Year, data, FUN = mean)


问:
Result of function vs loop
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

```<code>input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715
</code>```

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

```<code>for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773
</code>```

答:
As said in the comments, you need to create a loop and append the values inside just like so:</p>

```<code>import numpy as np
from scipy import integrate

input_= [0.1, 0.2]

def newvalue():
    values = []
    for i in input_:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        values.append(value[0])
    return values

print(newvalue()) #[1.8229239584193715, 1.2226505441838773]
</code>```

Title: Result of function vs loop

Body:
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773

Body:
As said in the comments, you need to create a loop and append the values inside just like so:

import numpy as np
from scipy import integrate

input_= [0.1, 0.2]

def newvalue():
    values = []
    for i in input_:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        values.append(value[0])
    return values

print(newvalue()) #[1.8229239584193715, 1.2226505441838773]


问:
Mutating constant object via pointer copied from 'this' in constructor
Example code:

```<code>struct Foo {
    Foo() { instance = this; }
    int value = 0;
    static Foo * instance;
};

Foo * Foo::instance = nullptr;

int main(int argc, char * argv[]) {
    Foo const foo;
    //foo.value = 1; // Compiler error, as expected.
    Foo::instance->value = 1; // Fine.
}
</code>```

Here foo is constant, but can be modified via the static instance pointer, which is assigned the value of this in Foo's constructor. Setting aside questions of why one might want to do something like this, my understanding is that there's nothing here that's technically incorrect.

I was confident this was safe, but in this thread there seem to be some suggestions to the contrary. One person seems to describe a similar example as ill-formed, while someone else mentions undefined behavior.

Advisability aside, is this technically correct and safe? Or is there some issue I'm missing?

答:
It is absolutely ill-advised to do so. For many reasons.

First, it's not thread-safe.

Second, mutating const-qualified objects by "unconsting" them by const_cast, or by the method that you've shown (or by any other method, for that matter), is simply undefined behaviour.

Body:
Example code:

struct Foo {
    Foo() { instance = this; }
    int value = 0;
    static Foo * instance;
};

Foo * Foo::instance = nullptr;

int main(int argc, char * argv[]) {
    Foo const foo;
    //foo.value = 1; // Compiler error, as expected.
    Foo::instance->value = 1; // Fine.
}

Here foo is constant, but can be modified via the static instance pointer, which is assigned the value of this in Foo's constructor. Setting aside questions of why one might want to do something like this, my understanding is that there's nothing here that's technically incorrect.

I was confident this was safe, but in this thread there seem to be some suggestions to the contrary. One person seems to describe a similar example as ill-formed, while someone else mentions undefined behavior.

Advisability aside, is this technically correct and safe? Or is there some issue I'm missing?


问:
how to show data from two database tables in vue with vuetify
I have a list of clients wiht a salesman field which is bound to a user id in the database, ¿how do i show in the table the user name that corresponds to its id?

```<code><v-data-table :headers="headers" :items="arrayClientes">
  <template v-slot:item.user_id="{ item }" :items="userLists">
          <span>{{item.user_id}}</span>
  </template>
</code>```

Script:

```<code>computed: {
      userLists() {
        return this.$store.state.user.users;
      },
    },
    created(){
        this.$store.dispatch('user/getUsers')
    },
</code>```

答:
You can try to create a method, which filters the specific user id and returns the user object.

For example:

export default {
  methods: {
    getUser(id) {
      return this.userLists.filter((user) => user.id === id))[0];
    },
  },
};
```

After that you can simply call this method in your span tag and specify the user id as a parameter.

Note: this does not check if the user id exists in the users list.

Body:
I have a list of clients wiht a salesman field which is bound to a user id in the database, ¿how do i show in the table the user name that corresponds to its id?

<v-data-table :headers="headers" :items="arrayClientes">
  <template v-slot:item.user_id="{ item }" :items="userLists">
          {{item.user_id}}
  </template>

Script:

computed: {
      userLists() {
        return this.$store.state.user.users;
      },
    },
    created(){
        this.$store.dispatch('user/getUsers')
    },

Body:
You can try to create a method, which filters the specific user id and returns the user object.

For example:

export default {
  methods: {
    getUser(id) {
      return this.userLists.filter((user) => user.id === id))[0];
    },
  },
};

After that you can simply call this method in your span tag and specify the user id as a parameter.

Note: this does not check if the user id exists in the users list.


问:
display if the numbers are consecutive for upto 3 positions exactly in pandas
I have a df "Index_label", which has only one column(name: column1) which contain numbers.

if we have consecutive position ==3. i would want it as out put

column1

25

26------------consecutive upto 2 positions

110

111

112

113---------------------consecutive upto 4 positions

455

456

457---------------------consecutive upto 3 positions

desired o/p:

110

111

112

455

456

457

答:
You can use this code (assuming you get the numbers as an iterable of some kind):</p>

```<code>def getConsecutive(numbers):
  consecutive = []                                 # all 3-consecutive numbers
  sub_series = []                                  # current sub-series of consecutive numbers

  for number in numbers:

    if len(sub_series) == 0:                       # if the current sub-series is empty
      sub_series.append(number)                    # add the current number to it
    else:
      prev = sub_series[-1]
      if number != prev+1:                         # if the current number is not consecutive
        if len(sub_series) >=3:                    # if there are at least 3 numbers in the sub_series
           consecutive.extend(sub_series[0:3])     # add the first 3 of the sub-series
        sub_series.clear()                         # clear the sub-series
      sub_series.append(number)                    # add the current number

  if len(sub_series) >=3:                          # check if a 3-consecutive sub series is found
    consecutive.extend(sub_series[0:3])            # add it in

  return consecutive

numbers1 = [25,26,110,111,112,113,455,456,457]
numbers2 = [110, 111, 112, 113, 114, 115, 116, 117]
print(getConsecutive(numbers1))         # output = [110, 111, 112, 455, 456, 457]
print(getConsecutive(numbers2))         # output = [110, 111, 112]
</code>```

Body:
You can use this code (assuming you get the numbers as an iterable of some kind):

def getConsecutive(numbers):
  consecutive = []                                 # all 3-consecutive numbers
  sub_series = []                                  # current sub-series of consecutive numbers

  for number in numbers:

    if len(sub_series) == 0:                       # if the current sub-series is empty
      sub_series.append(number)                    # add the current number to it
    else:
      prev = sub_series[-1]
      if number != prev+1:                         # if the current number is not consecutive
        if len(sub_series) >=3:                    # if there are at least 3 numbers in the sub_series
           consecutive.extend(sub_series[0:3])     # add the first 3 of the sub-series
        sub_series.clear()                         # clear the sub-series
      sub_series.append(number)                    # add the current number

  if len(sub_series) >=3:                          # check if a 3-consecutive sub series is found
    consecutive.extend(sub_series[0:3])            # add it in

  return consecutive

numbers1 = [25,26,110,111,112,113,455,456,457]
numbers2 = [110, 111, 112, 113, 114, 115, 116, 117]
print(getConsecutive(numbers1))         # output = [110, 111, 112, 455, 456, 457]
print(getConsecutive(numbers2))         # output = [110, 111, 112]


问:
neo4j look for users by radius
I am a new noob to neo4j. this is my second day.

Pretty excited about the technology and have many questions. please be patient ☺

in the desired application, users can view uses around them

(only in cases where both users are visible to each other using the location_radius ) property

for this exercise, I generated 100,000 users with a random location in my country inside MySql. and they are imported to neo4j (relationships are created manually by python neo4j)

1st attempt:

create a relationship between users that are visible by the desire criteria.

a. insert all users to neo4j (fast)

b. one by one create relationships by looking at the location of criteria of previous users (slow process, probably doing it wrong)

this is still running, currently 13,987 nodes. 22,460,068 relationships..... is this wrong a idea?

```<code>MATCH (src_u:User {user_id:1})-[:IN_SEARCH]-(u:User)
RETURN src_u, u
</code>```

2nd attempt  (one the same schema)

Run the query without using the relationships

```<code>MATCH (me:User {user_id:1}),(u:User)
WHERE u.user_id <> 1
AND me.gender <> u.gender
AND distance(me.location, u.location) < me.location_radius
AND distance(me.location, u.location) < u.location_radius
RETURN u
</code>```

3rd attempt

The same thing but try to optimize the 2nd attempt, will this query optimize the 2nd attempt?

```<code>MATCH (me:User {user_id:1})
WITH me
MATCH (u:User)
WHERE u.user_id <> 1
AND me.gender <> u.gender
WITH me, u, distance(me.location, u.location) as d
WHERE d < me.location_radius AND d < u.location_radius
RETURN u
</code>```

My questions are:

is the 1st attempt is the wrong way to go, dose millions of relationships is a wrong idea?

dose 2/3 attempt are superior to 1st attempt?

dose the 3rd attempt dose any optimization for the 2nd attempt?

dose a grid of "Station" (Station {point(...)} nodes (each kilometer square) and connecting users to the closest Station help (in case if 1st attempt is too much.)?

neo4j can replace the DB completely?, is it a good practice to store the RAW data in a relational database?

The User create query:

```<code>MERGE (u:User {user_id:$user_id})
ON CREATE SET u.name=$name, u.gender=$gender, u.location=point({latitude:$latitude,longitude:$longitude}), u.location_radius=$location_radius
RETURN u
</code>```

thank you

shay

答:
Creating/deleting "nearness" relationships between all Users is not practical, as you have seen, especially if you need to do that continuously. Generally speaking, relationships should be used when you expect relatively stable connections between nodes. It does not make sense to create/delete a lot relationships to keep track of the results of a continuously running process -- especially if you only care about the results for a handful of Users.

Instead, you should create a spatial index on :User(location):

```<code>CREATE INDEX user_distance FOR (u:User) ON (u.location)
</code>```

That can speed up certain distance queries. For example, PROFILE shows that the following query would use that spatial index (at least in neo4j 4.0.4). You should always profile your queries to help optimize them, and to make sure they remain optimized after version changes.

```<code>MATCH (p:User), (q:User)
WHERE
  p.user_id = 1 AND
  p.location_radius > distance(p.location, q.location) < q.location_radius
RETURN p, COLLECT(q) AS others_nearby
</code>```

Title: neo4j look for users by radius

Body:
I am a new noob to neo4j. this is my second day.

Pretty excited about the technology and have many questions. please be patient ☺

in the desired application, users can view uses around them

(only in cases where both users are visible to each other using the location_radius ) property

for this exercise, I generated 100,000 users with a random location in my country inside MySql. and they are imported to neo4j (relationships are created manually by python neo4j)

1st attempt:

create a relationship between users that are visible by the desire criteria.

a. insert all users to neo4j (fast)

b. one by one create relationships by looking at the location of criteria of previous users (slow process, probably doing it wrong)

this is still running, currently 13,987 nodes. 22,460,068 relationships..... is this wrong a idea?

MATCH (src_u:User {user_id:1})-[:IN_SEARCH]-(u:User)
RETURN src_u, u

2nd attempt  (one the same schema)

Run the query without using the relationships

MATCH (me:User {user_id:1}),(u:User)
WHERE u.user_id <> 1
AND me.gender <> u.gender
AND distance(me.location, u.location) < me.location_radius
AND distance(me.location, u.location) < u.location_radius
RETURN u

3rd attempt

The same thing but try to optimize the 2nd attempt, will this query optimize the 2nd attempt?

MATCH (me:User {user_id:1})
WITH me
MATCH (u:User)
WHERE u.user_id <> 1
AND me.gender <> u.gender
WITH me, u, distance(me.location, u.location) as d
WHERE d < me.location_radius AND d < u.location_radius
RETURN u

My questions are:

is the 1st attempt is the wrong way to go, dose millions of relationships is a wrong idea?

dose 2/3 attempt are superior to 1st attempt?

dose the 3rd attempt dose any optimization for the 2nd attempt?

dose a grid of "Station" (Station {point(...)} nodes (each kilometer square) and connecting users to the closest Station help (in case if 1st attempt is too much.)?

neo4j can replace the DB completely?, is it a good practice to store the RAW data in a relational database?

The User create query:

MERGE (u:User {user_id:$user_id})
ON CREATE SET u.name=$name, u.gender=$gender, u.location=point({latitude:$latitude,longitude:$longitude}), u.location_radius=$location_radius
RETURN u

thank you

shay

Body:
Creating/deleting "nearness" relationships between all Users is not practical, as you have seen, especially if you need to do that continuously. Generally speaking, relationships should be used when you expect relatively stable connections between nodes. It does not make sense to create/delete a lot relationships to keep track of the results of a continuously running process -- especially if you only care about the results for a handful of Users.

Instead, you should create a spatial index on :User(location):

CREATE INDEX user_distance FOR (u:User) ON (u.location)

That can speed up certain distance queries. For example, PROFILE shows that the following query would use that spatial index (at least in neo4j 4.0.4). You should always profile your queries to help optimize them, and to make sure they remain optimized after version changes.

MATCH (p:User), (q:User)
WHERE
  p.user_id = 1 AND
  p.location_radius > distance(p.location, q.location) < q.location_radius
RETURN p, COLLECT(q) AS others_nearby


问:
How to check successive values in a CSV file by awk?
In a two-column CSV, I want to check the successive numbers (the values are integers):

```<code>1,1
4,1
5,1
6,1
7,1
10,1
11,1
4,2
5,2
6,2
10,2
5,3
5,7
5,8
5,9
</code>```

I tried

```<code>awk -F, '
{
    if($1==a+1) { n+=1 }
    else { n = 1 }
{a=$1}
} {print $1"," n}
' file.txt
</code>```

to produce

```<code>1,1,1
4,1,1
5,1,2
6,1,3
7,1,4
10,1,1
11,1,2
4,2,1
5,2,2
6,2,3
10,2,1
5,3,1
5,7,1
5,8,1
5,9,1
</code>```

where the third column counts the successive rows with respect to the first column.

Is my approach is correct (particularly performance-wise because it is a huge file)?

What is the best way to calculate the fourth column based on the second column (counting the successive values in the second column)?

This is the expected output including the fourth column.

```<code>1,1,1,1
4,1,1,1
5,1,2,1
6,1,3,1
7,1,4,1
10,1,1,1
11,1,2,1
4,2,1,1
5,2,2,1
6,2,3,1
10,2,1,1
5,3,1,1
5,7,1,1
5,8,1,2
5,9,1,3
</code>```

My idea is to sort the produced 3-column CSV (sort -t, -k1,1n -k2,2n) and do the same thing with the second column, but I am not sure.

EDIT: I made a mistake in the first dataset. When we count the first column, the second column is constant, and vice versa.

Body:
In a two-column CSV, I want to check the successive numbers (the values are integers):

1,1
4,1
5,1
6,1
7,1
10,1
11,1
4,2
5,2
6,2
10,2
5,3
5,7
5,8
5,9

I tried

awk -F, '
{
    if($1==a+1) { n+=1 }
    else { n = 1 }
{a=$1}
} {print $1"," n}
' file.txt

to produce

1,1,1
4,1,1
5,1,2
6,1,3
7,1,4
10,1,1
11,1,2
4,2,1
5,2,2
6,2,3
10,2,1
5,3,1
5,7,1
5,8,1
5,9,1

where the third column counts the successive rows with respect to the first column.

Is my approach is correct (particularly performance-wise because it is a huge file)?

What is the best way to calculate the fourth column based on the second column (counting the successive values in the second column)?

This is the expected output including the fourth column.

1,1,1,1
4,1,1,1
5,1,2,1
6,1,3,1
7,1,4,1
10,1,1,1
11,1,2,1
4,2,1,1
5,2,2,1
6,2,3,1
10,2,1,1
5,3,1,1
5,7,1,1
5,8,1,2
5,9,1,3

My idea is to sort the produced 3-column CSV (sort -t, -k1,1n -k2,2n) and do the same thing with the second column, but I am not sure.

EDIT: I made a mistake in the first dataset. When we count the first column, the second column is constant, and vice versa.

Body:
This awk should work for you:

awk 'BEGIN {
   FS=OFS=","
}
{
    $3 = ($1 == p1+1 ? $3+1 : 1)
    $4 = ($1 == p1 && $2 == p2+1 ? $4+1 : 1)
}
{
   p1 = $1
   p2 = $2
} 1' file.csv

1,1,1,1
4,1,1,1
5,1,2,1
6,1,3,1
7,1,4,1
10,1,1,1
11,1,2,1
4,2,1,1
5,2,2,1
6,2,3,1
10,2,1,1
5,3,1,1
5,7,1,1
5,8,1,2
5,9,1,3


问:
How to prompt iOS user for geoLocation service permission in Ionic
I've created a social media app that uses geoLocation services.  It's an Ionic 4 app with a Firebase backend.  GeoLocation services are working with Android but with iOS it's not prompting users for geoLocation access.

I've been looking but can't find an example of how to prompt users for GeoLocation service permission on Platform ready.

Any example on how to check for location services permissions and then prompt a user for location services permissions would be greatly appreciated.

And I assume this would be added to the app.component.ts file.

答:
You're not supposed to prompt for permission until you request a location. When you ask for a location the first time the permissions system prompt will be displayed.

If you want to check the permission status for Geolocation at any time you can use the
cordova-diagnostic-plugin plugin (there is an Ionic wrapper).

Once installed you can enquire about permissions, status, etc.:

```<code>this.diagnostic.isLocationAvailable(); // returns a promise
this.diagnostic.isLocationAuthorized(); // returns a promise
// etc.
</code>```

Body:
You're not supposed to prompt for permission until you request a location. When you ask for a location the first time the permissions system prompt will be displayed.

If you want to check the permission status for Geolocation at any time you can use the
cordova-diagnostic-plugin plugin (there is an Ionic wrapper).

Once installed you can enquire about permissions, status, etc.:

this.diagnostic.isLocationAvailable(); // returns a promise
this.diagnostic.isLocationAuthorized(); // returns a promise
// etc.


问:
Working out how many hours worked after a certain time
I am working on some custom rules in a time managment system and need to know how many hours in a shift have been before a certain time (19:00pm) and how many hours after. Shifts can start in the evening and finish in the morning so need to take that into account.

So far I have the below (this is just a snippet for one day) however it seems very clumsy and eloborate what I have written, can't help but feel I am missing a simpler solution, anyone have any ideas?

```<code>        DateTime cutOffTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 00, 00);
        string cutOffTimeOfDay = GetTimeOfDayFromDateTime(cutOffTime);

        double baseMondayHours = 10.00;
        baseMondayHours = (baseMondayHours - 0.5);

        if (GetTimeOfDayOnlyFromDateTime(monday.ShiftStart.Value) == "AM" && GetTimeOfDayOnlyFromDateTime(monday.ShiftEnd.Value) == "PM"
            && monday.ShiftEnd.Value.TimeOfDay < cutOffTime.TimeOfDay)
        {
            postCutOffMondayHours = 0;
            baseMondayHours = monday.HoursWorked.Value;
        }
        else
        {
            string endTimeOfDay = GetTimeOfDayFromDateTime(monday.ShiftEnd.Value);
            double hoursAfterCutOff = GetDuration(cutOffTimeOfDay, endTimeOfDay);

            postCutOffMondayHours = hoursAfterCutOff;
            baseMondayHours = (baseMondayHours - hoursAfterCutOff);
        }

    public static string GetTimeOfDayFromDateTime(DateTime d)
    {
        return d.ToString("HH:mm") + " " + d.ToString("tt", CultureInfo.InvariantCulture);
    }

    public static string GetTimeOfDayOnlyFromDateTime(DateTime d)
    {
        return d.ToString("tt", CultureInfo.InvariantCulture).ToUpper();
    }

        public static double GetDuration(string startTime, string endTime)
        {
            DateTime start = DateTime.Parse(startTime);
            DateTime end = DateTime.Parse(endTime);
            if (start > end)
                end = end.AddDays(1);

            TimeSpan duration = end.Subtract(start);

            return duration.TotalHours;
        }
</code>```

答:
I'm  not sure if I'm missing something here, but isn't the built-in operator- of DateTime exactly what you're looking for? It returns the TimeSpan between the 2 DateTime, and if you can guarantee shiftStart < cutoffDateTime < shiftEnd, then you can get the hours worked by just using the TotalHours of TimeSpan (but adding that check is just an additional small if)

```<code>var shiftStart = new DateTime(2020, 6, 2, 17, 0, 0);
var shiftEnd = new DateTime(2020, 6, 3, 6, 30, 0);
var cutoffDateTime = new DateTime(2020, 6, 2, 19, 0, 0);

var hoursWorkedBefore = (cutoffDateTime - shiftStart).TotalHours;
var hoursWorkedAfter = (shiftEnd - cutoffDateTime).TotalHours;
</code>```

Body:
I am working on some custom rules in a time managment system and need to know how many hours in a shift have been before a certain time (19:00pm) and how many hours after. Shifts can start in the evening and finish in the morning so need to take that into account.

So far I have the below (this is just a snippet for one day) however it seems very clumsy and eloborate what I have written, can't help but feel I am missing a simpler solution, anyone have any ideas?

        DateTime cutOffTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 00, 00);
        string cutOffTimeOfDay = GetTimeOfDayFromDateTime(cutOffTime);

        double baseMondayHours = 10.00;
        baseMondayHours = (baseMondayHours - 0.5);

        if (GetTimeOfDayOnlyFromDateTime(monday.ShiftStart.Value) == "AM" && GetTimeOfDayOnlyFromDateTime(monday.ShiftEnd.Value) == "PM"
            && monday.ShiftEnd.Value.TimeOfDay < cutOffTime.TimeOfDay)
        {
            postCutOffMondayHours = 0;
            baseMondayHours = monday.HoursWorked.Value;
        }
        else
        {
            string endTimeOfDay = GetTimeOfDayFromDateTime(monday.ShiftEnd.Value);
            double hoursAfterCutOff = GetDuration(cutOffTimeOfDay, endTimeOfDay);

            postCutOffMondayHours = hoursAfterCutOff;
            baseMondayHours = (baseMondayHours - hoursAfterCutOff);
        }

    public static string GetTimeOfDayFromDateTime(DateTime d)
    {
        return d.ToString("HH:mm") + " " + d.ToString("tt", CultureInfo.InvariantCulture);
    }

    public static string GetTimeOfDayOnlyFromDateTime(DateTime d)
    {
        return d.ToString("tt", CultureInfo.InvariantCulture).ToUpper();
    }

        public static double GetDuration(string startTime, string endTime)
        {
            DateTime start = DateTime.Parse(startTime);
            DateTime end = DateTime.Parse(endTime);
            if (start > end)
                end = end.AddDays(1);

            TimeSpan duration = end.Subtract(start);

            return duration.TotalHours;
        }

Body:
I'm  not sure if I'm missing something here, but isn't the built-in operator- of DateTime exactly what you're looking for? It returns the TimeSpan between the 2 DateTime, and if you can guarantee shiftStart < cutoffDateTime < shiftEnd, then you can get the hours worked by just using the TotalHours of TimeSpan (but adding that check is just an additional small if)

var shiftStart = new DateTime(2020, 6, 2, 17, 0, 0);
var shiftEnd = new DateTime(2020, 6, 3, 6, 30, 0);
var cutoffDateTime = new DateTime(2020, 6, 2, 19, 0, 0);

var hoursWorkedBefore = (cutoffDateTime - shiftStart).TotalHours;
var hoursWorkedAfter = (shiftEnd - cutoffDateTime).TotalHours;


问:
TypeError: Cannot read property 'map' of undefined in React while fetching external API
I am trying to fetch some photos using external API - Unsplash in React  and getting the error = (see in title). API seems to work totally fine, since when I console log its there, but somehow I can not to print it out. Can you see if I am making mistake somewhere ?? I am really getting lost, already spent hours by trying to figure out.

This is my code :

```<code>import React, { useState } from "react";
import axios from "axios";

const PhotoList = () => {
  const [photography, setPhotography] = useState("");
  const [clientId, setClientId] = useState(
    "MyAPIKey"
  );
  const [result, setResult] = useState([]);

  const handleChange = ev => {
    setPhotography(ev.target.value);
  };
  const handleSubmit = ev => {
    console.log(photography);

    const url =
      "https://api.unsplash.com/photos?page=1&query" +
      photography +
      "&client_id=" +
      clientId;

    axios.get(url).then(response => {
      console.log(response);
      setResult(response.data.results);
    });
  };
</code>```

And returning in HTML :

```<code>  return (
    <>
      <h1>Here is the list of the photos</h1>
      <input
        onChange={handleChange}
        type="text"
        name="photography"
        placeholder="Get more inspiration here"
      ></input>
      <button onClick={handleSubmit} type="submit">
        Search
      </button>

      {result.map(photography => (
        <img src={photography.urls.small} />
      ))}
    </>
  );
};

export default PhotoList;
</code>```

答:
After reviewing the API response body, the API callback should be:

```<code>setResult(response.data);
</code>```

The results key does not exist in the API response body.

Body:
I am trying to fetch some photos using external API - Unsplash in React  and getting the error = (see in title). API seems to work totally fine, since when I console log its there, but somehow I can not to print it out. Can you see if I am making mistake somewhere ?? I am really getting lost, already spent hours by trying to figure out.

This is my code :

import React, { useState } from "react";
import axios from "axios";

const PhotoList = () => {
  const [photography, setPhotography] = useState("");
  const [clientId, setClientId] = useState(
    "MyAPIKey"
  );
  const [result, setResult] = useState([]);

  const handleChange = ev => {
    setPhotography(ev.target.value);
  };
  const handleSubmit = ev => {
    console.log(photography);

    const url =
      "https://api.unsplash.com/photos?page=1&query" +
      photography +
      "&client_id=" +
      clientId;

    axios.get(url).then(response => {
      console.log(response);
      setResult(response.data.results);
    });
  };

And returning in HTML :

  return (
    <>

Here is the list of the photos

      <input
        onChange={handleChange}
        type="text"
        name="photography"
        placeholder="Get more inspiration here"
      ></input>
      <button onClick={handleSubmit} type="submit">
        Search
      </button>

      {result.map(photography => (

      ))}
    </>
  );
};

export default PhotoList;

Body:
After reviewing the API response body, the API callback should be:

setResult(response.data);

The results key does not exist in the API response body.


问:
How can I forge a DHCP Discovery packet using Bash?
I would like to send via network (LAN) a classic DHCP Discover package using command line, in order to trigger a response from any DHCP server listening, so I could capture it with something like (say my IP address is 192.168.0.30 ):

```<code>tcpdump -i eth0 host 192.168.0.30 -n -s 0 -vvv -w listening.pcap
</code>```

I think about this as a simple method to detect rogue DHCP servers on a network.

How can I do this using Bash ?

Further data:

Other tools allowed, but lets try to keep ti simple: NetCat, sed, grep... etc.

Similar example for forging WOL packet: Bash one-line command to send wake on LAN magic packet without specific tool

答:
"Hacker" solution

The question asked raises three issues:

the use of Bash echo

Shipment of the UDP DHCPDISCOVER package

generating the DHCPDISCOVER package

For the DHCPDISCOVER packet to reach the DHCP server without distortion, it must be sent as binary data. Unfortunately, Bash receives some binary sequences as control commands. This excludes the use of echo Bash.

The cat command does not cause this problem as long as the input is from a file (bypassing bash). The package is shipped as follows:

```<code>cat blobfile | nc -w1 -u -b 255.255.255.255 67
</code>```

The package is sent correctly, server DHCP returns the package DHCP Offer. A fragment of the log from tcpdump:

```<code>DHCP-Message Option 53, length 1: Discover
</code>```

and server answer:

```<code>DHCP-Message Option 53, length 1: Offer
</code>```

Where to get the shipping details is a separate matter.
I got them by intercepting DHCPDISCOVER shipping using ncat in such a way:

```<code>ncat -l -p 67 --udp >blobfile
</code>```

Having such a block is enough to send DHCPDISCOVER packets and thus solve the basic task.

To be precise, you would have to write the DHCPDISCOVER package generator, unfortunately RFC 2132 and other has a rather complex structure and recording format - see my "full solution".

Body:
I would like to send via network (LAN) a classic DHCP Discover package using command line, in order to trigger a response from any DHCP server listening, so I could capture it with something like (say my IP address is 192.168.0.30 ):

tcpdump -i eth0 host 192.168.0.30 -n -s 0 -vvv -w listening.pcap

I think about this as a simple method to detect rogue DHCP servers on a network.

How can I do this using Bash ?

Further data:

Other tools allowed, but lets try to keep ti simple: NetCat, sed, grep... etc.

Similar example for forging WOL packet: Bash one-line command to send wake on LAN magic packet without specific tool

Body:
"Hacker" solution

The question asked raises three issues:

the use of Bash echo

Shipment of the UDP DHCPDISCOVER package

generating the DHCPDISCOVER package

For the DHCPDISCOVER packet to reach the DHCP server without distortion, it must be sent as binary data. Unfortunately, Bash receives some binary sequences as control commands. This excludes the use of echo Bash.

The cat command does not cause this problem as long as the input is from a file (bypassing bash). The package is shipped as follows:

cat blobfile | nc -w1 -u -b 255.255.255.255 67

The package is sent correctly, server DHCP returns the package DHCP Offer. A fragment of the log from tcpdump:

DHCP-Message Option 53, length 1: Discover

and server answer:

DHCP-Message Option 53, length 1: Offer

Where to get the shipping details is a separate matter.
I got them by intercepting DHCPDISCOVER shipping using ncat in such a way:

ncat -l -p 67 --udp >blobfile

Having such a block is enough to send DHCPDISCOVER packets and thus solve the basic task.

To be precise, you would have to write the DHCPDISCOVER package generator, unfortunately RFC 2132 and other has a rather complex structure and recording format - see my "full solution".


问:
How can I execute code from the Release / Release All buttons in the Release AR Documents screen
I've got a customization to the Invoice & Memo screen where I execute some custom code (web service calls) when the Release action is activated.  This works fine - I knew how to replace the PXAction code and proceeded from there.  Now I want to use the Release AR Documents processing screen to do the same thing, but I'm having trouble understanding where / what to override, or where to place my code.

I see the ARDocumentRelease graph constructor with the SetProcessDelegate in the source code, but I'm not sure how to proceed - whether this is where I need to be looking or not.  I need to execute my code for each line being released, using the RefNbr in my code.

答:
Please note that you must always call static methods from within long running process and create necessary objects there.

Processing delegate logic is implemented as long running process which creates worker thread to execute the processing logic.

You have AddAdditionalLogicToRelease() method which requires object instance in order to call and will fail during thread context switches and hence the issue. So, you must have create object instance inside the thread context and then call instance method.

In general, method that gets called from long running processes are declared static and required objects/graphs are created inside this static method to do some work.  See below example how to properly override ARDocumentRelease graph for this purpose:

```<code>public class ARDocumentRelease_Extension : PXGraphExtension<ARDocumentRelease>
{
    public override void Initialize()
    {

        Base.ARDocumentList.SetProcessDelegate(
            delegate (List<BalancedARDocument> list)
            {
                List<ARRegister> newlist = new List<ARRegister>(list.Count);
                foreach (BalancedARDocument doc in list)
                {
                    newlist.Add(doc);
                }

                // use override that allows to specify onsuccess routine
                ARDocumentRelease.ReleaseDoc(newlist, true, null, (ardoc, isAborted) =>
                {
                    //Custom code here, such as create your GL
                });
            }
        );

    }
}
</code>```

Body:
Please note that you must always call static methods from within long running process and create necessary objects there.

Processing delegate logic is implemented as long running process which creates worker thread to execute the processing logic.

You have AddAdditionalLogicToRelease() method which requires object instance in order to call and will fail during thread context switches and hence the issue. So, you must have create object instance inside the thread context and then call instance method.

In general, method that gets called from long running processes are declared static and required objects/graphs are created inside this static method to do some work.  See below example how to properly override ARDocumentRelease graph for this purpose:

public class ARDocumentRelease_Extension : PXGraphExtension<ARDocumentRelease>
{
    public override void Initialize()
    {

        Base.ARDocumentList.SetProcessDelegate(
            delegate (List<BalancedARDocument> list)
            {
                List<ARRegister> newlist = new List<ARRegister>(list.Count);
                foreach (BalancedARDocument doc in list)
                {
                    newlist.Add(doc);
                }

                // use override that allows to specify onsuccess routine
                ARDocumentRelease.ReleaseDoc(newlist, true, null, (ardoc, isAborted) =>
                {
                    //Custom code here, such as create your GL
                });
            }
        );

    }
}


问:
How to extract the last digits of strings using regular expressions?
I have a bunch of colnames

```<code>L_1_3
L_2_23
L_3_91
L_3_16
</code>```

I want to replace these colnames with new names using the last digits following the _ like this:

```<code>3
23
91
16
</code>```

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

Body:
I have a bunch of colnames

L_1_3
L_2_23
L_3_91
L_3_16

I want to replace these colnames with new names using the last digits following the _ like this:

3
23
91
16

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

Body:
We can use str_extract

library(stringr)
str_extract(X, "\\d+$")
#[1] "3"  "23" "91" "16"

data

X <- c("L_1_3", "L_2_23", "L_3_91", "L_3_16")


问:
how to use jquery in GWT application?
i am newbie for GWT.i had created one simple registration form using GWT.i want to add validation for each field using jquery.please help me to explain that how i am able to use jquery in GWT.

Thanks

答:
There is no need to use a external lib like jquery. What is jquery good for?

Selecting elements: You dont need to select elements cause you create them all by yourself and you can store them in variables for later use. This more efficient than traversing the DOM later to get the element you're looking for.

Animation: There is a Animation class in gwt that can be easily used to animate CSS properties of elements.

Creating new elements: This can be done with GWT as well.

Events: Can be done with GWT, plus you have an global eventbus and dont need to misuse the window object as eventbus. Also event delegation can be done with GWT, take a look at CellList source code to understand how to deal with it in GWT.

Working with GWT for a half year on a really large project I've seen no need for using external libraries like jquery. The only thing we missed was drag'n drop, we're using gwt-dnd for this.

Title: how to use jquery in GWT application?


问:
pandas dataframe match string in any place( column name or any cell)
So far  found  there is a way to match string in particular column using  df['A'].str.contains(re.compile("[Dd]ate")).  This is a way to find column A contains "date" or "Date".

How about any place in this dataframe, including column names or any cell?
Return True if any column names or cell contains this pattern, else False
.

答:
You could convert the whole df (including row and column indices) to a string and then search that string:</p>

```<code>re.search('[Dd]ate', df.to_string()) != None
</code>```

Body:
You could convert the whole df (including row and column indices) to a string and then search that string:

re.search('[Dd]ate', df.to_string()) != None


问:
Trouble finding page. Django url / views
this is the first time I had to ask something at StackOverflow, I'm both excited and scared, I don't know why.
I'm writing a Django app that just hosts web posts. The page is divided into three (3) categories (Index, lkmi and chiqung). Each post has a category (lkmi or chiqung).
On the INDEX page, you can see all the posts.
On the LKMI page, you can see only the lkmi posts.
On the CHIQUNG page, you can see only the chiqung posts.
All is controlled just by ONE VIEW called "index_page", which receives an argument called "cat" that is the URL from one of the categories (index, lkmi, chiqung). Based on that it dictates which posts to load.

* NOW THE PROBLEM *

I can't find why, but I'm only having trouble loading the lkmi section. The index page and the chiqung_page loads perfectly, but I'm having a

```<code>"Page Not Found (404)
 Request Method: GET
 Request URL:   http://127.0.0.1:8000/lkmi/
</code>```

Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order:

```<code> admin/
 <cat> [name='index_page']
 post/<int:pk> [name='post_detallado']
 ^ckeditor/
</code>```

The current path, lkmi/, didn't match any of these.
"
I'll leave here the models, views and urls.
Models
Category

```<code>class Category(models.Model):
    name = models.CharField(max_length=50)
    presentation = RichTextUploadingField(default='')
    order = models.IntegerField(null=True)
    url = models.CharField(max_length=50,default='',null=False,blank=True)
    class Meta:
        verbose_name = ("Categoria")
        verbose_name_plural = ("Categorias")

    def __str__(self):
        return self.name

    def get_postes(self):
        print('Entre get_postes')
        if self.url == '/':
            return Post.objects.all().order_by('-published_date')
        else:
            return Post.objects.filter(category=self.pk).order_by('-published_date')

</code>```

Post

```<code>class Post(models.Model):
    title = models.CharField(('Titulo'),max_length=50)
    category = models.ForeignKey("core.Category", verbose_name=("Categoria"), null=True, on_delete=models.CASCADE)
    creation_date = models.DateTimeField(auto_now = True)
    published_date = models.DateTimeField(auto_now=False, auto_now_add=False)
    content = RichTextUploadingField()
    author = models.CharField(("Autor/a"), max_length=50, default='El Autor')

    class Meta:
        verbose_name = ("Post")
        verbose_name_plural = ("Postes")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("_detail", kwargs={"pk": self.pk})

</code>```

View That Handles The Categorization

```<code>def index_page(request, cat):
    print('function index_page')
    print('cat ='+str(cat))
    category = get_object_or_404(Category,url=cat)
    print('get_object_or_404(Category,url=cat). Executed')
    print(str(category))
    postes = category.get_postes()
    print('category.get_postes(). Executed')
    return render(request, 'index.html',{'postes': postes,
                                         'category': category})
</code>```

URL file from the app

```<code>urlpatterns = [
    path('admin/',admin.site.urls),
    path('<cat>', views.index_page, name='index_page'),
    path('post/<int:pk>', views.detailed_post, name='detailed_post'),
]
</code>```

Index Page
It loads
Chiqung Page
It loads
LKMI Page
It doesn't load...

If i use python manage.py shell and look for the category using Category.objects.get(url='lkmi') it returns the desired Category. Based on the comments of the view, it doesn't even enter the view function, because in the console it doesn't output "function index_page", even though it is the first line of the function.

Also, if i try the url "**127.0.0.1:8000/lkmi" it gives

```<code>Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order:
1. admin/ -
2. <cat> name='index_page'] -
3. post/<int:pk> [name='post_detallado'].
</code>```

But if i just enter "127.0.0.1:8000/whatever" the error is just

```<code>No Categoria matches the given query.
</code>```

So in this case it entered the function and it gave the 404 error of not finding a matching Category. I still can't understand why it doens't execute the view when i try to enter to the lkmi url..

Thank you very much, I hope someone can help me with this so I cant continue going.

答:
Your class is called "Category", but you call get_object_or_404() on "Categoria"

View should be:

```<code>def index_page(request, cat):
    categoria = get_object_or_404(Category,url=cat)
    postes = categoria.get_postes()
    return render(request, 'index.html',{'postes': postes,
                                         'categoria': categoria})
</code>```

Body:
this is the first time I had to ask something at StackOverflow, I'm both excited and scared, I don't know why.
I'm writing a Django app that just hosts web posts. The page is divided into three (3) categories (Index, lkmi and chiqung). Each post has a category (lkmi or chiqung).
On the INDEX page, you can see all the posts.
On the LKMI page, you can see only the lkmi posts.
On the CHIQUNG page, you can see only the chiqung posts.
All is controlled just by ONE VIEW called "index_page", which receives an argument called "cat" that is the URL from one of the categories (index, lkmi, chiqung). Based on that it dictates which posts to load.

* NOW THE PROBLEM *

I can't find why, but I'm only having trouble loading the lkmi section. The index page and the chiqung_page loads perfectly, but I'm having a

"Page Not Found (404)
 Request Method: GET
 Request URL:   http://127.0.0.1:8000/lkmi/

Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order:

 admin/
 <cat> [name='index_page']
 post/<int:pk> [name='post_detallado']
 ^ckeditor/

The current path, lkmi/, didn't match any of these.
"
I'll leave here the models, views and urls.
Models
Category

class Category(models.Model):
    name = models.CharField(max_length=50)
    presentation = RichTextUploadingField(default='')
    order = models.IntegerField(null=True)
    url = models.CharField(max_length=50,default='',null=False,blank=True)
    class Meta:
        verbose_name = ("Categoria")
        verbose_name_plural = ("Categorias")

    def __str__(self):
        return self.name

    def get_postes(self):
        print('Entre get_postes')
        if self.url == '/':
            return Post.objects.all().order_by('-published_date')
        else:
            return Post.objects.filter(category=self.pk).order_by('-published_date')

Post

class Post(models.Model):
    title = models.CharField(('Titulo'),max_length=50)
    category = models.ForeignKey("core.Category", verbose_name=("Categoria"), null=True, on_delete=models.CASCADE)
    creation_date = models.DateTimeField(auto_now = True)
    published_date = models.DateTimeField(auto_now=False, auto_now_add=False)
    content = RichTextUploadingField()
    author = models.CharField(("Autor/a"), max_length=50, default='El Autor')

    class Meta:
        verbose_name = ("Post")
        verbose_name_plural = ("Postes")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("_detail", kwargs={"pk": self.pk})

View That Handles The Categorization

def index_page(request, cat):
    print('function index_page')
    print('cat ='+str(cat))
    category = get_object_or_404(Category,url=cat)
    print('get_object_or_404(Category,url=cat). Executed')
    print(str(category))
    postes = category.get_postes()
    print('category.get_postes(). Executed')
    return render(request, 'index.html',{'postes': postes,
                                         'category': category})

URL file from the app

urlpatterns = [
    path('admin/',admin.site.urls),
    path('<cat>', views.index_page, name='index_page'),
    path('post/<int:pk>', views.detailed_post, name='detailed_post'),
]

Index Page
It loads
Chiqung Page
It loads
LKMI Page
It doesn't load...

If i use python manage.py shell and look for the category using Category.objects.get(url='lkmi') it returns the desired Category. Based on the comments of the view, it doesn't even enter the view function, because in the console it doesn't output "function index_page", even though it is the first line of the function.

Also, if i try the url "**127.0.0.1:8000/lkmi" it gives

Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order:
1. admin/ -
2. <cat> name='index_page'] -
3. post/<int:pk> [name='post_detallado'].

But if i just enter "127.0.0.1:8000/whatever" the error is just

No Categoria matches the given query.

So in this case it entered the function and it gave the 404 error of not finding a matching Category. I still can't understand why it doens't execute the view when i try to enter to the lkmi url..

Thank you very much, I hope someone can help me with this so I cant continue going.

Body:
Your class is called "Category", but you call get_object_or_404() on "Categoria"

View should be:

def index_page(request, cat):
    categoria = get_object_or_404(Category,url=cat)
    postes = categoria.get_postes()
    return render(request, 'index.html',{'postes': postes,
                                         'categoria': categoria})


问:
Why won't my app render when state changes?
I'm building an application that allows for posting community concerns with the ability to upvote those concerns using React, and right now, I am working on the upvote functionality.  One way I'm trying to limit the currently logged in user to a single vote is to disable the button once an upvote has been successfully registered for any given post.

To do this, I created a function that checks if the logged in user's ID matches the ID of the upvote for each post.  If no match is found, this means the user hasn't voted for already and can register the new upvote.  Once this is complete, the button is disabled.  I created state for this and is set to false upon the initial render (not sure if this is what I should be doing).  I also created state for the all of the votes that have been successfully registered.  Both are included below.

```<code>const [alreadyVoted, setAlreadyVoted] = useState(false);
const [userVotes, setUserVotes] = useState(upvotes) // upvotes is being passed via props
</code>```

I'm using the useEffect hook (again, not sure if this is the best way) to check if each button should be enabled or disabled like so:

```<code>useEffect(() => {
  hasVoted()
}, [userVotes])
</code>```

Finally, my hasVoted function checks to see if the user has already voted for the issue before and determines the state.  It looks like:

```<code>function hasVoted() {
  userVotes.forEach(vote => {
    if (vote.issue_id === issue.id) {  // issue here is from props
      setAlreadyVoted(true) // I want this to then disable my button
    }
  })
}
</code>```

Right now, when I click the button to register the upvote, the page doesn't rerender upon clicking.  However, if I refresh the page, the button is successfully disabled as it should be.  It probably goes without saying, I'm still getting the hang of React, but any and all help is appreciated.

答:
I think hasVoted function should be in the useEffect scope. If it's outside, it might introduce bugs, as documented here: https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies

You could try if this helps to resolve your problem

Body:
I'm building an application that allows for posting community concerns with the ability to upvote those concerns using React, and right now, I am working on the upvote functionality.  One way I'm trying to limit the currently logged in user to a single vote is to disable the button once an upvote has been successfully registered for any given post.

To do this, I created a function that checks if the logged in user's ID matches the ID of the upvote for each post.  If no match is found, this means the user hasn't voted for already and can register the new upvote.  Once this is complete, the button is disabled.  I created state for this and is set to false upon the initial render (not sure if this is what I should be doing).  I also created state for the all of the votes that have been successfully registered.  Both are included below.

const [alreadyVoted, setAlreadyVoted] = useState(false);
const [userVotes, setUserVotes] = useState(upvotes) // upvotes is being passed via props

I'm using the useEffect hook (again, not sure if this is the best way) to check if each button should be enabled or disabled like so:

useEffect(() => {
  hasVoted()
}, [userVotes])

Finally, my hasVoted function checks to see if the user has already voted for the issue before and determines the state.  It looks like:

function hasVoted() {
  userVotes.forEach(vote => {
    if (vote.issue_id === issue.id) {  // issue here is from props
      setAlreadyVoted(true) // I want this to then disable my button
    }
  })
}

Right now, when I click the button to register the upvote, the page doesn't rerender upon clicking.  However, if I refresh the page, the button is successfully disabled as it should be.  It probably goes without saying, I'm still getting the hang of React, but any and all help is appreciated.


问:
elastic DSL query result from another query
can anyone help me to translate below SQL query to ELasticSearch DSL form for document selections?

SELECT * FROM table1 WHERE source_id IN (select source_id FROM table2)
```

答:
This JOIN semantics does not translate to Elasticsearch. If your index had parent/child mapping - you might be able to achieve what you want to do. Another option is to do a two-pass query.

This blog post gives an idea of how relations are modeled in Elasticsearch - Managing Relations in Elasticsearch


问:
How to filter out the array with lowest date value using SQL query
Ive run a query which results in an array of objects, i tried to filter out the objects in the array based on the lowest date value but i'm not able to get the required output. I tried to use min(tb2.date as Date) in the query to filter out based on lowest date with respects of each 'title', but it returns only one object with lowest date value.

The query I've used is :

```<code>SELECT
tb2.date as Date,
tb1.title as title,
tb1.descp as descp

FROM
table1 tb1
LEFT JOIN table2  tb2 ON ( tb2.id = tb1.id )

WHERE
tb1.id = x

ORDER BY
tb1.date,
tb1.status ASC
</code>```

The output i got is :

```<code>Array(
        [0] => Array
            (
                [Date] => 2020-05-05
                 [title] => new test
                [descp] => req changes
            )

        [1] => Array
            (
                [Date] => 2020-05-06
                [title] => new test
                 [descp] => req changes
            )

        [2] => Array
            (
                [Date] => 2020-05-08
                 [title] => Project
               [descp] => asdasdasda
            )

        [3] => Array
            (
                [Date] => 2020-05-18
                [title] => Project
                [descp] => asdasdasda
            )
)
</code>```

The output I required is :

```<code> [0] => Array
            (
                [Date] => 2020-05-05
                 [title] => new test
                [descp] => req changes
            )
[1] => Array
            (
                [Date] => 2020-05-08
                 [title] => Project
               [descp] => asdasdasda
            )
</code>```

答:
Test

SELECT MIN(tb2.date) AS `date`,
       tb1.title,
       tb1.`desc`
FROM table1 tb1
LEFT JOIN table2 tb2 USING ( id )
WHERE tb1.id = x     -- ??? transferred from the question text as-is
GROUP BY tb1.title, tb1.`desc`
ORDER BY `date`
```

Body:
Ive run a query which results in an array of objects, i tried to filter out the objects in the array based on the lowest date value but i'm not able to get the required output. I tried to use min(tb2.date as Date) in the query to filter out based on lowest date with respects of each 'title', but it returns only one object with lowest date value.

The query I've used is :

SELECT
tb2.date as Date,
tb1.title as title,
tb1.descp as descp

FROM
table1 tb1
LEFT JOIN table2  tb2 ON ( tb2.id = tb1.id )

WHERE
tb1.id = x

ORDER BY
tb1.date,
tb1.status ASC

The output i got is :

Array(
        [0] => Array
            (
                [Date] => 2020-05-05
                 [title] => new test
                [descp] => req changes
            )

        [1] => Array
            (
                [Date] => 2020-05-06
                [title] => new test
                 [descp] => req changes
            )

        [2] => Array
            (
                [Date] => 2020-05-08
                 [title] => Project
               [descp] => asdasdasda
            )

        [3] => Array
            (
                [Date] => 2020-05-18
                [title] => Project
                [descp] => asdasdasda
            )
)

The output I required is :

 [0] => Array
            (
                [Date] => 2020-05-05
                 [title] => new test
                [descp] => req changes
            )
[1] => Array
            (
                [Date] => 2020-05-08
                 [title] => Project
               [descp] => asdasdasda
            )


问:
How can we call println without it being called on an object in Scala and how does it have side effects?
How is it possible to call print() or println() without having the object on the left side? Also how are these two methods having a side effect? How would one determine if there is a side effect or not? All they do is give output to the console and not change anything from my understanding. </p>

答:
println() is defined in Predef.scala

The Predef object provides definitions that are accessible in all
  Scala compilation units without explicit qualification.

https://www.scala-lang.org/api/current/scala/Predef$.html

To check for side effect, you'll have to see what is actually being passed to println(). Demo in the below snippet:

```<code>object Test extends App {
  var x = 10
  def hello(): String = "hello"

  def helloWithSideEffect(): String = {
    x = 11
    "hello again"
  }

  println(x)
  println(hello())
  println(x)
  println(helloWithSideEffect())
  println(x)
}
</code>```

Result

```<code>10
hello
10
hello again
11
</code>```

Body:
println() is defined in Predef.scala

The Predef object provides definitions that are accessible in all
  Scala compilation units without explicit qualification.

https://www.scala-lang.org/api/current/scala/Predef$.html

To check for side effect, you'll have to see what is actually being passed to println(). Demo in the below snippet:

object Test extends App {
  var x = 10
  def hello(): String = "hello"

  def helloWithSideEffect(): String = {
    x = 11
    "hello again"
  }

  println(x)
  println(hello())
  println(x)
  println(helloWithSideEffect())
  println(x)
}

Result

10
hello
10
hello again
11


问:
Result of function vs loop
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

```<code>input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715
</code>```

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

```<code>for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773
</code>```

答:
The first script only provides one value because you have a return in the loop — the loop doesn’t continue after that.

There are two typical ways to handle this situation. The first is to create an empty array before your loop, add each result to the array during the loop, and return that results array after the loop. That approach is ok if the number of values / loops is small, i.e. you don’t want to build up a 10,000,000 element array.

If the number of values / loops is bigger, or if your outer function may not need all the values, use a yield in place of your return. That allows the called function to generate each value as needed when called from an outer loop.

Title: Result of function vs loop

Body:
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773


问:
Getting a json from an api with fetch js
I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:

```<code>function get(){
      fetch('http://localhost:8082/marca/listar', {
            method: 'GET',
            headers: {},
            mode: 'no-cors', // <---
            cache: 'default'
        })
        .then(Response => { return Response.json() })
        .then(data => {
            console.log(data.nombre)
        });

}
</code>```

This is the url of the api

And I get the following error:

console message image

答:
it is because the response you get from the server is an array not JSON object
so treat it as such </p>

Body:
I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:

function get(){
      fetch('http://localhost:8082/marca/listar', {
            method: 'GET',
            headers: {},
            mode: 'no-cors', // <---
            cache: 'default'
        })
        .then(Response => { return Response.json() })
        .then(data => {
            console.log(data.nombre)
        });

}

This is the url of the api

And I get the following error:

console message image