问:
No fields for dynamic SQL stored procedure in SSRS with SET FMTONLY
I have the following SP which works correctly when ran on its own:

```<code>USE [Orders]
GO
SET FMTONLY OFF;

CREATE PROCEDURE [dbo].[Get_Details_by_Type]

@isArchived varchar(10),
@Type varchar(50)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    declare @sqlQuery nvarchar(max)
          IF(@isArchived = 'ALL')
            BEGIN
                set @sqlQuery  = 'SELECT *  FROM [dbo].[Orders]
              WHERE ' + @Type + ' != €
                ORDER BY [IDNumber]'
                exec sp_executesql @sqlQuery
            END
        ELSE
            BEGIN
            set @sqlQuery  = 'SELECT * FROM [dbo].[Orders]
          WHERE ' + @Type + ' != € AND [isArchived] = ' + @isArchived + ' ORDER BY [IDNumber]'
            exec sp_executesql @sqlQuery
        END
END
SET FMTONLY ON;
</code>```

The problem I'm having is that when I add a DataSet for a SSRS report, it pulls no fields/columns in the Fields section. I'm guessing it's due to the dynamic SQL?

How can I resolve that?

答:
I ran into a similar issue. I have some debug statments that I often turn on/off w/ a flag variable.

this line was still affecting the results, even though it doesnt run (@debug =0)

```<code>--check your work
if @debug =1  select @reportStartDate  RSD ,@reportEndDate
         , @yearStart YS, @folderStartDate  FSD, @MonthCount MC
         , @dataStart  DataStart
</code>```

i discovered the issue by running the sp w/ fmtONly on

```<code>SET FMTONLY ON
exec rpt_mo_DashBoard_YTD_Total  'ajax20','12/1/2019'
</code>```

I solved the problem by commenting out the code in the SP.  Yes, now I have to uncomment /comment each return statement when its time to debug...

Body:
I have the following SP which works correctly when ran on its own:

USE [Orders]
GO
SET FMTONLY OFF;

CREATE PROCEDURE [dbo].[Get_Details_by_Type]

@isArchived varchar(10),
@Type varchar(50)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    declare @sqlQuery nvarchar(max)
          IF(@isArchived = 'ALL')
            BEGIN
                set @sqlQuery  = 'SELECT *  FROM [dbo].[Orders]
              WHERE ' + @Type + ' != €
                ORDER BY [IDNumber]'
                exec sp_executesql @sqlQuery
            END
        ELSE
            BEGIN
            set @sqlQuery  = 'SELECT * FROM [dbo].[Orders]
          WHERE ' + @Type + ' != € AND [isArchived] = ' + @isArchived + ' ORDER BY [IDNumber]'
            exec sp_executesql @sqlQuery
        END
END
SET FMTONLY ON;

The problem I'm having is that when I add a DataSet for a SSRS report, it pulls no fields/columns in the Fields section. I'm guessing it's due to the dynamic SQL?

How can I resolve that?

Body:
I ran into a similar issue. I have some debug statments that I often turn on/off w/ a flag variable.

this line was still affecting the results, even though it doesnt run (@debug =0)

--check your work
if @debug =1  select @reportStartDate  RSD ,@reportEndDate
         , @yearStart YS, @folderStartDate  FSD, @MonthCount MC
         , @dataStart  DataStart

i discovered the issue by running the sp w/ fmtONly on

SET FMTONLY ON
exec rpt_mo_DashBoard_YTD_Total  'ajax20','12/1/2019'

I solved the problem by commenting out the code in the SP.  Yes, now I have to uncomment /comment each return statement when its time to debug...


来源: stackexchange

问:
Trouble reading a .txt file and storing into an array
I've been given a .txt file with a specific structure: each line has a String with 5 characters but with a random number of lines, and we should read the file and store it as we want.
I've tried doing it with a linked list and it worked just fine but as the size of the file grew up, the time it took to execute was too long. Since then i've been trying to store the Strings into an array of strings, so everything would be stored contiguously in memory. When executing, i get a segmentation fault error and i have no idea why. The code goes as follows:

```<code>int nLines (char *path)
{
    int answer = 0;
    FILE* fp;
    fp = fopen(path,"r");
    char line[6];

    while (fgets(line, sizeof(line),fp))
    {
        answer++;
    }

    return answer;
}

int main (int argc, char *argv[])
{
    FILE* fp;
    fp = fopen(argv[1], "r");
    int numberLines = nLines(argv[1]);

    char **storage = malloc(numberLines * 6 * sizeof(char));

    if(storage != NULL)
    {
        int i = 0;
        char line [6];

        while (fgets(line, sizeof(line),fp))
        {
            strcpy(storage[i], line);
            i++;
        }
    }

    free(storage);
}
</code>```

The first function is supposed to return the number of lines there is in the file. With this information, i'm trying to allocate memory equal to the number of strings * the size of each string since i know before hand this value. I'm imagining the problem comes from the line:

```<code>char **storage = malloc (numberLines * 6 *sizeof(char));
</code>```

I haven't touched C in a long time and i'm kinda rusty with the whole pointers and memory stuff. Can someone help please. Thank you!

答:
If one wants to truly have an on-line algorithm, one isn't going to have the number of lines available. The idiomatic way to have a contiguous dynamic container is to reallocate geometrically increasing capacity, like vector or ArrayList. C doesn't have that type built-in, but it's worth the extra code if one uses it a lot. For example, this reads from stdin until EOF and uses a Fibonacci sequence as it's capacities.

```<code>#include <stddef.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>

/** One line of maximum 5 `char` plus 1 `NUL`. */
struct Line { char str[6]; };

/** A dynamic line array. */
struct LineArray {
    struct Line *data; /* data -> (c0 < c1 || c0 == c1 == max_size) */
    size_t capacity, next_capacity; /* !data -> !size, data -> size<=capacity */
    size_t size;
};

/** Ensures `min_capacity` of `a`. Return success, otherwise, `errno` will be
 set: `realloc` or `ERANGE` -- tried allocating more then can fit in `size_t`
 or `realloc` doesn't follow [IEEE Std 1003.1-2001
 ](https://pubs.opengroup.org/onlinepubs/009695399/functions/realloc.html). */
static int reserve(struct LineArray *const a, const size_t min_capacity) {
    size_t c0, c1;
    struct Line *data;
    const size_t max_size = (size_t)-1 / sizeof(struct Line *);
    assert(a);
    if(!a->data) {
        if(!min_capacity) return 1;
        c0 = 8, c1 = 13;
    } else {
        if(min_capacity <= a->capacity) return 1;
        c0 = a->capacity, c1 = a->next_capacity;
    }
    if(min_capacity > max_size) return errno = ERANGE, 0;
    assert(c0 < c1); /* Fibonacci: c0 ^= c1, c1 ^= c0, c0 ^= c1, c1 += c0. */
    while(c0 < min_capacity) {
        size_t temp = c0 + c1; c0 = c1; c1 = temp;
        if(c1 > max_size || c1 < c0) c1 = max_size;
    }
    if(!(data = realloc(a->data, c0 * sizeof *a->data)))
        { if(!errno) errno = ERANGE; return 0; }
    a->data = data;
    a->capacity = c0;
    a->next_capacity = c1;
    return 1;
}

/** Adds one to the size of `a` and returns it (`push_back`.) Exceptional
 return null and `errno` is `realloc` or `ERANGE`. */
static struct Line *new_line(struct LineArray *const a) {
    assert(a);
    if(a->size >= (size_t)-1) { errno = ERANGE; return 0; } /* Unlikely. */
    if(!reserve(a, a->size + 1)) return 0; /* (Less) unlikely. */
    return a->data + a->size++;
}

/** Destructor. */
static void linearray_(struct LineArray *const a) {
    assert(a);
    free(a->data);
    a->data = 0, a->capacity = a->next_capacity = a->size = 0;
}

#include <string.h>
#include <stdio.h>

int main(void)
{
    struct LineArray storage = { 0, 0, 0, 0 };
    struct Line *s, *s_end;
    size_t l = 0, line_len;
    char line[7] = "";
    int success = EXIT_FAILURE;

    /* `line` must be capable of storing the "*[,5]\n\0". */
    assert(sizeof line == sizeof ((struct Line *)0)->str + 1);

    while (fgets(line, sizeof line, stdin))
    {
        l++;
        line_len = strlen(line);
        assert(line_len && line_len < sizeof line);
        /* Too long. */
        if(line[line_len - 1] != '\n') { errno = ERANGE; goto catch; }
        /* Cut off the trailing new-line. */
        line[line_len-- - 1] = '\0';
        /* Store `line`. */
        if(!(s = new_line(&storage))) goto catch;
        strcpy(s->str, line);
    }
    if(ferror(stdin)) goto catch;
    /* Print all. */
    for(s = storage.data, s_end = s + storage.size; s < s_end; s++)
        printf("stored: %s\n", s->str);
    success = EXIT_SUCCESS;
    goto finally;
catch:
    perror("Error");
    fprintf(stderr, "On line %lu: \"%s\".\n", (unsigned long)l, line);
finally:
    linearray_(&storage);
    return success;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been given a .txt file with a specific structure: each line has a String with 5 characters but with a random number of lines, and we should read the file and store it as we want.
I've tried doing it with a linked list and it worked just fine but as the size of the file grew up, the time it took to execute was too long. Since then i've been trying to store the Strings into an array of strings, so everything would be stored contiguously in memory. When executing, i get a segmentation fault error and i have no idea why. The code goes as follows:

int nLines (char *path)
{
    int answer = 0;
    FILE* fp;
    fp = fopen(path,"r");
    char line[6];

    while (fgets(line, sizeof(line),fp))
    {
        answer++;
    }

    return answer;
}

int main (int argc, char *argv[])
{
    FILE* fp;
    fp = fopen(argv[1], "r");
    int numberLines = nLines(argv[1]);

    char **storage = malloc(numberLines * 6 * sizeof(char));

    if(storage != NULL)
    {
        int i = 0;
        char line [6];

        while (fgets(line, sizeof(line),fp))
        {
            strcpy(storage[i], line);
            i++;
        }
    }

    free(storage);
}

The first function is supposed to return the number of lines there is in the file. With this information, i'm trying to allocate memory equal to the number of strings * the size of each string since i know before hand this value. I'm imagining the problem comes from the line:

char **storage = malloc (numberLines * 6 *sizeof(char));

I haven't touched C in a long time and i'm kinda rusty with the whole pointers and memory stuff. Can someone help please. Thank you!

Body:
If one wants to truly have an on-line algorithm, one isn't going to have the number of lines available. The idiomatic way to have a contiguous dynamic container is to reallocate geometrically increasing capacity, like vector or ArrayList. C doesn't have that type built-in, but it's worth the extra code if one uses it a lot. For example, this reads from stdin until EOF and uses a Fibonacci sequence as it's capacities.

#include <stddef.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>

/** One line of maximum 5 `char` plus 1 `NUL`. */
struct Line { char str[6]; };

/** A dynamic line array. */
struct LineArray {
    struct Line *data; /* data -> (c0 < c1 || c0 == c1 == max_size) */
    size_t capacity, next_capacity; /* !data -> !size, data -> size<=capacity */
    size_t size;
};

/** Ensures `min_capacity` of `a`. Return success, otherwise, `errno` will be
 set: `realloc` or `ERANGE` -- tried allocating more then can fit in `size_t`
 or `realloc` doesn't follow [IEEE Std 1003.1-2001
 ](https://pubs.opengroup.org/onlinepubs/009695399/functions/realloc.html). */
static int reserve(struct LineArray *const a, const size_t min_capacity) {
    size_t c0, c1;
    struct Line *data;
    const size_t max_size = (size_t)-1 / sizeof(struct Line *);
    assert(a);
    if(!a->data) {
        if(!min_capacity) return 1;
        c0 = 8, c1 = 13;
    } else {
        if(min_capacity <= a->capacity) return 1;
        c0 = a->capacity, c1 = a->next_capacity;
    }
    if(min_capacity > max_size) return errno = ERANGE, 0;
    assert(c0 < c1); /* Fibonacci: c0 ^= c1, c1 ^= c0, c0 ^= c1, c1 += c0. */
    while(c0 < min_capacity) {
        size_t temp = c0 + c1; c0 = c1; c1 = temp;
        if(c1 > max_size || c1 < c0) c1 = max_size;
    }
    if(!(data = realloc(a->data, c0 * sizeof *a->data)))
        { if(!errno) errno = ERANGE; return 0; }
    a->data = data;
    a->capacity = c0;
    a->next_capacity = c1;
    return 1;
}

/** Adds one to the size of `a` and returns it (`push_back`.) Exceptional
 return null and `errno` is `realloc` or `ERANGE`. */
static struct Line *new_line(struct LineArray *const a) {
    assert(a);
    if(a->size >= (size_t)-1) { errno = ERANGE; return 0; } /* Unlikely. */
    if(!reserve(a, a->size + 1)) return 0; /* (Less) unlikely. */
    return a->data + a->size++;
}

/** Destructor. */
static void linearray_(struct LineArray *const a) {
    assert(a);
    free(a->data);
    a->data = 0, a->capacity = a->next_capacity = a->size = 0;
}

#include <string.h>
#include <stdio.h>

int main(void)
{
    struct LineArray storage = { 0, 0, 0, 0 };
    struct Line *s, *s_end;
    size_t l = 0, line_len;
    char line[7] = "";
    int success = EXIT_FAILURE;

    /* `line` must be capable of storing the "*[,5]\n\0". */
    assert(sizeof line == sizeof ((struct Line *)0)->str + 1);

    while (fgets(line, sizeof line, stdin))
    {
        l++;
        line_len = strlen(line);
        assert(line_len && line_len < sizeof line);
        /* Too long. */
        if(line[line_len - 1] != '\n') { errno = ERANGE; goto catch; }
        /* Cut off the trailing new-line. */
        line[line_len-- - 1] = '\0';
        /* Store `line`. */
        if(!(s = new_line(&storage))) goto catch;
        strcpy(s->str, line);
    }
    if(ferror(stdin)) goto catch;
    /* Print all. */
    for(s = storage.data, s_end = s + storage.size; s < s_end; s++)
        printf("stored: %s\n", s->str);
    success = EXIT_SUCCESS;
    goto finally;
catch:
    perror("Error");
    fprintf(stderr, "On line %lu: \"%s\".\n", (unsigned long)l, line);
finally:
    linearray_(&storage);
    return success;
}


问:
Different probability for ranges of random numbers
I'm looking for the best way of implementing random number generator, that will allow me to have control over probability from what range the generated number will be returned. To visualize what I'm trying to achieve I have a picture :

So to summarize :
Let's say that my range is 400. At the beginning I'd like to have 5% probability of getting number 0-20. But at some moment in time I'd like to have this probability increased up to 50%. Hope you get the idea.

答:
It sounds to me like what you're looking for is a way to generate numbers on a normal (or Gaussian) distribution (take a look at the Wikipedia page if you don't know what that means).

The Box-Muller transformation can be used to generate pairs of normally distributed numbers.

Here is a c++ implementation of the polar form of the Box-Muller transformation that shouldn't be hard to translate to javascript.

```<code>// Return a real number from a normal (Gaussian) distribution with given
// mean and standard deviation by polar form of Box-Muller transformation
double x, y, r;
do
{
    x = 2.0 * rand() - 1.0;
    y = 2.0 * rand() - 1.0;
    r = x * x + y * y;
}
while ( r >= 1.0 || r == 0.0 );
double s = sqrt( -2.0 * log(r) / r );
return mean + x * s * stddev;
</code>```

Where mean is the mean of the normal distribution and stddev is the Standard Deviation of the distribution. This code is from a MersesenneTwister C++ class that I've been using recently that you can find on Rick Wagner's page. You can find some more useful information about the Box-Muller transformation on this page.

ContentLicense: CC BY-SA 3.0

Body:
It sounds to me like what you're looking for is a way to generate numbers on a normal (or Gaussian) distribution (take a look at the Wikipedia page if you don't know what that means).

The Box-Muller transformation can be used to generate pairs of normally distributed numbers.

Here is a c++ implementation of the polar form of the Box-Muller transformation that shouldn't be hard to translate to javascript.

// Return a real number from a normal (Gaussian) distribution with given
// mean and standard deviation by polar form of Box-Muller transformation
double x, y, r;
do
{
    x = 2.0 * rand() - 1.0;
    y = 2.0 * rand() - 1.0;
    r = x * x + y * y;
}
while ( r >= 1.0 || r == 0.0 );
double s = sqrt( -2.0 * log(r) / r );
return mean + x * s * stddev;

Where mean is the mean of the normal distribution and stddev is the Standard Deviation of the distribution. This code is from a MersesenneTwister C++ class that I've been using recently that you can find on Rick Wagner's page. You can find some more useful information about the Box-Muller transformation on this page.


问:
Why I got out_of_range?
My function has to reverse the vector's values, but I got an out_of_range exception in one case. Please, explain to me what a difference between this to cases:</p>

```<code>/// working version of my function
void Reverse(vector<int>& v)
{
    for (int i = 0; i < v.size() / 2; i++)
    {
        int temp = v[i];
        v[i] = v[v.size() - (i + 1)]; /// look at round brackets
        v[v.size() - (i + 1)] = temp;
    }
}
/// wrong version
void Reverse2(vector<int>& v)
{
    for (int i = 0; i < v.size() / 2; i++)
    {

        int temp = v[i];
        v[i] = v[v.size() - i + 1];   /// this is wrong
        v[v.size() - i + 1] = temp;   /// same
    }
}
///
int main()
{
    vector<int> v = { 10, 22, 13, 144, 55, 167, 999};
    Reverse(v);
    for (auto c : v)
    {
        cout << c << " ";
    }
}
</code>```

答:
Without parentheses, it is left to right evaluation.

5 - 4 + 1 = 2,
where 5 - (4 +1) = 0.

Title: Why I got out_of_range?

Body:
My function has to reverse the vector's values, but I got an out_of_range exception in one case. Please, explain to me what a difference between this to cases:

/// working version of my function
void Reverse(vector<int>& v)
{
    for (int i = 0; i < v.size() / 2; i++)
    {
        int temp = v[i];
        v[i] = v[v.size() - (i + 1)]; /// look at round brackets
        v[v.size() - (i + 1)] = temp;
    }
}
/// wrong version
void Reverse2(vector<int>& v)
{
    for (int i = 0; i < v.size() / 2; i++)
    {

        int temp = v[i];
        v[i] = v[v.size() - i + 1];   /// this is wrong
        v[v.size() - i + 1] = temp;   /// same
    }
}
///
int main()
{
    vector<int> v = { 10, 22, 13, 144, 55, 167, 999};
    Reverse(v);
    for (auto c : v)
    {
        cout << c << " ";
    }
}


问:
MESSAGE_DELIVERED FCM events not exported to BigQuery starting from 17-12-2019
I have Cloud Messaging -> BigQuery integration enabled.

According to documentation (https://firebase.google.com/docs/cloud-messaging/understand-delivery), there are bunch of event types exported to it, including MESSAGE_DELIVERED. But the last date I got MESSAGE_DELIVERED events in table is Dec'17.

Interesting, that starting from Nov'30 I see new analytics event: notification_receive.

Is it a bug or undocumented changes?

答:
Got response from firebase support:

On December 17, 2019, we've made some changes to the data that is
  exported to BigQuery from Firebase Cloud Messaging (FCM) to improve
  cross-platform consistency. Messages sent on or after December 17,
  2019 will not include certain fields in the BigQuery export.

Specifically, the following Android-only data will no longer be
  exported: device_recently_active The following event types:

```<code>MESSAGE_DELIVERED_ON_RECONNECT
MESSAGE_EXPIRED
MESSAGE_DELAYED_DOZE
MESSAGE_COLLAPSED
MESSAGE_DELAYED_THROTTLED
DEVICE_NOT_FOUND
MESSAGE_ACKED
MESSAGE_DELIVERY_INTERNAL_ERROR
</code>```

Body:
Got response from firebase support:

On December 17, 2019, we've made some changes to the data that is
  exported to BigQuery from Firebase Cloud Messaging (FCM) to improve
  cross-platform consistency. Messages sent on or after December 17,
  2019 will not include certain fields in the BigQuery export.

Specifically, the following Android-only data will no longer be
  exported: device_recently_active The following event types:

MESSAGE_DELIVERED_ON_RECONNECT
MESSAGE_EXPIRED
MESSAGE_DELAYED_DOZE
MESSAGE_COLLAPSED
MESSAGE_DELAYED_THROTTLED
DEVICE_NOT_FOUND
MESSAGE_ACKED
MESSAGE_DELIVERY_INTERNAL_ERROR


问:
ASP Classic: Is it possible for a VbScript function to return an object?
I am learning VbScript and ASP Classic.

Is it possible for a VbScript function to return an object?

The code below is showing the following error on line 15:

Object doesn't support this property or method ('800a01b6' error)

```<code><%
Class Customer
    Public Id
    Public Name
End Class

Class CustomerFactory
    Public Function GetCustomer()
        Dim cust
        Set cust = New Customer
        cust.Id = 1
        cust.Name = "Andrew"

        ' Return
        GetCustomer = cust
    End Function
End Class

Dim factory
Dim cust_from_factory

Set factory = New CustomerFactory
Set cust_from_factory = factory.GetCustomer()
%>
</code>```

Thanks

答:
I discovered the cause of the error.

When returning the function, you must use the Set structure

Before (with error)

```<code>' Return
GetCustomer = cust
</code>```

After

```<code>' Return
Set GetCustomer = cust
</code>```

Body:
I am learning VbScript and ASP Classic.

Is it possible for a VbScript function to return an object?

The code below is showing the following error on line 15:

Object doesn't support this property or method ('800a01b6' error)

<%
Class Customer
    Public Id
    Public Name
End Class

Class CustomerFactory
    Public Function GetCustomer()
        Dim cust
        Set cust = New Customer
        cust.Id = 1
        cust.Name = "Andrew"

        ' Return
        GetCustomer = cust
    End Function
End Class

Dim factory
Dim cust_from_factory

Set factory = New CustomerFactory
Set cust_from_factory = factory.GetCustomer()
%>

Thanks

Body:
I discovered the cause of the error.

When returning the function, you must use the Set structure

Before (with error)

' Return
GetCustomer = cust

After

' Return
Set GetCustomer = cust


问:
Is it possible to realease a full set of potentially dependant artifacts (microservices) at once?
Traditionally we have to deliver our applications on the test and pre-production platforms one by one (usually by hand using setups). Applications like the front end javascript SPA UI are linked to backend services and their delivery sometimes goes together.
 Each service and each application has its own git repository. (we are using on premise TFS 2018 for now )
 Then when it is necessary to go into production, we deliver all of the front end services and applications at once that have been validated at once.

We would like to automate our process but we don't know if Azure Devops is suitable.
  From what I understand with Azure Devops, we can make an independent artifact for each microservice and each front end application. We can also deliver them independently.

It seems to me that Azure Devops by default allows you to manage the delivery cycle for a particular microservice but not for an assembly making up a complete system, right?

But is it possible to deliver a set of projects each with a particular version? For that, must all of our projects be in the same solution or the same git repository?

答:
Yes, you can use multiple artifacts from different sources (build artifacts, repositories, package feeds, github, docker hub, Azure Container Registry, ++) within a single pipeline or release definition. That's true for both the classic release definitions and the modern multi-stage pipeline implementation.

For example you can define a pipeline or release definition that consumes a front-end web app from a build artifact sourced from RepoA, a back-end service artifact consumed from a container registry originally from RepoB, and say a script library in the form of a Git artifact from RepoC. From there you could deploy each of those artifacts together, or in parallel stages, in sequence, partially, with approvals, conditionally, etc, all from the same pipeline.

The full configuration as code YAML multi-stage pipelines are still in preview, so there are some workflow orchestrations that are a little tougher to implement. But there is enough feature parity with the classic release definitions that I would default to using multi-stage for any net new needs.


问:
How to create cube window with css?

I found this image online and tryed to create these boxes with css. I failed. Has anyone an idea how to solve this problem?

This is my code. The problem is the left bar:

.box {
  position: relative;
  margin: 10px;
  display: inline-block;
}

.content {
  border-top: 2px solid red;
  border-right: 2px solid red;
  padding: 5px;
}

.box:before {
  content: '';
  position: absolute;
  top: 0;
  left: -10px;
  height: 100%;
  width: 10px;
  background-color: red;
  transform: skew(-45deg) rotate(-45deg);
}

.box:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: -5px;
  height: 10px;
  width: 100%;
  background-color: red;
  transform: skew(-45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="content">
  CONTENT<br />
  Some more content
  </div>
</div></code>```

答:
One way to achieve this effect is to use a ::before pseudo-element with a clip-path applied to it.

In the example below, I have repeatedly used the values 10px and 2px though these could straightforwardly be replaced with CSS Custom Properties such as:

```<code>:root {
  --cube-depth: 10px;
  --cube-border: 2px;
}
</code>```

and then used throughout the stylesheet as var(--cube-depth) and var(--cube-border).

Working Example:

.cube {
  position: relative;
  float: left;
  margin: 0 4px 8px 4px;
  padding: 2px 2px calc(2px + 10px) calc(2px + 10px);
  color: rgb(237, 62, 68);
  box-sizing: border-box;
}

.cube::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgb(237, 62, 68);
  clip-path: polygon(10px 0, 100% 0, 100% calc(100% - 10px), calc(100% - 10px) 100%, 0 100%, 0 10px, 10px 0, 10px calc(100% - 10px), calc(100% - 2px) calc(100% - 10px), calc(100% - 2px) 2px, 10px 2px);
}

.size-80x100 {
  width: calc(100px + 10px);
  height: calc(80px + 10px);
}

.size-80x200 {
  width: calc(200px + 10px);
  height: calc(80px + 10px);
}

.size-80x360 {
  width: calc(360px + 10px);
  height: calc(80px + 10px);
}

.size-80x440 {
  width: calc(440px + 10px);
  height: calc(80px + 10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cube size-80x100">80 x 100</div>
<div class="cube size-80x440">80 x 440</div>
<div class="cube size-80x360">80 x 360</div>
<div class="cube size-80x200">80 x 200</div></code>```

Title: How to create cube window with css?

Body:
I found this image online and tryed to create these boxes with css. I failed. Has anyone an idea how to solve this problem?

This is my code. The problem is the left bar:

.box {
  position: relative;
  margin: 10px;
  display: inline-block;
}

.content {
  border-top: 2px solid red;
  border-right: 2px solid red;
  padding: 5px;
}

.box:before {
  content: '';
  position: absolute;
  top: 0;
  left: -10px;
  height: 100%;
  width: 10px;
  background-color: red;
  transform: skew(-45deg) rotate(-45deg);
}

.box:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: -5px;
  height: 10px;
  width: 100%;
  background-color: red;
  transform: skew(-45deg);
}

  CONTENT

  Some more content

Body:
One way to achieve this effect is to use a ::before pseudo-element with a clip-path applied to it.

In the example below, I have repeatedly used the values 10px and 2px though these could straightforwardly be replaced with CSS Custom Properties such as:

:root {
  --cube-depth: 10px;
  --cube-border: 2px;
}

and then used throughout the stylesheet as var(--cube-depth) and var(--cube-border).

Working Example:

.cube {
  position: relative;
  float: left;
  margin: 0 4px 8px 4px;
  padding: 2px 2px calc(2px + 10px) calc(2px + 10px);
  color: rgb(237, 62, 68);
  box-sizing: border-box;
}

.cube::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgb(237, 62, 68);
  clip-path: polygon(10px 0, 100% 0, 100% calc(100% - 10px), calc(100% - 10px) 100%, 0 100%, 0 10px, 10px 0, 10px calc(100% - 10px), calc(100% - 2px) calc(100% - 10px), calc(100% - 2px) 2px, 10px 2px);
}

.size-80x100 {
  width: calc(100px + 10px);
  height: calc(80px + 10px);
}

.size-80x200 {
  width: calc(200px + 10px);
  height: calc(80px + 10px);
}

.size-80x360 {
  width: calc(360px + 10px);
  height: calc(80px + 10px);
}

.size-80x440 {
  width: calc(440px + 10px);
  height: calc(80px + 10px);
}

<div class="cube size-80x100">80 x 100</div>
<div class="cube size-80x440">80 x 440</div>
<div class="cube size-80x360">80 x 360</div>
<div class="cube size-80x200">80 x 200</div>


问:
Javascript/ES6: Insert Group-By-element in JSON object
I receive a JSON-object from an API like thhis:

```<code>       {
    "BuchungsvorgangKategorieId": 1,
    "BuchungsvorgangKategorie": "Miete",
    "Group": "Ideeller Bereich"
    },
      {
    "BuchungsvorgangKategorieId": 2,
    "BuchungsvorgangKategorie": "Taiko-Beitrag",
    "Group": "Ideeller Bereich"
    },
   {
    "BuchungsvorgangKategorieId": 5,
    "BuchungsvorgangKategorie": "Jahresbeitrag",
    "Group": "Ideeller Bereich"
},
      {
    "BuchungsvorgangKategorieId": 3,
    "BuchungsvorgangKategorie": "Reisekosten (Auftritt)",
    "Group": "Zweckbetrieb"
    },
      {
    "BuchungsvorgangKategorieId": 4,
    "BuchungsvorgangKategorie": "Auftritt",
    "Group": "Zweckbetrieb"
    },
</code>```

Now when using a Vuetify selection there's an option to group by some header. Thus I would like to transform my result like this:

```<code>    {header: "Ideller Bereich" },
    {
    "BuchungsvorgangKategorieId": 1,
    "BuchungsvorgangKategorie": "Miete",
    "Group": "Ideeller Bereich"
    },
      {
    "BuchungsvorgangKategorieId": 2,
    "BuchungsvorgangKategorie": "Monatsbeitrag",
    "Group": "Ideeller Bereich"
    },
  {
    "BuchungsvorgangKategorieId": 5,
    "BuchungsvorgangKategorie": "Jahresbeitrag",
    "Group": "Ideeller Bereich"
  },
  {header: Zweckbetrieb },
      {
    "BuchungsvorgangKategorieId": 3,
    "BuchungsvorgangKategorie": "Reisekosten",
    "Group": "Zweckbetrieb"
    },
      {
    "BuchungsvorgangKategorieId": 4,
    "BuchungsvorgangKategorie": "Auftritt",
    "Group": "Zweckbetrieb"
    }
</code>```

I suppose I should cycle (arr.map?) through the array of objects and have a check-variable which is initially empty. Always if the current value of Group is different from the check-variable I need to update the check variable and insert the new value on the position before the current item (arr.splice?)

Update:

Thanks to the comments by @trincot and @Natixco which helped me into investigating further I was able to create this little piece of code:

```<code> let checkVariable = ""
this.FilterKategorien.forEach((item,index) => { //this.FilterKategorien contained the records from the API.
            if(item.Group!=checkVariable) {
              this.FilterKategorien.splice(index,0,{header: item.Group})
              checkVariable=item.Group
            }
          })
          console.log(this.FilterKategorien)
</code>```

答:
I would just create a new array; you can always assign it back to the original variable:

```<code>let grouped = data.reduce((acc, item, i) =>
    !i || acc[acc.length-1].Group !== item.Group
        ? acc.concat({header: item.Group}, item)
        : acc.concat(item)
, []);
</code>```

If you really need to mutate the original array, you can also use the above, and splice it into the original:

```<code>data.splice(0, data.length, ...data.reduce((acc, item, i) =>
    !i || acc[acc.length-1].Group !== item.Group
        ? acc.concat({header: item.Group}, item)
        : acc.concat(item)
, []));
</code>```

Body:
I receive a JSON-object from an API like thhis:

       {
    "BuchungsvorgangKategorieId": 1,
    "BuchungsvorgangKategorie": "Miete",
    "Group": "Ideeller Bereich"
    },
      {
    "BuchungsvorgangKategorieId": 2,
    "BuchungsvorgangKategorie": "Taiko-Beitrag",
    "Group": "Ideeller Bereich"
    },
   {
    "BuchungsvorgangKategorieId": 5,
    "BuchungsvorgangKategorie": "Jahresbeitrag",
    "Group": "Ideeller Bereich"
},
      {
    "BuchungsvorgangKategorieId": 3,
    "BuchungsvorgangKategorie": "Reisekosten (Auftritt)",
    "Group": "Zweckbetrieb"
    },
      {
    "BuchungsvorgangKategorieId": 4,
    "BuchungsvorgangKategorie": "Auftritt",
    "Group": "Zweckbetrieb"
    },

Now when using a Vuetify selection there's an option to group by some header. Thus I would like to transform my result like this:

    {header: "Ideller Bereich" },
    {
    "BuchungsvorgangKategorieId": 1,
    "BuchungsvorgangKategorie": "Miete",
    "Group": "Ideeller Bereich"
    },
      {
    "BuchungsvorgangKategorieId": 2,
    "BuchungsvorgangKategorie": "Monatsbeitrag",
    "Group": "Ideeller Bereich"
    },
  {
    "BuchungsvorgangKategorieId": 5,
    "BuchungsvorgangKategorie": "Jahresbeitrag",
    "Group": "Ideeller Bereich"
  },
  {header: Zweckbetrieb },
      {
    "BuchungsvorgangKategorieId": 3,
    "BuchungsvorgangKategorie": "Reisekosten",
    "Group": "Zweckbetrieb"
    },
      {
    "BuchungsvorgangKategorieId": 4,
    "BuchungsvorgangKategorie": "Auftritt",
    "Group": "Zweckbetrieb"
    }

I suppose I should cycle (arr.map?) through the array of objects and have a check-variable which is initially empty. Always if the current value of Group is different from the check-variable I need to update the check variable and insert the new value on the position before the current item (arr.splice?)

Update:

Thanks to the comments by @trincot and @Natixco which helped me into investigating further I was able to create this little piece of code:

 let checkVariable = ""
this.FilterKategorien.forEach((item,index) => { //this.FilterKategorien contained the records from the API.
            if(item.Group!=checkVariable) {
              this.FilterKategorien.splice(index,0,{header: item.Group})
              checkVariable=item.Group
            }
          })
          console.log(this.FilterKategorien)

Body:
I would just create a new array; you can always assign it back to the original variable:

let grouped = data.reduce((acc, item, i) =>
    !i || acc[acc.length-1].Group !== item.Group
        ? acc.concat({header: item.Group}, item)
        : acc.concat(item)
, []);

If you really need to mutate the original array, you can also use the above, and splice it into the original:

data.splice(0, data.length, ...data.reduce((acc, item, i) =>
    !i || acc[acc.length-1].Group !== item.Group
        ? acc.concat({header: item.Group}, item)
        : acc.concat(item)
, []));


问:
Formula that lookup a row and get results like textjoin from non blank cells
Hy all

I need help with a formula I want result like textjoin but without zeros in empty cell, and to combine a column  name with cell data.
below table is example of results.
with textjoin I get for eg. Jill = 0,0,2,0,0 i want to skip zeros and combine name from b2:F3 with cell data.
Tnx

答:
Using Excel's new Filter() function available in 365 versions.

```<code>=FILTER($B$2:$F$2,INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),)>0)
&" "&FILTER(INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),),INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),)>0)
</code>```

In the screenshot below, the formula has been entered into B10 and copied down to B12. It automatically spills across to the other columns where required.

Edit: This sample is based on your sample data, with positive numbers, hence the check is for number > 0. If you have negative numbers, you need to change the formula. If the cells can contain zeros, please let me know.

Formula for numbers above and below 0

```<code>=FILTER($B$2:$F$2,INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),)<>0)&" "&FILTER(INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),),INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),)<>0)
</code>```

Body:
Using Excel's new Filter() function available in 365 versions.

=FILTER($B$2:$F$2,INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),)>0)
&" "&FILTER(INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),),INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),)>0)

In the screenshot below, the formula has been entered into B10 and copied down to B12. It automatically spills across to the other columns where required.

Edit: This sample is based on your sample data, with positive numbers, hence the check is for number > 0. If you have negative numbers, you need to change the formula. If the cells can contain zeros, please let me know.

Formula for numbers above and below 0

=FILTER($B$2:$F$2,INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),)<>0)&" "&FILTER(INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),),INDEX($B$3:$F$7,MATCH(A10,$A$3:$A$7,0),)<>0)


问:
Escaping URLs in an html attribute in PHP
I am currently working with some existing code that takes a URL out of the request and inputs it into the source of an anchor. This is clearly an opening for XSS and using urlencoding doesn't retain the sanity of the url inside the anchor. I'm curious what the safest way to escape the data without breaking the link would be.

i.e.

```<code> <?
    $url = $_REQUEST['url'];
    echo '<a href="' . $url . '">sometext</a>';
?>
</code>```

答: htmlspecialchars($url) will convert the HTML-sensitive characters to their entity equivalents. However, it is possible to insert javascript snippets into urls as well -- details of which I am personally not knowledgeable of. A more complex solution such as HTML Purifier may assist you in covering most vulnerabilities.

Body:
I am currently working with some existing code that takes a URL out of the request and inputs it into the source of an anchor. This is clearly an opening for XSS and using urlencoding doesn't retain the sanity of the url inside the anchor. I'm curious what the safest way to escape the data without breaking the link would be.

i.e.

 <?
    $url = $_REQUEST['url'];
    echo 'sometext';
?>


问:
SQL for new distinct users pers day
Bit rusty on my SQL and I've spent too long trying to figure this out so thought I'd ask here :)

I'm trying to get the number of distinct NEW users per day visiting my web UI. I have goals on Monthly Active Users and want track how I am getting to this month by month. For example I want to see how many distinct users I had on 16-Jan and compares it with 16-Feb.

My first problem is how to get the number of NEW users per day. I expect to have a higher number on the first day of the month with it decreasing as the month continues.

My SQL is:

```<code>select day, count(distinct(user)) as distinct_users
from mytable
where year = 2020 and month = 2
group by day
order by day desc
</code>```

But this does not remove duplicated. For example if I visited the website on 2 days and it got logged in mytable then I would appear in both days using the SQL above. Ideally I only want to appear in the first day I appear in mytable

Consider mytable had this

```<code>day  user
----------
1    richard
1    paul
1    alexis
2    richard
2    david
</code>```

I want the query to return

```<code>day   cnt
----------
1     3    (richard, paul, alexis)
2     1    (david - no richard as he has already been returned)
</code>```

How can I remove the users that have already appeared?

Thanks

答:
You can do this with two levels of aggregation:

```<code>select day, count(*) cnt
from (select min(day) day from mytable group by user) t
group by day
order by day
</code>```

Demo on DB Fiddle:

```
day | cnt
--: | --:
  1 |   3
  2 |   1
```

There is no need to join again the original table in the outer query: this makes the query more expensive, whithout adding significant value.

Title: SQL for new distinct users pers day

Body:
Bit rusty on my SQL and I've spent too long trying to figure this out so thought I'd ask here :)

I'm trying to get the number of distinct NEW users per day visiting my web UI. I have goals on Monthly Active Users and want track how I am getting to this month by month. For example I want to see how many distinct users I had on 16-Jan and compares it with 16-Feb.

My first problem is how to get the number of NEW users per day. I expect to have a higher number on the first day of the month with it decreasing as the month continues.

My SQL is:

select day, count(distinct(user)) as distinct_users
from mytable
where year = 2020 and month = 2
group by day
order by day desc

But this does not remove duplicated. For example if I visited the website on 2 days and it got logged in mytable then I would appear in both days using the SQL above. Ideally I only want to appear in the first day I appear in mytable

Consider mytable had this

day  user
----------
1    richard
1    paul
1    alexis
2    richard
2    david

I want the query to return

day   cnt
----------
1     3    (richard, paul, alexis)
2     1    (david - no richard as he has already been returned)

How can I remove the users that have already appeared?

Thanks

Body:
You can do this with two levels of aggregation:

select day, count(*) cnt
from (select min(day) day from mytable group by user) t
group by day
order by day

Demo on DB Fiddle:

day | cnt
--: | --:
  1 |   3
  2 |   1

There is no need to join again the original table in the outer query: this makes the query more expensive, whithout adding significant value.


问:
Ajax post request (HTML to Express app) not working
I am building a node express app for storing recipes. Via a 'new recipe' html form, users can add as many ingredients as they need, which are dynamically displayed via jquery and stored in an 'ingredients' array. Because I can't send this array via HTTP, I'm trying to send a new recipe object via an AJAX post request. I have limited experience with AJAX, and I cannot understand why the post request is not working at all. Here's my front end jquery:

```<code>script type="text/javascript">
    //$(document).ready(() => alert("Jquery works!"));
    $(document).ready(() => {
        $("#addIngBtn").click(() => {
            let ingredient = $("#ingredient").val();
            let quantity = $("#quantity").val();
            $("#ingredient").val(""); //reset ingredient input
            $("#quantity").val("");
            $("ul").append(
                "<li>" + ingredient + " - " + quantity + "</li>"
            );
        });
    })

    $("#newRecipeForm").submit(() => {
        event.preventDefault();
        var ingredients = [];
        $("#ingredientListUL li").each((index, element) =>
            ingredients.push($(element).text())
        )
        var recipe = {
            name: $("#name").val(),
            image: $("#image").val(),
            oneLiner: $("#oneLiner").val(),
            method: $("#method").val(),
            ingredients: ingredients
        }
        $.ajax({
            url: "/recipes",
            type: "POST",
            dataType: "json",
            data: recipe,
            contentType: "application/json",
            complete: function () {
                console.log("process complete");
            },
            success: function (data) {
                console.log(data);
                console.log("process success");
            },
            error: function () {
                console.log(err);
            }
        })

    })
</code>```

And my backend:

```<code>// note, this is in router file where default route "/" is equivalent to "/recipes"
router.post("/", (req, res) => {
    console.log(req.body.recipe);

})

</code>```

What am I doing wrong?

答:
Not an expert here, but the data your are sending doesn't contain the recipe key. In your backend (haha) try </p>

```<code>router.post("/", (req, res) => {
    console.log(req.body.name);
})
</code>```

Body:
I am building a node express app for storing recipes. Via a 'new recipe' html form, users can add as many ingredients as they need, which are dynamically displayed via jquery and stored in an 'ingredients' array. Because I can't send this array via HTTP, I'm trying to send a new recipe object via an AJAX post request. I have limited experience with AJAX, and I cannot understand why the post request is not working at all. Here's my front end jquery:

script type="text/javascript">
    //$(document).ready(() => alert("Jquery works!"));
    $(document).ready(() => {
        $("#addIngBtn").click(() => {
            let ingredient = $("#ingredient").val();
            let quantity = $("#quantity").val();
            $("#ingredient").val(""); //reset ingredient input
            $("#quantity").val("");
            $("ul").append(
                "
" + ingredient + " - " + quantity + "
"
            );
        });
    })

    $("#newRecipeForm").submit(() => {
        event.preventDefault();
        var ingredients = [];
        $("#ingredientListUL li").each((index, element) =>
            ingredients.push($(element).text())
        )
        var recipe = {
            name: $("#name").val(),
            image: $("#image").val(),
            oneLiner: $("#oneLiner").val(),
            method: $("#method").val(),
            ingredients: ingredients
        }
        $.ajax({
            url: "/recipes",
            type: "POST",
            dataType: "json",
            data: recipe,
            contentType: "application/json",
            complete: function () {
                console.log("process complete");
            },
            success: function (data) {
                console.log(data);
                console.log("process success");
            },
            error: function () {
                console.log(err);
            }
        })

    })

And my backend:

// note, this is in router file where default route "/" is equivalent to "/recipes"
router.post("/", (req, res) => {
    console.log(req.body.recipe);

})

What am I doing wrong?

Body:
Not an expert here, but the data your are sending doesn't contain the recipe key. In your backend (haha) try

router.post("/", (req, res) => {
    console.log(req.body.name);
})


问:
crate name has a dash : unresolved import error
Probably a very rookie question (I'm not much of a rust developer).

The source file has

```<code>use rustc_hash::FxHashMap;
</code>```

and the parent directory contains Cargo.toml that includes

```<code>[dependencies]
rustc-hash = "1.0"
</code>```

When I run cargo build in that parent directory, it seems to install rustc-hash, but I still get this error as if no dependencies were specified.

```<code>error[E0432]: unresolved import `rustc_hash`
...
maybe a missing crate `rustc_hash`?
</code>```

On the other hand, when I try to use an underscore

```<code>[dependencies]
rustc_hash = "1.0"
</code>```

cargo can't find this crate:

```<code>location searched: registry `https://github.com/rust-lang/crates.io-index`
perhaps you meant: rustc-hash
</code>```

What am I doing wrong?

答:
rustc-hash is the correct way to declare the rustc-hash crate in your dependencies.

Ex:

rustc-hash = { version = "1.0", default-features = false }

In your source code(lib.rs and/or main.rs) you need to declare extern crate rustc_hash;, followed by the relevant use statements.

Ex:

extern crate rustc_hash;
use rustc_hash::FxHashMap;
```

Body:
Probably a very rookie question (I'm not much of a rust developer).

The source file has

use rustc_hash::FxHashMap;

and the parent directory contains Cargo.toml that includes

[dependencies]
rustc-hash = "1.0"

When I run cargo build in that parent directory, it seems to install rustc-hash, but I still get this error as if no dependencies were specified.

error[E0432]: unresolved import `rustc_hash`
...
maybe a missing crate `rustc_hash`?

On the other hand, when I try to use an underscore

[dependencies]
rustc_hash = "1.0"

cargo can't find this crate:

location searched: registry `https://github.com/rust-lang/crates.io-index`
perhaps you meant: rustc-hash

What am I doing wrong?


问:
How to convert CSV to JSON-Python
I am having trouble converting a url from a csv file to json, change whatever changes anything always shows me the following error:

Traceback (most recent call last):
    File "c:/Users/Gamer/Downloads/TimingReady/PC/archivos/prueba.py", line 8, in
      with open(csvUrl) as csvFile:
  OSError: [Errno 22] Invalid argument: 'http://localhost/_144141/api/0WUFVJB4ZTBENW5F6JT3QAUV4ASMRH10.csv'

My code is as follows:

```<code>            import csv
            import json

            csvUrl = input("Paste the event URL: ")
            jsonFinal = "jsonEvento.json"

            data = {}
            with open(csvUrl) as csvFile:
                csvReader = csv.DictReader(csvFile)
                for csvRow in csvReader:
                    Place = csvRow["Place"]
                    data[Place] = csvRow

            root = {}
            roo["Participantes"] = data

            with open(jsonFinal, "w") as jsonFile:
                jsonFile.write(json.dumps(root, indent=4))
</code>```

And the CSV file is as follows:

"Place";"Chip";"Numero";"Apellido";"Nombre";"Tiempo"
  "1.";"739";"139";"MARTINEZ GUTIERREZ";"JOSE";"00:30:12,91"
  "2.";"707";"107";"SUAREZ MORERA";"DANIEL";"02:00:17,54"
  "3.";"1686";"274";"RODRIGUEZ VARGAS";"JOSE LUIS";"02:01:09,09"
  "4.";"761";"161";"GONZALEZ MORENO";"MAURICIO ALBERTO";"02:03:18,29"
  "5.";"775";"175";"HERNANDEZ";"ALEJANDRO";"02:05:05,93"
  "6.";"1709";"297";"CASTILLO";"JOSE GREGORIO";"02:09:51,26"
  "7.";"721";"121";"TELLEZ CRUZ";"CARLOS ALBERTO";"02:11:08,34"
  "8.";"1711";"299";"MEDINA JARAMILLO";"JEFERSON";"02:12:26,48"
  "9.";"766";"166";"JIMENEZ";"FRANCE ELIAS";"02:12:44,48"
  "10.";"1671";"259";"GOMEZ PRIETO";"JEAN JENNER";"02:14:03,54"
  "11.";"778";"178";"CAMPO SARMIENTO";"JOSE FRANCISCO";"02:15:45,05"
  "12.";"1702";"290";"BUITRAGO HERNANDEZ";"NORBEY";"02:15:45,49"

Which I need in JSON like this

```<code>            {
                "nombreEvento": "Intercontinental Sunset Cartagena",
                "participantes": [
                    {
                    "Apellido": "MARTINEZ GUTIERREZ",
                    "Chip": 739,
                    "Nombre": "JOSE",
                    "Numero": 139,
                    "Place": "1.",
                    "Tiempo": "00:30:12,91"
                    },
                    {
                    "Apellido": "SUAREZ MORERA",
                    "Chip": 707,
                    "Nombre": "DANIEL",
                    "Numero": 107,
                    "Place": "2.",
                    "Tiempo": "02:00:17,54"
                    },
                    {
                    "Apellido": "RODRIGUEZ VARGAS",
                    "Chip": 1686,
                    "Nombre": "JOSE LUIS",
                    "Numero": 274,
                    "Place": "3.",
                    "Tiempo": "02:01:09,09"
                    }
                ]
            }
</code>```

I want to make Python stream the csv file in real time to json.

答:
What I can read from your error message is that your code can't access the file. This is because the open() function can only read/write files from your local drive. If you want to get a file from an api for example (even if it's localhost) you need another package to do so. Checkout this guide in order to get the csv file you need: https://www.powercms.in/blog/how-get-json-data-remote-url-python-script

I would advise when coding to create the app step by step. So first start with getting the csv to load, by printing it to your console. Once that is working continue on to translating it to a json format.

Updated final solution for this specific case:

```<code>import csv
import json
from io import StringIO
from urllib.request import urlopen

url = input("Pega aqui la URL de RaceResult: ")
data = []
final = {}

csvfile = urlopen(url).read().decode('ascii', 'ignore')
datafile = StringIO(csvfile)

csvReader = csv.DictReader(datafile, delimiter=';')
for csvRow in csvReader:
    print(csvRow)
    data.append(csvRow)

final['nombreEvento'] = "Intercontinental Sunset Cartagena"
final['participantes'] = data
jsonFinal = "jsonEvento.json"
with open(jsonFinal, "w") as jsonFile:
   jsonFile.write(json.dumps(final, indent=4))
</code>```

Title: How to convert CSV to JSON-Python

Body:
I am having trouble converting a url from a csv file to json, change whatever changes anything always shows me the following error:

Traceback (most recent call last):
    File "c:/Users/Gamer/Downloads/TimingReady/PC/archivos/prueba.py", line 8, in
      with open(csvUrl) as csvFile:
  OSError: [Errno 22] Invalid argument: 'http://localhost/_144141/api/0WUFVJB4ZTBENW5F6JT3QAUV4ASMRH10.csv'

My code is as follows:

            import csv
            import json

            csvUrl = input("Paste the event URL: ")
            jsonFinal = "jsonEvento.json"

            data = {}
            with open(csvUrl) as csvFile:
                csvReader = csv.DictReader(csvFile)
                for csvRow in csvReader:
                    Place = csvRow["Place"]
                    data[Place] = csvRow

            root = {}
            roo["Participantes"] = data

            with open(jsonFinal, "w") as jsonFile:
                jsonFile.write(json.dumps(root, indent=4))

And the CSV file is as follows:

"Place";"Chip";"Numero";"Apellido";"Nombre";"Tiempo"
  "1.";"739";"139";"MARTINEZ GUTIERREZ";"JOSE";"00:30:12,91"
  "2.";"707";"107";"SUAREZ MORERA";"DANIEL";"02:00:17,54"
  "3.";"1686";"274";"RODRIGUEZ VARGAS";"JOSE LUIS";"02:01:09,09"
  "4.";"761";"161";"GONZALEZ MORENO";"MAURICIO ALBERTO";"02:03:18,29"
  "5.";"775";"175";"HERNANDEZ";"ALEJANDRO";"02:05:05,93"
  "6.";"1709";"297";"CASTILLO";"JOSE GREGORIO";"02:09:51,26"
  "7.";"721";"121";"TELLEZ CRUZ";"CARLOS ALBERTO";"02:11:08,34"
  "8.";"1711";"299";"MEDINA JARAMILLO";"JEFERSON";"02:12:26,48"
  "9.";"766";"166";"JIMENEZ";"FRANCE ELIAS";"02:12:44,48"
  "10.";"1671";"259";"GOMEZ PRIETO";"JEAN JENNER";"02:14:03,54"
  "11.";"778";"178";"CAMPO SARMIENTO";"JOSE FRANCISCO";"02:15:45,05"
  "12.";"1702";"290";"BUITRAGO HERNANDEZ";"NORBEY";"02:15:45,49"

Which I need in JSON like this

            {
                "nombreEvento": "Intercontinental Sunset Cartagena",
                "participantes": [
                    {
                    "Apellido": "MARTINEZ GUTIERREZ",
                    "Chip": 739,
                    "Nombre": "JOSE",
                    "Numero": 139,
                    "Place": "1.",
                    "Tiempo": "00:30:12,91"
                    },
                    {
                    "Apellido": "SUAREZ MORERA",
                    "Chip": 707,
                    "Nombre": "DANIEL",
                    "Numero": 107,
                    "Place": "2.",
                    "Tiempo": "02:00:17,54"
                    },
                    {
                    "Apellido": "RODRIGUEZ VARGAS",
                    "Chip": 1686,
                    "Nombre": "JOSE LUIS",
                    "Numero": 274,
                    "Place": "3.",
                    "Tiempo": "02:01:09,09"
                    }
                ]
            }

I want to make Python stream the csv file in real time to json.

Body:
What I can read from your error message is that your code can't access the file. This is because the open() function can only read/write files from your local drive. If you want to get a file from an api for example (even if it's localhost) you need another package to do so. Checkout this guide in order to get the csv file you need: https://www.powercms.in/blog/how-get-json-data-remote-url-python-script

I would advise when coding to create the app step by step. So first start with getting the csv to load, by printing it to your console. Once that is working continue on to translating it to a json format.

Updated final solution for this specific case:

import csv
import json
from io import StringIO
from urllib.request import urlopen

url = input("Pega aqui la URL de RaceResult: ")
data = []
final = {}

csvfile = urlopen(url).read().decode('ascii', 'ignore')
datafile = StringIO(csvfile)

csvReader = csv.DictReader(datafile, delimiter=';')
for csvRow in csvReader:
    print(csvRow)
    data.append(csvRow)

final['nombreEvento'] = "Intercontinental Sunset Cartagena"
final['participantes'] = data
jsonFinal = "jsonEvento.json"
with open(jsonFinal, "w") as jsonFile:
   jsonFile.write(json.dumps(final, indent=4))


问:
QtCOAP is missing DTLS Support on Mac OS-X
I want to play around with the QtCOAP plugin. Unfortunately the DTLS support is missing on my OS-X Catalina. All I got is this error:

qt.coap.connection: DTLS is disabled, falling back to QtCoap::NoSecurity mode.

I have fully installed Qt 5.14.1 (with sources) with the online installer and compiled the COAP Plugin afterwards by myself with the prebuilt qmake.

The DTLS specific parts in the QtCoap code are wrapped within #if QT_CONFIG(dtls) (qcoapqudpconnection_p.h) blocks. Which seems to be evaluated to false.

What can I do to enable DTLS support?

答:
From a quick look at the sources, it seems that DTLS is currently only available using OpenSSL. By default Qt is built using the SecureTranport framework on macOS which is the official cryptographic library for that OS.

You can rebuild the qtbase module to use OpenSSL instead but ensure to install the latest version of the 1.1 series.

You can use either macports or brew to get OpenSSL.


问:
Formatting Date Output Hash
The output from my hash is giving me the following date time:

```<code>16 May 11 13:12:14 +0000
</code>```

How do I go about formatting this into something sensible?

Thanks

答:
I'll assume you are wanting this output in a view... First, you can create some formats:

```<code># /config/locales/en.yml:
en:
  date:
    formats:
      full: "%b %d, %Y"

  time:
    formats:
      full: "%B %d, %Y at %I:%M%p"
</code>```

Then you can display a datetime in a view using the l method with specified format:

```<code><%= l @something.updated_at, :format => :full %>
</code>```

This would display something like the following:

```<code>May 16, 2011 at 01:12pm
</code>```

More on the i18n formats

List of available directives

Title: Formatting Date Output Hash

Body:
The output from my hash is giving me the following date time:

16 May 11 13:12:14 +0000

How do I go about formatting this into something sensible?

Thanks

Body:
I'll assume you are wanting this output in a view... First, you can create some formats:

# /config/locales/en.yml:
en:
  date:
    formats:
      full: "%b %d, %Y"

  time:
    formats:
      full: "%B %d, %Y at %I:%M%p"

Then you can display a datetime in a view using the l method with specified format:

<%= l @something.updated_at, :format => :full %>

This would display something like the following:

May 16, 2011 at 01:12pm

More on the i18n formats

List of available directives


问:
Putting Custom CSS into Laravel 6
I put my css in the public folder and linked to it in my template, but the css won't work. When I run the file out of Laravel using HTML index, it works fine. But, when I put it in Laravel it won't see the css.

This is my code in the template:

```<code><link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/media.css">
</code>```

Do I need to add anything to make it blade/laravel specific?

答:
can you confirm the CSS files are not reached by the browser ?
If not, maybe the css folder is not in your public folder :
public/css/style.css
This way it should works fine.</p>

Title: Putting Custom CSS into Laravel 6

Body:
I put my css in the public folder and linked to it in my template, but the css won't work. When I run the file out of Laravel using HTML index, it works fine. But, when I put it in Laravel it won't see the css.

This is my code in the template:

<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/media.css">

Do I need to add anything to make it blade/laravel specific?


问:
Can I make the output of a lambda function depend on conditionals without declaring a function to handle it?
I've been going through the Python tutorial on docs.python.org, and I just learned I could generate a list containing squared numbers by doing

```<code>lista1 = list(map(lambda x: x**2, range(19)))
</code>```

While trying this out I thought of writing something similar that would fill the list with x -> x when x is even, and with x -> x**3 when x is odd. I wanted to do it using lambda functions again, so I tried

```<code>lista1 = list(map(lambda x:
              if x % 2 == 0:
              x
              else:
              x***3, range(19)))
</code>```

I found out that sadly this isn't valid Python syntax. I know I could do this instead and it works because I tried:

```<code>def funcx(x):
if x % 2 == 0:
    return x
else:
    return x**3

lista4 = list(map(lambda x: funcx(x), range(19)))
</code>```

But I was wondering if I can do it without defining funcx(x), just using lambda functions.

Thank you!

答:
A lambda must be an expression that can be evaluated. They cannot contain any statement.

Luckily, Python has a ternary operator that allows you to express the "lambda" in your second snippet as

```<code>lambda x: (x) if (x % 2 == 0) else (x**3)
</code>```

(The parenthesis here are in fact unnecessary, but are included to make the syntax at play more clear.)

However, in this case, lambda's and map are not the most appropriate tool for the job. A better (more efficient) solution would make use of a list comprehension:

```<code>lista4 = [(x if x % 2 == 0 else x**3) for x in range(19)]
</code>```

Using this approach, we save the overhead of repetitive function calls and convey our intent much more clearly.

As a side note, the lambda in your second code snippet is superfluous. The expression lambda x: func(x) can be replaced by simply func. For instance,

```<code>map(lambda x: funcx(x), range(19))
</code>```

is the same as

```<code>map(funcx, range(19))
</code>```

only with added overhead and obscurity.

Body:
I've been going through the Python tutorial on docs.python.org, and I just learned I could generate a list containing squared numbers by doing

lista1 = list(map(lambda x: x**2, range(19)))

While trying this out I thought of writing something similar that would fill the list with x -> x when x is even, and with x -> x**3 when x is odd. I wanted to do it using lambda functions again, so I tried

lista1 = list(map(lambda x:
              if x % 2 == 0:
              x
              else:
              x***3, range(19)))

I found out that sadly this isn't valid Python syntax. I know I could do this instead and it works because I tried:

def funcx(x):
if x % 2 == 0:
    return x
else:
    return x**3

lista4 = list(map(lambda x: funcx(x), range(19)))

But I was wondering if I can do it without defining funcx(x), just using lambda functions.

Thank you!

Body:
A lambda must be an expression that can be evaluated. They cannot contain any statement.

Luckily, Python has a ternary operator that allows you to express the "lambda" in your second snippet as

lambda x: (x) if (x % 2 == 0) else (x**3)

(The parenthesis here are in fact unnecessary, but are included to make the syntax at play more clear.)

However, in this case, lambda's and map are not the most appropriate tool for the job. A better (more efficient) solution would make use of a list comprehension:

lista4 = [(x if x % 2 == 0 else x**3) for x in range(19)]

Using this approach, we save the overhead of repetitive function calls and convey our intent much more clearly.

As a side note, the lambda in your second code snippet is superfluous. The expression lambda x: func(x) can be replaced by simply func. For instance,

map(lambda x: funcx(x), range(19))

is the same as

map(funcx, range(19))

only with added overhead and obscurity.


问:
Interactive input of a Makefile variable
I want to run makefile with input variable. What I want is that if I write down the project name, a folder with that name will be created.

So I write read command:

```<code>CC = gcc
CFLAGS = -W -Wall
FILE := hi
src = $(wildcard *.c)
OBJ = $(src:.c=.o)

all : $(FILE)
$(FILE) : $(OBJ)
    $(CC) $(CFLAGS) -o $@ $^

.PHONY: clean

clean :
    rm *.o $(FILE)

move :
    mkdir -p ../../bin/$(FILE);
    mkdir -p ../../exe/$(FILE);
    mv *.o ../../bin/$(FILE);
    mv $(FILE) ../../exe/$(FILE)

afterclean :
    rm ../../bin/$(FILE)/*.o;
    rm ../../exe/$(FILE)/$(FILE)

execute :
    ./../../exe/$(FILE)/$(FILE)

read :
    @read -p "Enter : " enter; \
    $(FILE) := enter; \
    echo $FILE
</code>```

What I wanna do is if I get FILE name through read I want to change FILE variable, but I can't change it. How can I do that?

答:
Well in short, you cannot easily do that (and you should likely not want to, scroll down for rationale). If you have a closer look at your Makefile you'd notice that you're mixing make and shell syntax... and their contexts.

In your case, it literally passes the following string to shell (value of SHELL, likely defaults to /bin/sh) with -c:

```<code>read -p "Enter : " enter; \
hi := enter; \
echo ILE
</code>```

Which shows the effects of the intermixed syntax. $(FILE) (value hi) and $F (unset -> empty) are make variables substituted by make before invoking shell. (while read into enter variable is not used at all and instead literal string enter is used in attempted make variable assignment inside that running shell.)

If you wanted to run a shell command and assign a value from what it has done / learned to a make variable, you would have to do so using shell function (or generate a (temporary) file you would include, but that's even messier):

```<code>FILE := $(shell read -p "Enter: " enter ; echo $${enter})
</code>```

That however always asks... unless you use conditional assignment (?=) in which case you could choose already from the command line (make FILE=something, at which point we're about to close the circle). I am generally unsure what your intentions were how to tell make when to ask and when to use default value of hi.

That leads me to why this notion sounds suspect to me to start with and why suggestion made by @HolyBlackCat is a superior way of customizing invocation of make.

Also any runtime user interactions generally break automation (which is what we have make for) and also make builds non-reproducible. So, they better are to be avoided.

In other words, if you really had to, I'd say write an interactive_make_call.sh around it for this type of invocation:

```<code>#!/bin/bash
read -p "Enter : " enter
make FILE="${enter}" "$@"
</code>```

Or even:

```<code>#!/bin/bash
read -p "Enter : " enter
if [[ -n "${enter}" ]] ; then
        make FILE="${enter}" "$@"
else
        make "$@"
fi
</code>```

To fallback on the default value of FILE from the Makefile if you just press enter.

Body:
I want to run makefile with input variable. What I want is that if I write down the project name, a folder with that name will be created.

So I write read command:

CC = gcc
CFLAGS = -W -Wall
FILE := hi
src = $(wildcard *.c)
OBJ = $(src:.c=.o)

all : $(FILE)
$(FILE) : $(OBJ)
    $(CC) $(CFLAGS) -o $@ $^

.PHONY: clean

clean :
    rm *.o $(FILE)

move :
    mkdir -p ../../bin/$(FILE);
    mkdir -p ../../exe/$(FILE);
    mv *.o ../../bin/$(FILE);
    mv $(FILE) ../../exe/$(FILE)

afterclean :
    rm ../../bin/$(FILE)/*.o;
    rm ../../exe/$(FILE)/$(FILE)

execute :
    ./../../exe/$(FILE)/$(FILE)

read :
    @read -p "Enter : " enter; \
    $(FILE) := enter; \
    echo $FILE

What I wanna do is if I get FILE name through read I want to change FILE variable, but I can't change it. How can I do that?

Body:
Well in short, you cannot easily do that (and you should likely not want to, scroll down for rationale). If you have a closer look at your Makefile you'd notice that you're mixing make and shell syntax... and their contexts.

In your case, it literally passes the following string to shell (value of SHELL, likely defaults to /bin/sh) with -c:

read -p "Enter : " enter; \
hi := enter; \
echo ILE

Which shows the effects of the intermixed syntax. $(FILE) (value hi) and $F (unset -> empty) are make variables substituted by make before invoking shell. (while read into enter variable is not used at all and instead literal string enter is used in attempted make variable assignment inside that running shell.)

If you wanted to run a shell command and assign a value from what it has done / learned to a make variable, you would have to do so using shell function (or generate a (temporary) file you would include, but that's even messier):

FILE := $(shell read -p "Enter: " enter ; echo $${enter})

That however always asks... unless you use conditional assignment (?=) in which case you could choose already from the command line (make FILE=something, at which point we're about to close the circle). I am generally unsure what your intentions were how to tell make when to ask and when to use default value of hi.

That leads me to why this notion sounds suspect to me to start with and why suggestion made by @HolyBlackCat is a superior way of customizing invocation of make.

Also any runtime user interactions generally break automation (which is what we have make for) and also make builds non-reproducible. So, they better are to be avoided.

In other words, if you really had to, I'd say write an interactive_make_call.sh around it for this type of invocation:

#!/bin/bash
read -p "Enter : " enter
make FILE="${enter}" "$@"

Or even:

#!/bin/bash
read -p "Enter : " enter
if [[ -n "${enter}" ]] ; then
        make FILE="${enter}" "$@"
else
        make "$@"
fi

To fallback on the default value of FILE from the Makefile if you just press enter.


问:
Flash Button (Creating a menu page with flash buttons to open SWF Files)
Good day to everyone. I'm here today to seek help about Flash CS4 and ActionScript 3.0. The story starts when one day, my boss asked me to make a flash presentation about their upcoming user training for a newly developed software. I was enthusiastic and excited about it because it's been a long time that I did not use Flash (note that I don't have any experience in ActionScript 3.0). At first, everything was a bit rough as I need to recall how to properly use the frames to create a successful animation. As I was about to finish the project, my boss approached me again and asked if I could insert a menu page in front so that the users won't have to replay the whole thing again just to look for a little something on that part of the movie. So yea, at first I was abit hesitant to accept. I said that it will work with Powerpoint. But she's a total pusher and I was forced to say yes. Now I'm having this problem about how to make a flash button load a swf movie. I've tried searching all over the net for tutorials but most of the times the "getUrl" and other stuff are said to be outdated. Help please?</p>

答:
This answer is based on my interpretation of your question, which is: "Can I create an SWF that acts as a menu, and load in different SWF files based on what the user clicks in the menu?".

The answer is of course yes, and here's how:

A few things you need to understand / look at:

Loader and URLRequest classes.

Event Listeners for buttons.

Here's a function to load your SWF:

```<code>var loadedSWF:Loader = null;

/**
 * Loads an SWF and adds it to container once complete
 * @param file The URL to the SWF to load
 * @param container The container to add the SWF to
 */
function loadSWF(file:String, container:MovieClip=null):void
{
    if(container == null) container = MovieClip(root);

    // removes the previously loaded SWF
    if(loadedSWF != null)
    {
        if(loadedSWF.parent) loadedSWF.parent.removeChild(loadedSWF);
    }

    var req:URLRequest = new URLRequest(file);
    loadedSWF = new Loader();
    loadedSWF.load(req);

    addChild(loadedSWF);
}
</code>```

And here's how to use this function when you click a button:

```<code>mybutton.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent):void
{
    loadSWF("myfile1.swf");
}
</code>```

As per question in comments:

You could use navigateToURL() instead of a Loader and set up your external SWFs on different pages (like a website basically). If you're going to do this it might even make more sense to keep your main index page just plain HTML and launch your pages in new windows. If you still want to have your main page as flash then clicking through to a page in a new window is done like this:

```<code>button.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent):void
{
    var req:URLRequest = new URLRequest("somepage.html");
    navigateToURL(req, "_blank");
}
</code>```

Body:
This answer is based on my interpretation of your question, which is: "Can I create an SWF that acts as a menu, and load in different SWF files based on what the user clicks in the menu?".

The answer is of course yes, and here's how:

A few things you need to understand / look at:

Loader and URLRequest classes.

Event Listeners for buttons.

Here's a function to load your SWF:

var loadedSWF:Loader = null;

/**
 * Loads an SWF and adds it to container once complete
 * @param file The URL to the SWF to load
 * @param container The container to add the SWF to
 */
function loadSWF(file:String, container:MovieClip=null):void
{
    if(container == null) container = MovieClip(root);

    // removes the previously loaded SWF
    if(loadedSWF != null)
    {
        if(loadedSWF.parent) loadedSWF.parent.removeChild(loadedSWF);
    }

    var req:URLRequest = new URLRequest(file);
    loadedSWF = new Loader();
    loadedSWF.load(req);

    addChild(loadedSWF);
}

And here's how to use this function when you click a button:

mybutton.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent):void
{
    loadSWF("myfile1.swf");
}

As per question in comments:

You could use navigateToURL() instead of a Loader and set up your external SWFs on different pages (like a website basically). If you're going to do this it might even make more sense to keep your main index page just plain HTML and launch your pages in new windows. If you still want to have your main page as flash then clicking through to a page in a new window is done like this:

button.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent):void
{
    var req:URLRequest = new URLRequest("somepage.html");
    navigateToURL(req, "_blank");
}


问:
How do I capture a tap on a custom card view in a ZStack?
I'm trying pretty hard to recreate something like the Wallet view, but cannot really figure it out. I've hard-coded offsets into my ZStack, but of course I want to avoid that too. It seems like the offsets are keeping the taps from registering at all. Here is my code so far, tapping a card should change its title's colour between white and yellow.

Eventually, of course, I want to add animations to the stack of cards and be able to "pull" one from it place to make it the primary view. But I have to figure out how to catch the taps first...

I used this video as a base, but it doesn't really go as far as I'd like:

https://nsscreencast.com/episodes/399-swiftui-transforms-and-animations

```<code>import SwiftUI

struct BetterCards: View {
    var body: some View {

        ScrollView (.vertical) {
                ZStack {
                    CardView(title: "adidas", color: .blue, offset: 0.0)
                    CardView(title: "Le Crueset", color: .pink, offset: 90.0)
                    CardView(title: " Card", color: .black, offset: 180.0)
                    CardView(title: "Sandusk", color: .orange, offset: 270.0)
            }
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    let offset: CGFloat

    var body: some View {

        Button(action: {
            self.isYellow.toggle()
        }) {
            ZStack {
                 Rectangle()
                    .fill(color)
                    .cornerRadius(10)
                    .frame(width: 320, height: 210)
                VStack {
                    Text(title)
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(isYellow ? .yellow : .white)
                        .padding()
                    Spacer()
                }

            }.shadow(radius: 2.0)
            .offset(x: 0, y: offset)

            }.onTapGesture {
            print("Tapped: \(self.title)")
        }
    }
}

struct BetterCards_Previews: PreviewProvider {
    static var previews: some View {
        BetterCards()
    }
}
</code>```

答:
I don't think you need both a Button and an onTapGesture on the same view. Your CardView is already a button, so it will register tap gestures. In order for it to function properly, I suggest you move the offset on the button itself. Also looks like it will register taps on all the views only if it has a sufficient height, so I set a frame on the button after setting an offset.
Overall the code would look something like this:

import SwiftUI

struct BetterCards: View {
    var body: some View {

        ScrollView (.vertical) {
            ZStack(alignment: .top) {
                CardView(title: "adidas", color: .blue, offset: 0.0)
                CardView(title: "Le Crueset", color: .pink, offset: 90.0)
                CardView(title: " Card", color: .black, offset: 180.0)
                CardView(title: "Sandusk", color: .orange, offset: 270.0)
            }
        .padding()
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    let offset: CGFloat

    var body: some View {

        Button(action: {
            self.isYellow.toggle()
            print("Tapped: \(self.title)")
        }) {
            ZStack {
                Rectangle()
                    .fill(color)
                    .cornerRadius(10)
                    .frame(width: 320, height: 210)
                VStack {
                    Text(title)
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(isYellow ? .yellow : .white)
                        .padding()
                    Spacer()
                }
                .frame(width: 320, height: 210)

            }
            .shadow(radius: 2.0)

        }
        .offset(x: 0, y: offset)
        .frame(width: 320, height: 210 + offset, alignment: .top)
    }

}
```

You can play with alignment and padding on different views to get what you need.

Body:
I'm trying pretty hard to recreate something like the Wallet view, but cannot really figure it out. I've hard-coded offsets into my ZStack, but of course I want to avoid that too. It seems like the offsets are keeping the taps from registering at all. Here is my code so far, tapping a card should change its title's colour between white and yellow.

Eventually, of course, I want to add animations to the stack of cards and be able to "pull" one from it place to make it the primary view. But I have to figure out how to catch the taps first...

I used this video as a base, but it doesn't really go as far as I'd like:

https://nsscreencast.com/episodes/399-swiftui-transforms-and-animations

import SwiftUI

struct BetterCards: View {
    var body: some View {

        ScrollView (.vertical) {
                ZStack {
                    CardView(title: "adidas", color: .blue, offset: 0.0)
                    CardView(title: "Le Crueset", color: .pink, offset: 90.0)
                    CardView(title: " Card", color: .black, offset: 180.0)
                    CardView(title: "Sandusk", color: .orange, offset: 270.0)
            }
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    let offset: CGFloat

    var body: some View {

        Button(action: {
            self.isYellow.toggle()
        }) {
            ZStack {
                 Rectangle()
                    .fill(color)
                    .cornerRadius(10)
                    .frame(width: 320, height: 210)
                VStack {
                    Text(title)
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(isYellow ? .yellow : .white)
                        .padding()
                    Spacer()
                }

            }.shadow(radius: 2.0)
            .offset(x: 0, y: offset)

            }.onTapGesture {
            print("Tapped: \(self.title)")
        }
    }
}

struct BetterCards_Previews: PreviewProvider {
    static var previews: some View {
        BetterCards()
    }
}

Body:
I don't think you need both a Button and an onTapGesture on the same view. Your CardView is already a button, so it will register tap gestures. In order for it to function properly, I suggest you move the offset on the button itself. Also looks like it will register taps on all the views only if it has a sufficient height, so I set a frame on the button after setting an offset.
Overall the code would look something like this:

import SwiftUI

struct BetterCards: View {
    var body: some View {

        ScrollView (.vertical) {
            ZStack(alignment: .top) {
                CardView(title: "adidas", color: .blue, offset: 0.0)
                CardView(title: "Le Crueset", color: .pink, offset: 90.0)
                CardView(title: " Card", color: .black, offset: 180.0)
                CardView(title: "Sandusk", color: .orange, offset: 270.0)
            }
        .padding()
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    let offset: CGFloat

    var body: some View {

        Button(action: {
            self.isYellow.toggle()
            print("Tapped: \(self.title)")
        }) {
            ZStack {
                Rectangle()
                    .fill(color)
                    .cornerRadius(10)
                    .frame(width: 320, height: 210)
                VStack {
                    Text(title)
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(isYellow ? .yellow : .white)
                        .padding()
                    Spacer()
                }
                .frame(width: 320, height: 210)

            }
            .shadow(radius: 2.0)

        }
        .offset(x: 0, y: offset)
        .frame(width: 320, height: 210 + offset, alignment: .top)
    }

}

You can play with alignment and padding on different views to get what you need.


问:
is there a way to write a clojure function that destructures a map and returns any portion of the map?
I would like to write a function that accepts a specific structure of a map and returns (prints out) any portion of the map I want. Is this possible?

I haven't been successful so far. The following below are the functions I wrote to print portion a, b and c of the map but i seem to be missing some logic in this whole thing.

The test map is {:nums {:test number?}}. My true goal is to return the test value i.e number? or whichever value the user wishes to test e.g symbol? or vector?. This is why I have chosen to use this method.

I wish to understand the logic that's why I have chosen to return all the parts of the map i.e a, b, c.

Thanks.

```<code>(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str a)))
  )
=> #'user/des
(des {:nums {:test number?}})
{:nums {:test #object[clojure.core$number_QMARK_ 0x1089d00e "clojure.core$number_QMARK_@1089d00e"]}}
=> nil

(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str b)))
  )
=> #'user/des
(des {:nums {:test number?}})

=> nil

(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str c)))
  )
=> #'user/des
(des {:nums {:test number?}})

=> nil
</code>```

答:
According to the comments, the problem at hand is to find the any :test key in a map of maps.  So some+vals can be used to produces such a result:

user=> (some :test (vals {:nums {:test number?}}))
#<Fn@45297e7 clojure.core/number_QMARK_>
```

This is aggressive, since it assumes, :test (as a function) can be called on each map value (at least until the result is found).

Body:
I would like to write a function that accepts a specific structure of a map and returns (prints out) any portion of the map I want. Is this possible?

I haven't been successful so far. The following below are the functions I wrote to print portion a, b and c of the map but i seem to be missing some logic in this whole thing.

The test map is {:nums {:test number?}}. My true goal is to return the test value i.e number? or whichever value the user wishes to test e.g symbol? or vector?. This is why I have chosen to use this method.

I wish to understand the logic that's why I have chosen to return all the parts of the map i.e a, b, c.

Thanks.

(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str a)))
  )
=> #'user/des
(des {:nums {:test number?}})
{:nums {:test #object[clojure.core$number_QMARK_ 0x1089d00e "clojure.core$number_QMARK_@1089d00e"]}}
=> nil

(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str b)))
  )
=> #'user/des
(des {:nums {:test number?}})

=> nil

(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str c)))
  )
=> #'user/des
(des {:nums {:test number?}})

=> nil

Body:
According to the comments, the problem at hand is to find the any :test key in a map of maps.  So some+vals can be used to produces such a result:

user=> (some :test (vals {:nums {:test number?}}))
#<Fn@45297e7 clojure.core/number_QMARK_>

This is aggressive, since it assumes, :test (as a function) can be called on each map value (at least until the result is found).


问:
What is the simplest way to get the least value and second least value from multiple columns (MIN function does not work this)?
Below table is from Teradata database

```<code>SELECT
  sku.Item_id,
  sku.Item_length,
  sku.Item_width,
  sku.Item_heigth,
FROM  Category_item sku

Item_id | Item_length | Item_width |Item_heigth
-------------------------------------------
104174        8            6           1
9482763       8            8           8
8434610       8            9           1
2109145       54           34          2
567106        41           41          2
2028731       3            4           3
</code>```

The final result that I want is,

```<code> Item_id | Item_length | Item_width |Item_heigth | MinValue | SecondMinVale
    ---------------------------------------------------------------------------
    104174        8            6           1          1            6
    9482763       8            8           8          8            8
    8434610       8            9           1          1            8
    2109145       54           34          2          2            34
    567106        41           41          2          2            41
    2028731       3            4           3          3            3
</code>```

So I did a little research online, most of them used MIN function with a subquery or raw over by partition. Min function does not work for me, because I have three separate columns. I want to get minimum or least two values from the above three columns.

I tried to do subquery or CTE using Least function, but I am stuck with getting the second least value. I am not sure how to use raw over partition for this.

Any help regarding this will be highly appreciated.

Thank you so much!!

答:
If you actually got three columns you can simply apply this brute-force logic:

```<code>SELECT sku.*,
   Least(Item_length,Item_width,Item_height) AS MinValue,
   CASE
     WHEN Item_length BETWEEN Least(Item_width, Item_height) AND
                           Greatest(Item_width, Item_height)
     THEN Item_length
     WHEN Item_width BETWEEN Least(Item_length, Item_height) AND
                           Greatest(Item_length, Item_height)
     THEN Item_width
     WHEN Item_height BETWEEN Least(Item_width, Item_length) AND
                           Greatest(Item_width, Item_length)
     THEN Item_height
   END AS SecondMinValue
FROM  Category_item sku
</code>```

For more than three columns you need Tim's approach, this is a slight variation (if your TD release supports UNPIVOT) avoiding the join-back:

```<code>WITH cte AS
 (
   SELECT up.*
     ,Row_Number() Over (PARTITION BY item_id ORDER BY val) AS rn
   FROM Category_item
   UNPIVOT
    ( val
      FOR measure
      IN (Item_length AS 'l'
         ,Item_width  AS 'w'
         ,Item_height AS 'h')
    ) AS up
 )
SELECT
    Item_id,
    Max(CASE WHEN measure = 'l' THEN val END) AS item_length,
    Max(CASE WHEN measure = 'w' THEN val END) AS item_width,
    Max(CASE WHEN measure = 'h' THEN val END) AS item_height,
    Max(CASE WHEN rn = 1 THEN val END) AS MINVALUE,
    Max(CASE WHEN rn = 2 THEN val END) AS SecondMinValue
FROM cte
GROUP BY
    Item_id
</code>```

Body:
Below table is from Teradata database

SELECT
  sku.Item_id,
  sku.Item_length,
  sku.Item_width,
  sku.Item_heigth,
FROM  Category_item sku

Item_id | Item_length | Item_width |Item_heigth
-------------------------------------------
104174        8            6           1
9482763       8            8           8
8434610       8            9           1
2109145       54           34          2
567106        41           41          2
2028731       3            4           3

The final result that I want is,

 Item_id | Item_length | Item_width |Item_heigth | MinValue | SecondMinVale
    ---------------------------------------------------------------------------
    104174        8            6           1          1            6
    9482763       8            8           8          8            8
    8434610       8            9           1          1            8
    2109145       54           34          2          2            34
    567106        41           41          2          2            41
    2028731       3            4           3          3            3

So I did a little research online, most of them used MIN function with a subquery or raw over by partition. Min function does not work for me, because I have three separate columns. I want to get minimum or least two values from the above three columns.

I tried to do subquery or CTE using Least function, but I am stuck with getting the second least value. I am not sure how to use raw over partition for this.

Any help regarding this will be highly appreciated.

Thank you so much!!

Body:
If you actually got three columns you can simply apply this brute-force logic:

SELECT sku.*,
   Least(Item_length,Item_width,Item_height) AS MinValue,
   CASE
     WHEN Item_length BETWEEN Least(Item_width, Item_height) AND
                           Greatest(Item_width, Item_height)
     THEN Item_length
     WHEN Item_width BETWEEN Least(Item_length, Item_height) AND
                           Greatest(Item_length, Item_height)
     THEN Item_width
     WHEN Item_height BETWEEN Least(Item_width, Item_length) AND
                           Greatest(Item_width, Item_length)
     THEN Item_height
   END AS SecondMinValue
FROM  Category_item sku

For more than three columns you need Tim's approach, this is a slight variation (if your TD release supports UNPIVOT) avoiding the join-back:

WITH cte AS
 (
   SELECT up.*
     ,Row_Number() Over (PARTITION BY item_id ORDER BY val) AS rn
   FROM Category_item
   UNPIVOT
    ( val
      FOR measure
      IN (Item_length AS 'l'
         ,Item_width  AS 'w'
         ,Item_height AS 'h')
    ) AS up
 )
SELECT
    Item_id,
    Max(CASE WHEN measure = 'l' THEN val END) AS item_length,
    Max(CASE WHEN measure = 'w' THEN val END) AS item_width,
    Max(CASE WHEN measure = 'h' THEN val END) AS item_height,
    Max(CASE WHEN rn = 1 THEN val END) AS MINVALUE,
    Max(CASE WHEN rn = 2 THEN val END) AS SecondMinValue
FROM cte
GROUP BY
    Item_id


问:
Count on a UNION with Eloquent in Laravel
I have the following eloquent query:

```<code>$x = DB::table("x")->select("x.*");
$y = DB::table("x")->select("x.*");

$union = $x->union($y);
</code>```

However if I do

```<code>$union->count();
</code>```

it fails saying:

```<code>Cardinality violation: 1222 The used SELECT statements have a different number of columns
</code>```

Please, note I'm using table x twice for the union.

From what I understand it's applying the count to the first table rather than to the whole union.

答:
Try this:</p>

```<code>$x = DB::table("x")->select("x.*")->get();
$y = DB::table("x")->select("x.*")->get();

$union = $x->union($y);
</code>```

Body:
I have the following eloquent query:

$x = DB::table("x")->select("x.*");
$y = DB::table("x")->select("x.*");

$union = $x->union($y);

However if I do

$union->count();

it fails saying:

Cardinality violation: 1222 The used SELECT statements have a different number of columns

Please, note I'm using table x twice for the union.

From what I understand it's applying the count to the first table rather than to the whole union.

Body:
Try this:

$x = DB::table("x")->select("x.*")->get();
$y = DB::table("x")->select("x.*")->get();

$union = $x->union($y);


问:
Unable to make the x-zoom to work when xAxes type is different from 'time'
I'm trying to apply the zooming function on a chart I have on my website.
More or less, the actual code of the chart is the one I added in the following CodePen: https://codepen.io/leonardodaga/pen/eYNZdVV

This example works, but I'm trying to use a different xAxis type (not "time") and to format the xAxis ticks with a callback (now commented in the CodePen):

callback: function (value, index, values) {
    return Math.floor(value).toFixed(0) + '.' + (((value - Math.floor(value)) * 12).toFixed(0));
},
```

Removing type: "time" the zoom ends to work.
Is there something wrong with what I'm doing?

答:
It was my mistake, I was passing the data with a wrong format.

In codepen code above, X and Y data were passed using two different array (the first as labels). I should have passed the XY data as a single, two components array.
There is another codepen in my dashboard (Chart.js Linear Zoom example) that shows the way to beginners like me :-)

Callback for ticks was definitely not the problem.

Body:
I'm trying to apply the zooming function on a chart I have on my website.
More or less, the actual code of the chart is the one I added in the following CodePen: https://codepen.io/leonardodaga/pen/eYNZdVV

This example works, but I'm trying to use a different xAxis type (not "time") and to format the xAxis ticks with a callback (now commented in the CodePen):

callback: function (value, index, values) {
    return Math.floor(value).toFixed(0) + '.' + (((value - Math.floor(value)) * 12).toFixed(0));
},

Removing type: "time" the zoom ends to work.
Is there something wrong with what I'm doing?