答:
This is 2 questions. I can't answer the first because you don't say where the exception happens, and I don't know what you mean by "draw" the array.

For the second, your problem is here (and in similar places):

```<code>for (int column = 0; DayOfTheMonth.length < 4; column++)
</code>```

DayOfTheMonth.length will always evaluate to 3, so column will keep increasing. What you probably want is

```<code>for (int column = 0; column < DayOfTheMonth.length; column++)
</code>```

I make no claims as to whether this is the only problem.

Title: How to initialize a two-dimensional array?

Body:
This is 2 questions. I can't answer the first because you don't say where the exception happens, and I don't know what you mean by "draw" the array.

For the second, your problem is here (and in similar places):

for (int column = 0; DayOfTheMonth.length < 4; column++)

DayOfTheMonth.length will always evaluate to 3, so column will keep increasing. What you probably want is

for (int column = 0; column < DayOfTheMonth.length; column++)

I make no claims as to whether this is the only problem.


来源: stackexchange

问:
Conditional calculation based on another column
I have a cross reference table and another table with the list of "Items"

I connect "PKG" to "Item" as "PKG" has distinct values.

```<code> Example:

 **Cross table**              **Item table**
  Bulk   PKG                    Item  Value
  A        D                      A     2
  A        E                      B     1
  B        F                      C     4
  C        G                      D     5
                                  E     8
                                  F     3
                                  G     1
</code>```

After connecting the 2 above tables by PKG and ITEM i get the following result

```<code> Item  Value  Bulk  PKG
   A     2
   B     1
   C     4
   D     5      A     D
   E     8      A     E
   F     3      B     F
   G     1      C     G
</code>```

As you can see nothing shows up for the first 3 values since it is connected by pkg and those are "Bulk" values.

I am trying to create a new column that uses the cross reference table

I want to create the following with a new column

```<code>      Item  Value  Bulk  PKG   NEW COLUMN
        A     2                    5
        B     1                    3
        C     4                    1
        D     5      A     D       5.75
        E     8      A     E       9.2
        F     3      B     F       3.45
        G     1      C     G       1.15
</code>```

The new column is what I am trying to create.

I want the original values to show up for bulk as they appear for pkg.  I then want the Pkg items to be 15% higher than the original value.

How can I calculate this based on the setup?

答:
Just write a conditional custom column in the query editor:

```<code>New Column = if [Bulk] = null then [Value] else 1.15 * [Value]
</code>```

You can also do this as a DAX calculated column:

```<code>New Column = IF( ISBLANK( Table1[Bulk] ), Table1[Value], 1.15 * Table1[Value] )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a cross reference table and another table with the list of "Items"

I connect "PKG" to "Item" as "PKG" has distinct values.

 Example:

 **Cross table**              **Item table**
  Bulk   PKG                    Item  Value
  A        D                      A     2
  A        E                      B     1
  B        F                      C     4
  C        G                      D     5
                                  E     8
                                  F     3
                                  G     1

After connecting the 2 above tables by PKG and ITEM i get the following result

 Item  Value  Bulk  PKG
   A     2
   B     1
   C     4
   D     5      A     D
   E     8      A     E
   F     3      B     F
   G     1      C     G

As you can see nothing shows up for the first 3 values since it is connected by pkg and those are "Bulk" values.

I am trying to create a new column that uses the cross reference table

I want to create the following with a new column

      Item  Value  Bulk  PKG   NEW COLUMN
        A     2                    5
        B     1                    3
        C     4                    1
        D     5      A     D       5.75
        E     8      A     E       9.2
        F     3      B     F       3.45
        G     1      C     G       1.15

The new column is what I am trying to create.

I want the original values to show up for bulk as they appear for pkg.  I then want the Pkg items to be 15% higher than the original value.

How can I calculate this based on the setup?

Body:
Just write a conditional custom column in the query editor:

New Column = if [Bulk] = null then [Value] else 1.15 * [Value]

You can also do this as a DAX calculated column:

New Column = IF( ISBLANK( Table1[Bulk] ), Table1[Value], 1.15 * Table1[Value] )


问:
Entity Framework see SQL sentence when calling stored procedure

Is there a way to see the underlying SQL sentence when executing a stored procedure in Entity Framework (3.5)?

To use the stored procedure I did from the diagram: Add, Function Import… etc

Thanks

UPDATE 1

I downloaded 'AnjLab Sql Profiler' from.

http://code.google.com/p/sqlexpressprofiler/downloads/list

And was able to see that the stored procedure is executed correctly.

答: You can use any type of database profiler - for example SQL profiler for SQL server or you can use either EFTracingProvider or any EF profiler (these tools are usually commercial). Here is whole article about these techniques.</p>

ContentLicense: CC BY-SA 3.0


问:
Add spaces to Camelcase with Caps in it
I have an external app passing strings in camelcase. Users are looking to report on the string and want it formatted as a sentence. The string may have words in it with all caps that I need to add spaces around.

built out a function based on this question here: Is there any SQL Server built-in function to convert string in camel case?
however, it does not work with the all caps words. Below is my modified version.

```<code>
DECLARE @String    NVARCHAR(MAX) = 'ThisIsASentenceWithCAPTIInIt'
    --, @Len       INT         --  = LEN(@String)
      , @Delimiter CHAR(1)       = ' '
      , @Iterator  INT           = 2; --Don't put space to left of first even if it's a capital

WHILE @Iterator <= LEN(@String)
-- Iterate through string
    BEGIN
        -- Check if current character is Uppercase (lowercase = 0)
        IF PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator, 1) COLLATE Latin1_General_CS_AI) <> 0
        -- Do this if capital
            BEGIN
                -- check if the previous character is lowercase, if it is then add a space before the current character.
                IF(
                   (PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator - 1, 1) COLLATE Latin1_General_CS_AI) = 0
                    AND SUBSTRING(@String, @Iterator - 1, 1) <> ' '
                   )
                   OR PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator + 1, 1) COLLATE Latin1_General_CS_AI) = 0)
                    BEGIN
                        SET @String = STUFF(@String, @Iterator, 0, @Delimiter);
                        SET @Iterator+=1;
                END;
                -- check if the next character is lowercase, if it is then add a space before the current character.
                SET @Iterator+=1;
        END;
        ---- Don't care about current character being lowercase. Just continue iterating
        SET @Iterator+=1;
    END;

SELECT @String;
</code>```

Example of what I get from the app - "ThisIsASentenceWithCAPTIInIt"

What I want to pass back - "This Is A Sentence With CAPTI In It"

What I am getting back from my modified version - "This Is ASentence With CAPTIIn It"

答:
doing it this in SQL Server is not the best choice. also rewriting existing string can be challenging somewhat challenging.

I think there are many more way to simplify this code, but here is a version that I believe will achieve the result you are looking for.

```<code>DECLARE @String    NVARCHAR(MAX) = 'ThisIsASentenceWithCAPTIInIt'
    --, @Len       INT         --  = LEN(@String)
      , @Delimiter CHAR(1)       = ' '
      , @Iterator  INT           = 1; --Don't put space to left of first even if it's a capital

DECLARE @retval nvarchar(max) = '';

WHILE @Iterator <= LEN(@String)
-- Iterate through string
    BEGIN
        -- Check if current character is Uppercase (lowercase = 0)
        IF PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator, 1) COLLATE Latin1_General_CS_AI) <> 0
        -- Do this if capital
            BEGIN
                -- check if the previous character is lowercase, if it is then add a space before the current character.
                IF(
                   (PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator - 1, 1) COLLATE Latin1_General_CS_AI) = 0
                    AND SUBSTRING(@String, @Iterator - 1, 1) <> ' '
                   )
                   OR PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator + 1, 1) COLLATE Latin1_General_CS_AI) = 0)
                    BEGIN
                        set @retval += ' ' ;
                        --SET @String = STUFF(@String, @Iterator, 0, @Delimiter);
                        --SET @Iterator+=1;
                END;
                -- check if the next character is lowercase, if it is then add a space before the current character.
                --Set @retval += SUBSTRING(@String, @Iterator, 1);
                --SET @Iterator+=1;
            END;
        ---- Don't care about current character being lowercase. Just continue iterating
        Set @retval += SUBSTRING(@String, @Iterator, 1);
        SET @Iterator+=1;
    END;
SET @retval = Ltrim(@retval);
SELECT @retval;
</code>```

Title: Add spaces to Camelcase with Caps in it

Body:
I have an external app passing strings in camelcase. Users are looking to report on the string and want it formatted as a sentence. The string may have words in it with all caps that I need to add spaces around.

built out a function based on this question here: Is there any SQL Server built-in function to convert string in camel case?
however, it does not work with the all caps words. Below is my modified version.

DECLARE @String    NVARCHAR(MAX) = 'ThisIsASentenceWithCAPTIInIt'
    --, @Len       INT         --  = LEN(@String)
      , @Delimiter CHAR(1)       = ' '
      , @Iterator  INT           = 2; --Don't put space to left of first even if it's a capital

WHILE @Iterator <= LEN(@String)
-- Iterate through string
    BEGIN
        -- Check if current character is Uppercase (lowercase = 0)
        IF PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator, 1) COLLATE Latin1_General_CS_AI) <> 0
        -- Do this if capital
            BEGIN
                -- check if the previous character is lowercase, if it is then add a space before the current character.
                IF(
                   (PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator - 1, 1) COLLATE Latin1_General_CS_AI) = 0
                    AND SUBSTRING(@String, @Iterator - 1, 1) <> ' '
                   )
                   OR PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator + 1, 1) COLLATE Latin1_General_CS_AI) = 0)
                    BEGIN
                        SET @String = STUFF(@String, @Iterator, 0, @Delimiter);
                        SET @Iterator+=1;
                END;
                -- check if the next character is lowercase, if it is then add a space before the current character.
                SET @Iterator+=1;
        END;
        ---- Don't care about current character being lowercase. Just continue iterating
        SET @Iterator+=1;
    END;

SELECT @String;

Example of what I get from the app - "ThisIsASentenceWithCAPTIInIt"

What I want to pass back - "This Is A Sentence With CAPTI In It"

What I am getting back from my modified version - "This Is ASentence With CAPTIIn It"

Body:
doing it this in SQL Server is not the best choice. also rewriting existing string can be challenging somewhat challenging.

I think there are many more way to simplify this code, but here is a version that I believe will achieve the result you are looking for.

DECLARE @String    NVARCHAR(MAX) = 'ThisIsASentenceWithCAPTIInIt'
    --, @Len       INT         --  = LEN(@String)
      , @Delimiter CHAR(1)       = ' '
      , @Iterator  INT           = 1; --Don't put space to left of first even if it's a capital

DECLARE @retval nvarchar(max) = '';

WHILE @Iterator <= LEN(@String)
-- Iterate through string
    BEGIN
        -- Check if current character is Uppercase (lowercase = 0)
        IF PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator, 1) COLLATE Latin1_General_CS_AI) <> 0
        -- Do this if capital
            BEGIN
                -- check if the previous character is lowercase, if it is then add a space before the current character.
                IF(
                   (PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator - 1, 1) COLLATE Latin1_General_CS_AI) = 0
                    AND SUBSTRING(@String, @Iterator - 1, 1) <> ' '
                   )
                   OR PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator + 1, 1) COLLATE Latin1_General_CS_AI) = 0)
                    BEGIN
                        set @retval += ' ' ;
                        --SET @String = STUFF(@String, @Iterator, 0, @Delimiter);
                        --SET @Iterator+=1;
                END;
                -- check if the next character is lowercase, if it is then add a space before the current character.
                --Set @retval += SUBSTRING(@String, @Iterator, 1);
                --SET @Iterator+=1;
            END;
        ---- Don't care about current character being lowercase. Just continue iterating
        Set @retval += SUBSTRING(@String, @Iterator, 1);
        SET @Iterator+=1;
    END;
SET @retval = Ltrim(@retval);
SELECT @retval;


问:
gremlinpython - How do you select(keys) in a graph_traversal?
In this stackoverflow question a suggestion was made to use the query supplied in the first answer to do a particular gremlin_python traversal. Namely

```<code>g.V().has('name', 'USA').limit(1000).hasLabel('Country').
  map(union(project('id','label').
              by(id).
              by(label),
            valueMap()).unfold().
      group().
        by(keys).
        by(select(values)))
</code>```

I am able to import all but "keys" from the gremlin_python graph traversal library like the following

```<code>from gremlin_python.process.graph_traversal import union, project, valueMap, select, key, values, id, label, map
</code>```

Looking at the gremlin_python repo, I don't see a way to define the portion that is "by(keys)"

Does anyone know how this can be accomplished?

答: keys and values in that context should import from the Column enum - in the source code here. Note the full list of recommended imports in the Reference Documentation.

Body:
In this stackoverflow question a suggestion was made to use the query supplied in the first answer to do a particular gremlin_python traversal. Namely

g.V().has('name', 'USA').limit(1000).hasLabel('Country').
  map(union(project('id','label').
              by(id).
              by(label),
            valueMap()).unfold().
      group().
        by(keys).
        by(select(values)))

I am able to import all but "keys" from the gremlin_python graph traversal library like the following

from gremlin_python.process.graph_traversal import union, project, valueMap, select, key, values, id, label, map

Looking at the gremlin_python repo, I don't see a way to define the portion that is "by(keys)"

Does anyone know how this can be accomplished?


问:
Object.keys() with nested objects: get correct types
I have 3 objects a, b and c, each of them has a prop field, whose value can be anything.

```<code>const a = { prop: { foo: 'bar', bar: true } }
const b = { prop: { baz: 1234 } }
const c = { prop: true }
</code>```

These objects are organized into sections:

```<code>const sectionA = { a, b }
const sectionB = { c }
const allSections = {sectionA, sectionB}
</code>```

I want to construct the following object dynamically:

```<code>const myObject = {
  sectionA: {
    a: {foo: 'bar', bar: true},
    b: {baz: 1234}
  },
  sectionB: {
    c: true
  }
}
</code>```

I.e. correctly organized into nested objects, but without the prop field.

Here's what I did:

```<code>type ObjectWithProp = { prop: any }

type ObjectTypes<Section extends {[index:string]: ObjectWithProp}> = {
    [K in keyof Section]: Section[K]['prop']
}

type AllSectionTypes<AllSection extends { [index: string]: { [index: string]: ObjectWithProp } }> = {
    [K in keyof AllSection]: ObjectTypes<AllSection[K]>
}

const result = Object.keys(allSections).reduce((outerAcc, _key) => {
    const key = _key as keyof typeof allSections;
    const section = allSections[key];

    outerAcc[key] = Object.keys(section).reduce((innerAcc, _objectName) => {
        const objectName = _objectName as keyof typeof section;
        const obj = section[_objectName];

        innerAcc[objectName] = obj.prop;

        return innerAcc;
    }, {} as ObjectTypes<typeof section>);

    return outerAcc;
}, {} as AllSectionTypes<typeof allSections>)
</code>```

[Link to TS Playground]

At line const objectName = _objectName as keyof typeof section;, objectName is unfortunately never (logical since there are no common fields between the objects). But then I cannot do innerAcc[objectName].

How can I solve that?

答:
Note: the following works in TS3.4+ as it relies on higher order type inference from generic functions.

Here's how I'd go about it.  It's a fairly sizable refactor, mostly because all the nested types were hurting my brain.  You can probably copy the types from this into your original code, but I wouldn't try to do it.  The actual behavior, though, is pretty much the same (e.g., using Object.keys().reduce() instead of a for loop):

```<code>// a technically unsafe version of Object.keys(o) that assumes that
// o only has known properties of T
function keys<T extends object>(o: T) {
  return Object.keys(o) as Array<keyof T>;
}

// Turn {k1: {prop: v2}, k3: {prop: v4} into {k1: v2, k3: v4}
function pullOutProp<TK extends Record<keyof TK, { prop: any }>>(o: TK) {
  return keys(o).reduce(
    <P extends keyof TK>(
      acc: { [P in keyof TK]: TK[P]['prop'] },
      k: P
    ) => (acc[k] = o[k].prop, acc),
    {} as { [P in keyof TK]: TK[P]['prop'] });
}

// Turn {k1: {k2: {prop: v3}, k4: {prop: v5}}, k6: {k7: {prop: v8}}} into
// {k1: {k2: v3, k4: v5}, k6: {k7: v8}}
function nestedPullOutProp<T extends {
  [K in keyof T]: Record<keyof T[K], { prop: any }> }
>(o: T) {
  return keys(o).reduce(
    <K extends keyof T>(
      acc: { [K in keyof T]: { [P in keyof T[K]]: T[K][P]['prop'] } },
      k: K
    ) => (acc[k] = pullOutProp(o[k]), acc),
    {} as { [K in keyof T]: { [P in keyof T[K]]: T[K][P]['prop'] } }
  )
}

const result = nestedPullOutProp(allSections); // your desired result
</code>```

You can verify that result is the type you expect.  The trick here is basically to make pullOutProp() and nestedPullOutProp() as generic as possible, operating over a type with the minimum requirements to function (e.g., T extends { [K in keyof T]: Record<keyof T[K], { prop: any }> }> means that t.x.y.prop will exist whenever t.x.y exists), and making the callback to reduce() generic.  At each step, the generic types are straightforward enough for the compiler to follow the logic and not complain about the assignments... especially because of the improvements made to higher order type inference in generic functions introduced in TS3.4.

Only at the very end, when you call nestedPullOutProp(allSections) does the compiler actually go ahead and try to evaluate the generics, at which point it becomes the expected type.

Okay, hope that helps; good luck!

Link to code

Body:
I have 3 objects a, b and c, each of them has a prop field, whose value can be anything.

const a = { prop: { foo: 'bar', bar: true } }
const b = { prop: { baz: 1234 } }
const c = { prop: true }

These objects are organized into sections:

const sectionA = { a, b }
const sectionB = { c }
const allSections = {sectionA, sectionB}

I want to construct the following object dynamically:

const myObject = {
  sectionA: {
    a: {foo: 'bar', bar: true},
    b: {baz: 1234}
  },
  sectionB: {
    c: true
  }
}

I.e. correctly organized into nested objects, but without the prop field.

Here's what I did:

type ObjectWithProp = { prop: any }

type ObjectTypes
 = {
    [K in keyof Section]: Section[K]['prop']
}

type AllSectionTypes<AllSection extends { [index: string]: { [index: string]: ObjectWithProp } }> = {
    [K in keyof AllSection]: ObjectTypes<AllSection[K]>
}

const result = Object.keys(allSections).reduce((outerAcc, _key) => {
    const key = _key as keyof typeof allSections;
    const section = allSections[key];

    outerAcc[key] = Object.keys(section).reduce((innerAcc, _objectName) => {
        const objectName = _objectName as keyof typeof section;
        const obj = section[_objectName];

        innerAcc[objectName] = obj.prop;

        return innerAcc;
    }, {} as ObjectTypes<typeof section>);

    return outerAcc;
}, {} as AllSectionTypes<typeof allSections>)

<a href="https://www.typescriptlang.org/play/#src=type%20ObjectWithProp%20%3D%20%7B%20prop%3A%20any%20%7D%0D%0A%0D%0Atype%20ObjectTypes%3CSection%20extends%20%7B%5Bindex%3Astring%5D%3A%20ObjectWithProp%7D%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BK%20in%20keyof%20Section%5D%3A%20Section%5BK%5D%5B'prop'%5D%0D%0A%7D%0D%0A%0D%0Atype%20AllSectionTypes%3CAllSection%20extends%20%7B%20%5Bindex%3A%20string%5D%3A%20%7B%20%5Bindex%3A%20string%5D%3A%20ObjectWithProp%20%7D%20%7D%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BK%20in%20keyof%20AllSection%5D%3A%20ObjectTypes%3CAllSection%5BK%5D%3E%0D%0A%7D%0D%0A%0D%0Aconst%20a%20%3D%20%7B%20prop%3A%20%7B%20foo%3A%20'bar'%2C%20bar%3A%20true%20%7D%20%7D%0D%0Aconst%20b%20%3D%20%7B%20prop%3A%20%7B%20baz%3A%201234%20%7D%20%7D%0D%0Aconst%20c%20%3D%20%7B%20prop%3A%20true%20%7D%0D%0A%0D%0Aconst%20sectionA%20%3D%20%7B%20a%2C%20b%20%7D%0D%0Aconst%20sectionB%20%3D%20%7B%20c%20%7D%0D%0A%0D%0Aconst%20allSections%20%3D%20%7BsectionA%2C%20sectionB%7D%0D%0A%0D%0Aconst%20result%20%3D%20Object.keys(allSections).reduce((outerAcc%2C%20_key)%20%3D%3E%20%7B%0D%0A%20%20%20%20const%20key%20%3D%20_key%20as%20keyof%20typeof%20allSections%3B%0D%0A%20%20%20%20const%20section%20%3D%20allSections%5Bkey%5D%3B%0D%0A%0D%0A%20%20%20%20outerAcc%5Bkey%5D%20%3D%20Object.keys(section).reduce((innerAcc%2C%20_objectName)%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20const%20objectName%20%3D%20_objectName%20as%20keyof%20typeof%20section%3B%0D%0A%20%20%20%20%20%20%20%20const%20obj%20%3D%20section%5B_objectName%5D%3B%0D%0A%0D%0A%20%20%20%20%20%20%20%20innerAcc%5BobjectName%5D%20%3D%20obj.prop%3B%0D%0A%0D%0A%20%20%20%20%20%20%20%20return%20innerAcc%3B%0D%0A%20%20%20%20%7D%2C%20%7B%7D%20as%20ObjectTypes%3Ctypeof%20section%3E)%3B%0D%0A%0D%0A%20%20%20%20return%20outerAcc%3B%0D%0A%7D%2C%20%7B%7D%20as%20AllSectionTypes%3Ctypeof%20allSections%3E)%0D%0A%0D%0Aconsole.log(result)%3B%0D%0A%0D%0Aresult.sectionA.a.bar%3B" rel="nofollow noreferrer">[Link to TS Playground]

At line const objectName = _objectName as keyof typeof section;, objectName is unfortunately never (logical since there are no common fields between the objects). But then I cannot do innerAcc[objectName].

How can I solve that?

Body:
Note: the following works in TS3.4+ as it relies on higher order type inference from generic functions.

Here's how I'd go about it.  It's a fairly sizable refactor, mostly because all the nested types were hurting my brain.  You can probably copy the types from this into your original code, but I wouldn't try to do it.  The actual behavior, though, is pretty much the same (e.g., using Object.keys().reduce() instead of a for loop):

// a technically unsafe version of Object.keys(o) that assumes that
// o only has known properties of T
function keys<T extends object>(o: T) {
  return Object.keys(o) as Array<keyof T>;
}

// Turn {k1: {prop: v2}, k3: {prop: v4} into {k1: v2, k3: v4}
function pullOutProp<TK extends Record<keyof TK, { prop: any }>>(o: TK) {
  return keys(o).reduce(
    <P extends keyof TK>(
      acc: { [P in keyof TK]: TK[P]['prop'] },
      k: P
    ) => (acc[k] = o[k].prop, acc),
    {} as { [P in keyof TK]: TK[P]['prop'] });
}

// Turn {k1: {k2: {prop: v3}, k4: {prop: v5}}, k6: {k7: {prop: v8}}} into
// {k1: {k2: v3, k4: v5}, k6: {k7: v8}}
function nestedPullOutProp<T extends {
  [K in keyof T]: Record<keyof T[K], { prop: any }> }
>(o: T) {
  return keys(o).reduce(
    <K extends keyof T>(
      acc: { [K in keyof T]: { [P in keyof T[K]]: T[K][P]['prop'] } },
      k: K
    ) => (acc[k] = pullOutProp(o[k]), acc),
    {} as { [K in keyof T]: { [P in keyof T[K]]: T[K][P]['prop'] } }
  )
}

const result = nestedPullOutProp(allSections); // your desired result

You can verify that result is the type you expect.  The trick here is basically to make pullOutProp() and nestedPullOutProp() as generic as possible, operating over a type with the minimum requirements to function (e.g., T extends { [K in keyof T]: Record<keyof T[K], { prop: any }> }> means that t.x.y.prop will exist whenever t.x.y exists), and making the callback to reduce() generic.  At each step, the generic types are straightforward enough for the compiler to follow the logic and not complain about the assignments... especially because of the improvements made to higher order type inference in generic functions introduced in TS3.4.

Only at the very end, when you call nestedPullOutProp(allSections) does the compiler actually go ahead and try to evaluate the generics, at which point it becomes the expected type.

Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play//#src=const%20a%20%3D%20%7B%20prop%3A%20%7B%20foo%3A%20%27bar%27%2C%20bar%3A%20true%20%7D%20%7D%0Aconst%20b%20%3D%20%7B%20prop%3A%20%7B%20baz%3A%201234%20%7D%20%7D%0Aconst%20c%20%3D%20%7B%20prop%3A%20true%20%7D%0A%0Aconst%20sectionA%20%3D%20%7B%20a%2C%20b%20%7D%0Aconst%20sectionB%20%3D%20%7B%20c%20%7D%0Aconst%20allSections%20%3D%20%7B%20sectionA%2C%20sectionB%20%7D%0A%0Aconst%20myObject%20%3D%20%7B%0A%20%20sectionA%3A%20%7B%0A%20%20%20%20a%3A%20%7B%20foo%3A%20%27bar%27%2C%20bar%3A%20true%20%7D%2C%0A%20%20%20%20b%3A%20%7B%20baz%3A%201234%20%7D%0A%20%20%7D%2C%0A%20%20sectionB%3A%20%7B%0A%20%20%20%20c%3A%20true%0A%20%20%7D%0A%7D%0A%0Afunction%20keys%3CT%20extends%20object%3E%28o%3A%20T%29%20%7B%0A%20%20return%20Object.keys%28o%29%20as%20Array%3Ckeyof%20T%3E%3B%0A%7D%0A%0Afunction%20pullOutProp%3CTK%20extends%20Record%3Ckeyof%20TK%2C%20%7B%20prop%3A%20any%20%7D%3E%3E%28o%3A%20TK%29%20%7B%0A%20%20return%20keys%28o%29.reduce%28%0A%20%20%20%20%3CP%20extends%20keyof%20TK%3E%28%0A%20%20%20%20%20%20acc%3A%20%7B%20%5BP%20in%20keyof%20TK%5D%3A%20TK%5BP%5D%5B%27prop%27%5D%20%7D%2C%0A%20%20%20%20%20%20k%3A%20P%0A%20%20%20%20%29%20%3D%3E%20%28acc%5Bk%5D%20%3D%20o%5Bk%5D.prop%2C%20acc%29%2C%0A%20%20%20%20%7B%7D%20as%20%7B%20%5BP%20in%20keyof%20TK%5D%3A%20TK%5BP%5D%5B%27prop%27%5D%20%7D%29%3B%0A%7D%0A%0Afunction%20nestedPullOutProp%3CT%20extends%20%7B%20%5BK%20in%20keyof%20T%5D%3A%20Record%3Ckeyof%20T%5BK%5D%2C%20%7B%20prop%3A%20any%20%7D%3E%20%7D%3E%28o%3A%20T%29%20%7B%0A%20%20return%20keys%28o%29.reduce%28%0A%20%20%20%20%3CK%20extends%20keyof%20T%3E%28%0A%20%20%20%20%20%20acc%3A%20%7B%20%5BK%20in%20keyof%20T%5D%3A%20%7B%20%5BP%20in%20keyof%20T%5BK%5D%5D%3A%20T%5BK%5D%5BP%5D%5B%27prop%27%5D%20%7D%20%7D%2C%0A%20%20%20%20%20%20k%3A%20K%0A%20%20%20%20%29%20%3D%3E%20%28acc%5Bk%5D%20%3D%20pullOutProp%28o%5Bk%5D%29%2C%20acc%29%2C%0A%20%20%20%20%7B%7D%20as%20%7B%20%5BK%20in%20keyof%20T%5D%3A%20%7B%20%5BP%20in%20keyof%20T%5BK%5D%5D%3A%20T%5BK%5D%5BP%5D%5B%27prop%27%5D%20%7D%20%7D%0A%20%20%29%0A%7D%0A%0A%0Aconst%20result%20%3D%20nestedPullOutProp%28allSections%29%3B" rel="nofollow noreferrer">Link to code


问:
lit-html: concatenating strings to use html``
I am programming a web-component with lit-element and wonder, how I can render a string inside of a variable which still has intact @click listeners with the html "processor" instead of the pure string.

```<code>someFunction() {
    var someString=`<button @click="alert('hi')">blah</button>`;
    return html([someString]);
}
render() {
    return this.someFunction();
}
</code>```

doesn't work, while

```<code>someFunction() {
    return html`<button @click="alert('hi')">blah</button>`
}
render() {
    return this.someFunction();
}
</code>```

works.

Thanks for your help!

答:
That is not possible. These are two tagged template literal and function call fundamentally different things:

Tagged template literal

```<code>html`<button @click="alert('hi')">blah</button>`
</code>```

Calling html as a tagged template function will call html function with n-argument parameters. First will be an array of the constant part of the template and arguments from second onwards will be interpolated valued.

Ordinary function call

```<code>const someString = `<button @click="alert('hi')">blah</button>`;
html([someString]);
</code>```

Calling html as a function html([someString]) will call that function with array as its first argument.

Being a language feature, the browser needs to understand a tagged template from ordinary function. It happens at a lexical/syntactical level and thus a tagged function must and must be followed by backtick(`) character.

In summary, tagged function html cannot exist without backtick. You can read more here on MDN docs.

Body:
I am programming a web-component with lit-element and wonder, how I can render a string inside of a variable which still has intact @click listeners with the html "processor" instead of the pure string.

someFunction() {
    var someString=`<button @click="alert('hi')">blah</button>`;
    return html([someString]);
}
render() {
    return this.someFunction();
}

doesn't work, while

someFunction() {
    return html`<button @click="alert('hi')">blah</button>`
}
render() {
    return this.someFunction();
}

works.

Thanks for your help!

Body:
That is not possible. These are two tagged template literal and function call fundamentally different things:

Tagged template literal

html`<button @click="alert('hi')">blah</button>`

Calling html as a tagged template function will call html function with n-argument parameters. First will be an array of the constant part of the template and arguments from second onwards will be interpolated valued.

Ordinary function call

const someString = `<button @click="alert('hi')">blah</button>`;
html([someString]);

Calling html as a function html([someString]) will call that function with array as its first argument.

Being a language feature, the browser needs to understand a tagged template from ordinary function. It happens at a lexical/syntactical level and thus a tagged function must and must be followed by backtick(`) character.

In summary, tagged function html cannot exist without backtick. You can read more here on MDN docs.


问:
Awk: generating icalendar file. How to print some consecutive lines?

Thanks to Ed Morton's answer, I could do some testing with Thunderbird and icalendar validator. I edited my question adding entries without description and the expected result with precise requirements.

I'm writing a script to generate an icalendar file from a planing text file. I'd like to get the description content with the lines coming after the date. Say I've got a planning file:

```<code>lun 06 05 2019 08 15 09 00 F206
    A descritpion text.
ven 10 05 2019 11 00 11 45 G202
    Another description text
    - on multiple;
    - lines.
lun 13 05 2019 08 15 09 00 F206
ven 17 05 2019 11 00 11 45 G202
    A long description with more than 75 characters.
    This happen often when multiple lines are
    joined in one. So the program shoud split every lines
    To 75 characters including the word description.
lun 20 05 2019 08 15 09 00 F206
    A description text.
</code>```

My script looks like this, I'm a newbie with awk:

```<code>#!/bin/bash
awk ' BEGIN { print "BEGIN:VCALENDAR\r\n\
... some entries here ...\r\n\
END:VTIMEZONE\r" ;}
$1~/^(lun|mar|mer|jeu|ven)$/ { print "BEGIN:VEVENT\r\n\
... some entries here ...\r\n\
DTSTART;TZID=Europe/Zurich:"$4""$3""$2"T"$5""$6"00\r\n\
DTEND;TZID=Europe/Zurich:"$4""$3""$2"T"$7""$8"00\r\n\
TRANSP:OPAQUE\r\n\
DESCRIPTION: >>>HERE I NEED THE DESCRIPTIVE LINES<<<< \r\n\
END:VEVENT\r"}
END { print "END:VCALENDAR" } ' < $1 > $1.ics
</code>```

expected result:

```<code>BEGIN:VCALENDAR
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190506T081500
DTEND;TZID=Europe/Zurich:20190506T090000
DESCRIPTION:A descritpion text.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190510T110000
DTEND;TZID=Europe/Zurich:20190510T114500
DESCRIPTION:Another description text\n- on multiple;\n- lines.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190513T081500
DTEND;TZID=Europe/Zurich:20190513T090000
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190517T110000
DTEND;TZID=Europe/Zurich:20190517T114500
DESCRIPTION:A long description with more than 75 characters.\nThis happen
 often when multiple lines are\njoined in one. So the program shoud split
 every lines\nTo 75 characters including the word description.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190520T081500
DTEND;TZID=Europe/Zurich:20190520T090000
DESCRIPTION: A description text.
END:VEVENT
END:VCALENDAR
</code>```

So the exact requirements are:

Lines without description should not print DESCRIPTION:.

Multiline description should be joined an separated with a literal \n. This is working with a printf "%s%s", $0, "\\n"

The lines should be splited to fewer than 75 characters, ending with a \r\n

The additional description lines should begin with a space.

答:
```<code>$ cat tst.awk
BEGIN {
    ORS="\r\n"

    print "BEGIN:VCALENDAR"
    print "... some entries here ..."
    print "END:VTIMEZONE"
}
/^[^[:space:]]/ {
    prtEndVevent()

    print "BEGIN:VEVENT"
    print "... some entries here ..."

    date = $4 $3 $2
    begt = $5 $6 "00"
    endt = $7 $8 "00"

    print "DTSTART;TZID=Europe/Zurich:" date "T" begt
    print "DTEND;TZID=Europe/Zurich:"   date "T" endt
    next
}
{
    gsub(/^[[:space:]]+|[[:space:]]+$/,"")
    desc = (desc == "" ? "DESCRIPTION:" : desc RS) $0
}
END {
    prtEndVevent()
    print "END:VCALENDAR"
}

function prtEndVevent(       wid) {
    if ( desc != "" ) {
        wid = 74
        gsub(RS,"\\n",desc)
        while ( desc !~ /^ ?$/ ) {
            print substr(desc,1,wid)
            desc = " " substr(desc,wid+1)
        }
        desc = ""
    }
    if ( endVevent != "" ) {
        print endVevent
    }
    endVevent = "END:VEVENT"
}
</code>```

.

```<code>$ awk -f tst.awk file
BEGIN:VCALENDAR
... some entries here ...
END:VTIMEZONE
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190506T081500
DTEND;TZID=Europe/Zurich:20190506T090000
DESCRIPTION:A descritpion text.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190510T110000
DTEND;TZID=Europe/Zurich:20190510T114500
DESCRIPTION:Another description text\n- on multiple;\n- lines.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190513T081500
DTEND;TZID=Europe/Zurich:20190513T090000
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190517T110000
DTEND;TZID=Europe/Zurich:20190517T114500
DESCRIPTION:A long description with more than 75 characters.\nThis happen
 often when multiple lines are\njoined in one. So the program shoud split
 every lines\nTo 75 characters including the word description.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190520T081500
DTEND;TZID=Europe/Zurich:20190520T090000
DESCRIPTION:A description text.
END:VEVENT
END:VCALENDAR
</code>```

Note that this is wrapping at character positions, not word boundaries, so if a word crosses the 75th char position it will be split. If that's not desirable you can update prtDesc() to print one word at a time, checking if the total length of all words + blanks printed plus the next word would be less than 75 (and decide how to handle a description string that is 75+ chars long with no spaces!) or call the UNIX command fold to do the wrapping for you.

If you're ever considering using getline make sure to read and completely understand http://awk.freeshell.org/AllAboutGetline first.

Body:
Thanks to Ed Morton's answer, I could do some testing with Thunderbird and icalendar validator. I edited my question adding entries without description and the expected result with precise requirements.

I'm writing a script to generate an icalendar file from a planing text file. I'd like to get the description content with the lines coming after the date. Say I've got a planning file:

lun 06 05 2019 08 15 09 00 F206
    A descritpion text.
ven 10 05 2019 11 00 11 45 G202
    Another description text
    - on multiple;
    - lines.
lun 13 05 2019 08 15 09 00 F206
ven 17 05 2019 11 00 11 45 G202
    A long description with more than 75 characters.
    This happen often when multiple lines are
    joined in one. So the program shoud split every lines
    To 75 characters including the word description.
lun 20 05 2019 08 15 09 00 F206
    A description text.

My script looks like this, I'm a newbie with awk:

#!/bin/bash
awk ' BEGIN { print "BEGIN:VCALENDAR\r\n\
... some entries here ...\r\n\
END:VTIMEZONE\r" ;}
$1~/^(lun|mar|mer|jeu|ven)$/ { print "BEGIN:VEVENT\r\n\
... some entries here ...\r\n\
DTSTART;TZID=Europe/Zurich:"$4""$3""$2"T"$5""$6"00\r\n\
DTEND;TZID=Europe/Zurich:"$4""$3""$2"T"$7""$8"00\r\n\
TRANSP:OPAQUE\r\n\
DESCRIPTION: >>>HERE I NEED THE DESCRIPTIVE LINES<<<< \r\n\
END:VEVENT\r"}
END { print "END:VCALENDAR" } ' < $1 > $1.ics

expected result:

BEGIN:VCALENDAR
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190506T081500
DTEND;TZID=Europe/Zurich:20190506T090000
DESCRIPTION:A descritpion text.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190510T110000
DTEND;TZID=Europe/Zurich:20190510T114500
DESCRIPTION:Another description text\n- on multiple;\n- lines.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190513T081500
DTEND;TZID=Europe/Zurich:20190513T090000
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190517T110000
DTEND;TZID=Europe/Zurich:20190517T114500
DESCRIPTION:A long description with more than 75 characters.\nThis happen
 often when multiple lines are\njoined in one. So the program shoud split
 every lines\nTo 75 characters including the word description.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190520T081500
DTEND;TZID=Europe/Zurich:20190520T090000
DESCRIPTION: A description text.
END:VEVENT
END:VCALENDAR

So the exact requirements are:

Lines without description should not print DESCRIPTION:.

Multiline description should be joined an separated with a literal \n. This is working with a printf "%s%s", $0, "\\n"

The lines should be splited to fewer than 75 characters, ending with a \r\n

The additional description lines should begin with a space.

Body:
$ cat tst.awk
BEGIN {
    ORS="\r\n"

    print "BEGIN:VCALENDAR"
    print "... some entries here ..."
    print "END:VTIMEZONE"
}
/^[^[:space:]]/ {
    prtEndVevent()

    print "BEGIN:VEVENT"
    print "... some entries here ..."

    date = $4 $3 $2
    begt = $5 $6 "00"
    endt = $7 $8 "00"

    print "DTSTART;TZID=Europe/Zurich:" date "T" begt
    print "DTEND;TZID=Europe/Zurich:"   date "T" endt
    next
}
{
    gsub(/^[[:space:]]+|[[:space:]]+$/,"")
    desc = (desc == "" ? "DESCRIPTION:" : desc RS) $0
}
END {
    prtEndVevent()
    print "END:VCALENDAR"
}

function prtEndVevent(       wid) {
    if ( desc != "" ) {
        wid = 74
        gsub(RS,"\\n",desc)
        while ( desc !~ /^ ?$/ ) {
            print substr(desc,1,wid)
            desc = " " substr(desc,wid+1)
        }
        desc = ""
    }
    if ( endVevent != "" ) {
        print endVevent
    }
    endVevent = "END:VEVENT"
}

.

$ awk -f tst.awk file
BEGIN:VCALENDAR
... some entries here ...
END:VTIMEZONE
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190506T081500
DTEND;TZID=Europe/Zurich:20190506T090000
DESCRIPTION:A descritpion text.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190510T110000
DTEND;TZID=Europe/Zurich:20190510T114500
DESCRIPTION:Another description text\n- on multiple;\n- lines.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190513T081500
DTEND;TZID=Europe/Zurich:20190513T090000
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190517T110000
DTEND;TZID=Europe/Zurich:20190517T114500
DESCRIPTION:A long description with more than 75 characters.\nThis happen
 often when multiple lines are\njoined in one. So the program shoud split
 every lines\nTo 75 characters including the word description.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190520T081500
DTEND;TZID=Europe/Zurich:20190520T090000
DESCRIPTION:A description text.
END:VEVENT
END:VCALENDAR

Note that this is wrapping at character positions, not word boundaries, so if a word crosses the 75th char position it will be split. If that's not desirable you can update prtDesc() to print one word at a time, checking if the total length of all words + blanks printed plus the next word would be less than 75 (and decide how to handle a description string that is 75+ chars long with no spaces!) or call the UNIX command fold to do the wrapping for you.

If you're ever considering using getline make sure to read and completely understand http://awk.freeshell.org/AllAboutGetline first.


问:
Access Reading Violation when writing a DICOM with vtkDICOMWriter
I'm trying to write vtkImageData as a DICOM. I keep getting an "Access Reading Violation" when I try to write the image.

Unhandled exception at 0x00007FFDA30ECA50 : 0xC0000005: Access violation reading location 0x000001BD38D5C000

Here is my code:

```<code>vtkSmartPointer<vtkDICOMWriter> dcmWriter = vtkSmartPointer<vtkDICOMWriter>::New();
dcmWriter->SetInputData(testDat);
dcmWriter->SetFileName(fullPath.toStdString().c_str());
dcmWriter->Update(); // this line breaks
dcmWriter->Write();
</code>```

testDat is a vtkSmartPointer<vtkImageData> type and has data in it. Any thoughts on whats causing the error? I can't find anything similar online.

I followed this example: https://github.com/dgobbi/vtk-dicom/blob/master/Examples/TestDICOMWriter.cxx

I don't have metadata, but that shouldn't be a problem.

答:
These lines are from the example you posted:

```<code>writer->SetFilePrefix("/tmp");
writer->SetFilePattern("%s/IM-0001-%04.4d.dcm");
</code>```

and you use

```<code>dcmWriter->SetFileName(fullPath.toStdString().c_str());
</code>```

It seems that vtkDICOMWriter writes several files so you probably need to provide a file pattern. Anyway, it's hard to guess why it gives a reading error and it's hard to help if you don't post a full working example.

Last, vtkDICOMWriter is not a class from vtk, it was released separetely (it seems) in 2017. This means it's not tested against the rest of VTK at every new release.

Body:
I'm trying to write vtkImageData as a DICOM. I keep getting an "Access Reading Violation" when I try to write the image.

Unhandled exception at 0x00007FFDA30ECA50 : 0xC0000005: Access violation reading location 0x000001BD38D5C000

Here is my code:

vtkSmartPointer<vtkDICOMWriter> dcmWriter = vtkSmartPointer<vtkDICOMWriter>::New();
dcmWriter->SetInputData(testDat);
dcmWriter->SetFileName(fullPath.toStdString().c_str());
dcmWriter->Update(); // this line breaks
dcmWriter->Write();

testDat is a vtkSmartPointer<vtkImageData> type and has data in it. Any thoughts on whats causing the error? I can't find anything similar online.

I followed this example: https://github.com/dgobbi/vtk-dicom/blob/master/Examples/TestDICOMWriter.cxx

I don't have metadata, but that shouldn't be a problem.

Body:
These lines are from the example you posted:

writer->SetFilePrefix("/tmp");
writer->SetFilePattern("%s/IM-0001-%04.4d.dcm");

and you use

dcmWriter->SetFileName(fullPath.toStdString().c_str());

It seems that vtkDICOMWriter writes several files so you probably need to provide a file pattern. Anyway, it's hard to guess why it gives a reading error and it's hard to help if you don't post a full working example.

Last, vtkDICOMWriter is not a class from vtk, it was released separetely (it seems) in 2017. This means it's not tested against the rest of VTK at every new release.


问:
How to use a dynamic connection string in asp.net?
So, I'm writing a program that imports excel files to a database, finds matches, non matches, shows the tables, etc.

In the beginning I added manually just my database connection string, but I have to make my program let the connection string change.

In case none is inserted, it will use the last one inserted.

Behind code:

```<code>protected void BtnFazerTudo_Click(object sender, EventArgs e)
    {
        var connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
        connectionString = connectionString.Replace("{username}", TxtUtilizador.Text);
        connectionString = connectionString.Replace("{pwd}",TxtPalavraPasse.Text);
        connectionString = connectionString.Replace("{DataSource}", TxtHost.Text);
        connectionString = connectionString.Replace("{Initial}", TxtBaseDeDados.Text);

        Debug.Write(con);
    }
</code>```

Web Config:

```<code><add name="Db" connectionString="Data Source ={DataSource} ;Initial Catalog=
{Initial};Persist Security
Info=True;User ID={username};Password={pwd}"/>
</code>```

I already tried the String builder. I was able to output it in the debug window but I have no idea in how I transfer that connection made by string builder to other web forms.

答:
The connection string you're creating needs to be stored somewhere so as all pages of your web application can access it. While there are some choices that let you pass data among pages none of them suits you mainly because (a) the connection string contains security sensitive information such as the password!!! and (b) they do not offer the level of persistence required by your scenario (unless you want the user to fill the textboxes every time he connects to your application).

Having said that, one viable option is to store the connection string in a database and retrieve it every time you need it. You can either store it as a whole string or each user data separately (i.e catalog, user id, password etc). In the latter case, you'd have to re-create the connection string every time you need it.

How you create the connection string has nothing to do with your original question. It is just about string concatenation in C# for which you can use the + or += operators, string interpolation or the String.Format, String.Concat, String.Join or StringBuilder.Append methods.

Body:
So, I'm writing a program that imports excel files to a database, finds matches, non matches, shows the tables, etc.

In the beginning I added manually just my database connection string, but I have to make my program let the connection string change.

In case none is inserted, it will use the last one inserted.

Behind code:

protected void BtnFazerTudo_Click(object sender, EventArgs e)
    {
        var connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
        connectionString = connectionString.Replace("{username}", TxtUtilizador.Text);
        connectionString = connectionString.Replace("{pwd}",TxtPalavraPasse.Text);
        connectionString = connectionString.Replace("{DataSource}", TxtHost.Text);
        connectionString = connectionString.Replace("{Initial}", TxtBaseDeDados.Text);

        Debug.Write(con);
    }

Web Config:

<add name="Db" connectionString="Data Source ={DataSource} ;Initial Catalog=
{Initial};Persist Security
Info=True;User ID={username};Password={pwd}"/>

I already tried the String builder. I was able to output it in the debug window but I have no idea in how I transfer that connection made by string builder to other web forms.


问:
dumping data from multiple tables with common fields
Hey All.
I have a bunch of tables that have some common fields tying them together, but I can't figure out the right way to dump them in a meaningful way.

Basically, users will be given two tests, and each test may be taken multiple times.

The main table stores information about the user and the test, similar to the below (we'll call this table MAIN):

```<code>user_id     test     iteration    completion_time
   1         1          1              1:00
   1         2          1              1:30
   1         1          2              0:49
   1         2          2              1:30
</code>```

Each test page then has its own table to store the answers provided, since some pages have a ton of questions. We'll call this one sample table RESULTS, but there are many tables like this that are basically the same.

```<code>user_id     test     iteration     q1   q2   q3
   1         1          1          A    B    A
   1         2          1          B    B    A
   1         1          2          A    B    B
   1         2          2          A    B    B
</code>```

These results tables (again, there are many) basically store the results, plus just enough information to accurately tie the results together across all tables. I set it up this way because to use just one table for the results would have left me with a table with several hundred columns, which I had read was not recommended.

So the problem here is i can't figure out how best to tie together these tables and get the results out. I've read up on joins and unions and neither one seems right, as far as I can tell, because i need to pull data from ~10-15 tables at once.

I can do a huge complex select -- something along the lines of

```<code>select m.*, a.*, b.*, c.* from main m, results_a a, results_b b, results_c c where a.user_id=m.user_id and b.user_id=m.user_id and c.user_id=m.user_id'
</code>```

and that works, but there's got to be a better way. Keep in mind that i've only given 3 results tables in this example -- in my actual application, it's going to be more like 15-20 tables of results.

Beyond being really complicated, it returns duplicates of some rows, and if i want to throw in any extra logic (lets say, for example, that i only want the same data i queried before, but only for test 2) it gets even more complicated. And lets not even talk about sorting.

From what I've read, JOIN is for 2 tables, and UNION combines rows of results, not columns.

I don't claim to be a mysql expert, but i have looked into this before posting. I feel like I must be close to the right answer, but just not quite hitting on it.

Can anyone give me some guidance?

答:
I think you've designed your database in a way that you're going to have to do joins.  It sounds better than the alternative (large, non-normalized table).  What are you trying to get out?  View all tests and determine a user's best score?

So if I understand the tables you have multiple users (obviously).  Each user can take multiple tests.  Each test could be taken multiple times.

```<code>select m.*, a.*, b.*, c.* from main m
join results_a a
on a.user_id = m.user_id and a.test_id = m.test_id and a.iteration_id = m.iteration_id
join results_b b
on b.user_id = m.user_id and b.test_id = m.test_id and b.iteration_id = m.iteration_id
join results_c c
on c.user_id = m.user_id and c.test_id = m.test_id and c.iteration_id = m.iteration_id
</code>```

That should give you one row per iteration, per test, per user.  If you want a certain test for a user then add:

```<code>where m.user_id = @userid and m.test_id = @testid
</code>```

and then you can look at all the iterations for a test, by a user.

If you want the latest iteration:
select top(1) ...

```<code>where m.user_id = @userid and m.test_id = @testid
order by m.iteration_id desc
</code>```

You might consider generating a view when your questions are set-up so you don't have to generate the select statement at run-time which represents a particular test.

Body:
Hey All.
I have a bunch of tables that have some common fields tying them together, but I can't figure out the right way to dump them in a meaningful way.

Basically, users will be given two tests, and each test may be taken multiple times.

The main table stores information about the user and the test, similar to the below (we'll call this table MAIN):

user_id     test     iteration    completion_time
   1         1          1              1:00
   1         2          1              1:30
   1         1          2              0:49
   1         2          2              1:30

Each test page then has its own table to store the answers provided, since some pages have a ton of questions. We'll call this one sample table RESULTS, but there are many tables like this that are basically the same.

user_id     test     iteration     q1   q2   q3
   1         1          1          A    B    A
   1         2          1          B    B    A
   1         1          2          A    B    B
   1         2          2          A    B    B

These results tables (again, there are many) basically store the results, plus just enough information to accurately tie the results together across all tables. I set it up this way because to use just one table for the results would have left me with a table with several hundred columns, which I had read was not recommended.

So the problem here is i can't figure out how best to tie together these tables and get the results out. I've read up on joins and unions and neither one seems right, as far as I can tell, because i need to pull data from ~10-15 tables at once.

I can do a huge complex select -- something along the lines of

select m.*, a.*, b.*, c.* from main m, results_a a, results_b b, results_c c where a.user_id=m.user_id and b.user_id=m.user_id and c.user_id=m.user_id'

and that works, but there's got to be a better way. Keep in mind that i've only given 3 results tables in this example -- in my actual application, it's going to be more like 15-20 tables of results.

Beyond being really complicated, it returns duplicates of some rows, and if i want to throw in any extra logic (lets say, for example, that i only want the same data i queried before, but only for test 2) it gets even more complicated. And lets not even talk about sorting.

From what I've read, JOIN is for 2 tables, and UNION combines rows of results, not columns.

I don't claim to be a mysql expert, but i have looked into this before posting. I feel like I must be close to the right answer, but just not quite hitting on it.

Can anyone give me some guidance?

Body:
I think you've designed your database in a way that you're going to have to do joins.  It sounds better than the alternative (large, non-normalized table).  What are you trying to get out?  View all tests and determine a user's best score?

So if I understand the tables you have multiple users (obviously).  Each user can take multiple tests.  Each test could be taken multiple times.

select m.*, a.*, b.*, c.* from main m
join results_a a
on a.user_id = m.user_id and a.test_id = m.test_id and a.iteration_id = m.iteration_id
join results_b b
on b.user_id = m.user_id and b.test_id = m.test_id and b.iteration_id = m.iteration_id
join results_c c
on c.user_id = m.user_id and c.test_id = m.test_id and c.iteration_id = m.iteration_id

That should give you one row per iteration, per test, per user.  If you want a certain test for a user then add:

where m.user_id = @userid and m.test_id = @testid

and then you can look at all the iterations for a test, by a user.

If you want the latest iteration:
select top(1) ...

where m.user_id = @userid and m.test_id = @testid
order by m.iteration_id desc

You might consider generating a view when your questions are set-up so you don't have to generate the select statement at run-time which represents a particular test.


问:
Check checked checkbox in Laravel
I have this code:

```<code>$arrayWithSelectedValues = [[user_id] => 3,[language_id] => 2], [user_id] => 3,[language_id] => 12]]
</code>```

And I have checkbox :

```<code>@foreach($languages as $language)
<fieldset>
<input type="checkbox"
   class="icheckbox_square-red"
   id="input-15" name="languages[]"
   value="{{ $language->id }}">
<label for="input-15">{{ $language->name }}</label>
</fieldset>
@endforeach
</code>```

How can I mark checkboxes as marked - those that have language_id from the array = $ language-> id?

答:
Use the php function in_array() to check if the $language_id exists in the array of $languages</p>

```<code>@foreach($languages as $language)
<fieldset>
<input type="checkbox"
   class="icheckbox_square-red"
   id="input-15" name="languages[]"
   value="{{ $language->id }}"
   @if(in_array($language_id, $languages))
      checked
   @endif
>
<label for="input-15">{{ $language->name }}</label>
</fieldset>
@endforeach
</code>```

Title: Check checked checkbox in Laravel

Body:
I have this code:

$arrayWithSelectedValues = [[user_id] => 3,[language_id] => 2], [user_id] => 3,[language_id] => 12]]

And I have checkbox :

@foreach($languages as $language)
<fieldset>
<input type="checkbox"
   class="icheckbox_square-red"
   id="input-15" name="languages[]"
   value="{{ $language->id }}">
{{ $language->name }}
</fieldset>
@endforeach

How can I mark checkboxes as marked - those that have language_id from the array = $ language-> id?

Body:
Use the php function in_array() to check if the $language_id exists in the array of $languages

@foreach($languages as $language)
<fieldset>
<input type="checkbox"
   class="icheckbox_square-red"
   id="input-15" name="languages[]"
   value="{{ $language->id }}"
   @if(in_array($language_id, $languages))
      checked
   @endif
>
<label for="input-15">{{ $language->name }}</label>
</fieldset>
@endforeach


问:
IdentityServer 3 failing under load testing
We are using IdentityServer 3 together with the Entity Framework package as the persistence layer. Using Serilog for trace/logging outputs

The current version we are using is 2.6.0

When put under some basic load tests, for example making requests with a valid token to our api host: https://oauth-something.co.uk/connect/accesstokenvalidation

We are finding load of failures in the logs. The token we are using is valid and we've configured the LoggingOption as follows

```<code>options.LoggingOptions.EnableHttpLogging = true;
options.LoggingOptions.EnableWebApiDiagnostics = true;
options.LoggingOptions.EnableKatanaLogging = true;
options.LoggingOptions.WebApiDiagnosticsIsVerbose = true;
</code>```

Any guidance on what might be causing this or how to get to the logging to give more relevant details about the cuase would be much appreciated

An example entry in the log:

```<code>2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Request received, Method=POST, Url=https://oauth-something.co.uk/connect/accesstokenvalidation, Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='https://oauth-something.co.uk/connect/accesstokenvalidation'

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.MessageHandlers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=DependencyScopeHandler.SendAsync

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.MessageHandlers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=PassiveAuthenticationMessageHandler.SendAsync

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='Route='controller:AccessTokenValidation'', Operation=DefaultHttpControllerSelector.SelectController

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='AccessTokenValidation', Operation=DefaultHttpControllerSelector.SelectController

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=HttpControllerDescriptor.CreateController

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=DefaultHttpControllerActivator.Create

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='IdentityServer3.Core.Endpoints.AccessTokenValidationController', Operation=DefaultHttpControllerActivator.Create

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='IdentityServer3.Core.Endpoints.AccessTokenValidationController', Operation=HttpControllerDescriptor.CreateController

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=AccessTokenValidationController.ExecuteAsync

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Action', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=ApiControllerActionSelector.SelectAction

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.Action', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Selected action 'Post()'', Operation=ApiControllerActionSelector.SelectAction

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.ModelBinding', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=HttpActionBinding.ExecuteBindingAsync

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.ModelBinding', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=HttpActionBinding.ExecuteBindingAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Filters', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Action filter for 'Post()'', Operation=NoCacheAttribute.OnActionExecutingAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Filters', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=NoCacheAttribute.OnActionExecutingAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Warn, Kind=End, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Cancelled', Operation=AccessTokenValidationController.ExecuteAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='IdentityServer3.Core.Endpoints.AccessTokenValidationController', Operation=DefaultHttpControllerActivator.Create

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Warn, Kind=End, Category='System.Web.Http.MessageHandlers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Cancelled', Operation=PassiveAuthenticationMessageHandler.SendAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='IdentityServer3.Core.Endpoints.AccessTokenValidationController', Operation=HttpControllerDescriptor.CreateController

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=AccessTokenValidationController.ExecuteAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Warn, Kind=End, Category='System.Web.Http.MessageHandlers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Cancelled', Operation=DependencyScopeHandler.SendAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=Begin, Category='System.Web.Http.Action', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=ApiControllerActionSelector.SelectAction

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Sending response, Method=POST, Url=https://oauth-something.co.uk/connect/accesstokenvalidation, Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Cancelled'

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Action', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='Selected action 'Post()'', Operation=ApiControllerActionSelector.SelectAction

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=AccessTokenValidationController.Dispose

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=AccessTokenValidationController.Dispose

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=Begin, Category='System.Web.Http.ModelBinding', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=HttpActionBinding.ExecuteBindingAsync

2017-02-09 16:50:12.109 +00:00 [Debug] HTTP Response Exception

System.OperationCanceledException: The operation was canceled.

   at System.Threading.CancellationToken.ThrowOperationCanceledException()

   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Owin.PassiveAuthenticationMessageHandler.<SendAsync>d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<InvokeCore>d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at Owin.ConfigureHttpLoggingExtension.<<ConfigureHttpLogging>b__0>d__2.MoveNext()
</code>```

答: Make sure you're using Windows Server as the IIS host as your load testing target. Windows desktop machines have a very limited number of concurrent connections to IIS (10x IIRC) will result in this issue (I had a similar set of errors).</p>

Body:
We are using IdentityServer 3 together with the Entity Framework package as the persistence layer. Using Serilog for trace/logging outputs

The current version we are using is 2.6.0

When put under some basic load tests, for example making requests with a valid token to our api host: https://oauth-something.co.uk/connect/accesstokenvalidation

We are finding load of failures in the logs. The token we are using is valid and we've configured the LoggingOption as follows

options.LoggingOptions.EnableHttpLogging = true;
options.LoggingOptions.EnableWebApiDiagnostics = true;
options.LoggingOptions.EnableKatanaLogging = true;
options.LoggingOptions.WebApiDiagnosticsIsVerbose = true;

Any guidance on what might be causing this or how to get to the logging to give more relevant details about the cuase would be much appreciated

An example entry in the log:

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Request received, Method=POST, Url=https://oauth-something.co.uk/connect/accesstokenvalidation, Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='https://oauth-something.co.uk/connect/accesstokenvalidation'

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.MessageHandlers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=DependencyScopeHandler.SendAsync

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.MessageHandlers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=PassiveAuthenticationMessageHandler.SendAsync

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='Route='controller:AccessTokenValidation'', Operation=DefaultHttpControllerSelector.SelectController

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='AccessTokenValidation', Operation=DefaultHttpControllerSelector.SelectController

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=HttpControllerDescriptor.CreateController

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=DefaultHttpControllerActivator.Create

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='IdentityServer3.Core.Endpoints.AccessTokenValidationController', Operation=DefaultHttpControllerActivator.Create

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='IdentityServer3.Core.Endpoints.AccessTokenValidationController', Operation=HttpControllerDescriptor.CreateController

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=AccessTokenValidationController.ExecuteAsync

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Action', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=ApiControllerActionSelector.SelectAction

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.Action', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Selected action 'Post()'', Operation=ApiControllerActionSelector.SelectAction

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.ModelBinding', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=HttpActionBinding.ExecuteBindingAsync

2017-02-09 16:50:12.093 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=End, Category='System.Web.Http.ModelBinding', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=HttpActionBinding.ExecuteBindingAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.0934966Z] Level=Info, Kind=Begin, Category='System.Web.Http.Filters', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Action filter for 'Post()'', Operation=NoCacheAttribute.OnActionExecutingAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Filters', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=NoCacheAttribute.OnActionExecutingAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Warn, Kind=End, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Cancelled', Operation=AccessTokenValidationController.ExecuteAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='IdentityServer3.Core.Endpoints.AccessTokenValidationController', Operation=DefaultHttpControllerActivator.Create

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Warn, Kind=End, Category='System.Web.Http.MessageHandlers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Cancelled', Operation=PassiveAuthenticationMessageHandler.SendAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='IdentityServer3.Core.Endpoints.AccessTokenValidationController', Operation=HttpControllerDescriptor.CreateController

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=AccessTokenValidationController.ExecuteAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Warn, Kind=End, Category='System.Web.Http.MessageHandlers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Cancelled', Operation=DependencyScopeHandler.SendAsync

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=Begin, Category='System.Web.Http.Action', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=ApiControllerActionSelector.SelectAction

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Sending response, Method=POST, Url=https://oauth-something.co.uk/connect/accesstokenvalidation, Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Message='Cancelled'

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Action', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Message='Selected action 'Post()'', Operation=ApiControllerActionSelector.SelectAction

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=Begin, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=AccessTokenValidationController.Dispose

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=End, Category='System.Web.Http.Controllers', Id=41a2f1bd-a654-4d5f-9265-953acda437c3, Operation=AccessTokenValidationController.Dispose

2017-02-09 16:50:12.109 +00:00 [Debug] [2017-02-09T16:50:12.1092195Z] Level=Info, Kind=Begin, Category='System.Web.Http.ModelBinding', Id=7fb64bc6-0509-4661-ad21-ab7c7380d51c, Operation=HttpActionBinding.ExecuteBindingAsync

2017-02-09 16:50:12.109 +00:00 [Debug] HTTP Response Exception

System.OperationCanceledException: The operation was canceled.

   at System.Threading.CancellationToken.ThrowOperationCanceledException()

   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Owin.PassiveAuthenticationMessageHandler.<SendAsync>d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<InvokeCore>d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at Owin.ConfigureHttpLoggingExtension.<<ConfigureHttpLogging>b__0>d__2.MoveNext()


问:
"REST API Client" option in Visual Studio for ASP.NET Core projects?
I've got a ASP.NET REST API up and running in Azure. From an older .NET 4.5 project in Visual I've generated a client using this menu option:

But when I create a new ASP.NET Core (ASP.NET 5) project, and want to generate the client there is no such option:

What is the intended way to generate the client for my REST api in ASP.NET Core projects?

答:
I also had this problem so I built a tool called REST API Client Code Generator to solve it. I worked in teams where we used tools like AutoRest, NSwag, and Swagger Codegen to generate our REST API Clients and consume it from .NET Core web applications. It always annoyed me that the "Add New - REST API Client..." tooling in Visual Studio didn't always work and was very troublesome when it was time to re-generate the client

This would add the OpenAPI specification file (Swagger.json) to the project and set a custom tool so that every time changes are made to it the REST API Client code is re-generated. You can also right click on the Swagger.json file and switch code generators

And for NSwag Studio files you can also just right click and re-generate

I built the tool mainly for personal use and for use within my teams but if you find it useful and think it lacks something you really need then please reach out


问:
How can I return vector<vector<float>> from JNI?
I have a function in C++:

std::vector<std::vector<float>> const &GetVertices() { return m_Vertices; }
```

<p>I need to return this value to Java through JNI.</p>

<p>So, because of the fact that I need to return <code>vector</code> of <code>vector</code>, I think that I have to use <code>jobjectArray</code>, like this:</p>

<pre class="lang-cpp prettyprint-override"><code>extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_
java_helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */
)
</code>```

In Java, I have this method:

public native Object[] fillListWithData();
```

<p><strong>So, my question is, how to convert <code>vector<vector<float>></code> to <code>jobjectArray</code>?</strong></p>

<p>I know that there is a method that could create <code>jobjectArray</code>:</p>

<pre class="lang-cpp prettyprint-override"><code>jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);
</code>```

Then how can I put in the values ?

Full class implementation

extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_java_
helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */
) {
    //verticesVec
    vector<vector<float>> verticesVec = initializer->GetVertices(); // THIS VECTOR I NEED TO CONVERT TO JOBJECTARRAY
    jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);

    //HOW TO FILL THE ARRAY HERE??

    return verticesArr;
}
```

答:
You have to play with java.util.Vector. This way, you can make a very simple mapping of

```<code>(C++ side) vector<vector<float> >  --->  Vector<Vector<Float>> (Java side)
</code>```

The code itself will be little bit ugly. Remember that playing with JNI is not quite pleasant experience (due to esoteric syntax).

Anyway, what you want to do is to create all the stuff on C++ side and pass it back to Java.

Just an excerpt

```<code>  vector<vector<float> > vect {
                                 { 1.1, 1.2, 1.3 },
                                 { 2.1, 2.2, 2.3 },
                                 { 3.1, 3.2, 3.3 }
                              };
  ...
  ...

  jclass vectorClass = env->FindClass("java/util/Vector");
  ...

  jclass floatClass = env->FindClass("java/lang/Float");
  ...

  jmethodID mid = env->GetMethodID(vectorClass, "<init>", "()V");
  jmethodID addMethodID = env->GetMethodID(vectorClass, "add", "(Ljava/lang/Object;)Z");

  // Outer vector
  jobject outerVector = env->NewObject(vectorClass, mid);
  ...

  for(vector<float> i : vect) {

    // Inner vector
    jobject innerVector = env->NewObject(vectorClass, mid);

    for(float f : i) {
      jmethodID floatConstructorID = env->GetMethodID(floatClass, "<init>", "(F)V");
      ...

      // Now, we have object created by Float(f)
      jobject floatValue = env->NewObject(floatClass, floatConstructorID, f);
      ...

      env->CallBooleanMethod(innerVector, addMethodID, floatValue);
    }

    env->CallBooleanMethod(outerVector, addMethodID, innerVector);

  }

  env->DeleteLocalRef(vectorClass);
  env->DeleteLocalRef(floatClass);
</code>```

You can find full sample code here:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo045

Once you run the test, you can see that C++ based data was passed to Java

```<code>> make test
/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java -Djava.library.path=:./lib -cp target recipeNo045.VectorOfVectors
library: :./lib
[1.1,1.2,1.3]
[2.1,2.2,2.3]
[3.1,3.2,3.3]
</code>```

Body:
I have a function in C++:

std::vector<std::vector<float>> const &GetVertices() { return m_Vertices; }

I need to return this value to Java through JNI.

So, because of the fact that I need to return vector of vector, I think that I have to use jobjectArray, like this:

extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_
java_helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */
)

In Java, I have this method:

public native Object[] fillListWithData();

So, my question is, how to convert vector<vector<float>> to jobjectArray?

I know that there is a method that could create jobjectArray:

jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);

Then how can I put in the values ?

Full class implementation

extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_java_
helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */
) {
    //verticesVec
    vector<vector<float>> verticesVec = initializer->GetVertices(); // THIS VECTOR I NEED TO CONVERT TO JOBJECTARRAY
    jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);

    //HOW TO FILL THE ARRAY HERE??

    return verticesArr;
}

Body:
You have to play with java.util.Vector. This way, you can make a very simple mapping of

(C++ side) vector<vector<float> >  --->  Vector<Vector<Float>> (Java side)

The code itself will be little bit ugly. Remember that playing with JNI is not quite pleasant experience (due to esoteric syntax).

Anyway, what you want to do is to create all the stuff on C++ side and pass it back to Java.

Just an excerpt

  vector<vector<float> > vect {
                                 { 1.1, 1.2, 1.3 },
                                 { 2.1, 2.2, 2.3 },
                                 { 3.1, 3.2, 3.3 }
                              };
  ...
  ...

  jclass vectorClass = env->FindClass("java/util/Vector");
  ...

  jclass floatClass = env->FindClass("java/lang/Float");
  ...

  jmethodID mid = env->GetMethodID(vectorClass, "<init>", "()V");
  jmethodID addMethodID = env->GetMethodID(vectorClass, "add", "(Ljava/lang/Object;)Z");

  // Outer vector
  jobject outerVector = env->NewObject(vectorClass, mid);
  ...

  for(vector<float> i : vect) {

    // Inner vector
    jobject innerVector = env->NewObject(vectorClass, mid);

    for(float f : i) {
      jmethodID floatConstructorID = env->GetMethodID(floatClass, "<init>", "(F)V");
      ...

      // Now, we have object created by Float(f)
      jobject floatValue = env->NewObject(floatClass, floatConstructorID, f);
      ...

      env->CallBooleanMethod(innerVector, addMethodID, floatValue);
    }

    env->CallBooleanMethod(outerVector, addMethodID, innerVector);

  }

  env->DeleteLocalRef(vectorClass);
  env->DeleteLocalRef(floatClass);

You can find full sample code here:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo045

Once you run the test, you can see that C++ based data was passed to Java

> make test
/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java -Djava.library.path=:./lib -cp target recipeNo045.VectorOfVectors
library: :./lib
[1.1,1.2,1.3]
[2.1,2.2,2.3]
[3.1,3.2,3.3]


问:
Are tables still the preferred method of designing email templates?
I am redesigning my company's email templates and I opted to code the basic structure from scratch rather than wrestling with what has been created in the distant past.

I ran into a problem designing the footer when I started testing the email in multiple mail apps. In researching the best way to fix it, I stumbled upon the factoid that you should design emails with table-based layouts. I was rather surprised as table-based layouts have been out of date for years.

In 2019 are tables still the go-to method for designing email templates in HTML?

Sources:
https://templates.mailchimp.com/getting-started/html-email-basics/
https://www.campaignmonitor.com/blog/email-marketing/2019/04/tables-in-html-emails-nesting/

答:
Based on all of my experience with responsive emails, yes, they are still the way to go. There are frameworks to help with the process of creating the layouts though.

Check out:
https://mjml.io/

https://foundation.zurb.com/emails/email-templates.html

There are others, but I've played around with both of these.


问:
Fail to install package Facebook in CMD
When I type pip3 install --user Facebook in my CMD. Output appear as below

Could not find a version that satisfies the requirement facebook (from versions: )
No matching distribution found for facebook

答:
I just face this same issue. I solved by installing facebook-sdk instead just facebook.
Run :-  pip install facebook-sdk or  pip3 install facebook-sdk

Title: Fail to install package Facebook in CMD


问:
Creating a shortcut to rename files
Every week we get the same 5 excel files. I made a vba macro that copies the data from those files into the main excel sheet. However, in order for the code to work correctly, I call "Workbooks("Workbook1").worksheet("sheet1").Activate, where the Workbook1 file is actually called 2019-5-12_Workbook1 (which is given as that weeks date). All 5 files have this prefix with the date (eg. 2019-5-12_workbook2...etc). I'd like a way to rename all 5 of those files to the ones that don't have the date in front of them.

I've already found a way to mass rename the files using the ren command in cmd, but I want a faster way to rename them all at once using a simple shortcut on my desktop that runs the cmd command. If possible, I'd only have to save the original files to a folder on the desktop, click the shortcut, and have all 5 files renamed from 2019-5-12_Workbook1 to Workbook1, 2019-5-12_Workbook2 to Workbook2, etc, etc.

答: You can save the ren command in a .bat file and run it from your desktop.

Title: Creating a shortcut to rename files


问:
How to validate if an element is enabled only after 60 seconds
I have a link in my application which gets enabled after 60 seconds. I have to verify , that the link only gets enabled after 60 seconds not before that.
Have tried below ways:

I have tried element to be clickable()  with fluent wait/webdriver wait/thread.sleep and all are returning that element is enabled where as it's actually disabled till 60 seconds.

i have tried getAttribute("disabled")also , it also returns false.

The only difference i can see in the html is the class attribute. When it is disabled , class attribute value has additional text (disabled) added to it.

答:
As the link within the application gets enabled after 60 seconds and till then (being disabled) the class attribute contains the additional value disabled, to validate this usecase you can use a try-catch{} block and you can use either of the following Python based Locator Strategies:

CSS_SELECTOR:

```<code>try:
    WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "tag_name[some_attribute='value_of_some_attribute']:not(.disabled)")))
    print("Class attribute failed to contain the value disabled for 60 seconds")
except TimeoutException:
    print("Class attribute successfully contained the value disabled for 60 seconds")
</code>```

XPATH:

```<code>try:
    WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, "//tag_name[@some_attribute='value_of_some_attribute' and not(@class='disabled')]")))
    print("Class attribute failed to contain the value disabled for 60 seconds")
except TimeoutException:
    print("Class attribute successfully contained the value disabled for 60 seconds")
</code>```

Body:
As the link within the application gets enabled after 60 seconds and till then (being disabled) the class attribute contains the additional value disabled, to validate this usecase you can use a try-catch{} block and you can use either of the following Python based Locator Strategies:

CSS_SELECTOR:

try:
    WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "tag_name[some_attribute='value_of_some_attribute']:not(.disabled)")))
    print("Class attribute failed to contain the value disabled for 60 seconds")
except TimeoutException:
    print("Class attribute successfully contained the value disabled for 60 seconds")

XPATH:

try:
    WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, "//tag_name[@some_attribute='value_of_some_attribute' and not(@class='disabled')]")))
    print("Class attribute failed to contain the value disabled for 60 seconds")
except TimeoutException:
    print("Class attribute successfully contained the value disabled for 60 seconds")


问:
Javascript closure test- why am I having "undefined" as result?
Here is my code -

```<code>function test1 () {
  let num = 15;

  return function test2 () {
    console.log(num);
    num++;
  }
}

let f = test1();
console.log(f());
console.log(f());
console.log(f());
</code>```

This is the output I am getting -

My question is why am I getting the Undefined results after each value?

答:
f and test2 don't return a value. What do you expect to see in the console logs? If you add return num, then you'll see the numbers printed twice.

function test1() {
  let num = 15;

  return function test2() {
    console.log(num);
    num++;
    return num;
  }
}

let f = test1();
console.log(f());
console.log(f());
console.log(f());```

Body:
Here is my code -

function test1 () {
  let num = 15;

  return function test2 () {
    console.log(num);
    num++;
  }
}

let f = test1();
console.log(f());
console.log(f());
console.log(f());

This is the output I am getting -

My question is why am I getting the Undefined results after each value?