问:
C++ Lua userdata messing with Mathfu float values
I'm trying to use Mathfu::Vector from Lua to create vectors but I've got an issue when I try to retrieve the user data back from the stack.

here is the function I use to define the user data

static int vec4(lua_State *L)
{
  const float x = luaL_checknumber(L, 1);
  const float y = luaL_checknumber(L, 2);
  const float z = luaL_checknumber(L, 3);
  const float w = luaL_checknumber(L, 4);

  mathfu::Vector<float, 4> vec(x, y, z, w);
  *static_cast<mathfu::Vector<float, 4> **>(
      lua_newuserdata(L, sizeof(mathfu::Vector<float, 4> *))) = &vec;
  luaL_setmetatable(L, VECTOR_LIB_NAME);

  return 1;
}
```

<p>And I have a function that gets the dot product of two vectors based on a <code>self</code> value and an argument (both userdata)</p>

<pre class="lang-cpp prettyprint-override"><code>static int dotVector(lua_State *L)
{
  mathfu::Vector<float, 4> *vecA = *static_cast<mathfu::Vector<float, 4> **>(luaL_checkudata(L, 1, VECTOR_LIB_NAME));
  mathfu::Vector<float, 4> *vecB = *static_cast<mathfu::Vector<float, 4> **>(luaL_checkudata(L, 2, VECTOR_LIB_NAME));

  LOGI("A: %f, %f, %f", vecA->x, vecA->y, vecA->z);
  LOGI("B: %f, %f, %f", vecB->x, vecB->y, vecB->z);
  float dot = mathfu::Vector<float, 4>::DotProduct(*vecA, *vecB);
  lua_pushnumber(L, dot);

  return 1;
};
</code>```

called from lua like

local vecA = vec4(1, 2, 3, 4)
local vecB = vec4(5, 6, 7, 8)
vecA:dot(vecB)
```

<p>But the values that get printed are crazy like it's converting bad data to a float</p>

```A: -8055257885499399810754615288266752.000000, 0.000000, 0.000000
B: 0.000000, 3746318080.000000, 3573.204346
```

I've examined the stack and the first two elements are definitely UserData but I don't seem to be able to dig any deeper into the user data. The vars in C++ contain those values but I'm at a loss as to what might be causing this. Pretty sure the userdata isn't what I expect it to be where I expect it to be.

答:
No, you did memory leak. 1st version was pointer to stack allocated object (&vec) which is gets destroyed once function ends.
2nd version (new mathfu::Vector) creates properly on heap ... and i guess u never delete it later = memory leak.

Also try avoid static_cast of pointers. Or any forced cast. That will add problems, for example if g++ will use "strict-aliasing" (implicit by -O3) then any pointers casts will be broken. "strict-aliasing" assumes 1 memory block is never pointed by different type pointers. Or you should explicit configure compiler to stay away from that.
General good idea is to use memcpy. Compilers understand & optimize it properly. For example if you want pointer as char to int32:

```<code>int32 a;
char b[sizeof(a)];
memcpy(b, &a, sizeof(a));
</code>```

and use b now instead

```<code>static_cast<char*>(&a);
</code>```

Body:
I'm trying to use Mathfu::Vector from Lua to create vectors but I've got an issue when I try to retrieve the user data back from the stack.

here is the function I use to define the user data

static int vec4(lua_State *L)
{
  const float x = luaL_checknumber(L, 1);
  const float y = luaL_checknumber(L, 2);
  const float z = luaL_checknumber(L, 3);
  const float w = luaL_checknumber(L, 4);

  mathfu::Vector<float, 4> vec(x, y, z, w);
  *static_cast<mathfu::Vector<float, 4> **>(
      lua_newuserdata(L, sizeof(mathfu::Vector<float, 4> *))) = &vec;
  luaL_setmetatable(L, VECTOR_LIB_NAME);

  return 1;
}

And I have a function that gets the dot product of two vectors based on a self value and an argument (both userdata)

static int dotVector(lua_State *L)
{
  mathfu::Vector<float, 4> *vecA = *static_cast<mathfu::Vector<float, 4> **>(luaL_checkudata(L, 1, VECTOR_LIB_NAME));
  mathfu::Vector<float, 4> *vecB = *static_cast<mathfu::Vector<float, 4> **>(luaL_checkudata(L, 2, VECTOR_LIB_NAME));

  LOGI("A: %f, %f, %f", vecA->x, vecA->y, vecA->z);
  LOGI("B: %f, %f, %f", vecB->x, vecB->y, vecB->z);
  float dot = mathfu::Vector<float, 4>::DotProduct(*vecA, *vecB);
  lua_pushnumber(L, dot);

  return 1;
};

called from lua like

local vecA = vec4(1, 2, 3, 4)
local vecB = vec4(5, 6, 7, 8)
vecA:dot(vecB)

But the values that get printed are crazy like it's converting bad data to a float

A: -8055257885499399810754615288266752.000000, 0.000000, 0.000000
B: 0.000000, 3746318080.000000, 3573.204346

I've examined the stack and the first two elements are definitely UserData but I don't seem to be able to dig any deeper into the user data. The vars in C++ contain those values but I'm at a loss as to what might be causing this. Pretty sure the userdata isn't what I expect it to be where I expect it to be.

Body:
No, you did memory leak. 1st version was pointer to stack allocated object (&vec) which is gets destroyed once function ends.
2nd version (new mathfu::Vector) creates properly on heap ... and i guess u never delete it later = memory leak.

Also try avoid static_cast of pointers. Or any forced cast. That will add problems, for example if g++ will use "strict-aliasing" (implicit by -O3) then any pointers casts will be broken. "strict-aliasing" assumes 1 memory block is never pointed by different type pointers. Or you should explicit configure compiler to stay away from that.
General good idea is to use memcpy. Compilers understand & optimize it properly. For example if you want pointer as char to int32:

int32 a;
char b[sizeof(a)];
memcpy(b, &a, sizeof(a));

and use b now instead

static_cast<char*>(&a);


来源: stackexchange

问:
Filter with terniary operator
I have a method

```<code>AddOrUpdateList(this List<T> list, T scope, Func<T, bool>, Func<T, bool> when = null){
    T item = default;
    if (when == null)
        list.SingleOrDefault(t => t.Equals(scope)); //Check Single
    else
        item = list.SingleOrDefault(when);
    .
    .
    .
}
</code>```

When I'm going to use it I have two possible starts:

I receive an element which element.Title is something, so I use the Title as filter

I receive an element which has no title, so I need to get the last one from a List

I was thinking to use terniary operator and lambda to create a filter that contemplates both cases.

What I came up with is:

```<code>var filter = (element.Title != "")
   ? (Func<T, bool>)(e => e.Title == element.Title)
   : (Func<T, bool>)(e = list.Select(ele => ele).Last());
</code>```

But that gives me: Error CS0030  Cannot convert type 'T' to 'System.Func<T, bool>'

Any idea or help you can give me??

Im pretty new to C# and Linq so I don't understand to well how some things should work

Thanks in advance.

答:
What type of element? So, AddOrUpdateList(Func<T, bool>) uses T as type of some generic code. When you have concrete element, you should know what type of code. And set a concrete class name.

If you show more code, I will try to help you.

May be I сlimbing out of business, but it seems strange. Acording to method name, you want to Add element if it is not exist or update it if it already in list.

So, here is an example of typicaly such method implementation.

```<code>public void AddOrUpdate<T, K>(this List<T> list, T element, Func<T, K> keySelector, Action<T, T> mapFunction) : T new()
{
    var elementKey = keySelector(element);
    var elementForUpdate = list.FirstOrDefault(x => keySelector(x) == elementKey);

    var exists = elementForUpdate != null;

    if (!exists)
    {
        var newElement = new T();
        list.Add(newElement);
        elementForUpdate = list.Last();
    }

    mapFunction(elementForUpdate, element);
}
</code>```

So, then in other part of code you can use it like:

```<code>...
var itemToAdd = new ClassWithTitle { Title = "Title 1"};
list.AddOrUpdate(itemToAdd , x => x.Title, (destination, origin) =>
{
    //Logic to map fields
    destination.Title = origin.Title;
    destination.SomeOtherField = origin.SomeOtherField;
})
...
</code>```

Please, pay attention.

One more option, if you work with list (not with database), you can use method IndexOf() then this method will very simple.

```<code>public void AddOrUpdate<T, K>(this List<T> list, T element, Func<T, K> keySelector)
{
    var elementKey = keySelector(element);
    var elementFounded = list.FirstOrDefault(x => keySelector(x) == elementKey);

    var exists = elementForUpdate != null;

    if (!exists)
    {
        //IMPORTANT: Here you add element that sended to method. You should take it into consideration.
        //If you want to add a clone of this object, implement interface IClonable and use this method like   list.Add(element.Clone());
        list.Add(element);
        return;
    }

    var indexOfFoundedElement = list.IndexOf(elementFounded);

     //IMPORTANT: Here you replace element that sended to method. You should take it into consideration.
    list[indexOfFoundedElement] = element;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Filter with terniary operator

Body:
I have a method

AddOrUpdateList(this List<T> list, T scope, Func<T, bool>, Func<T, bool> when = null){
    T item = default;
    if (when == null)
        list.SingleOrDefault(t => t.Equals(scope)); //Check Single
    else
        item = list.SingleOrDefault(when);
    .
    .
    .
}

When I'm going to use it I have two possible starts:

I receive an element which element.Title is something, so I use the Title as filter

I receive an element which has no title, so I need to get the last one from a List

I was thinking to use terniary operator and lambda to create a filter that contemplates both cases.

What I came up with is:

var filter = (element.Title != "")
   ? (Func<T, bool>)(e => e.Title == element.Title)
   : (Func<T, bool>)(e = list.Select(ele => ele).Last());

But that gives me: Error CS0030  Cannot convert type 'T' to 'System.Func<T, bool>'

Any idea or help you can give me??

Im pretty new to C# and Linq so I don't understand to well how some things should work

Thanks in advance.

Body:
What type of element? So, AddOrUpdateList(Func<T, bool>) uses T as type of some generic code. When you have concrete element, you should know what type of code. And set a concrete class name.

If you show more code, I will try to help you.

May be I сlimbing out of business, but it seems strange. Acording to method name, you want to Add element if it is not exist or update it if it already in list.

So, here is an example of typicaly such method implementation.

public void AddOrUpdate<T, K>(this List<T> list, T element, Func<T, K> keySelector, Action<T, T> mapFunction) : T new()
{
    var elementKey = keySelector(element);
    var elementForUpdate = list.FirstOrDefault(x => keySelector(x) == elementKey);

    var exists = elementForUpdate != null;

    if (!exists)
    {
        var newElement = new T();
        list.Add(newElement);
        elementForUpdate = list.Last();
    }

    mapFunction(elementForUpdate, element);
}

So, then in other part of code you can use it like:

...
var itemToAdd = new ClassWithTitle { Title = "Title 1"};
list.AddOrUpdate(itemToAdd , x => x.Title, (destination, origin) =>
{
    //Logic to map fields
    destination.Title = origin.Title;
    destination.SomeOtherField = origin.SomeOtherField;
})
...

Please, pay attention.

One more option, if you work with list (not with database), you can use method IndexOf() then this method will very simple.

public void AddOrUpdate<T, K>(this List<T> list, T element, Func<T, K> keySelector)
{
    var elementKey = keySelector(element);
    var elementFounded = list.FirstOrDefault(x => keySelector(x) == elementKey);

    var exists = elementForUpdate != null;

    if (!exists)
    {
        //IMPORTANT: Here you add element that sended to method. You should take it into consideration.
        //If you want to add a clone of this object, implement interface IClonable and use this method like   list.Add(element.Clone());
        list.Add(element);
        return;
    }

    var indexOfFoundedElement = list.IndexOf(elementFounded);

     //IMPORTANT: Here you replace element that sended to method. You should take it into consideration.
    list[indexOfFoundedElement] = element;
}


答:
If you just want to output the rows that have 3 consecutive days with a sum >= 150, you can use an analytic function to determine the moving total across each 3 day period per id, and then find the aggregate max value of the moving total per id, returning the id where it's >= 150.

E.g.:

```<code>WITH your_table AS (SELECT 1 ID, to_date('01/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 1 ID, to_date('02/01/2020', 'dd/mm/yyyy') dy, 50 total FROM dual UNION ALL
                    SELECT 1 ID, to_date('03/01/2020', 'dd/mm/yyyy') dy, 50 total FROM dual UNION ALL
                    SELECT 1 ID, to_date('04/01/2020', 'dd/mm/yyyy') dy, 50 total FROM dual UNION ALL
                    SELECT 1 ID, to_date('05/01/2020', 'dd/mm/yyyy') dy, 20 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('01/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('02/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('03/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('04/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('05/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual),
    moving_sums AS (SELECT ID,
                           dy,
                           total,
                           SUM(total) OVER (PARTITION BY ID ORDER BY dy RANGE BETWEEN 2 PRECEDING AND CURRENT ROW) moving_sum
                    FROM   your_table)
SELECT ID
FROM   moving_sums
GROUP BY ID
HAVING MAX(moving_sum) >= 150;

        ID
----------
         1
</code>```

Title: With Oracle SQL how can I find 3 days where total sum >= 150

Body:
I have a report that needs to list activity where total is >= 150 over 3 consecutive days.

Let's say I've created a temp table foo, to summarize daily totals.

| ID | Day        | Total |
| -- | ---------- | ----- |
| 01 | 2020-01-01 |   10  |
| 01 | 2020-01-02 |   50  |
| 01 | 2020-01-03 |   50  |
| 01 | 2020-01-04 |   50  |
| 01 | 2020-01-05 |   20  |
| 02 | 2020-01-01 |   10  |
| 02 | 2020-01-02 |   10  |
| 02 | 2020-01-03 |   10  |
| 02 | 2020-01-04 |   10  |
| 02 | 2020-01-05 |   10  |

How Would I write SQL to return ID 01, but not 02?

Example Result:

| ID |
| -- |
| 01 |

Body:
If you just want to output the rows that have 3 consecutive days with a sum >= 150, you can use an analytic function to determine the moving total across each 3 day period per id, and then find the aggregate max value of the moving total per id, returning the id where it's >= 150.

E.g.:

WITH your_table AS (SELECT 1 ID, to_date('01/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 1 ID, to_date('02/01/2020', 'dd/mm/yyyy') dy, 50 total FROM dual UNION ALL
                    SELECT 1 ID, to_date('03/01/2020', 'dd/mm/yyyy') dy, 50 total FROM dual UNION ALL
                    SELECT 1 ID, to_date('04/01/2020', 'dd/mm/yyyy') dy, 50 total FROM dual UNION ALL
                    SELECT 1 ID, to_date('05/01/2020', 'dd/mm/yyyy') dy, 20 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('01/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('02/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('03/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('04/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual UNION ALL
                    SELECT 2 ID, to_date('05/01/2020', 'dd/mm/yyyy') dy, 10 total FROM dual),
    moving_sums AS (SELECT ID,
                           dy,
                           total,
                           SUM(total) OVER (PARTITION BY ID ORDER BY dy RANGE BETWEEN 2 PRECEDING AND CURRENT ROW) moving_sum
                    FROM   your_table)
SELECT ID
FROM   moving_sums
GROUP BY ID
HAVING MAX(moving_sum) >= 150;

        ID
----------
         1


问:
How to get the top row in C# of a stored procedure?
I just need the top row, the stored procedure uses TOP 1, but I would like to have it in the C# to future proof this app a little.</p>

```<code>        protected void Load()
        {
            using (SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["Connection"]))
            using (SqlCommand com = new SqlCommand("StoredProcedure", objConn))
            {
                objConn.Open();
                com.CommandType = CommandType.StoredProcedure;

                using (SqlDataReader dr = com.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        txtLabel.Text = dr["label"].ToString();
                        txtLabel.Text = dr["label"].ToString();
                        txtLabel.Text = dr["label"].ToString();
                    }
                }
            }
        }
</code>```

答:
Get rid of the loop while(dr.Read()):

```<code>    protected void Load()
    {
        using (SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["Connection"]))
        using (SqlCommand com = new SqlCommand("StoredProcedure", objConn))
        {
            objConn.Open();
            com.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader dr = com.ExecuteReader())
            {
                if(dr.HasRows && dr.Read()) // <----- This is the change
                {
                    txtLabel.Text = dr["label"].ToString();
                    txtLabel.Text = dr["label"].ToString();
                    txtLabel.Text = dr["label"].ToString();
                }
            }
        }
    }
</code>```

Body:
I just need the top row, the stored procedure uses TOP 1, but I would like to have it in the C# to future proof this app a little.

        protected void Load()
        {
            using (SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["Connection"]))
            using (SqlCommand com = new SqlCommand("StoredProcedure", objConn))
            {
                objConn.Open();
                com.CommandType = CommandType.StoredProcedure;

                using (SqlDataReader dr = com.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        txtLabel.Text = dr["label"].ToString();
                        txtLabel.Text = dr["label"].ToString();
                        txtLabel.Text = dr["label"].ToString();
                    }
                }
            }
        }

Body:
Get rid of the loop while(dr.Read()):

    protected void Load()
    {
        using (SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["Connection"]))
        using (SqlCommand com = new SqlCommand("StoredProcedure", objConn))
        {
            objConn.Open();
            com.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader dr = com.ExecuteReader())
            {
                if(dr.HasRows && dr.Read()) // <----- This is the change
                {
                    txtLabel.Text = dr["label"].ToString();
                    txtLabel.Text = dr["label"].ToString();
                    txtLabel.Text = dr["label"].ToString();
                }
            }
        }
    }


问:
How to append some object arrays in C#?

Possible Duplicate:

  How do I concatenate two arrays in C#?

How do I append some object arrays into one big object array?

For example, I have 3 elements of type: object[] and want to make one of it. How to do this?

答:
Use this:

```<code>object[] element1 = ...;
object[] element2 = ...;
object[] element3 = ...;
var list = new List<object>();
list.AddRange(element1);
list.AddRange(element2);
list.AddRange(element3);
var result = list.ToArray();
</code>```

An alternative would be:

```<code>var result = element1.Concat(element2).Concat(element3).ToArray();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to append some object arrays in C#?

Body:
Use this:

object[] element1 = ...;
object[] element2 = ...;
object[] element3 = ...;
var list = new List<object>();
list.AddRange(element1);
list.AddRange(element2);
list.AddRange(element3);
var result = list.ToArray();

An alternative would be:

var result = element1.Concat(element2).Concat(element3).ToArray();


问:
Extract seasons from datetime pandas
I am trying to extract the seasons from a large dataframe with a date time column. This is the code I have used:

```<code>def season_of_date(date_UTC):
    year = str(date_UTC.year)
    seasons = {'spring': pd.date_range(start= year +'-03-21 00:00:00', end=year + '-06-20 00:00:00'),
               'summer': pd.date_range(start= year + '-06-21 00:00:00', end= year + '-09-22 00:00:00'),
               'autumn': pd.date_range(start= year + '-09-23 00:00:00', end= year + '-12-20 00:00:00')}
    if date_UTC in seasons['spring']:
        return 'spring'
    if date_UTC in seasons['summer']:
        return 'summer'
    if date_UTC in seasons['autumn']:
        return 'autumn'
    else:
        return 'winter'

df['season'] = df.date_UTC.map(season_of_date)

</code>```

The issue lies in the fact that I dont know how to handle the hours minutes and seconds in my datetime column, so I end up with a result that is mostly winter, apart from datetime entries when the time is 00:00:00:

```<code>date_UTC    season
616602  2019-11-24 17:00:00 winter
792460  2019-06-18 13:00:00 winter
230088  2019-11-30 07:00:00 winter
560826  2019-05-20 08:00:00 winter
718547  2019-03-23 04:00:00 winter
241890  2020-01-11 03:00:00 winter
513845  2018-12-23 22:00:00 winter
665954  2019-03-18 00:00:00 winter
474988  2019-05-20 08:00:00 winter
120281  2019-04-22 12:00:00 winter
697519  2018-10-12 05:00:00 winter
669144  2019-09-10 11:00:00 winter
310637  2019-11-03 04:00:00 winter
127973  2018-12-01 10:00:00 winter
325177  2019-03-16 11:00:00 winter
785162  2019-05-07 21:00:00 winter
840131  2018-11-24 00:00:00 autumn
580472  2020-01-10 19:00:00 winter
635219  2019-12-16 23:00:00 winter
799642  2019-11-11 18:00:00 winter

</code>```

Can I have some advice on how to modify my code so that the seasons map correctly?

UPDATE:

I modified the code to create a string for the timestamp element and thought this would fix the issue but it didnt.. After making the modification like so I end up with this error:

```<code>def season_of_date(date_UTC):
    year = str(date_UTC.year)
    time = str(date_UTC.time)
    seasons = {'spring': pd.date_range(start= year +'-03-21' + time, end=year + '-06-20' + time),
               'summer': pd.date_range(start= year + '-06-21' + time, end= year + '-09-22' + time),
               'autumn': pd.date_range(start= year + '-09-23' + time, end= year + '-12-20' + time)}
    if date_UTC in seasons['spring']:
        return 'spring'
    if date_UTC in seasons['summer']:
        return 'summer'
    if date_UTC in seasons['autumn']:
        return 'autumn'
    else:
        return 'winter'

df['season'] = df.date_UTC.map(season_of_date)
</code>```

```<code>ValueError: could not convert string to Timestamp
</code>```

SECOND UPDATE:

What I ended up doing was the following, it is fast but I don't like the solution since it wrongly groups whole months into seasons, when actually for a given year a season may start mid way through a month.

```<code>df['season'] = (df['date_UTC'].dt.month%12 + 3)//3

seasons = {
             1: 'Winter',
             2: 'Spring',
             3: 'Summer',
             4: 'Autumn'
}

df['season_name'] = df['season'].map(seasons)
</code>```

答:
first you want your date_UTC in datetime format, second, you can use pd.cut:

```<code>date = df.date_UTC.dt.month*100 + df.date_UTC.dt.day
df['season'] = (pd.cut(date,[0,321,620,922,1220,1300],
                       labels=['winter','spring','summer','autumn','winter '])
                  .str.strip()
               )
</code>```

With a little numeric trick, you can get rid of the slow str.strip() :

```<code>df['date_offset'] = (df.date_UTC.dt.month*100 + df.date_UTC.dt.day - 320)%1300

df['season'] = pd.cut(df['date_offset'], [0, 300, 602, 900, 1300],
                      labels=['spring', 'summer', 'autumn', 'winter'])
</code>```

Title: Extract seasons from datetime pandas

Body:
I am trying to extract the seasons from a large dataframe with a date time column. This is the code I have used:

def season_of_date(date_UTC):
    year = str(date_UTC.year)
    seasons = {'spring': pd.date_range(start= year +'-03-21 00:00:00', end=year + '-06-20 00:00:00'),
               'summer': pd.date_range(start= year + '-06-21 00:00:00', end= year + '-09-22 00:00:00'),
               'autumn': pd.date_range(start= year + '-09-23 00:00:00', end= year + '-12-20 00:00:00')}
    if date_UTC in seasons['spring']:
        return 'spring'
    if date_UTC in seasons['summer']:
        return 'summer'
    if date_UTC in seasons['autumn']:
        return 'autumn'
    else:
        return 'winter'

df['season'] = df.date_UTC.map(season_of_date)

The issue lies in the fact that I dont know how to handle the hours minutes and seconds in my datetime column, so I end up with a result that is mostly winter, apart from datetime entries when the time is 00:00:00:

date_UTC    season
616602  2019-11-24 17:00:00 winter
792460  2019-06-18 13:00:00 winter
230088  2019-11-30 07:00:00 winter
560826  2019-05-20 08:00:00 winter
718547  2019-03-23 04:00:00 winter
241890  2020-01-11 03:00:00 winter
513845  2018-12-23 22:00:00 winter
665954  2019-03-18 00:00:00 winter
474988  2019-05-20 08:00:00 winter
120281  2019-04-22 12:00:00 winter
697519  2018-10-12 05:00:00 winter
669144  2019-09-10 11:00:00 winter
310637  2019-11-03 04:00:00 winter
127973  2018-12-01 10:00:00 winter
325177  2019-03-16 11:00:00 winter
785162  2019-05-07 21:00:00 winter
840131  2018-11-24 00:00:00 autumn
580472  2020-01-10 19:00:00 winter
635219  2019-12-16 23:00:00 winter
799642  2019-11-11 18:00:00 winter

Can I have some advice on how to modify my code so that the seasons map correctly?

UPDATE:

I modified the code to create a string for the timestamp element and thought this would fix the issue but it didnt.. After making the modification like so I end up with this error:

def season_of_date(date_UTC):
    year = str(date_UTC.year)
    time = str(date_UTC.time)
    seasons = {'spring': pd.date_range(start= year +'-03-21' + time, end=year + '-06-20' + time),
               'summer': pd.date_range(start= year + '-06-21' + time, end= year + '-09-22' + time),
               'autumn': pd.date_range(start= year + '-09-23' + time, end= year + '-12-20' + time)}
    if date_UTC in seasons['spring']:
        return 'spring'
    if date_UTC in seasons['summer']:
        return 'summer'
    if date_UTC in seasons['autumn']:
        return 'autumn'
    else:
        return 'winter'

df['season'] = df.date_UTC.map(season_of_date)

ValueError: could not convert string to Timestamp

SECOND UPDATE:

What I ended up doing was the following, it is fast but I don't like the solution since it wrongly groups whole months into seasons, when actually for a given year a season may start mid way through a month.

df['season'] = (df['date_UTC'].dt.month%12 + 3)//3

seasons = {
             1: 'Winter',
             2: 'Spring',
             3: 'Summer',
             4: 'Autumn'
}

df['season_name'] = df['season'].map(seasons)

Body:
first you want your date_UTC in datetime format, second, you can use pd.cut:

date = df.date_UTC.dt.month*100 + df.date_UTC.dt.day
df['season'] = (pd.cut(date,[0,321,620,922,1220,1300],
                       labels=['winter','spring','summer','autumn','winter '])
                  .str.strip()
               )

With a little numeric trick, you can get rid of the slow str.strip() :

df['date_offset'] = (df.date_UTC.dt.month*100 + df.date_UTC.dt.day - 320)%1300

df['season'] = pd.cut(df['date_offset'], [0, 300, 602, 900, 1300],
                      labels=['spring', 'summer', 'autumn', 'winter'])


问:
python IndexError: string index out of range when i try to get single characters from a string
I'am trying to make a simple socket server in python that is able to serve multiple files but I get this error:

```<code>Traceback (most recent call last):
  File "webserver.py", line 43, in <module>
    if b[x] == "G":
IndexError: string index out of range
</code>```

I don't get what the problem is as the character I'm trying to get is perfectly in range and has left me completely confused. The specific part that has the error in it is supposed to get the desired file from the request.
My code:

```<code>import sys;
import socket;

port = 80
host = socket.gethostbyname("localhost")
file = ""
file_ready = 0
x = 0
y = 0

#Create socket
print("# Creating socket")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Bind port & host
print("# Binding to port " + str(port))
try:
    s.bind((host, port))
except socket.gaierror:
    print("# An error occured whilst binding the port\nerrorno. " + socket.errno)

#Main loop
while 1:
    #Listen for request
    print("# Now listening for incoming requests")
    s.listen(5)

    #Accept request
    conn, addr = s.accept()
    print(("# Connected with " + addr[0]))

    #Receive data from client as "b"
    b = conn.recv(1024)
    print("# Received data")

    #Decode "b", encoding = "utf-8"
    b = b.decode("utf-8")
    print("# Data decoded")

    #Request processing
    print("# Processing request")
    while 1:
        if b[x] == "G":
            x = x + 1
            if b[x] == "E":
                x = x + 1
                if b[x] == "T":
                    x = x + 1
                    if b[x] == " ":
                        x = x + 1
                        if b[x] == "/":
                            x = x + 1
                            while 1:
                                if b[x] == "/":
                                    file_ready = file_ready + 1
                                    break
                                else:
                                    file[y] = b[x]
                                    x = x + 1
                                    y = y + 1
                            if file_ready == 1:
                                print("# Request processed")
                                break
                            else:
                                pass
                        else:
                            x = x + 1
                    else:
                        x = x + 1
                else:
                    x = x + 1
            else:
                x = x + 1
        else:
            x = x + 1

    #Prepare file to send to client
    print("# Preparing file")
    f = open(file, "r+")
    content = f.read()
    f.close()
    content_len = len(content)

    #Send data to the client
    conn.send('''
    HTTP/1.1 200 OK
    Server: Test
    Last-Modified: Tue, 18 Feb 2020 15:12:00 GMT
    Content-Length: ''' + content_len + '''
    Connection: close
    b\'''' + content + "'")
    print("# Data sent")
</code>```

答:
You aren't resetting x to zero between connections.

The first connection may work perfectly fine, but for subsequent connections, x is not in range.

That said, you may want to just use b.split() to parse that string – or better yet, since you're apparently implementing a rudimentary HTTP/1.0 server, use the built-in batteries for HTTP servers!

For the sake of exercise, though, here's an adaptation of your code that works for multiple subsequent connections:

```<code>import socket

def handle_request(conn):
    request = conn.recv(1024).decode("utf-8")
    bits = request.split()  # Split by any runs of whitespace (non-spec-compliant but works for now)
    verb = bits[0]
    if verb == "GET":
        filename = bits[1].lstrip("/")
    else:
        conn.sendall(b"HTTP/1.1 400 Error\r\n\r\nInvalid verb")
        return

    with open(filename, "rb") as f:  # Warning: this allows reading any file on your syste
        content = f.read()

    conn.sendall(b"HTTP/1.1 200 OK\r\n")
    conn.sendall(f"Content-length: {len(content)}\r\n".encode())
    conn.sendall(b"\r\n")
    conn.sendall(content)
    conn.close()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind(("localhost", 8081))
    s.listen(5)
    while 1:
        conn, addr = s.accept()
        print(("# Connected with " + addr[0]))
        try:
            handle_request(conn)
        finally:
            conn.close()
finally:
    s.close()
</code>```

Body:
I'am trying to make a simple socket server in python that is able to serve multiple files but I get this error:

Traceback (most recent call last):
  File "webserver.py", line 43, in <module>
    if b[x] == "G":
IndexError: string index out of range

I don't get what the problem is as the character I'm trying to get is perfectly in range and has left me completely confused. The specific part that has the error in it is supposed to get the desired file from the request.
My code:

import sys;
import socket;

port = 80
host = socket.gethostbyname("localhost")
file = ""
file_ready = 0
x = 0
y = 0

#Create socket
print("# Creating socket")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Bind port & host
print("# Binding to port " + str(port))
try:
    s.bind((host, port))
except socket.gaierror:
    print("# An error occured whilst binding the port\nerrorno. " + socket.errno)

#Main loop
while 1:
    #Listen for request
    print("# Now listening for incoming requests")
    s.listen(5)

    #Accept request
    conn, addr = s.accept()
    print(("# Connected with " + addr[0]))

    #Receive data from client as "b"
    b = conn.recv(1024)
    print("# Received data")

    #Decode "b", encoding = "utf-8"
    b = b.decode("utf-8")
    print("# Data decoded")

    #Request processing
    print("# Processing request")
    while 1:
        if b[x] == "G":
            x = x + 1
            if b[x] == "E":
                x = x + 1
                if b[x] == "T":
                    x = x + 1
                    if b[x] == " ":
                        x = x + 1
                        if b[x] == "/":
                            x = x + 1
                            while 1:
                                if b[x] == "/":
                                    file_ready = file_ready + 1
                                    break
                                else:
                                    file[y] = b[x]
                                    x = x + 1
                                    y = y + 1
                            if file_ready == 1:
                                print("# Request processed")
                                break
                            else:
                                pass
                        else:
                            x = x + 1
                    else:
                        x = x + 1
                else:
                    x = x + 1
            else:
                x = x + 1
        else:
            x = x + 1

    #Prepare file to send to client
    print("# Preparing file")
    f = open(file, "r+")
    content = f.read()
    f.close()
    content_len = len(content)

    #Send data to the client
    conn.send('''
    HTTP/1.1 200 OK
    Server: Test
    Last-Modified: Tue, 18 Feb 2020 15:12:00 GMT
    Content-Length: ''' + content_len + '''
    Connection: close
    b\'''' + content + "'")
    print("# Data sent")

Body:
You aren't resetting x to zero between connections.

The first connection may work perfectly fine, but for subsequent connections, x is not in range.

That said, you may want to just use b.split() to parse that string – or better yet, since you're apparently implementing a rudimentary HTTP/1.0 server, use the built-in batteries for HTTP servers!

For the sake of exercise, though, here's an adaptation of your code that works for multiple subsequent connections:

import socket

def handle_request(conn):
    request = conn.recv(1024).decode("utf-8")
    bits = request.split()  # Split by any runs of whitespace (non-spec-compliant but works for now)
    verb = bits[0]
    if verb == "GET":
        filename = bits[1].lstrip("/")
    else:
        conn.sendall(b"HTTP/1.1 400 Error\r\n\r\nInvalid verb")
        return

    with open(filename, "rb") as f:  # Warning: this allows reading any file on your syste
        content = f.read()

    conn.sendall(b"HTTP/1.1 200 OK\r\n")
    conn.sendall(f"Content-length: {len(content)}\r\n".encode())
    conn.sendall(b"\r\n")
    conn.sendall(content)
    conn.close()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind(("localhost", 8081))
    s.listen(5)
    while 1:
        conn, addr = s.accept()
        print(("# Connected with " + addr[0]))
        try:
            handle_request(conn)
        finally:
            conn.close()
finally:
    s.close()


问:
In a similar manner as SQL injection, is it possible to exploit text-entry fields?
For example, it would make sense that in a comment section on a website which does not prevent the processing of escape characters that an escape character followed by code could <em>"infiltrate"</em> the backend code. How do big websites prevent this and is it absolutely impossible? </p>

答:
It is not impossible.

Big websites and small websites prevent SQL injection exactly the same way:

Using query parameters.

This works for text fields as well as shorter strings, dates, numbers, etc.

Here's a hypothetical example in PHP, but similar examples exist for any other programming language.

```<code>$text = $_POST['textfield'];
$stmt = $pdo->prepare("INSERT INTO mytable (textcol) VALUES (?)");
$stmt->execute( [ $text ] );
</code>```

By keeping the content separate from the SQL query until execute(), this avoids a risk of SQL injection.

Body: For example, it would make sense that in a comment section on a website which does not prevent the processing of escape characters that an escape character followed by code could "infiltrate" the backend code. How do big websites prevent this and is it absolutely impossible?

Body:
It is not impossible.

Big websites and small websites prevent SQL injection exactly the same way:

Using query parameters.

This works for text fields as well as shorter strings, dates, numbers, etc.

Here's a hypothetical example in PHP, but similar examples exist for any other programming language.

$text = $_POST['textfield'];
$stmt = $pdo->prepare("INSERT INTO mytable (textcol) VALUES (?)");
$stmt->execute( [ $text ] );

By keeping the content separate from the SQL query until execute(), this avoids a risk of SQL injection.


问:
html can not display fist for-loop result, django
I'm new in django, I would like to display my view.py to index.html,

the view.py:

```<code>def index(request):
context_dict = {}

customers = Customer.objects.all()
carts = Cart.objects.select_related('customer')
goods = Good.objects.select_related('cart__customer')

context_dict['Cart']=carts
context_dict['Good']=goods
context_dict['Customer'] = customers

return render(request, 'index.html', context=context_dict)
</code>```

and the index.html for loop is like this:

```<code><ul>
            {% for customer in Customer %}
                <li>{{ customer.name }}</li>
                {% for cart in Cart %}
                    {% if customer.id == cart.id %}
                        {% for good in Good %}
                            {% if cart.id == good.id %}
                                {{good.name}}--{{good.count}}--{{good.price}}
                            {% endif %}
                        {% endfor %}
                    {% endif %}
                {% endfor %}
            {% endfor %}

        </ul>
</code>```

but the result displayed like this:

Bob should have water--2--50 under it.
it seems customer.id == cart.id cannot match.
but I don't know how to fix it.
please help, thanks a lot!

答:
customer.id should match card.customer_id and so on (cart.good_id == good.id)

if you have a single cart with a single good in it your solution will still return all of the customers, all of the goods to show a single line on the page - this is not really a good solution.

So try using joins and retrieve only needed data, e.g.:

```<code>actual_carts = Cart.objects.all().select_related('customer', 'good').order_by('customer_id', )
</code>```

This will return only customers and goods mentioned in carts. select_related will let you access all the needed info from customers as well as from goods.

Body:
I'm new in django, I would like to display my view.py to index.html,

the view.py:

def index(request):
context_dict = {}

customers = Customer.objects.all()
carts = Cart.objects.select_related('customer')
goods = Good.objects.select_related('cart__customer')

context_dict['Cart']=carts
context_dict['Good']=goods
context_dict['Customer'] = customers

return render(request, 'index.html', context=context_dict)

and the index.html for loop is like this:

            {% for customer in Customer %}

{{ customer.name }}

                {% for cart in Cart %}
                    {% if customer.id == cart.id %}
                        {% for good in Good %}
                            {% if cart.id == good.id %}
                                {{good.name}}--{{good.count}}--{{good.price}}
                            {% endif %}
                        {% endfor %}
                    {% endif %}
                {% endfor %}
            {% endfor %}

but the result displayed like this:

Bob should have water--2--50 under it.
it seems customer.id == cart.id cannot match.
but I don't know how to fix it.
please help, thanks a lot!

Body:
customer.id should match card.customer_id and so on (cart.good_id == good.id)

if you have a single cart with a single good in it your solution will still return all of the customers, all of the goods to show a single line on the page - this is not really a good solution.

So try using joins and retrieve only needed data, e.g.:

actual_carts = Cart.objects.all().select_related('customer', 'good').order_by('customer_id', )

This will return only customers and goods mentioned in carts. select_related will let you access all the needed info from customers as well as from goods.


问:
Azure Event Hubs limits and its comparison to pure Kafka cluster
Recently Azure released a feature called Azure Event Hubs for Kafka that allows to use Event Hubs like if it were a Kafka cluster, using the same Kafka libraries. That would allow us to migrate from our current IaaS Kafka solution to a PaaS solution, with all the advantages of a fully managed solution, and with only minimal changes in our base code (at least that's the promise).

However, while analyzing the migration we are finding it hard to get our infrastructure inside the Azure Event Hub limits. We have hundreds of topics in Kafka and we know we will scale to thousands in the future, but that can't be easily be fit inside Event hubs.

In Azure the match for the concept of topic is the Event Hub, and then you also have namespaces, that match a Kafka cluster. In fact, each namespace has a different DNS name, making it a complete different system. The limitations are the following: you can have up to 10 event hubs per namespace, up to 100 namespaces per subscription. That, translated into Kafka jargon, is up to 1000 topics. Let's suppose that's enough for our purposes, however I would need different parts of my application to connect to different Kafka clusters (namespaces) per each 10 topics I have, adding an unneeded complexity to the whole story.

It seems like in the end I am changing the difficulty of managing the infrastructure of my own cluster by the difficulty of re-architecturing my application so that it fits inside that strange 10 topic per cluster limit. With Kafka I can have 100 topics in one cluster. With Event Hubs I need 10 clusters of 10 topics each, what adds the complexity of knowing to which cluster your consumers and producers need to connect to. That completely changes the architecture of your application (making it much more complex).

I've looked through the Internet for an answer to this with no luck, everyone seems to see a lot of advantages using Event Hubs, so I am starting to think maybe I am missing something. Which would be a efficient way of fitting lots of topics inside that 10 topic limit without changing my architecture a lot?

答:
Azure Event Hubs offers Kafka/EH for data streaming in two different umbrellas - Single Tenancy and Multi-tenancy. While multi-tenancy gives you the flexibility to reserve small and use small capacity, it is enforces with Quotas and Limits. These are stringent and cannot be flexed out. Reason, analogically you can imagine multi-tenancy to be a huge kafka cluster of which %CPU and %memory is shared with strict boundaries among different tenants. With this infrastructure to honor multi-tenancy we define boundaries and these boundaries are enforced by quotas and limits. Event Hubs is the only PaaS service that charges you for reserving your bandwidth and the ingress of events. There is no egress charge. We also let you ingress xMBps and egress 2xMBps and the quotas lets us with this boundary. Our single tenant clusters can be thought of as mimicking the exact KAfka cluster where there are no quotas attached. The limits here that we enforce are the actual physical limits. The limits of 1000 topics per namespace and 50 namespace per Capacity units are soft limits which can be relaxed as they are just enforcing the best practices. The cost justification when you compare Standard and Dedicated is not any different and in fact when you do > 50MBps, you can an advantage as the whole capacity is dedicated to one tenant with Dedicated. Also a single Capacity Unit (in which the Dedicated clusters are sold) lets you achieve anywhere between 100MBps - 250MBps based on your send/recieve pattern, payload size, frequency and more. For comparison purpose, although we do not do 0TUs on Standard and there is no direct relation/mapping between dedicate CUs and Standard

TU's, below is a pricing example,
50TU's =  $0.03/hr x 50 =  $1.5 per hour | 50,000 events per second = 180,000,000 events per hour
180,000,000 / 1,000,000 = 180 units of 1,000,000 messages | 180 X $0.028 = $5.04 | So, a grand total of $6.54 per hour

Note that the above does not include Capture pricing. And for a grand total of $6.85 per hour you get Dedicated with Capture included.


问:
How to respond a HTTPGET calling in ASP?
I’m using a SMS service which forwards the received SMSs to my web page by calling my URL using get method. My webpage should respond with an ‘Ok’ in plain text, however I don’t know how to do that, can you give me any idea?</p>

答:
In the Page_Load event of code behind:

```<code>Response.Clear();
Response.Write("Ok");
Response.End();
</code>```

Body:
In the Page_Load event of code behind:

Response.Clear();
Response.Write("Ok");
Response.End();


问:
How do you reference APEX Application Items in Trigger
I am creating a BEFORE DELETE trigger to insert records into an archive table that are deleted through an APEX form on another table. I want to update two columns "UPDATED_BY" and "UPDATED"_DATE" based on the SYSDATE and :APP_USER (APEX Application Item). I'm getting an error related to the :APP_USER (PLS-00049: bad bind variable 'APP_USER'). Is there a specific syntax I have to use to reference APEX app items when creating the trigger?</p>

```<code>CREATE OR REPLACE TRIGGER  "ARCHIVE_DELETED_RECORDS"
BEFORE
delete on "RECORD_TABLE"
for each row
begin
INSERT INTO DELETED_RECORD_TABLE (
    STAGING_ID,
    SOURCE_FILE_ID,
    DELETION_DATE,
    DELETED_BY,
    DELETED_FROM)
SELECT
    STAGING_ID,
    SOURCE_FILE_ID,
    SYSDATE,
    :APP_USER,
    'Record Table 1'
FROM RECORD_TABLE
end;
/
ALTER TRIGGER  "ARCHIVE_DELETED_RECORDS" ENABLE;
</code>```

答:
You can use the V() function to refer directly to APEX bind variables like :APP_USER in a database trigger, or really in any PL/SQL outside of APEX. APEX also generally uses package state to store global variables which need to be accessed externally. See here for some discussion.

In your case, instead of :APP_USER, you could use either V('APP_USER') or APEX_APPLICATION.G_USER. Documentation is here.

Note that if records are deleted from your table outside of APEX (for example, by a DBA running delete from RECORD_TABLE), the DELETED_BY field will be null. So you might want something like:

```<code>COALESCE(V('APP_USER'), SYS_CONTEXT ('USERENV', 'OS_USER'), USER)
</code>```

To prefer the APEX user if that's available, or the OS user if that's available, or finally the current schema user if nothing else is available.

Body:
I am creating a BEFORE DELETE trigger to insert records into an archive table that are deleted through an APEX form on another table. I want to update two columns "UPDATED_BY" and "UPDATED"_DATE" based on the SYSDATE and :APP_USER (APEX Application Item). I'm getting an error related to the :APP_USER (PLS-00049: bad bind variable 'APP_USER'). Is there a specific syntax I have to use to reference APEX app items when creating the trigger?

CREATE OR REPLACE TRIGGER  "ARCHIVE_DELETED_RECORDS"
BEFORE
delete on "RECORD_TABLE"
for each row
begin
INSERT INTO DELETED_RECORD_TABLE (
    STAGING_ID,
    SOURCE_FILE_ID,
    DELETION_DATE,
    DELETED_BY,
    DELETED_FROM)
SELECT
    STAGING_ID,
    SOURCE_FILE_ID,
    SYSDATE,
    :APP_USER,
    'Record Table 1'
FROM RECORD_TABLE
end;
/
ALTER TRIGGER  "ARCHIVE_DELETED_RECORDS" ENABLE;

Body:
You can use the V() function to refer directly to APEX bind variables like :APP_USER in a database trigger, or really in any PL/SQL outside of APEX. APEX also generally uses package state to store global variables which need to be accessed externally. See here for some discussion.

In your case, instead of :APP_USER, you could use either V('APP_USER') or APEX_APPLICATION.G_USER. Documentation is here.

Note that if records are deleted from your table outside of APEX (for example, by a DBA running delete from RECORD_TABLE), the DELETED_BY field will be null. So you might want something like:

COALESCE(V('APP_USER'), SYS_CONTEXT ('USERENV', 'OS_USER'), USER)

To prefer the APEX user if that's available, or the OS user if that's available, or finally the current schema user if nothing else is available.


问:
How can I display my primary key as a column when using inner join?
```<code>select StaffNo, SName, BranchName from STAFF  inner join BRANCH on staff.branchno = Branch.branchno;
</code>```

I am trying to display BranchNo in the results from the above query, whenever I add BranchNo after branch name like this.

```<code>select StaffNo, SName, BranchName, Branchno from STAFF  inner join BRANCH on staff.branchno = Branch.branchno;
</code>```

I get this error code ORA-00918: column ambiguously defined. To my understanding it is something to do with the fact that BranchNo is my primary key, is there a way I can get around this and display BranchNo in the query results? Many thanks.

答:
Just prefix the ambiguous column name with the table it belongs to.

Actually, you should always prefix the columns in multi-table queries with the relevant table names; this makes the queries unambiguous for your database and for the readers
(and future maintainers) of the query.

For this, table aliases come handy (they make the query shorter).

Here is your updated query - I made a few assumptions on from which table each column comes from, that you might need to review:

```<code>select
    s.staffno,
    s.sname,
    b.branchname,
    s.branchno
from staff s
inner join branch b on s.branchno = b.branchno;
</code>```

Body:
select StaffNo, SName, BranchName from STAFF  inner join BRANCH on staff.branchno = Branch.branchno;

I am trying to display BranchNo in the results from the above query, whenever I add BranchNo after branch name like this.

select StaffNo, SName, BranchName, Branchno from STAFF  inner join BRANCH on staff.branchno = Branch.branchno;

I get this error code ORA-00918: column ambiguously defined. To my understanding it is something to do with the fact that BranchNo is my primary key, is there a way I can get around this and display BranchNo in the query results? Many thanks.

Body:
Just prefix the ambiguous column name with the table it belongs to.

Actually, you should always prefix the columns in multi-table queries with the relevant table names; this makes the queries unambiguous for your database and for the readers
(and future maintainers) of the query.

For this, table aliases come handy (they make the query shorter).

Here is your updated query - I made a few assumptions on from which table each column comes from, that you might need to review:

select
    s.staffno,
    s.sname,
    b.branchname,
    s.branchno
from staff s
inner join branch b on s.branchno = b.branchno;


问:
How do I get the current date in JavaScript?
How do I get the current date in JavaScript?</p>

答:
A straightforward way to pull that off (whilst considering your current time zone it taking advantage of the ISO yyyy-mm-dd format) is:

```<code>let d = new Date().toISOString().substring(0,19).replace("T"," ") // "2020-02-18 16:41:58"
</code>```

Usually, this is a pretty all-purpose compatible date format and you can convert it to pure date value if needed:

```<code>Date.parse(d); // 1582044297000
</code>```

Body:
A straightforward way to pull that off (whilst considering your current time zone it taking advantage of the ISO yyyy-mm-dd format) is:

let d = new Date().toISOString().substring(0,19).replace("T"," ") // "2020-02-18 16:41:58"

Usually, this is a pretty all-purpose compatible date format and you can convert it to pure date value if needed:

Date.parse(d); // 1582044297000


问:
Python Newbie: Calculating with two lists one of it a 2d list
Yeah, first of all i'm a Python Newbie.
I've got the task to code something similiar, more easier variant of the analytic hierarchy process (ahp).
I'm not allowed to take any packages like numpy.

I need a list input [n*m] like:

```<code>liste = [[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]
</code>```

I've realised it like this:

```<code>liste = input("Put in the Matrix: ")
</code>```

I need to sum up the Columns:

```<code> col_sums = [ sum(x) for x in zip(*liste) ]
</code>```

Now it need to calc the normalized list, it looks like this:

```<code>liste = [[1.0,2.0,3.0],
        [4.0,5.0,6.0],
        [7.0,8.0,9.0]]

list_norm = 1.0/col_sums[0] 2.0/col_sums[1] ...
            4.0/col_sums[0] 5.0/col_sums[1] ...
            7.0/col_sums[0] 8.0/col_sums[1] ...
</code>```

What is the proper way to realize it?

Thank's for your feedback & attention.

答:
The way you're doing everything else so far looks right. You just need another list comprehension for list_norm:

```<code>liste = [[1.0,2.0,3.0],
        [4.0,5.0,6.0],
        [7.0,8.0,9.0]]
col_sums = [ sum(x) for x in zip(*liste) ]
list_norm = [[e / col_sums[c] for c, e in enumerate(row)] for row in liste]
# [[0.083, 0.133, 0.166],
#  [0.333, 0.333, 0.333],
#  [0.583, 0.533, 0.5]]
</code>```

We use enumerate() to get both the element and its list index here, and use the index to get the appropriate sum from col_sums.

Alternate, cleaner, solution, as mentioned by @kaya3 in a comment:

```<code>list_norm = [[e / s for e, s in zip(row, col_sums)] for row in liste]
</code>```

where zip() produces the pairs of corresponding elements from both of its arguments. Functionally, this is the same snippet of code, and produces the same thing.

There aren't any particularly clean ways to get the entire process in one line, but I would argue it doesn't need to be.

Body:
Yeah, first of all i'm a Python Newbie.
I've got the task to code something similiar, more easier variant of the analytic hierarchy process (ahp).
I'm not allowed to take any packages like numpy.

I need a list input [n*m] like:

liste = [[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]

I've realised it like this:

liste = input("Put in the Matrix: ")

I need to sum up the Columns:

 col_sums = [ sum(x) for x in zip(*liste) ]

Now it need to calc the normalized list, it looks like this:

liste = [[1.0,2.0,3.0],
        [4.0,5.0,6.0],
        [7.0,8.0,9.0]]

list_norm = 1.0/col_sums[0] 2.0/col_sums[1] ...
            4.0/col_sums[0] 5.0/col_sums[1] ...
            7.0/col_sums[0] 8.0/col_sums[1] ...

What is the proper way to realize it?

Thank's for your feedback & attention.

Body:
The way you're doing everything else so far looks right. You just need another list comprehension for list_norm:

liste = [[1.0,2.0,3.0],
        [4.0,5.0,6.0],
        [7.0,8.0,9.0]]
col_sums = [ sum(x) for x in zip(*liste) ]
list_norm = [[e / col_sums[c] for c, e in enumerate(row)] for row in liste]
# [[0.083, 0.133, 0.166],
#  [0.333, 0.333, 0.333],
#  [0.583, 0.533, 0.5]]

We use enumerate() to get both the element and its list index here, and use the index to get the appropriate sum from col_sums.

Alternate, cleaner, solution, as mentioned by @kaya3 in a comment:

list_norm = [[e / s for e, s in zip(row, col_sums)] for row in liste]

where zip() produces the pairs of corresponding elements from both of its arguments. Functionally, this is the same snippet of code, and produces the same thing.

There aren't any particularly clean ways to get the entire process in one line, but I would argue it doesn't need to be.


问:
BEL in Bash / Zsh PROMPT
I do have the following config in my .zshrc:

```<code>BEL=$(tput bel)
PROMPT+='%(?::$BEL)'
</code>```

That works/worked in some environment (always Cygwin on Windows), but currently does not anymore.

(Same behaviour: not working, in Bash on Ubuntu on Windows.)

What is wrong?

答:
In zsh, unlike bash, parameter expansions embedded in a prompt are only expanded when the prompt is displayed if the PROMPT_SUBST option is set.

%(...) is a zsh-specific escape sequence, and PROMPT itself is a zsh-specific name, so this will not work in bash, which would require something like

```<code>PS1+='$(if test $? -ne 0; then tput bel; fi)'
</code>```

(which, incidentally, would work in zsh as well, assuming PROMPT_SUBST were enabled. A command that would conditionally enable it if the current shell is, in fact, zsh, might be

```<code>if [ -z "$ZSH_VERSION" ]; then
  setopt PROMPT_SUBST
fi
</code>```

Title: BEL in Bash / Zsh PROMPT

Body:
I do have the following config in my .zshrc:

BEL=$(tput bel)
PROMPT+='%(?::$BEL)'

That works/worked in some environment (always Cygwin on Windows), but currently does not anymore.

(Same behaviour: not working, in Bash on Ubuntu on Windows.)

What is wrong?

Body:
In zsh, unlike bash, parameter expansions embedded in a prompt are only expanded when the prompt is displayed if the PROMPT_SUBST option is set.

%(...) is a zsh-specific escape sequence, and PROMPT itself is a zsh-specific name, so this will not work in bash, which would require something like

PS1+='$(if test $? -ne 0; then tput bel; fi)'

(which, incidentally, would work in zsh as well, assuming PROMPT_SUBST were enabled. A command that would conditionally enable it if the current shell is, in fact, zsh, might be

if [ -z "$ZSH_VERSION" ]; then
  setopt PROMPT_SUBST
fi


问:
Splitting an array of points into multiple arrays that have a specific distance from each other
I have an array of points that look like this (x,y):

```<code>6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25
18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25
</code>```

This array represents a two, separate, series of points that are on a 1.25" offset from each other.  There is two series, but there can be [n] series, and I need to split them up into the appropriate number of arrays based on the specific offset like this:

```<code>6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25

18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25
</code>```

The offset can be in the X or the Y, but not both.  I have been working on it for a little while now and am kind of stuck.

Edit

What I have tried so far, is to get a point in the array, and search for all points that are on the interval specified (getDist calculates the distance from one point to another):

```<code>foreach(Point firstPoint in points){
    foreach(Point nextPoint in points){
        if(isSame(firstPoint, nextPoint)
            continue;

        if(getDist(firstPoint, nextPoint) % 1.25 == 0){
            // add to new array
        }
    }
}

double getDist(Point p1, Point p2) => Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

bool isSame(Point p1, Point p2) => p1.X == p2.X && p1.Y == p2.Y;
</code>```

The problem I run into is that this looks at all the points, then looks at them each one again creating a huge set of arrays.

答:
So, thanks for all you responses, with them I was able to get this working.  I used something similar to this.  I can't share the exact code as there is code from my company that I can't share.  I get the points in a collection that is very similar to an array, and I HAVE to use them in this type of collection.

```<code>while(points.Length > 0){
    Point currentPoint = points[0];
    List<Point> selectedPoints = new List<Point>();

    selectedPoints.Add(currentPoint)

    for(int i = 1; i <= points.Length; i++){
        Point nextPoint = points[i];
        double dist = getDist(currentPoint, nextPoint);
        if(Math.Abs(dist % 1.25 - 0) < 1.19e-4){
            selectedPoints.Add(nextPoint);
        }
    }

    // remove selected points from all points
    // add them to my list of points that I needed
}
</code>```

Thanks for the help!

Body:
I have an array of points that look like this (x,y):

6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25
18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25

This array represents a two, separate, series of points that are on a 1.25" offset from each other.  There is two series, but there can be [n] series, and I need to split them up into the appropriate number of arrays based on the specific offset like this:

6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25

18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25

The offset can be in the X or the Y, but not both.  I have been working on it for a little while now and am kind of stuck.

Edit

What I have tried so far, is to get a point in the array, and search for all points that are on the interval specified (getDist calculates the distance from one point to another):

foreach(Point firstPoint in points){
    foreach(Point nextPoint in points){
        if(isSame(firstPoint, nextPoint)
            continue;

        if(getDist(firstPoint, nextPoint) % 1.25 == 0){
            // add to new array
        }
    }
}

double getDist(Point p1, Point p2) => Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

bool isSame(Point p1, Point p2) => p1.X == p2.X && p1.Y == p2.Y;

The problem I run into is that this looks at all the points, then looks at them each one again creating a huge set of arrays.

Body:
So, thanks for all you responses, with them I was able to get this working.  I used something similar to this.  I can't share the exact code as there is code from my company that I can't share.  I get the points in a collection that is very similar to an array, and I HAVE to use them in this type of collection.

while(points.Length > 0){
    Point currentPoint = points[0];
    List<Point> selectedPoints = new List<Point>();

    selectedPoints.Add(currentPoint)

    for(int i = 1; i <= points.Length; i++){
        Point nextPoint = points[i];
        double dist = getDist(currentPoint, nextPoint);
        if(Math.Abs(dist % 1.25 - 0) < 1.19e-4){
            selectedPoints.Add(nextPoint);
        }
    }

    // remove selected points from all points
    // add them to my list of points that I needed
}

Thanks for the help!


问:
Running npm release with webpack causes an error
Im following the tutorial from microsoft:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr-typescript-webpack?view=aspnetcore-3.1&tabs=visual-studio

But when I try to start the programm with npm run release I get following console output:

```<code>    PS C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack> npm run release
> NetCoreTSWebpack@1.0.0 release C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack
> webpack --mode=production

webpack not installed

Install webpack to start bundling:
  $ npm install --save-dev webpack

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! NetCoreTSWebpack@1.0.0 release: `webpack --mode=production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the NetCoreTSWebpack@1.0.0 release script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2020-02-18T16_40_09_332Z-debug.log
PS C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack>
</code>```

This is my log file:

```<code>0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'release'
1 verbose cli ]
2 info using npm@6.13.4
3 info using node@v12.16.0
4 verbose run-script [ 'prerelease', 'release', 'postrelease' ]
5 info lifecycle NetCoreTSWebpack@1.0.0~prerelease: NetCoreTSWebpack@1.0.0
6 info lifecycle NetCoreTSWebpack@1.0.0~release: NetCoreTSWebpack@1.0.0
7 verbose lifecycle NetCoreTSWebpack@1.0.0~release: unsafe-perm in lifecycle true
8 verbose lifecycle NetCoreTSWebpack@1.0.0~release: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack\node_modules\.bin;.\node_modules\.bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files\nodejs\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\Users\user\AppData\Local\Microsoft\WindowsApps;;C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\user\AppData\Roaming\npm;C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Web\External;C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Web\External\git
9 verbose lifecycle NetCoreTSWebpack@1.0.0~release: CWD: C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack
10 silly lifecycle NetCoreTSWebpack@1.0.0~release: Args: [ '/d /s /c', 'webpack --mode=production' ]
11 silly lifecycle NetCoreTSWebpack@1.0.0~release: Returned: code: 1  signal: null
12 info lifecycle NetCoreTSWebpack@1.0.0~release: Failed to exec release script
13 verbose stack Error: NetCoreTSWebpack@1.0.0 release: `webpack --mode=production`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:321:20)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:321:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid NetCoreTSWebpack@1.0.0
15 verbose cwd C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack
16 verbose Windows_NT 10.0.18363
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "release"
18 verbose node v12.16.0
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 1
22 error NetCoreTSWebpack@1.0.0 release: `webpack --mode=production`
22 error Exit status 1
23 error Failed at the NetCoreTSWebpack@1.0.0 release script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
</code>```

答:
It looks like you may have skipped step 3 from the "Configure Webpack and TypeScript" phase, where you needed to run the code below.  Webpack isn't installed according to your output, and step 3 is supposed to install it.</p>

```<code>npm i -D -E clean-webpack-plugin@3.0.0 css-loader@3.4.2 html-webpack-plugin@3.2.0 mini-css-extract-plugin@0.9.0 ts-loader@6.2.1 typescript@3.7.5 webpack@4.41.5 webpack-cli@3.3.10
</code>```

Body:
Im following the tutorial from microsoft:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr-typescript-webpack?view=aspnetcore-3.1&tabs=visual-studio

But when I try to start the programm with npm run release I get following console output:

    PS C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack> npm run release
> NetCoreTSWebpack@1.0.0 release C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack
> webpack --mode=production

webpack not installed

Install webpack to start bundling:
  $ npm install --save-dev webpack

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! NetCoreTSWebpack@1.0.0 release: `webpack --mode=production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the NetCoreTSWebpack@1.0.0 release script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2020-02-18T16_40_09_332Z-debug.log
PS C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack>

This is my log file:

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'release'
1 verbose cli ]
2 info using npm@6.13.4
3 info using node@v12.16.0
4 verbose run-script [ 'prerelease', 'release', 'postrelease' ]
5 info lifecycle NetCoreTSWebpack@1.0.0~prerelease: NetCoreTSWebpack@1.0.0
6 info lifecycle NetCoreTSWebpack@1.0.0~release: NetCoreTSWebpack@1.0.0
7 verbose lifecycle NetCoreTSWebpack@1.0.0~release: unsafe-perm in lifecycle true
8 verbose lifecycle NetCoreTSWebpack@1.0.0~release: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack\node_modules\.bin;.\node_modules\.bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files\nodejs\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\Users\user\AppData\Local\Microsoft\WindowsApps;;C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\user\AppData\Roaming\npm;C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Web\External;C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Web\External\git
9 verbose lifecycle NetCoreTSWebpack@1.0.0~release: CWD: C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack
10 silly lifecycle NetCoreTSWebpack@1.0.0~release: Args: [ '/d /s /c', 'webpack --mode=production' ]
11 silly lifecycle NetCoreTSWebpack@1.0.0~release: Returned: code: 1  signal: null
12 info lifecycle NetCoreTSWebpack@1.0.0~release: Failed to exec release script
13 verbose stack Error: NetCoreTSWebpack@1.0.0 release: `webpack --mode=production`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:321:20)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:321:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid NetCoreTSWebpack@1.0.0
15 verbose cwd C:\tfs_2020\Developers\User\NetCoreTSWebpack\NetCoreTSWebpack
16 verbose Windows_NT 10.0.18363
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "release"
18 verbose node v12.16.0
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 1
22 error NetCoreTSWebpack@1.0.0 release: `webpack --mode=production`
22 error Exit status 1
23 error Failed at the NetCoreTSWebpack@1.0.0 release script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Body:
It looks like you may have skipped step 3 from the "Configure Webpack and TypeScript" phase, where you needed to run the code below.  Webpack isn't installed according to your output, and step 3 is supposed to install it.

npm i -D -E clean-webpack-plugin@3.0.0 css-loader@3.4.2 html-webpack-plugin@3.2.0 mini-css-extract-plugin@0.9.0 ts-loader@6.2.1 typescript@3.7.5 webpack@4.41.5 webpack-cli@3.3.10


问:
jquery helper like htmlgenericcontrol in asp.net
I want to build a webpage containing jquery draggables in asp.net (c#).
How can I add my jquery code to my page in an object oriented way?

So I want to make a c# myDraggables.cs class that I add to the asp page with the htmlgenericcontrol. How do I add this jquery code (eg: $('#mydraggables').draggable(); ) in my class.
I could do it with the htmlgenericcontrol by adding a "script"-tag. But isn't there a way to do it with a jquery helper (can't find that)?
tx

A sample:
Basicly, in my myDraggables-class I could have;

```<code>public HtmlControl Draw()
{
    HtmlGenericControl aDiv= new HtmlGenericControl("div");
    aDiv.Attributes.Add("id", "dragtest");
    return aDiv;
}

public HtmlControl DrawJquery()
{
    HtmlGenericControl js = new HtmlGenericControl("script");
    js.Attributes["type"] = "text/javascript";
    js.InnerHtml = "$('#dragtest').draggable();";
    return js;
}
</code>```

And the code behind of my asp.page would look like;

```<code>protected void Page_Load(object sender, EventArgs e)
{
    myDraggables md = new myDraggables ('..some props ..');
    Page.Header.Controls.Add(md.DrawJquery());
    myPlaceHolder.Controls.Add(md.Draw());
}
</code>```

That works, but jquery-code will become more complex. And will not be readable anymore...
how can this be achieved in json? Or another more readable way?

Thanks

答:
If I understand you correctly, you want to write a strongly-typed .NET class in the back-end which also functions as a jQuery object on the front-end, right? If so, the best way to do it is probably to serialize your .NET object into JSON format, store it in a variable and print it out in a script tag when generating the markup. Then, on the front-end, parse the JSON string into a Javascript object and you can use it from there.

Can you post any .NET and JS code you have already?

Body:
I want to build a webpage containing jquery draggables in asp.net (c#).
How can I add my jquery code to my page in an object oriented way?

So I want to make a c# myDraggables.cs class that I add to the asp page with the htmlgenericcontrol. How do I add this jquery code (eg: $('#mydraggables').draggable(); ) in my class.
I could do it with the htmlgenericcontrol by adding a "script"-tag. But isn't there a way to do it with a jquery helper (can't find that)?
tx

A sample:
Basicly, in my myDraggables-class I could have;

public HtmlControl Draw()
{
    HtmlGenericControl aDiv= new HtmlGenericControl("div");
    aDiv.Attributes.Add("id", "dragtest");
    return aDiv;
}

public HtmlControl DrawJquery()
{
    HtmlGenericControl js = new HtmlGenericControl("script");
    js.Attributes["type"] = "text/javascript";
    js.InnerHtml = "$('#dragtest').draggable();";
    return js;
}

And the code behind of my asp.page would look like;

protected void Page_Load(object sender, EventArgs e)
{
    myDraggables md = new myDraggables ('..some props ..');
    Page.Header.Controls.Add(md.DrawJquery());
    myPlaceHolder.Controls.Add(md.Draw());
}

That works, but jquery-code will become more complex. And will not be readable anymore...
how can this be achieved in json? Or another more readable way?

Thanks


问:
SAS SQL using a where condition with macro variable
I have a proc sql procedure in SAS where my where clause should be dynamic (the set of ID numbers will be updated in the future).

I could do something as follows for a unique character condition:

```<code>%let value1=A ;
proc sql  ;
select * from sashelp.class
where upcase(name) contains symget('value1');
;
quit;
</code>```

However, how could do the same to check several numbers? How could I make the following work?

```<code>%let value2= (11,12,13);
    proc sql  ;
    select * from sashelp.class
    where age not in symget('value2');
    ;
    quit;
</code>```

答:
Resolve the value of VALUE2 before execution.</p>

```<code>%let value2= (11,12,13);
proc sql  ;
   select * from sashelp.class
      where age not in &value2
      ;
   quit;
</code>```

Body:
I have a proc sql procedure in SAS where my where clause should be dynamic (the set of ID numbers will be updated in the future).

I could do something as follows for a unique character condition:

%let value1=A ;
proc sql  ;
select * from sashelp.class
where upcase(name) contains symget('value1');
;
quit;

However, how could do the same to check several numbers? How could I make the following work?

%let value2= (11,12,13);
    proc sql  ;
    select * from sashelp.class
    where age not in symget('value2');
    ;
    quit;

Body:
Resolve the value of VALUE2 before execution.

%let value2= (11,12,13);
proc sql  ;
   select * from sashelp.class
      where age not in &value2
      ;
   quit;


问:
Group Products by Brand then by Category - linq
There is three table:

```<code>Brand                               Category
-----------------------          --------------------------------
BrandID     BrandName             CategoryID        CategoryName
-----------------------          --------------------------------
1           Brand1                    1             cat1
2           Brand2                    2             cat2

Product
------------------------------------------------------------
ProductID       BrandID      CategoryID    ProductName
------------------------------------------------------------
1                 1             1          Product1
2                 1             1          Product2
3                 1             2          Product3
4                 2             1          Product4
</code>```

I want to write Llinq query to get output like below:

```<code>Brand1
|__ cat1
|   |__ Product1
|   |__ Product2
|
|__ Cat2
|   |__ Product3
|
|__ Brand2
|__ cat1
|   |__ Product4
</code>```

I Wrote this query to get Product group by Category:

```<code>    var query2 = db.Brands
        .GroupBy(x => new { x.BrandID, x.BrandName })
                    .Select(x => new
                    {
                        x.Key.BrandID,
                        x.Key.BrandName,
                        ProductsNames = db.Products
                                            .Where(p => p.BrandID == x.Key.BrandID)
                                            .Select(p => p.ProductName).ToList()
                    }).ToList();
</code>```

How can Group Products by Brand then by Category?

答:
In one step , more compact manner</p>

```<code>public class Product
    {
        public int ProductID { get; internal set; }
        public string ProductName { get; internal set; }
        public Brand brand { get; set; }
        public Category cat { get; set; }
        public Product()
        {
            brand = new Brand();
            cat = new Category();
        }
    }

    public class Brand
    {
        public int BrandID { get; internal set; }
        public string BrandName { get; internal set; }
    }

    public class Category
    {
        public int CategoryID { get; internal set; }
        public string CategoryName { get; internal set; }
    }

private void a1()
{
    var products = new List<Product>{
    new Product { ProductID = 1,
                                brand =new Brand { BrandID = 1, BrandName = "Brand1" },
                                cat = new Category { CategoryID = 1, CategoryName = "cat1" },
                                ProductName = "Product1" },
    new Product { ProductID = 2,
                                brand =new Brand { BrandID = 1, BrandName = "Brand1" },
                                cat = new Category { CategoryID = 1, CategoryName = "cat1" },
                                ProductName = "Product2" },
    new Product { ProductID = 3,
                                brand =new Brand { BrandID = 1, BrandName = "Brand1" },
                                cat = new Category { CategoryID = 2, CategoryName = "cat2" },
                                ProductName = "Product3" },
    new Product { ProductID = 4,
                                brand =new Brand { BrandID = 2, BrandName = "Brand2" },
                                cat = new Category { CategoryID = 1, CategoryName = "cat1" },
                                ProductName = "Product4" }
    };

    var g1 = products.GroupBy(p => new { p.brand, p.cat, p })
                        .Select(y => new
                        {
                            k1 = y.Key.brand.BrandName,
                            k2 = y.Key.cat.CategoryName,
                            k3 = y.Key.p.ProductName
                        }
                        );
}

// Result/Output as below
{ k1 = "Brand1", k2 = "cat1", k3 = "Product1" }
{ k1 = "Brand1", k2 = "cat1", k3 = "Product2" }
{ k1 = "Brand1", k2 = "cat2", k3 = "Product3" }
{ k1 = "Brand2", k2 = "cat1", k3 = "Product4" }

</code>```

Body:
There is three table:

Brand                               Category
-----------------------          --------------------------------
BrandID     BrandName             CategoryID        CategoryName
-----------------------          --------------------------------
1           Brand1                    1             cat1
2           Brand2                    2             cat2

Product
------------------------------------------------------------
ProductID       BrandID      CategoryID    ProductName
------------------------------------------------------------
1                 1             1          Product1
2                 1             1          Product2
3                 1             2          Product3
4                 2             1          Product4

I want to write Llinq query to get output like below:

Brand1
|__ cat1
|   |__ Product1
|   |__ Product2
|
|__ Cat2
|   |__ Product3
|
|__ Brand2
|__ cat1
|   |__ Product4

I Wrote this query to get Product group by Category:

    var query2 = db.Brands
        .GroupBy(x => new { x.BrandID, x.BrandName })
                    .Select(x => new
                    {
                        x.Key.BrandID,
                        x.Key.BrandName,
                        ProductsNames = db.Products
                                            .Where(p => p.BrandID == x.Key.BrandID)
                                            .Select(p => p.ProductName).ToList()
                    }).ToList();

How can Group Products by Brand then by Category?

Body:
In one step , more compact manner

public class Product
    {
        public int ProductID { get; internal set; }
        public string ProductName { get; internal set; }
        public Brand brand { get; set; }
        public Category cat { get; set; }
        public Product()
        {
            brand = new Brand();
            cat = new Category();
        }
    }

    public class Brand
    {
        public int BrandID { get; internal set; }
        public string BrandName { get; internal set; }
    }

    public class Category
    {
        public int CategoryID { get; internal set; }
        public string CategoryName { get; internal set; }
    }

private void a1()
{
    var products = new List<Product>{
    new Product { ProductID = 1,
                                brand =new Brand { BrandID = 1, BrandName = "Brand1" },
                                cat = new Category { CategoryID = 1, CategoryName = "cat1" },
                                ProductName = "Product1" },
    new Product { ProductID = 2,
                                brand =new Brand { BrandID = 1, BrandName = "Brand1" },
                                cat = new Category { CategoryID = 1, CategoryName = "cat1" },
                                ProductName = "Product2" },
    new Product { ProductID = 3,
                                brand =new Brand { BrandID = 1, BrandName = "Brand1" },
                                cat = new Category { CategoryID = 2, CategoryName = "cat2" },
                                ProductName = "Product3" },
    new Product { ProductID = 4,
                                brand =new Brand { BrandID = 2, BrandName = "Brand2" },
                                cat = new Category { CategoryID = 1, CategoryName = "cat1" },
                                ProductName = "Product4" }
    };

    var g1 = products.GroupBy(p => new { p.brand, p.cat, p })
                        .Select(y => new
                        {
                            k1 = y.Key.brand.BrandName,
                            k2 = y.Key.cat.CategoryName,
                            k3 = y.Key.p.ProductName
                        }
                        );
}

// Result/Output as below
{ k1 = "Brand1", k2 = "cat1", k3 = "Product1" }
{ k1 = "Brand1", k2 = "cat1", k3 = "Product2" }
{ k1 = "Brand1", k2 = "cat2", k3 = "Product3" }
{ k1 = "Brand2", k2 = "cat1", k3 = "Product4" }


问:
Angular AgmMaps: can't use PolylineManager, with error: "[Front for longstractor/server0.conn0.child1/longstractor372]"
I am trying to draw a polyline (some lines that follow each other, for describing a bicycle route, per example) in my map. The map currently has some entities that are loaded via template, with the typical *nFor.

As the AGM library states, there are many injectables that can draw things in the map. One of those injetables is PolylineManager, which is perfect for my use case. As it's supposed to be an injectable that is present in the @agm/core module (which is properly imported in my module and working), I just injected it in my map component's constructor, just like:

```<code> private agmPolyManager: PolylineManager
</code>```

Well, thing is, that when I do this, even before using it anywhere in the app, the view crashes when I try to enter, and I get the following, totally non-sense error:

Error: "[Front for longstractor/server0.conn0.child1/longstractor372]"

I haven't found this error anywhere in the web. Tried to update the package and so, but it didn't give any results...

答:
I'm not sure if this error is related but I had a similar error while trying to redirect to another route.

```<code>ERROR Error: "[Front for longstractor/server0.conn8.child1/longstractor59654]"
</code>```

The error didn't say anything about what was wrong, so I enabled the tracing on my routing module and the logs showed me what was the error.

```<code>imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only
    )
]
</code>```

Body:
I am trying to draw a polyline (some lines that follow each other, for describing a bicycle route, per example) in my map. The map currently has some entities that are loaded via template, with the typical *nFor.

As the AGM library states, there are many injectables that can draw things in the map. One of those injetables is PolylineManager, which is perfect for my use case. As it's supposed to be an injectable that is present in the @agm/core module (which is properly imported in my module and working), I just injected it in my map component's constructor, just like:

 private agmPolyManager: PolylineManager

Well, thing is, that when I do this, even before using it anywhere in the app, the view crashes when I try to enter, and I get the following, totally non-sense error:

Error: "[Front for longstractor/server0.conn0.child1/longstractor372]"

I haven't found this error anywhere in the web. Tried to update the package and so, but it didn't give any results...

Body:
I'm not sure if this error is related but I had a similar error while trying to redirect to another route.

ERROR Error: "[Front for longstractor/server0.conn8.child1/longstractor59654]"

The error didn't say anything about what was wrong, so I enabled the tracing on my routing module and the logs showed me what was the error.

imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only
    )
]


问:
Cleaning dataframe columns for classification
I'm trying to remove all the irrelevant information from one of my columns in my dataframe but have no idea how to do it. I import the data from a CSV file straight to my dataframe.

```<code>0       [{"id": 28, "name": "Action"}, {"id": 12, "nam...

1       [{"id": 12, "name": "Adventure"}, {"id": 14, "...
2       [{"id": 28, "name": "Action"}, {"id": 12, "nam...

4798    [{"id": 28, "name": "Action"}, {"id": 80, "nam...
4799    [{"id": 35, "name": "Comedy"}, {"id": 10749, "...
4800    [{"id": 35, "name": "Comedy"}, {"id": 18, "nam...
</code>```

I would like to just have the genre e.g action, comedy, adventure. If anyone could help me or send me in the correct direction to do this it would be greatly appreciated.

答:
You can apply functions to columns using apply method.

```<code>df[column_name] = df[column_name].apply(lambda x: x if x in ['action', 'comedy', 'adventure'] else None)
</code>```

Body:
I'm trying to remove all the irrelevant information from one of my columns in my dataframe but have no idea how to do it. I import the data from a CSV file straight to my dataframe.

0       [{"id": 28, "name": "Action"}, {"id": 12, "nam...

1       [{"id": 12, "name": "Adventure"}, {"id": 14, "...
2       [{"id": 28, "name": "Action"}, {"id": 12, "nam...

4798    [{"id": 28, "name": "Action"}, {"id": 80, "nam...
4799    [{"id": 35, "name": "Comedy"}, {"id": 10749, "...
4800    [{"id": 35, "name": "Comedy"}, {"id": 18, "nam...

I would like to just have the genre e.g action, comedy, adventure. If anyone could help me or send me in the correct direction to do this it would be greatly appreciated.

Body:
You can apply functions to columns using apply method.

df[column_name] = df[column_name].apply(lambda x: x if x in ['action', 'comedy', 'adventure'] else None)


问:
Why am I getting ClassCastException in Jenkins build
I am new to Jenkins. I am getting the following error. Please help</p>

```<code>FATAL: hudson.scm.SCMRevisionState$None cannot be cast to hudson.scm.SVNRevisionState
java.lang.ClassCastException: hudson.scm.SCMRevisionState$None cannot be cast to hudson.scm.SVNRevisionState
    at hudson.scm.SubversionSCM.calcChangeLog(SubversionSCM.java:730)
    at hudson.scm.SubversionSCM.checkout(SubversionSCM.java:865)
    at hudson.scm.SCM.checkout(SCM.java:496)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1278)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:604)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:529)
    at hudson.model.Run.execute(Run.java:1728)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:405)
</code>```

答: install svn plugin  if you are trying to checkout SVN Repo</p>

Body:
I am new to Jenkins. I am getting the following error. Please help

FATAL: hudson.scm.SCMRevisionState$None cannot be cast to hudson.scm.SVNRevisionState
java.lang.ClassCastException: hudson.scm.SCMRevisionState$None cannot be cast to hudson.scm.SVNRevisionState
    at hudson.scm.SubversionSCM.calcChangeLog(SubversionSCM.java:730)
    at hudson.scm.SubversionSCM.checkout(SubversionSCM.java:865)
    at hudson.scm.SCM.checkout(SCM.java:496)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1278)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:604)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:529)
    at hudson.model.Run.execute(Run.java:1728)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:405)


问:
RouterExtension.back() not working Nativescript Angular
I have a module called TransactionModule which contains the following routes:

transaction-routing.module.ts

```<code>export const routes: Route[] = [
  {
    path: 'transaction',
    component: TransactionComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: 'deposit',
        component: DepositComponent,
        outlet: 'depositTab'
      },
      {
        path: 'skrill-deposit',
        component: SkrillDepositComponent,
        outlet: 'depositTab'
      },
      {
        path: 'withdrawal',
        component: WithdrawalComponent,
        outlet: 'withdrawalTab'
      }
    ]
  },
</code>```

What my transasction component do is that it holds my Tab and its template is like this:

```<code><ActionBar title="ActionBar title">
  <NavigationButton android.systemIcon="ic_menu_back" text="Back To Dashboard" (tap)="goBack()"></NavigationButton>
</ActionBar>
<TabView androidTabsPosition="bottom" selectedIndex="0">
  <page-router-outlet *tabItem="{title: 'Deposit'}" name="depositTab" actionBarVisibility="never">
  </page-router-outlet>

  <page-router-outlet *tabItem="{title: 'Withdrawal'}" name="withdrawalTab" actionBarVisibility="never">
  </page-router-outlet>
</TabView>
</code>```

Here's the component's code:

transaction.component.ts:

```<code>export class TransactionComponent implements OnInit {

  constructor(private routerExtensions: RouterExtensions,
    private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.routerExtensions.navigate(
      [{ outlets: { depositTab: ['deposit'], withdrawalTab: ['withdrawal'] } }],
      { relativeTo: this.activatedRoute }
   );
  }

  goBack() {
    console.log(this.routerExtensions.canGoBack());
    this.routerExtensions.back();
  }
}
</code>```

Now, what I want to do is when the back button of ActionBar has been clicked it should go back to the Dashboard (/dashboard, this is the origination route before going to transaction). However, it is not working.

When I try to log this.routerExtensions.canGoBack() it returns false.
Why is that so? Why I cant navigate back to dashboard?

答:
Try to add in transaction.component.ts:

```<code>get canGoBack() {
    return this.router.canGoBack();
}
</code>```

And in .html file:

```<code><NavigationButton
    android.systemIcon="ic_menu_back"
    text="Back To Dashboard"
    (tap)="onGoBack()" (tap)="goBack()">
</NavigationButton>
</code>```

Body:
I have a module called TransactionModule which contains the following routes:

transaction-routing.module.ts

export const routes: Route[] = [
  {
    path: 'transaction',
    component: TransactionComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: 'deposit',
        component: DepositComponent,
        outlet: 'depositTab'
      },
      {
        path: 'skrill-deposit',
        component: SkrillDepositComponent,
        outlet: 'depositTab'
      },
      {
        path: 'withdrawal',
        component: WithdrawalComponent,
        outlet: 'withdrawalTab'
      }
    ]
  },

What my transasction component do is that it holds my Tab and its template is like this:

<ActionBar title="ActionBar title">
  <NavigationButton android.systemIcon="ic_menu_back" text="Back To Dashboard" (tap)="goBack()"></NavigationButton>
</ActionBar>
<TabView androidTabsPosition="bottom" selectedIndex="0">
  <page-router-outlet *tabItem="{title: 'Deposit'}" name="depositTab" actionBarVisibility="never">
  </page-router-outlet>

  <page-router-outlet *tabItem="{title: 'Withdrawal'}" name="withdrawalTab" actionBarVisibility="never">
  </page-router-outlet>
</TabView>

Here's the component's code:

transaction.component.ts:

export class TransactionComponent implements OnInit {

  constructor(private routerExtensions: RouterExtensions,
    private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.routerExtensions.navigate(
      [{ outlets: { depositTab: ['deposit'], withdrawalTab: ['withdrawal'] } }],
      { relativeTo: this.activatedRoute }
   );
  }

  goBack() {
    console.log(this.routerExtensions.canGoBack());
    this.routerExtensions.back();
  }
}

Now, what I want to do is when the back button of ActionBar has been clicked it should go back to the Dashboard (/dashboard, this is the origination route before going to transaction). However, it is not working.

When I try to log this.routerExtensions.canGoBack() it returns false.
Why is that so? Why I cant navigate back to dashboard?

Body:
Try to add in transaction.component.ts:

get canGoBack() {
    return this.router.canGoBack();
}

And in .html file:

<NavigationButton
    android.systemIcon="ic_menu_back"
    text="Back To Dashboard"
    (tap)="onGoBack()" (tap)="goBack()">
</NavigationButton>