问:
Angular: scroll to top on route change
We have an application with over 300 components with many sub router-outlets. So far only one nested deep. For example) <router-outlet #root-router> -> <wrapper-component> -> <router-outlet #child-router>

For some reason, we cannot get the angular router set up in a way that scrolls the view to the top after each navigation. We have tried many of the SO solutions presented but there seems to be a specific issue with the way our application is set up. I believe it may have something to do with our CSS.

Regardless, these solutions arent working for us for some reason:

```<code>this.router.events.subscribe((evt) => {
  if (!(evt instanceof NavigationEnd)) {
    return;
  }
  window.scrollTo(0, 0);
});
</code>```

```<code>RouterModule.forRoot(routes, {
  scrollPositionRestoration: 'enabled'
})
</code>```

We have tried placing it both in the app.component, and in the child wrapper components that hold the child .

Either way, it would be absurd to have to put this logic in EVERY component (let alone every child wrapper component). Has anyone encountered a similar issue? is there some CSS or animation that could be blocking this from being applied globally?

Router Animations file

```<code>export const fadeAnimation = trigger('fadeAnimation', [
  // The '* => *' will trigger the animation to change between any two states
  transition('* => *', [
    style({position: 'relative'}),
    query(
      ':enter, :leave',
      [style({
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        padding: '0 20px 20px 20px'
      })],
      {optional: true}
    ),
    query(
      ':enter',
      [style({opacity: 0})],
      {optional: true}
    ),
    query(
      ':leave',
      [style({opacity: 1}), animate('0.2s', style({opacity: 0}))],
      {optional: true}
    ),
    query(
      ':enter',
      [style({opacity: 0}), animate('0.2s', style({opacity: 1}))],
      {optional: true}
    )
  ])
]);
</code>```

app.component.html

```<code><div [ngClass]="theme" class="theme">
  <app-topnav></app-topnav>

  <mat-sidenav-container>
    <mat-sidenav (closed)="navItemService.sideNavOpened = false" [(opened)]="navItemService.sideNavOpened" mode="over"
                 position="end">
      <app-sidenav></app-sidenav>
    </mat-sidenav>

    <mat-sidenav-content>
      <main [@fadeAnimation]="o.isActivated ? o.activatedRoute : ''">
        <router-outlet #o="outlet"></router-outlet>
      </main>
      <app-footer></app-footer>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>
</code>```

app.component.css

```<code>div.theme {
  display: grid;
  grid-template-rows: min-content 1fr;
  height: 100%;
}

mat-sidenav {
  height: 100%;
  width: 20em;
  background: #428bca;
  border-right: 2px lightgray solid;
}

mat-sidenav-content {
  display: grid;
  grid-template-rows: 1fr min-content;
}

main {
  padding: 0 20px 20px 20px;
}
</code>```

答:
```<code>    @NgModule({
     imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: "top"})],
    exports: [RouterModule]
  })
</code>```

Use scrollPositionRestoration: "top" in forRoot

Title: Angular: scroll to top on route change

Body:
We have an application with over 300 components with many sub router-outlets. So far only one nested deep. For example) <router-outlet #root-router> -> <wrapper-component> -> <router-outlet #child-router>

For some reason, we cannot get the angular router set up in a way that scrolls the view to the top after each navigation. We have tried many of the SO solutions presented but there seems to be a specific issue with the way our application is set up. I believe it may have something to do with our CSS.

Regardless, these solutions arent working for us for some reason:

this.router.events.subscribe((evt) => {
  if (!(evt instanceof NavigationEnd)) {
    return;
  }
  window.scrollTo(0, 0);
});

RouterModule.forRoot(routes, {
  scrollPositionRestoration: 'enabled'
})

We have tried placing it both in the app.component, and in the child wrapper components that hold the child .

Either way, it would be absurd to have to put this logic in EVERY component (let alone every child wrapper component). Has anyone encountered a similar issue? is there some CSS or animation that could be blocking this from being applied globally?

Router Animations file

export const fadeAnimation = trigger('fadeAnimation', [
  // The '* => *' will trigger the animation to change between any two states
  transition('* => *', [
    style({position: 'relative'}),
    query(
      ':enter, :leave',
      [style({
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        padding: '0 20px 20px 20px'
      })],
      {optional: true}
    ),
    query(
      ':enter',
      [style({opacity: 0})],
      {optional: true}
    ),
    query(
      ':leave',
      [style({opacity: 1}), animate('0.2s', style({opacity: 0}))],
      {optional: true}
    ),
    query(
      ':enter',
      [style({opacity: 0}), animate('0.2s', style({opacity: 1}))],
      {optional: true}
    )
  ])
]);

app.component.html

  <app-topnav></app-topnav>

  <mat-sidenav-container>
    <mat-sidenav (closed)="navItemService.sideNavOpened = false" [(opened)]="navItemService.sideNavOpened" mode="over"
                 position="end">
      <app-sidenav></app-sidenav>
    </mat-sidenav>

    <mat-sidenav-content>

        <router-outlet #o="outlet"></router-outlet>

      <app-footer></app-footer>
    </mat-sidenav-content>
  </mat-sidenav-container>

app.component.css

div.theme {
  display: grid;
  grid-template-rows: min-content 1fr;
  height: 100%;
}

mat-sidenav {
  height: 100%;
  width: 20em;
  background: #428bca;
  border-right: 2px lightgray solid;
}

mat-sidenav-content {
  display: grid;
  grid-template-rows: 1fr min-content;
}

main {
  padding: 0 20px 20px 20px;
}

Body:
    @NgModule({
     imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: "top"})],
    exports: [RouterModule]
  })

Use scrollPositionRestoration: "top" in forRoot


来源: stackexchange

问:
Recursive SQL Query with Postgres Ranges To Find Availability
I followed this blogpost: https://info.crunchydata.com/blog/range-types-recursion-how-to-search-availability-with-postgresql

CREATE TABLE travels (
    id serial PRIMARY KEY,
    travel_dates daterange NOT NULL,
    EXCLUDE USING spgist (travel_dates WITH &&)
);

```

<p>and found this function to be buggy when I've inserted rows with duration back to back</p>

<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(available_dates daterange)
AS $$
    WITH RECURSIVE calendar AS (
        SELECT
            $1 AS left,
             $1 AS center,
             $1 AS right
        UNION
        SELECT
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN daterange(lower(calendar.left), lower(travels.travel_dates * calendar.left))
                ELSE daterange(lower(calendar.right), lower(travels.travel_dates * calendar.right))
            END AS left,
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN travels.travel_dates * calendar.left
                ELSE travels.travel_dates * calendar.right
            END AS center,
            CASE travels.travel_dates && calendar.right
                WHEN TRUE THEN daterange(upper(travels.travel_dates * calendar.right), upper(calendar.right))
                ELSE daterange(upper(travels.travel_dates * calendar.left), upper(calendar.left))
            END AS right
        FROM calendar
        JOIN travels ON
            travels.travel_dates && $1 AND
            travels.travel_dates <> calendar.center AND (
                travels.travel_dates && calendar.left OR
                travels.travel_dates && calendar.right
            )
)
SELECT *
FROM (
    SELECT
        a.left AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.left <> b.left AND
        a.left @> b.left
    GROUP BY a.left
    HAVING NOT bool_or(COALESCE(a.left @> b.left, FALSE))
    UNION
    SELECT
        a.right AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.right <> b.right AND
        a.right @> b.right
    GROUP BY a.right
    HAVING NOT bool_or(COALESCE(a.right @> b.right, FALSE))
) a
$$ LANGUAGE SQL STABLE;

</code>```

```<code>INSERT INTO travels (travel_dates)
VALUES
    (daterange('2018-03-02', '2018-03-02', '[]')),
    (daterange('2018-03-06', '2018-03-09', '[]')),
    (daterange('2018-03-11', '2018-03-12', '[]')),
    (daterange('2018-03-16', '2018-03-17', '[]')),
    (daterange('2018-03-25', '2018-03-27', '[]'));
</code>```

This works as expected at this point.

```<code>SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;
</code>```

```<code>available_dates
-------------------------
[2018-03-01,2018-03-02)
[2018-03-03,2018-03-06)
[2018-03-10,2018-03-11)
[2018-03-13,2018-03-16)
[2018-03-18,2018-03-25)
[2018-03-28,2018-04-01)
</code>```

But when this row is added:

INSERT INTO travels (travel_dates)
VALUES
(daterange('2018-03-03', '2018-03-05', '[]'));
```

<p>And re-run</p>

```SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;
```

<p>I get</p>

```available_dates
-------------------------
empty
```

答:
I've added a comment on the original blog post as to where I think the error is arising from, that is, in the way empty ranges are handled.

When the date ranges are consecutive, or rather adjacent, it results in 'empty' ranges in either, or even both the 'left' and 'right' columns. Now, after the recursive CTE completes, (and supposing that the empty ranges are in the 'left' column), in the 'LEFT OUTER JOIN ... ON ...' clause, a free and valid travel_date gets paired with an 'empty' range from B.left range since A.left <> 'empty' && A.left @> 'empty' since all ranges contain the empty range trivially. Ideally, it should be paired with a NULL since this is a left outer join for it to be included in the final result set but the 'empty' kinda got in the way. The 'empty' then pops up again in the 'GROUP BY ... HAVING ...' clause where a.left @> 'empty' evaluates to true and it's negated hence all valid travel dates are discared resulting in an empty table. My solution is as follows, have the 'emptys' as NULL, and discard any daterange that's in the 'center':

CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(available_dates daterange)
AS $$
    WITH RECURSIVE calendar AS (
        SELECT
            $1 AS left,
             $1 AS center,
             $1 AS right
        UNION
        SELECT
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN daterange(lower(calendar.left), lower(travels.travel_dates * calendar.left))
                ELSE daterange(lower(calendar.right), lower(travels.travel_dates * calendar.right))
            END AS left,
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN travels.travel_dates * calendar.left
                ELSE travels.travel_dates * calendar.right
            END AS center,
            CASE travels.travel_dates && calendar.right
                WHEN TRUE THEN daterange(upper(travels.travel_dates * calendar.right), upper(calendar.right))
                ELSE daterange(upper(travels.travel_dates * calendar.left), upper(calendar.left))
            END AS right
        FROM calendar
        JOIN travels ON
            travels.travel_dates && $1 AND
            travels.travel_dates <> calendar.center AND (
                travels.travel_dates && calendar.left OR
                travels.travel_dates && calendar.right
            )
)
SELECT *
FROM (
    SELECT
        a.left AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.left <> b.left AND
        a.left @> b.left
    GROUP BY a.left
    HAVING NOT bool_or(coalesce(a.left @> case when isempty(b.left) then null else b.left end, FALSE))

    UNION

    SELECT
        a.right AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.right <> b.right AND
        a.right @> b.right
    GROUP BY a.right
    HAVING NOT bool_or(coalesce(a.right @> case when isempty(b.right) then null else b.right end, false))

    EXCEPT

    SELECT a.center AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.center <> b.center AND
        a.center @> b.center
    GROUP BY a.center
    HAVING NOT bool_or(COALESCE(a.center @> b.center, FALSE))
) a
WHERE NOT isempty(a.available_dates)
$$ LANGUAGE SQL STABLE;
```

ContentLicense: CC BY-SA 4.0

Body:
I followed this blogpost: https://info.crunchydata.com/blog/range-types-recursion-how-to-search-availability-with-postgresql

CREATE TABLE travels (
    id serial PRIMARY KEY,
    travel_dates daterange NOT NULL,
    EXCLUDE USING spgist (travel_dates WITH &&)
);

and found this function to be buggy when I've inserted rows with duration back to back

CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(available_dates daterange)
AS $$
    WITH RECURSIVE calendar AS (
        SELECT
            $1 AS left,
             $1 AS center,
             $1 AS right
        UNION
        SELECT
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN daterange(lower(calendar.left), lower(travels.travel_dates * calendar.left))
                ELSE daterange(lower(calendar.right), lower(travels.travel_dates * calendar.right))
            END AS left,
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN travels.travel_dates * calendar.left
                ELSE travels.travel_dates * calendar.right
            END AS center,
            CASE travels.travel_dates && calendar.right
                WHEN TRUE THEN daterange(upper(travels.travel_dates * calendar.right), upper(calendar.right))
                ELSE daterange(upper(travels.travel_dates * calendar.left), upper(calendar.left))
            END AS right
        FROM calendar
        JOIN travels ON
            travels.travel_dates && $1 AND
            travels.travel_dates <> calendar.center AND (
                travels.travel_dates && calendar.left OR
                travels.travel_dates && calendar.right
            )
)
SELECT *
FROM (
    SELECT
        a.left AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.left <> b.left AND
        a.left @> b.left
    GROUP BY a.left
    HAVING NOT bool_or(COALESCE(a.left @> b.left, FALSE))
    UNION
    SELECT
        a.right AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.right <> b.right AND
        a.right @> b.right
    GROUP BY a.right
    HAVING NOT bool_or(COALESCE(a.right @> b.right, FALSE))
) a
$$ LANGUAGE SQL STABLE;

INSERT INTO travels (travel_dates)
VALUES
    (daterange('2018-03-02', '2018-03-02', '[]')),
    (daterange('2018-03-06', '2018-03-09', '[]')),
    (daterange('2018-03-11', '2018-03-12', '[]')),
    (daterange('2018-03-16', '2018-03-17', '[]')),
    (daterange('2018-03-25', '2018-03-27', '[]'));

This works as expected at this point.

SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;

available_dates
-------------------------
[2018-03-01,2018-03-02)
[2018-03-03,2018-03-06)
[2018-03-10,2018-03-11)
[2018-03-13,2018-03-16)
[2018-03-18,2018-03-25)
[2018-03-28,2018-04-01)

But when this row is added:

INSERT INTO travels (travel_dates)
VALUES
(daterange('2018-03-03', '2018-03-05', '[]'));

And re-run

SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;

I get

available_dates
-------------------------
empty


问:
determine if an application is shutting down normally
is there a way to determing if a jvm is shutting down normally?  Shutdown hook can only spawn a thread, is there a way to determine if the JVM is existing normally or abnormally at that time?</p>

答:
I remembered a similar question being asked time ago. One possible course of action is the use of SignalHandler.

You can read the full article here. It appears to be related to IBM JVM but I think it is equally valid for Java Hotspot.

A little-known feature of Java is the
  ability of an application to install
  its own signal handler, which is
  supported through the sun.misc.Signal
  class. However, use caution when using
  classes from the sun.misc package
  because it contains undocumented
  support classes that may change
  between releases of Java. You can
  install a Java handler for any signal
  that is not used by the JVM. These
  signal handlers are similar to native
  handlers because they're invoked when
  a native system signal is raised, but
  they will always run as a separate
  Java thread. Essentially, when a
  signal is raised for which a Java
  signal handler is available, the JVM's
  "signal dispatcher thread" is woken up
  and informed of the signal. The signal
  dispatcher thread then invokes a Java
  method to create and start a new
  thread for the installed Java signal
  handler. To write a Java signal
  handler, define a class that
  implements the sun.misc.SignalHandler
  interface and register the handler by
  using the sun.misc.Signal.handle()
  method.

ContentLicense: CC BY-SA 3.0


问:
How do I display data from firebase in a flatlist?
I've looked at some similar question and tried to change the code but the data still won't show. I've watch a few tutorials and I've got this far.
This is my code.

```<code> export default class HomeScreen extends React.Component {

  state = {
    dateItems: [],
    loading: false,
  }

  unsubscribe = null;

  async getAppointment() {
    const dateList = [];
    var snapshot = await firebase.firestore()
      .collection('appointment')
      .orderBy('createdAt', 'desc')
      .get()

    snapshot.docs.forEach(doc => {
      dateList.push({
        key: doc.id,
        date: doc.data().date,
        createdAt: doc.data().createdAt,
      });
      this.setState({
        dateItems: dateList,
        loading: false,
      });
    });
    console.log(dateList);
  }

  componentDidMount() {
    this.getAppointment();
  }

  render() {
    return (
      <View style={styles.container}>

        <View >
          <View style={styles.header}>
            <Text style={styles.headerTitle}>Appointments</Text>
            <Button
              onPress={() => this.props.navigation.navigate('Booking')} title="Add"
            />
          </View>
          <FlatList
            data={this.state.dateItems}
            renderItem={(item, index) => (
              <View>
                <Text style={styles.item}>{item.date}</Text>
                <Text>Created: {item.createdAt}</Text>
                <View style={styles.hr}></View>
              </View>
            )}
            keyExtractor={item => item.id}
          />
        </View>
      </View>
    );
  }
}
</code>```

The data shows in an array in the console

```<code>Array [
  Object {
    "createdAt": t {
      "nanoseconds": 467000000,
      "seconds": 1591023433,
    },
    "date": t {
      "nanoseconds": 478000000,
      "seconds": 1592740813,
    },
    "key": "Qlaq8Nd5GYaxFYr9M6Iq",
  },
  Object {
    "createdAt": t {
      "nanoseconds": 31000000,
      "seconds": 1591020391,
    },
    "date": t {
      "nanoseconds": 859000000,
      "seconds": 1593327612,
    },
    "key": "ZsP2pBcNNgb4Nj6Jrpce",
  },
]
</code>```

I need to show the date and not the timestamp for both date and createdAt. i don't know where I can implement this.

答:
Formatting dates in Javascript can be very messy since you get into all sorts of complications with timezones, etc.

But in general, to start with, you'll want a new Date object. To get that, you would do:

```<code>const date = new Date(doc.data().date.seconds * 1000)
</code>```

This is because the Date constructor takes (as one option) the number of milliseconds since 1970 as its argument.

However, this will only give you a Date object, and console.log will return a very long string like "Mon Jun 01 2020 07:57:13 GMT-0700 (Mountain Standard Time)". To format it, you want Intl.DateTimeFormat:

```<code>const dateObj = new Date(doc.data().date.seconds * 1000)
const date = new Intl.DateTimeFormat('en-US').format(dateObj) // "6/1/2020"
</code>```

If you want to have more granular control than that over the date format, look at this SO answer or, to make your life much easier, use something like Moment.js.

If you're ok with the default en-US formatting (or any other locale), your code will end up looking something like the following. I'm not sure why you are calling setState inside every loop of the forEach statement, but assuming you can save that until dateList is fully built, you can use map instead, which is more efficient:

```<code>const dateFormat = new Intl.DateTimeFormat('en-US')
const dateList = snapshot.docs.map(doc => {
  const dateObj = new Date(doc.data().date.seconds * 1000)
  const createdAtObj = new Date(doc.data().createdAt.seconds * 1000)
  return {
    key: doc.id,
    date: dateFormat.format(dateObj),
    createdAt: dateFormat.format(createdAtObj)
  }
 });

 this.setState({
    dateItems: dateList,
    loading: false,
 })
</code>```

Body:
I've looked at some similar question and tried to change the code but the data still won't show. I've watch a few tutorials and I've got this far.
This is my code.

 export default class HomeScreen extends React.Component {

  state = {
    dateItems: [],
    loading: false,
  }

  unsubscribe = null;

  async getAppointment() {
    const dateList = [];
    var snapshot = await firebase.firestore()
      .collection('appointment')
      .orderBy('createdAt', 'desc')
      .get()

    snapshot.docs.forEach(doc => {
      dateList.push({
        key: doc.id,
        date: doc.data().date,
        createdAt: doc.data().createdAt,
      });
      this.setState({
        dateItems: dateList,
        loading: false,
      });
    });
    console.log(dateList);
  }

  componentDidMount() {
    this.getAppointment();
  }

  render() {
    return (
      <View style={styles.container}>

        <View >
          <View style={styles.header}>
            <Text style={styles.headerTitle}>Appointments</Text>
            <Button
              onPress={() => this.props.navigation.navigate('Booking')} title="Add"
            />
          </View>
          <FlatList
            data={this.state.dateItems}
            renderItem={(item, index) => (
              <View>
                <Text style={styles.item}>{item.date}</Text>
                <Text>Created: {item.createdAt}</Text>
                <View style={styles.hr}></View>
              </View>
            )}
            keyExtractor={item => item.id}
          />
        </View>
      </View>
    );
  }
}

The data shows in an array in the console

Array [
  Object {
    "createdAt": t {
      "nanoseconds": 467000000,
      "seconds": 1591023433,
    },
    "date": t {
      "nanoseconds": 478000000,
      "seconds": 1592740813,
    },
    "key": "Qlaq8Nd5GYaxFYr9M6Iq",
  },
  Object {
    "createdAt": t {
      "nanoseconds": 31000000,
      "seconds": 1591020391,
    },
    "date": t {
      "nanoseconds": 859000000,
      "seconds": 1593327612,
    },
    "key": "ZsP2pBcNNgb4Nj6Jrpce",
  },
]

I need to show the date and not the timestamp for both date and createdAt. i don't know where I can implement this.

Body:
Formatting dates in Javascript can be very messy since you get into all sorts of complications with timezones, etc.

But in general, to start with, you'll want a new Date object. To get that, you would do:

const date = new Date(doc.data().date.seconds * 1000)

This is because the Date constructor takes (as one option) the number of milliseconds since 1970 as its argument.

However, this will only give you a Date object, and console.log will return a very long string like "Mon Jun 01 2020 07:57:13 GMT-0700 (Mountain Standard Time)". To format it, you want Intl.DateTimeFormat:

const dateObj = new Date(doc.data().date.seconds * 1000)
const date = new Intl.DateTimeFormat('en-US').format(dateObj) // "6/1/2020"

If you want to have more granular control than that over the date format, look at this SO answer or, to make your life much easier, use something like Moment.js.

If you're ok with the default en-US formatting (or any other locale), your code will end up looking something like the following. I'm not sure why you are calling setState inside every loop of the forEach statement, but assuming you can save that until dateList is fully built, you can use map instead, which is more efficient:

const dateFormat = new Intl.DateTimeFormat('en-US')
const dateList = snapshot.docs.map(doc => {
  const dateObj = new Date(doc.data().date.seconds * 1000)
  const createdAtObj = new Date(doc.data().createdAt.seconds * 1000)
  return {
    key: doc.id,
    date: dateFormat.format(dateObj),
    createdAt: dateFormat.format(createdAtObj)
  }
 });

 this.setState({
    dateItems: dateList,
    loading: false,
 })


问:
javascript mongoose dynamic model assignment
Ive looked related posts and couldn't quite find what I was looking for.

So I am build a backend rest api and I have certain tests I am collecting data on. The tests have their own models, and these models are associated with collections (obviously).

So I have a separate controller for each model. Now I have a "job" controller which queries data from each separate test. Now I have a separate script where I store these model objects in an JSON object. I am wondering how I can access these models properly (I am close but cant quite assign properly). Here is the block:

```<code>const testMappings = {
    'aprobe':aprobe,
    'status':status,
    //'rxserial':rxserial,
}
</code>```

Now when I try assignment as follows, where testMappings is the imported script variable:

```<code>const testMappings = activeTests.testMappings;
console.log(testMappings['aprobe']);
</code>```

I get the following output:

```<code>Model {aprobe}
</code>```

I would like to access the actual aprobe object. Also if anyone knows a better way of dynamically assigning these (instead of having bunch of if statements ie if(name == 'aprobe').... do something), it would be much appreciated.

答:
You are probably looking for something like below :

```<code>const name = 'aprobe';
Object.keys(testMappings).indexOf(name) > -1 ? testMappings[name] : null
</code>```

the above should give you: Model {aprobe}

So basically if the key exists in your object then you'd like to fetch the value of that key which would give you your model dynamically.

Body:
Ive looked related posts and couldn't quite find what I was looking for.

So I am build a backend rest api and I have certain tests I am collecting data on. The tests have their own models, and these models are associated with collections (obviously).

So I have a separate controller for each model. Now I have a "job" controller which queries data from each separate test. Now I have a separate script where I store these model objects in an JSON object. I am wondering how I can access these models properly (I am close but cant quite assign properly). Here is the block:

const testMappings = {
    'aprobe':aprobe,
    'status':status,
    //'rxserial':rxserial,
}

Now when I try assignment as follows, where testMappings is the imported script variable:

const testMappings = activeTests.testMappings;
console.log(testMappings['aprobe']);

I get the following output:

Model {aprobe}

I would like to access the actual aprobe object. Also if anyone knows a better way of dynamically assigning these (instead of having bunch of if statements ie if(name == 'aprobe').... do something), it would be much appreciated.

Body:
You are probably looking for something like below :

const name = 'aprobe';
Object.keys(testMappings).indexOf(name) > -1 ? testMappings[name] : null

the above should give you: Model {aprobe}

So basically if the key exists in your object then you'd like to fetch the value of that key which would give you your model dynamically.


问:
Delay loading of Google Tag Manager
I want to delay loading of GTM based on these conditions:

When page DOM is fully ready, then after 2 seconds

When mouse is moved

When page is scrolled

When click event is registered

This way initial page load time will not be slowed down, and PageSpeed scores will go up.

In my initial testing I have tried removing the script tag, and then adding it later in the console. However, initial PageView is not registered. None of the other events is neither. If I add the script while the page is still loading, it seems to work.

Question is: How can I delay GTM and when GTM is loaded, it finds the events in dataLayer and submits theese too?

答:
This was my work around:</p>

```<code>const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
// specifically this line below makes PageView get's properly triggered and fired
script.onload = () => { dataLayer.push({ event: 'gtm.js', 'gtm.start': (new Date()).getTime(), 'gtm.uniqueEventId': 0 }); }
script.src = 'https://www.googletagmanager.com/gtm.js?id=YOUR-GTM-ID-HERE'

document.head.appendChild(script);
</code>```

Title: Delay loading of Google Tag Manager

Body:
This was my work around:

const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
// specifically this line below makes PageView get's properly triggered and fired
script.onload = () => { dataLayer.push({ event: 'gtm.js', 'gtm.start': (new Date()).getTime(), 'gtm.uniqueEventId': 0 }); }
script.src = 'https://www.googletagmanager.com/gtm.js?id=YOUR-GTM-ID-HERE'

document.head.appendChild(script);


问:
Mongoid Aggregate result into an instance of a rails model

Introduction

Correcting a legacy code, there is an index of object LandingPage where most columns are supposed to be sortable, but aren't. This was mostly corrected, but few columns keep posing me trouble.

Theses columns are the one needing an aggregation, because based on a count of other documents. To simplify the explanation of the problem, I will speak only about one of them which is called Visit, as the rest of the code will just be duplication.

The code fetch sorted and paginate data, then modify each object using LandingPage methods before sending the json back. It was already like this and I can't modify it.

Because of that, I need to do an aggregation (to sort LandingPage by Visit counts), then get the object as LandingPage instance to let the legacy code work on them.

The problem is the incapacity to transform Mongoid::Document to a LandingPage instance

Here is the error I got:

Mongoid::Errors::UnknownAttribute:
Message:
  unknown_attribute : message
Summary:
  unknown_attribute : summary
Resolution:
  unknown_attribute : resolution
```

<h2>Here is my code:</h2>

<pre class="lang-rb prettyprint-override"><code>def controller_function
    landing_pages = fetch_landing_page
    landing_page_hash[:data] = landing_pages.map do |landing_page|
        landing_page.do_something
        # Do other things
    end
    render json: landing_page_hash
end

def fetch_landing_page
    criteria = LandingPage.where(archived: false)

    columns_name = params[:columns_name]
    column_direction = params[:column_direction]

    case order_column_name
    when 'visit'
      order_by_visits(criteria, column_direction)
    else
      criteria.order_by(columns_name => column_direction).paginate(
                   per_page: params[:length],
                   page: (params[:start].to_i / params[:length].to_i) + 1
                 )
    end

    def order_by_visit(criteria, order_direction)

  def order_by_visits(landing_pages, column_direction)
      LandingPage.collection.aggregate([
          { '$match': landing_pages.selector },
          { '$lookup': {
              from: 'visits',
              localField: '_id',
              foreignField: 'landing_page_id',
              as: 'visits'
          }},
          { '$addFields': {  'visits_count': { '$size': '$visits' }}},
          { '$sort': { 'visits_count': column_direction == 'asc' ? 1 : -1 }},
          { '$unset': ['visits', 'visits_count'] },
          { '$skip': params[:start].to_i },
          { '$limit': params[:length].to_i }
      ]).map { |attrs| LandingPage.new(attrs) { |o| o.new_record = false } }
  end
end
</code>```

What I have tried

Copy and past the hash in console to LandingPage.new(attributes), and the instance was created and valid.

Change the attributes key from string to symbole, and it still didn't work.

Using is_a?(hash) on any element of the returned array returns true.

Put it to json and then back to a hash. Still got a Mongoid::Document.

How can I make the return of the Aggregate be a valid instance of LandingPage ?

答:
Aggregation pipeline is implemented by the Ruby MongoDB driver, not by Mongoid, and as such does not return Mongoid model instances.

An example of how one might obtain Mongoid model instances is given in documentation.

Body:
Introduction

Correcting a legacy code, there is an index of object LandingPage where most columns are supposed to be sortable, but aren't. This was mostly corrected, but few columns keep posing me trouble.

Theses columns are the one needing an aggregation, because based on a count of other documents. To simplify the explanation of the problem, I will speak only about one of them which is called Visit, as the rest of the code will just be duplication.

The code fetch sorted and paginate data, then modify each object using LandingPage methods before sending the json back. It was already like this and I can't modify it.

Because of that, I need to do an aggregation (to sort LandingPage by Visit counts), then get the object as LandingPage instance to let the legacy code work on them.

The problem is the incapacity to transform Mongoid::Document to a LandingPage instance

Here is the error I got:

Mongoid::Errors::UnknownAttribute:
Message:
  unknown_attribute : message
Summary:
  unknown_attribute : summary
Resolution:
  unknown_attribute : resolution

Here is my code:

def controller_function
    landing_pages = fetch_landing_page
    landing_page_hash[:data] = landing_pages.map do |landing_page|
        landing_page.do_something
        # Do other things
    end
    render json: landing_page_hash
end

def fetch_landing_page
    criteria = LandingPage.where(archived: false)

    columns_name = params[:columns_name]
    column_direction = params[:column_direction]

    case order_column_name
    when 'visit'
      order_by_visits(criteria, column_direction)
    else
      criteria.order_by(columns_name => column_direction).paginate(
                   per_page: params[:length],
                   page: (params[:start].to_i / params[:length].to_i) + 1
                 )
    end

    def order_by_visit(criteria, order_direction)

  def order_by_visits(landing_pages, column_direction)
      LandingPage.collection.aggregate([
          { '$match': landing_pages.selector },
          { '$lookup': {
              from: 'visits',
              localField: '_id',
              foreignField: 'landing_page_id',
              as: 'visits'
          }},
          { '$addFields': {  'visits_count': { '$size': '$visits' }}},
          { '$sort': { 'visits_count': column_direction == 'asc' ? 1 : -1 }},
          { '$unset': ['visits', 'visits_count'] },
          { '$skip': params[:start].to_i },
          { '$limit': params[:length].to_i }
      ]).map { |attrs| LandingPage.new(attrs) { |o| o.new_record = false } }
  end
end

What I have tried

Copy and past the hash in console to LandingPage.new(attributes), and the instance was created and valid.

Change the attributes key from string to symbole, and it still didn't work.

Using is_a?(hash) on any element of the returned array returns true.

Put it to json and then back to a hash. Still got a Mongoid::Document.

How can I make the return of the Aggregate be a valid instance of LandingPage ?


问:
While executing mysql insert select query- can we do condition check?
I am trying to execute mysql select insert query as below.

```<code>INSERT INTO ACCOUNTS.TABLE1 (NAME,ID,STARTTIME,ENDTIME) SELECT NAME,ID,CREATIONTIME,EXPIRYTIME FROM ACCOUNTS.TABLE2 WHERE ...;
</code>```

Now, if EXPIRYTIME in table2 is null, then i want to update the ENDTIME in table1 to current timestamp. I have overriden the default behavior of this timestamp field by the description

```<code>ENDTIME TIMESTAMP NULL DEFAULT NULL
</code>```

for some reason.

Is it possible in the above select insert query to include some something like an if condition saying if (expirytime == null) then update endtime to current timestamp?

答: How about using a insert trigger to do that?</p>

Body:
I am trying to execute mysql select insert query as below.

INSERT INTO ACCOUNTS.TABLE1 (NAME,ID,STARTTIME,ENDTIME) SELECT NAME,ID,CREATIONTIME,EXPIRYTIME FROM ACCOUNTS.TABLE2 WHERE ...;

Now, if EXPIRYTIME in table2 is null, then i want to update the ENDTIME in table1 to current timestamp. I have overriden the default behavior of this timestamp field by the description

ENDTIME TIMESTAMP NULL DEFAULT NULL

for some reason.

Is it possible in the above select insert query to include some something like an if condition saying if (expirytime == null) then update endtime to current timestamp?


问:
Problem with reading csv file Python Flask Application
I created a Python Flask App. It reads salary.csv file and outputs some data from that file. Right now, my app works perfectly fine as long as the salary.csv file is inside the same folder where app.py is located. But If I don't have salary.csv in the same folder and try to upload it, it gives me this error
FileNotFoundError

FileNotFoundError: [Errno 2] File salary.csv does not exist: 'salary.csv'

app.py

```<code>import pandas
app = Flask(__name__)

@app.route('/')

def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])

def index_post():
    if request.method == 'POST':
#Storing salaries.csv data into a pandas dataframe
        req = request.form['fileToUpload']
        df = pandas.read_csv(req)
#Just calculating some data from dataframe
        base_pay_MEAN = "{:.2f}".format(df['BasePay'].mean())
        base_pay_MAX = "{:.2f}".format(df['BasePay'].max())
        base_pay_MIN = "{:.2f}".format(df['BasePay'].min())

        overtime_MAX = df['OvertimePay'].max()
        highest_paid_Person_NAME = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['EmployeeName']
        highest_paid_Person_SALARY = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['TotalPayBenefits']
        highest_paid_Person_JOB = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['JobTitle']

        lowest_paid_Person_NAME = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['EmployeeName']
        lowest_paid_Person_SALARY = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['TotalPayBenefits']
        lowest_paid_Person_JOB = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['JobTitle']
        num_Unique_Jobs = df['JobTitle'].nunique()
        most_common_jobs = df.groupby('JobTitle').count().sort_values(by='Id', ascending=False)['Id'].head(3)

#Returning the data to webpage
        return render_template('index.html',
        base_pay_Title="Basepay",
        base_pay_MEAN=( "Mean: $" + str(base_pay_MEAN)),
        base_pay_MAX=( "Max: $" + str(base_pay_MAX)),
        base_pay_MIN=( "Min: $" + str(base_pay_MIN)),
        over_time_Title="Overtime",
        over_time_MAX=("Max: $" + str(overtime_MAX)),
        highest_paid_Title = "Highest Paid",
        highest_paid_person=("Name: " + str(highest_paid_Person_NAME)),
        highest_paid_job=("Job: " + str(highest_paid_Person_JOB)),
        highest_paid_salary=("Salary: $" + str(highest_paid_Person_SALARY)),
        lowest_pay_Title = "Lowest Paid",
        lowest_paid_person=("Name: " + str(lowest_paid_Person_NAME)),
        lowest_paid_job=("Job: " + str(lowest_paid_Person_JOB)),
        lowest_paid_salary=("Salary: $" + str(lowest_paid_Person_SALARY))
        )
    else:
        render_template('index.html')

if __name__ == '__main__':
   app.run(host="localhost", port=7000, debug=True)
</code>```

index.html

```<code><html>
    <head>
        <link rel="stylesheet" type="text/css" href="static/main.css">
    </head>

    <body>
        <div class="container">
            <h1>
                Some Title
            </h1>

            <p>Please upload your CSV file. The values containing addresses should be in a column named <em>address</em> or <em>Address</em></p>
            <form method='POST'>
                <input type="file" name="fileToUpload" id="fileToUpload">
                <button id="download">Submit</button>
            </form>
            <div class="results">
                <h3 class="base-pay">{{base_pay_Title}}</h3>
                <p class="base-pay-mean">{{ base_pay_MEAN }}</p>
                <p class="base-pay-high">{{base_pay_MAX}}</p>
                <p class="base-pay-low">{{base_pay_MIN}}</p>

                <h3 class="over-time">{{over_time_Title}}</h3>
                <p class="over-time-max">{{over_time_MAX}}</p>

                <h3 class="highest-paid">{{highest_paid_Title}}</h3>
                <p class="highest-paid-person">{{highest_paid_person}}</p>
                <p class="highest-paid-job">{{highest_paid_job}}</p>
                <p class="highest-paid-salary">{{highest_paid_salary}}</p>

                <h3 class="lowest-paid">{{lowest_pay_Title}}</h3>
                <p class="lowest-paid-person">{{lowest_paid_person}}</p>
                <p class="lowest-paid-job">{{lowest_paid_job}}</p>
                <p class="lowest-paid-salary">{{lowest_paid_salary}}</p>

            </div>
        </div>
    </body>
</html>```
```

答:
That is happening because Pandas is trying to read a local file instead of your submitted file.

Instead of reading the form dictionary, you need to access the files dictionary and pass its content to a Pandas DataFrame

req = request.files.get('fileToUpload')
df = pandas.read_csv(req)
```

Body:
I created a Python Flask App. It reads salary.csv file and outputs some data from that file. Right now, my app works perfectly fine as long as the salary.csv file is inside the same folder where app.py is located. But If I don't have salary.csv in the same folder and try to upload it, it gives me this error
FileNotFoundError

FileNotFoundError: [Errno 2] File salary.csv does not exist: 'salary.csv'

app.py

import pandas
app = Flask(__name__)

@app.route('/')

def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])

def index_post():
    if request.method == 'POST':
#Storing salaries.csv data into a pandas dataframe
        req = request.form['fileToUpload']
        df = pandas.read_csv(req)
#Just calculating some data from dataframe
        base_pay_MEAN = "{:.2f}".format(df['BasePay'].mean())
        base_pay_MAX = "{:.2f}".format(df['BasePay'].max())
        base_pay_MIN = "{:.2f}".format(df['BasePay'].min())

        overtime_MAX = df['OvertimePay'].max()
        highest_paid_Person_NAME = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['EmployeeName']
        highest_paid_Person_SALARY = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['TotalPayBenefits']
        highest_paid_Person_JOB = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['JobTitle']

        lowest_paid_Person_NAME = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['EmployeeName']
        lowest_paid_Person_SALARY = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['TotalPayBenefits']
        lowest_paid_Person_JOB = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['JobTitle']
        num_Unique_Jobs = df['JobTitle'].nunique()
        most_common_jobs = df.groupby('JobTitle').count().sort_values(by='Id', ascending=False)['Id'].head(3)

#Returning the data to webpage
        return render_template('index.html',
        base_pay_Title="Basepay",
        base_pay_MEAN=( "Mean: $" + str(base_pay_MEAN)),
        base_pay_MAX=( "Max: $" + str(base_pay_MAX)),
        base_pay_MIN=( "Min: $" + str(base_pay_MIN)),
        over_time_Title="Overtime",
        over_time_MAX=("Max: $" + str(overtime_MAX)),
        highest_paid_Title = "Highest Paid",
        highest_paid_person=("Name: " + str(highest_paid_Person_NAME)),
        highest_paid_job=("Job: " + str(highest_paid_Person_JOB)),
        highest_paid_salary=("Salary: $" + str(highest_paid_Person_SALARY)),
        lowest_pay_Title = "Lowest Paid",
        lowest_paid_person=("Name: " + str(lowest_paid_Person_NAME)),
        lowest_paid_job=("Job: " + str(lowest_paid_Person_JOB)),
        lowest_paid_salary=("Salary: $" + str(lowest_paid_Person_SALARY))
        )
    else:
        render_template('index.html')

if __name__ == '__main__':
   app.run(host="localhost", port=7000, debug=True)

index.html

        <link rel="stylesheet" type="text/css" href="static/main.css">

                Some Title

Please upload your CSV file. The values containing addresses should be in a column named address or Address

            <form method='POST'>
                <input type="file" name="fileToUpload" id="fileToUpload">
                <button id="download">Submit</button>
            </form>

{{base_pay_Title}}

{{ base_pay_MEAN }}

{{base_pay_MAX}}

{{base_pay_MIN}}

{{over_time_Title}}

{{over_time_MAX}}

{{highest_paid_Title}}

{{highest_paid_person}}

{{highest_paid_job}}

{{highest_paid_salary}}

{{lowest_pay_Title}}

{{lowest_paid_person}}

{{lowest_paid_job}}

{{lowest_paid_salary}}

```


问:
How to fix java.net.SocketException: Broken pipe?
I am using apache commons http client to call url using post method to post the parameters and it is throwing the below error rarely.

```<code>java.net.SocketException: Broken pipe
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
        at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
        at java.io.FilterOutputStream.write(FilterOutputStream.java:80)
        at org.apache.commons.httpclient.methods.ByteArrayRequestEntity.writeRequest(ByteArrayRequestEntity.java:90)
        at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
        at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
</code>```

Can someone suggest what is causing this Exception and how to debug it?

答:
I'd the same problem while I was developing a simple Java application that listens on a specific TCP. Usually, I had no problem, but when I run some stress test I noticed that some connection broke with error socket write exception.

After Investigation I found a solution that solves my problem. I know this question is quite old, but I prefer to share my solution, someone can find it useful.

The problem was on ServerSocket creation. I read from Javadoc there is a default limit of 50 pending sockets. If you try opening another connection, these will be refused. The solution consist simply in change this default configuration at server side. In the following case, I create a Socket server that listen at TCP port 10_000 and accept max 200 pending sockets.

new Thread(() -> {
      try (ServerSocket serverSocket = new ServerSocket(10_000, 200)) {
        logger.info("Server starts listening on TCP port {}", port);

        while (true) {
          try {
            ClientHandler clientHandler = clientHandlerProvider.getObject(serverSocket.accept(), this);
            executor.execute(clientHandler::start);
          } catch (Exception e) {
            logger.error(e.getMessage());
          }
        }

      } catch (IOException | SecurityException | IllegalArgumentException e) {
        logger.error("Could not open server on TCP port {}. Reason: {}", port, e.getMessage());
      }
    }).start();
```

From Javadoc of ServerSocket:

The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused.

OwnerDisplayName: Mani

Body:
I am using apache commons http client to call url using post method to post the parameters and it is throwing the below error rarely.

java.net.SocketException: Broken pipe
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
        at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
        at java.io.FilterOutputStream.write(FilterOutputStream.java:80)
        at org.apache.commons.httpclient.methods.ByteArrayRequestEntity.writeRequest(ByteArrayRequestEntity.java:90)
        at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
        at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)

Can someone suggest what is causing this Exception and how to debug it?

Body:
I'd the same problem while I was developing a simple Java application that listens on a specific TCP. Usually, I had no problem, but when I run some stress test I noticed that some connection broke with error socket write exception.

After Investigation I found a solution that solves my problem. I know this question is quite old, but I prefer to share my solution, someone can find it useful.

The problem was on ServerSocket creation. I read from Javadoc there is a default limit of 50 pending sockets. If you try opening another connection, these will be refused. The solution consist simply in change this default configuration at server side. In the following case, I create a Socket server that listen at TCP port 10_000 and accept max 200 pending sockets.

new Thread(() -> {
      try (ServerSocket serverSocket = new ServerSocket(10_000, 200)) {
        logger.info("Server starts listening on TCP port {}", port);

        while (true) {
          try {
            ClientHandler clientHandler = clientHandlerProvider.getObject(serverSocket.accept(), this);
            executor.execute(clientHandler::start);
          } catch (Exception e) {
            logger.error(e.getMessage());
          }
        }

      } catch (IOException | SecurityException | IllegalArgumentException e) {
        logger.error("Could not open server on TCP port {}. Reason: {}", port, e.getMessage());
      }
    }).start();

From Javadoc of ServerSocket:

The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused.


问:
Acrobat pdf importAnXFDF from external sources
I have created a pdf form using acrobat with below script.

Below the script:

```<code>function importXFDF() {
    var url = "https://<Server>/first-form_data.xfdf";
    this.importAnXFDF(url);
}
importXFDF();
</code>```

If any users download and open the form i am trying to Prefill the form values from XFDF file  using importAnXFDF() function. XFDF file is dynamically created by php script.

The issue is: if i pass any local xfdf file then the values are populated. But it fails if it is server file. Is it possible to import data to pdf form from server?

答: You can't import an XFDF from a URL, only from a local file path. Instead, create an FDF file on your server then in your form, use submitForm where the URL is the URL to your server plus "#FDF". Thi will tell Acrobat to expect an FDF to be returned. Return the FDF using application/vnd.fdf as the mime type. Acrobat should populate the values.</p>

Body:
I have created a pdf form using acrobat with below script.

Below the script:

function importXFDF() {
    var url = "https://<Server>/first-form_data.xfdf";
    this.importAnXFDF(url);
}
importXFDF();

If any users download and open the form i am trying to Prefill the form values from XFDF file  using importAnXFDF() function. XFDF file is dynamically created by php script.

The issue is: if i pass any local xfdf file then the values are populated. But it fails if it is server file. Is it possible to import data to pdf form from server?


问:
Using JavaScript's Document.write() to create a HTML link
I have an URL stored in a variable (var URL).

I thought this would work:

```<code>document.write("<a href='"+url+"'>LINK</a>");

</code>```

But it isn't! Any solution??

This is exactly what I'm trying to do:

```<code>         <script>

          var url2="https://wa.me/(phonenumber)/?text=";
          var url3="<data:post.title/>";
          var url4=url2+url3;
          var url5="<a href='"+url4+"'>ORDER VIA WHATSAPP</a>";
          document.write(url5);

              </script>
</code>```

(EDIT: IT'S WORKING NOW. SOLVED!)

答:
variables are case sensitive, this should work.

document.write("LINK");
```

<p>Also if you really want to use vanilla js to dynamically create an html element, I would recommend avoiding document.write because of cross site scripting attacks.</p>

<pre class="lang-js prettyprint-override"><code>var url = 'www.yoururl/cpm'
var a = document.createElement('a')
a.textContent = 'LINK'
a.href = url
document.body.appendChild(a)
</code>```

Body:
I have an URL stored in a variable (var URL).

I thought this would work:

document.write("LINK");

But it isn't! Any solution??

This is exactly what I'm trying to do:

(EDIT: IT'S WORKING NOW. SOLVED!)

Body:
variables are case sensitive, this should work.

document.write("<a href='"+URL+"'>LINK</a>");

Also if you really want to use vanilla js to dynamically create an html element, I would recommend avoiding document.write because of cross site scripting attacks.

var url = 'www.yoururl/cpm'
var a = document.createElement('a')
a.textContent = 'LINK'
a.href = url
document.body.appendChild(a)


问:
params[] element not passed into new object in create action
I have a very simple form, with the scaffold controller action. the DB schema for the relevant is as follows:

```<code>  create_table "uploads", :force => true do |t|
    t.string   "name"
    t.string   "location"
    t.string   "type"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "filename"
  end
</code>```

When the form is submitted, the params contains the following (look at the specific type parameter):

```<code>{"utf8"=>"âœ“",
 "authenticity_token"=>"NGV4rS/tZDWg2ZdMLpiSbTJQBDmMyjfYyZqZ6GX/7Kc=",
 "upload"=>{"name"=>"AEGFAEF",
 "type"=>"Sales",
 "file"=>#<ActionDispatch::Http::UploadedFile:0x4dff958 @original_filename="Google.pdf",
 @content_type="application/pdf",
 @headers="Content-Disposition: form-data; name=\"upload[file]\"; filename=\"Google.pdf\"\r\nContent-Type: application/pdf\r\n",
 @tempfile=#<File:C:/Users/kaya/AppData/Local/Temp/RackMultipart20110602-2876-1wyskk3>>},
 "commit"=>"Create Upload"}
</code>```

the first command in the create action of UploadsController is

```<code>@upload = Upload.new(params[:upload])
</code>```

and right after this line I have

```<code>@upload.type = nil
</code>```

I really don't get how such a basic thing is failing. can someone please give a hand?

thanks a bunch in advance.

答: Column 'type' is reserved for STI. I dont know if you are using it. If don't, change 'type' to another name.</p>

Body:
I have a very simple form, with the scaffold controller action. the DB schema for the relevant is as follows:

  create_table "uploads", :force => true do |t|
    t.string   "name"
    t.string   "location"
    t.string   "type"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "filename"
  end

When the form is submitted, the params contains the following (look at the specific type parameter):

{"utf8"=>"âœ“",
 "authenticity_token"=>"NGV4rS/tZDWg2ZdMLpiSbTJQBDmMyjfYyZqZ6GX/7Kc=",
 "upload"=>{"name"=>"AEGFAEF",
 "type"=>"Sales",
 "file"=>#<ActionDispatch::Http::UploadedFile:0x4dff958 @original_filename="Google.pdf",
 @content_type="application/pdf",
 @headers="Content-Disposition: form-data; name=\"upload[file]\"; filename=\"Google.pdf\"\r\nContent-Type: application/pdf\r\n",
 @tempfile=#<File:C:/Users/kaya/AppData/Local/Temp/RackMultipart20110602-2876-1wyskk3>>},
 "commit"=>"Create Upload"}

the first command in the create action of UploadsController is

@upload = Upload.new(params[:upload])

and right after this line I have

@upload.type = nil

I really don't get how such a basic thing is failing. can someone please give a hand?

thanks a bunch in advance.


问:
Extract specific URL from a string with Google Apps Script
I have a string like:

```<code>link|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755|
link_of_pdf|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf|
link_of_xml|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.xml|
</code>```

I need to extract the second URL:

```<code>https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf
</code>```

Each URL is contained between 2 sticks and changes with each script execution, but the extension is always the same (* .pdf).

答:
I believe your goal as follows.

You want to retrieve https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf from the following string using Google Apps Script.

```<code>const str = `link|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755|
link_of_pdf|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf|
link_of_xml|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.xml|`;
</code>```

For this, how about this answer?

Pattern 1:

In this pattern, split is used. In this case, when the position of the URL you want is the same, this can be used.

Sample script:

const str = `link|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755|
link_of_pdf|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf|
link_of_xml|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.xml|`;

const res = str.split("|")[3];
console.log(res)```
</div>
</div>
</p>

<h2>Pattern 2:</h2>

<p>In this pattern, regex is used. In this case, when the URL you want is enclosed by <code>link_of_pdf|</code> and <code>|</code>, this can be used.</p>

<h3>Sample script:</h3>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const str = `link|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755|
link_of_pdf|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf|
link_of_xml|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.xml|`;

const res = str.match(/link_of_pdf\|(.+)\|/)[1];
console.log(res)</code>```

References:

split()

match()

Body:
I have a string like:

link|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755|
link_of_pdf|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf|
link_of_xml|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.xml|

I need to extract the second URL:

https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf

Each URL is contained between 2 sticks and changes with each script execution, but the extension is always the same (* .pdf).

Body:
I believe your goal as follows.

You want to retrieve https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf from the following string using Google Apps Script.

const str = `link|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755|
link_of_pdf|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf|
link_of_xml|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.xml|`;

For this, how about this answer?

Pattern 1:

In this pattern, split is used. In this case, when the position of the URL you want is the same, this can be used.

Sample script:

const str = `link|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755|
link_of_pdf|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf|
link_of_xml|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.xml|`;

const res = str.split("|")[3];
console.log(res)

Pattern 2:

In this pattern, regex is used. In this case, when the URL you want is enclosed by link_of_pdf| and |, this can be used.

Sample script:

const str = `link|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755|
link_of_pdf|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.pdf|
link_of_xml|https://www.nubefact.com/cpe/3a5c76ea-9447-4f34-9b90-7f514345cbf8-474b0936-c936-49f5-acb6-9e94102ce755.xml|`;

const res = str.match(/link_of_pdf\|(.+)\|/)[1];
console.log(res)

References:

split()

match()


答:
It works if you write same name

var url="https://www.google.com.tr/"
document.write("LINK");```

Title: Using JavaScript's Document.write() to create a HTML link

Body:
It works if you write same name

var url="https://www.google.com.tr/"
document.write("<a href='"+url+"'>LINK</a>");


问:
Spring Boot Security - Use token from Cookies if Authorization header missing
I currently authenticate my requests against the JWK of my authorization server.
I'm using the spring-boot-starter-oauth2-resource-server package on spring-boot 2.3.
The JWT is taken out from the Authorization: Bearer <token> header and validated against the JWK endpoint.
My security config looks like this:

SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  protected Environment env;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/logs").permitAll();
    http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
    http.oauth2ResourceServer().jwt();
  }
}
```

<p>application.properties</p>

```spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://auth.work.com/v1/jwk
```

<p>External users don't have the <code>Authorization: ...</code> header in their requests, but instead have the following 2 cookies that make up the JWT:</p>

```auth.token_type = Bearer
auth.access_token = <token>
```

Is there a way to extract the JWT from the cookies and validate against the auth server if the the Authorization: ... header is missing?
Could I extract the cookies and add a header to the request before it tries to authorize?
Or it could even be a second method in the authentication chain.

答:
I found out about custom token resolvers and ended up creating one to validate both the header and the cookie. I'm not sure if this is the cleanest solution, but it works.

The only issue I have with this is that it doesn't automatically validate the Authorization: Bearer ... header anymore, so I had to add the code for it too.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/logs").permitAll();
    http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
    http.oauth2ResourceServer().jwt().and().bearerTokenResolver(this::tokenExtractor);
  }

  public String tokenExtractor(HttpServletRequest request) {
    String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (header != null)
      return header.replace("Bearer ", "");
    Cookie cookie = WebUtils.getCookie(request, "auth.access_token");
    if (cookie != null)
      return cookie.getValue();
    return null;
  }
}
```

Body:
I currently authenticate my requests against the JWK of my authorization server.
I'm using the spring-boot-starter-oauth2-resource-server package on spring-boot 2.3.
The JWT is taken out from the Authorization: Bearer <token> header and validated against the JWK endpoint.
My security config looks like this:

SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  protected Environment env;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/logs").permitAll();
    http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
    http.oauth2ResourceServer().jwt();
  }
}

application.properties

spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://auth.work.com/v1/jwk

External users don't have the Authorization: ... header in their requests, but instead have the following 2 cookies that make up the JWT:

auth.token_type = Bearer
auth.access_token = <token>

Is there a way to extract the JWT from the cookies and validate against the auth server if the the Authorization: ... header is missing?
Could I extract the cookies and add a header to the request before it tries to authorize?
Or it could even be a second method in the authentication chain.


问:
Finding matched pairs in two character strings
I have a dataset that looks like the example I've created below

```<code>ex_data <- data.frame(
  House = c("House 1", "House 2", "House 3"),
  features = c("Roof, Walls, Windows, Oven", "Oven, Roof, Walls, TV", "Size, Oven, Bedrooms"),
  attributes = c("Large, White, 5, Whirlpool", "Samsung, Large, White, Sony", "4000 sq ft, KitchenAid, 5")
)
</code>```

Essentially my dataset has the main grouper (House) and has characteristics about that House. The characteristics are comma-separated values.

I am trying to figure out how to find the Oven and the brand that is attributed to the Oven in each house. I know that each house has an oven in the features string but I don't know how to find the corresponding brand.

My thinking is that I would use the function separate to create a new column for each feature and attribute however my real dataset has up to 100 comma-separated features/attributes.

I would like the end result to look like this

```<code>ex_data_result <- data.frame(
  House = c("House 1", "House 2", "House 3"),
  features = c("Oven", "Oven", "Oven"),
  attributes = c("Whirlpool", "Samsung", "KitchenAid")
)
</code>```

Thank you in advance.

答:
We can use separate_rows from tidyr to split the columns 'features', 'attributes' to long format by specifying the sep as , followed by zero or more digits, then filter the rows where 'features' is 'Oven'

```<code>library(dplyr)
library(tidyr)
 ex_data %>%
  separate_rows(features, attributes, sep=",\\s*") %>%
  filter(features == 'Oven')
</code>```

Body:
I have a dataset that looks like the example I've created below

ex_data <- data.frame(
  House = c("House 1", "House 2", "House 3"),
  features = c("Roof, Walls, Windows, Oven", "Oven, Roof, Walls, TV", "Size, Oven, Bedrooms"),
  attributes = c("Large, White, 5, Whirlpool", "Samsung, Large, White, Sony", "4000 sq ft, KitchenAid, 5")
)

Essentially my dataset has the main grouper (House) and has characteristics about that House. The characteristics are comma-separated values.

I am trying to figure out how to find the Oven and the brand that is attributed to the Oven in each house. I know that each house has an oven in the features string but I don't know how to find the corresponding brand.

My thinking is that I would use the function separate to create a new column for each feature and attribute however my real dataset has up to 100 comma-separated features/attributes.

I would like the end result to look like this

ex_data_result <- data.frame(
  House = c("House 1", "House 2", "House 3"),
  features = c("Oven", "Oven", "Oven"),
  attributes = c("Whirlpool", "Samsung", "KitchenAid")
)

Thank you in advance.

Body:
We can use separate_rows from tidyr to split the columns 'features', 'attributes' to long format by specifying the sep as , followed by zero or more digits, then filter the rows where 'features' is 'Oven'

library(dplyr)
library(tidyr)
 ex_data %>%
  separate_rows(features, attributes, sep=",\\s*") %>%
  filter(features == 'Oven')


问:
multiple conditions + regex in awk command
I'm using the following awk command to replace strings in a swift source file:

```<code>awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" "$file" > ./temp
</code>```

Trying not to edit commented out values. At a minimum, need to ignore lines that start with "//" but it seems possible to ignore inline comments (e.g. when the line is only partially commented like "MATCH // <- Ok" or "foo // MATCH <- Not Ok").

Something like...

```<code>    s=index($0,old) && !($0 =~ "^//") { ... }
</code>```

Sample Input:

```<code>old="\"Some \(value) with %@ special \n characters\""
new="\"some_key\".localized"

file {contents}...
    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "Some \(value) with %@ special \n characters" // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters"
</code>```

Expected Output:

```<code>    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "some_key".localized // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters"
</code>```

EDIT

Although @RavinderSingh13's answer did not match expected output, it was close and I used it to modify my command like so:

```<code>BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
s=index($0,old) { if (!(match($0,/.*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }' "$old" "$new" "$file"
</code>```

This meets the original requirement, but ignores ANY line that has two slashes. This is problematic, because it doesn't support in line comments (e.g. the above command would not edit any of the sample input; unless the "// <-- This should change" comment is removed. If no one replies, I'll use this as the answer, but I'll wait a day or so in case someone posts a version of the command that meets all the requirements. Will accept that answer.

It would be something like this...

```<code>s=index($0,old) { if (!(match($0,/.*\/\//)) || (match($0,/"$old".*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }
</code>```

答:
Only look for "old" in the part of each line before the start of any comment, e.g.:</p>

```<code>awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    { preCmt = $0; sub("//.*","", preCmt) }
    s=index(preCmt,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" file
    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "some_key".localized // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters
</code>```

Body:
I'm using the following awk command to replace strings in a swift source file:

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" "$file" > ./temp

Trying not to edit commented out values. At a minimum, need to ignore lines that start with "//" but it seems possible to ignore inline comments (e.g. when the line is only partially commented like "MATCH // <- Ok" or "foo // MATCH <- Not Ok").

Something like...

    s=index($0,old) && !($0 =~ "^//") { ... }

Sample Input:

old="\"Some \(value) with %@ special \n characters\""
new="\"some_key\".localized"

file {contents}...
    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "Some \(value) with %@ special \n characters" // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters"

Expected Output:

    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "some_key".localized // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters"

EDIT

Although @RavinderSingh13's answer did not match expected output, it was close and I used it to modify my command like so:

BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
s=index($0,old) { if (!(match($0,/.*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }' "$old" "$new" "$file"

This meets the original requirement, but ignores ANY line that has two slashes. This is problematic, because it doesn't support in line comments (e.g. the above command would not edit any of the sample input; unless the "// <-- This should change" comment is removed. If no one replies, I'll use this as the answer, but I'll wait a day or so in case someone posts a version of the command that meets all the requirements. Will accept that answer.

It would be something like this...

s=index($0,old) { if (!(match($0,/.*\/\//)) || (match($0,/"$old".*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }

Body:
Only look for "old" in the part of each line before the start of any comment, e.g.:

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    { preCmt = $0; sub("//.*","", preCmt) }
    s=index(preCmt,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$old" "$new" file
    /// - Returns: "Some \(value) with %@ special \n characters"
    static let someValue = "some_key".localized // <-- This should change

    static let otherValue = "This line does NOT change" // "Some \(value) with %@ special \n characters


问:
How to enable picking Google Docs files (kept on Google Drive) with Intent?
I want in my Android app to choose Google Docs file that is kept on Google Drive and after that - to read some data from it (but it's out of this question's scope). So for the start I just want to click on that file and get some callback. I follow this recommendations on Google Drive Android API Deprecation and migration to Google Drive Rest API.

I managed to get dialog with list of Google Drive's files, but I can't choose Google Docs files (I can see them but they are not active to click on them). At the same time I can choose another types of files - for example, PDF, PNG, if I set their MIME-type.

For now I use this piece of code:

```<code>val pickerIntent = Intent(Intent.ACTION_OPEN_DOCUMENT)
pickerIntent.addCategory(Intent.CATEGORY_OPENABLE)
pickerIntent.type = "*/*"
val mimeTypes = arrayOf(
     "application/pdf", // works
     "image/png", //works
     // none of MIME below works
     "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
     "application/vnd.google-apps.document",
     "application/vnd.google-apps.file"
)
pickerIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
</code>```

In the official sample they used MIME "text/plain" as an example, so it's of no help to me.

I tried several MIME-types I could find (here and here for example), but all of them haven't fixed problem.

What MIME-type should be used for this? Or maybe problem is not in MIME-type?

答:
I found what was a source of problem in this official documentation's article.

The thing is Google Doc files - are not the same as "real" PDF|PNG files, they are so-called "virtual" files, since they don't have a binary representation.

The clear answer to my problem is the next note in documentation:

Note: Because an app cannot directly open a virtual file by using the openInputStream() method, don't use the CATEGORY_OPENABLE category when creating the intent that contains the ACTION_OPEN_DOCUMENT or ACTION_OPEN_DOCUMENT_TREE action

So problem was solved after I removed next line:

```<code>pickerIntent.addCategory(Intent.CATEGORY_OPENABLE)
</code>```

In addition I can admit, that picker's filter for Google Doc works well with the next MIME:

```<code>"application/vnd.google-apps.document"
</code>```

Body:
I want in my Android app to choose Google Docs file that is kept on Google Drive and after that - to read some data from it (but it's out of this question's scope). So for the start I just want to click on that file and get some callback. I follow this recommendations on Google Drive Android API Deprecation and migration to Google Drive Rest API.

I managed to get dialog with list of Google Drive's files, but I can't choose Google Docs files (I can see them but they are not active to click on them). At the same time I can choose another types of files - for example, PDF, PNG, if I set their MIME-type.

For now I use this piece of code:

val pickerIntent = Intent(Intent.ACTION_OPEN_DOCUMENT)
pickerIntent.addCategory(Intent.CATEGORY_OPENABLE)
pickerIntent.type = "*/*"
val mimeTypes = arrayOf(
     "application/pdf", // works
     "image/png", //works
     // none of MIME below works
     "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
     "application/vnd.google-apps.document",
     "application/vnd.google-apps.file"
)
pickerIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)

In the official sample they used MIME "text/plain" as an example, so it's of no help to me.

I tried several MIME-types I could find (here and here for example), but all of them haven't fixed problem.

What MIME-type should be used for this? Or maybe problem is not in MIME-type?

Body:
I found what was a source of problem in this official documentation's article.

The thing is Google Doc files - are not the same as "real" PDF|PNG files, they are so-called "virtual" files, since they don't have a binary representation.

The clear answer to my problem is the next note in documentation:

Note: Because an app cannot directly open a virtual file by using the openInputStream() method, don't use the CATEGORY_OPENABLE category when creating the intent that contains the ACTION_OPEN_DOCUMENT or ACTION_OPEN_DOCUMENT_TREE action

So problem was solved after I removed next line:

pickerIntent.addCategory(Intent.CATEGORY_OPENABLE)

In addition I can admit, that picker's filter for Google Doc works well with the next MIME:

"application/vnd.google-apps.document"


问:
Adding sorting override to tree data with CTE
I have a catalog tree that sorts on the catalog name (actually the full catalog path - "root > sub1 > sub2 > my catalog"). I added an "Index" column to override the sorting within a catalog. I was able to make it work when viewing the immediate decedents of a single catalog but I can't get it to work when viewing the entire catalog tree.

```<code>dbo.Catalogs
- CatalogID (int,identity,key)
- Name
- ParentCatalogID (int - 0 for root level catalogs)
- Index (int=0, new field to override alpha sort - higher numbers should take priority)
</code>```

My query to get the entire catalog tree is:

```<code>;with CatalogList as
    (
        -- top level catalogs
        select Catalogs.CatalogID, [Name],
            ParentCatalogID, 1 as CatalogLevel,
            cast([Name] as varchar(max)) as CatalogPath, Catalogs.[Index]
        from Catalogs
        where ParentCatalogID = 0

        union all

        -- sub catalogs, building CatalogPath & CatalogLevel
        select Catalogs.CatalogID, Catalogs.[Name],
            Catalogs.ParentCatalogID, CL.CatalogLevel + 1,
            CL.CatalogPath + ' > ' + Catalogs.[Name] as CatalogPath, Catalogs.[Index]
        from Catalogs
        inner join CatalogList as CL on CL.CatalogID = Catalogs.ParentCatalogID
        where Catalogs.ParentCatalogID > 0
    )
select CatalogList.*
from CatalogList
order by CatalogPath
</code>```

Currently this only works for alpha sorting. The output below would need to have CatalogID 1667 come before 1665 because the Index is higher. I tried looking at ROW_NUMBER() OVER(PARTITION BY...) but haven't been able to make it work.

答:
You were on the right path with row_number()

Example

```<code>Declare @YourTable Table ([CatalogID] int,[Name] varchar(50),[ParentCatalogID] int,[Index] int)
Insert Into @YourTable Values
 (1661,'Canada',0,0)
,(1663,'All Provinces',1661,0)
,(1665,'AG Install & Leasing',1663,0)
,(1666,'Canada Multi-Use',1663,0)
,(1667,'Construnction & Forestry',1663,1)
,(1668,'Turf',1663,'')
,(1664,'Quebec Only',1661,0)

;with cteP as (
      Select CatalogID
            ,[Name]
            ,ParentCatalogID
            ,CatalogLevel = 1
            ,CatalogPath = convert(varchar(500),[Name])
            ,[Index]
            ,Seq = convert(varchar(500),concat('',10000+row_number() over (partition by ParentCatalogID order by [Index] desc,[Name])))
      From   @YourTable
      Where  ParentCatalogID =0
      Union  All
      Select r.CatalogID
            ,r.[Name]
            ,r.ParentCatalogID
            ,p.CatalogLevel + 1
            ,CatalogPath = convert(varchar(500),concat(p.CatalogPath,' > ',r.[Name]))
            ,r.[Index]
            ,Seq = convert(varchar(500),concat(p.Seq,concat('\',10000+row_number() over (partition by r.ParentCatalogID  order by r.[Index] desc,r.[Name]))))
      From   @YourTable r
      Join   cteP p on r.ParentCatalogID  = p.CatalogID
)
Select *
 From  cteP
 Order By Seq
</code>```

Returns

Body:
I have a catalog tree that sorts on the catalog name (actually the full catalog path - "root > sub1 > sub2 > my catalog"). I added an "Index" column to override the sorting within a catalog. I was able to make it work when viewing the immediate decedents of a single catalog but I can't get it to work when viewing the entire catalog tree.

dbo.Catalogs
- CatalogID (int,identity,key)
- Name
- ParentCatalogID (int - 0 for root level catalogs)
- Index (int=0, new field to override alpha sort - higher numbers should take priority)

My query to get the entire catalog tree is:

;with CatalogList as
    (
        -- top level catalogs
        select Catalogs.CatalogID, [Name],
            ParentCatalogID, 1 as CatalogLevel,
            cast([Name] as varchar(max)) as CatalogPath, Catalogs.[Index]
        from Catalogs
        where ParentCatalogID = 0

        union all

        -- sub catalogs, building CatalogPath & CatalogLevel
        select Catalogs.CatalogID, Catalogs.[Name],
            Catalogs.ParentCatalogID, CL.CatalogLevel + 1,
            CL.CatalogPath + ' > ' + Catalogs.[Name] as CatalogPath, Catalogs.[Index]
        from Catalogs
        inner join CatalogList as CL on CL.CatalogID = Catalogs.ParentCatalogID
        where Catalogs.ParentCatalogID > 0
    )
select CatalogList.*
from CatalogList
order by CatalogPath

Currently this only works for alpha sorting. The output below would need to have CatalogID 1667 come before 1665 because the Index is higher. I tried looking at ROW_NUMBER() OVER(PARTITION BY...) but haven't been able to make it work.

Body:
You were on the right path with row_number()

Example

Declare @YourTable Table ([CatalogID] int,[Name] varchar(50),[ParentCatalogID] int,[Index] int)
Insert Into @YourTable Values
 (1661,'Canada',0,0)
,(1663,'All Provinces',1661,0)
,(1665,'AG Install & Leasing',1663,0)
,(1666,'Canada Multi-Use',1663,0)
,(1667,'Construnction & Forestry',1663,1)
,(1668,'Turf',1663,'')
,(1664,'Quebec Only',1661,0)

;with cteP as (
      Select CatalogID
            ,[Name]
            ,ParentCatalogID
            ,CatalogLevel = 1
            ,CatalogPath = convert(varchar(500),[Name])
            ,[Index]
            ,Seq = convert(varchar(500),concat('',10000+row_number() over (partition by ParentCatalogID order by [Index] desc,[Name])))
      From   @YourTable
      Where  ParentCatalogID =0
      Union  All
      Select r.CatalogID
            ,r.[Name]
            ,r.ParentCatalogID
            ,p.CatalogLevel + 1
            ,CatalogPath = convert(varchar(500),concat(p.CatalogPath,' > ',r.[Name]))
            ,r.[Index]
            ,Seq = convert(varchar(500),concat(p.Seq,concat('\',10000+row_number() over (partition by r.ParentCatalogID  order by r.[Index] desc,r.[Name]))))
      From   @YourTable r
      Join   cteP p on r.ParentCatalogID  = p.CatalogID
)
Select *
 From  cteP
 Order By Seq

Returns


问:
Update columns of spark dataframe of type Map with desired key and value
I have a following spark dataframe where all the columns (except for primary key column emp_id) consist of a map (with keys 'from' and 'to' which can have null values). I want to evaluate 'from' and 'to' of each column(except emp_id) and add a new key to the map(named 'change') which has a value of
a) 'insert' if 'from' value is null and 'to' is not null
b) 'delete' if 'to' value is null and 'from' is not null
b) 'update' if 'from' and 'to' are not null & 'from' value is different from 'to' value

Note: columns which have null value will remain untouched.

How can we achieve this in Scala.

```<code>|emp_id|emp_city             |emp_name                    |emp_phone            |emp_sal                    |emp_site                          |

|1     |null                 |[from -> Will, to -> Watson]|null                 |[from -> 1000, to -> 8000]|[from ->, to -> Seattle]          |
|3     |null                 |[from -> Norman, to -> Nate]|null                 |[from -> 1000, to -> 8000]|[from -> CherryHill, to -> Newark]|
|4     |[from ->, to -> Iowa]|[from ->, to -> Ian]        |[from ->, to -> 1004]|[from ->, to -> 8000]     |[from ->, to -> Des Moines]       |
</code>```

Expected:

```<code>|emp_id|emp_city             |emp_name                    |emp_phone            |emp_sal                    |emp_site                          |

|1     |null                 |[from -> Will, to -> Watson, change -> update]|null                 |[from -> 1000, to -> 8000, change -> update]|[from ->, to -> Seattle, change -> insert]          |
|3     |null                 |[from -> Norman, to -> Nate, change -> update]|null                 |[from -> 1000, to -> 8000, change -> update]|[from -> CherryHill, to -> Newark, change -> update]|
|4     |[from ->, to -> Iowa, change -> insert]|[from ->, to -> Ian, change -> insert]        |[from ->, to -> 1004, change -> insert]|[from ->, to -> 8000, change -> insert]     |[from ->, to -> Des Moines, change -> insert]       |
</code>```

答:
One way to achieve this is by using UDF, which is not a great solution but I can't think of other solutions.

Try not to use UDF as possible

```<code>val updateMap = udf((input: Map[String, String]) => {
  if (input == null || input.isEmpty)
    Map.empty[String, String]
  else if (input("from") == null && input("to") != null)
    input + ("change" -> "insert")
  else if (input("from") != null && input("to") == null)
    input + ("change" -> "delete")
  else if (!(input("from").equals(input("to"))))
    input + ("change" -> "update")
  else
    Map.empty[String, String]
</code>```

})

```<code>val result = df.columns.tail.foldLeft(df) { (acc, name) =>
  acc.withColumn(name, updateMap(col(name)))
}
</code>```

Make sure your columns are Map[String, String]

Hope this helps!

Body:
I have a following spark dataframe where all the columns (except for primary key column emp_id) consist of a map (with keys 'from' and 'to' which can have null values). I want to evaluate 'from' and 'to' of each column(except emp_id) and add a new key to the map(named 'change') which has a value of
a) 'insert' if 'from' value is null and 'to' is not null
b) 'delete' if 'to' value is null and 'from' is not null
b) 'update' if 'from' and 'to' are not null & 'from' value is different from 'to' value

Note: columns which have null value will remain untouched.

How can we achieve this in Scala.

|emp_id|emp_city             |emp_name                    |emp_phone            |emp_sal                    |emp_site                          |

|1     |null                 |[from -> Will, to -> Watson]|null                 |[from -> 1000, to -> 8000]|[from ->, to -> Seattle]          |
|3     |null                 |[from -> Norman, to -> Nate]|null                 |[from -> 1000, to -> 8000]|[from -> CherryHill, to -> Newark]|
|4     |[from ->, to -> Iowa]|[from ->, to -> Ian]        |[from ->, to -> 1004]|[from ->, to -> 8000]     |[from ->, to -> Des Moines]       |

Expected:

|emp_id|emp_city             |emp_name                    |emp_phone            |emp_sal                    |emp_site                          |

|1     |null                 |[from -> Will, to -> Watson, change -> update]|null                 |[from -> 1000, to -> 8000, change -> update]|[from ->, to -> Seattle, change -> insert]          |
|3     |null                 |[from -> Norman, to -> Nate, change -> update]|null                 |[from -> 1000, to -> 8000, change -> update]|[from -> CherryHill, to -> Newark, change -> update]|
|4     |[from ->, to -> Iowa, change -> insert]|[from ->, to -> Ian, change -> insert]        |[from ->, to -> 1004, change -> insert]|[from ->, to -> 8000, change -> insert]     |[from ->, to -> Des Moines, change -> insert]       |

Body:
One way to achieve this is by using UDF, which is not a great solution but I can't think of other solutions.

Try not to use UDF as possible

val updateMap = udf((input: Map[String, String]) => {
  if (input == null || input.isEmpty)
    Map.empty[String, String]
  else if (input("from") == null && input("to") != null)
    input + ("change" -> "insert")
  else if (input("from") != null && input("to") == null)
    input + ("change" -> "delete")
  else if (!(input("from").equals(input("to"))))
    input + ("change" -> "update")
  else
    Map.empty[String, String]

})

val result = df.columns.tail.foldLeft(df) { (acc, name) =>
  acc.withColumn(name, updateMap(col(name)))
}

Make sure your columns are Map[String, String]

Hope this helps!


问:
Mapping keys from dictionary to values in cases where column being mapped contains a larger string
I have a dictionary with the following keys that pertain to "London" as the value. The problem I am running into is that I want to check if column values contain my key value. So the postal code values should map to 'London" however they are currently mapping to "All Other".

In other words, postal code 'SW4 7SS' has "SW4' in it and therefore should map to 'London' however, it is currently being mapped to 'All Other' with my code.

I only have a mapping available for the current keys in the dictionary. Please advise on how to do so with pandas.

```<code>postal_code= {'SE10':'London',
'SW4':'London',
'SW9':'London',
'SW18':'London',
'   ': 'All Other'
}
</code>```

```<code>Postal Code
SW4 7SS
SW4 6QD
SW4 7UD
</code>```

```<code>df['Region']=df['Postal Code'].map(postal_code)
</code>```

答:
First join the dict.keys by | which is the or operator in regular expression. Then use Series.str.extract to extract these values from your column. Finally use Series.map to map the values with your dict:

```<code>regex = '|'.join(postal_code.keys())
df['Region'] = df['Postal Code'].str.extract(f"({regex})")[0].map(postal_code)

  Postal Code  Region
0     SW4 7SS  London
1     SW4 6QD  London
2     SW4 7UD  London
</code>```

Body:
I have a dictionary with the following keys that pertain to "London" as the value. The problem I am running into is that I want to check if column values contain my key value. So the postal code values should map to 'London" however they are currently mapping to "All Other".

In other words, postal code 'SW4 7SS' has "SW4' in it and therefore should map to 'London' however, it is currently being mapped to 'All Other' with my code.

I only have a mapping available for the current keys in the dictionary. Please advise on how to do so with pandas.

postal_code= {'SE10':'London',
'SW4':'London',
'SW9':'London',
'SW18':'London',
'   ': 'All Other'
}

Postal Code
SW4 7SS
SW4 6QD
SW4 7UD

df['Region']=df['Postal Code'].map(postal_code)

Body:
First join the dict.keys by | which is the or operator in regular expression. Then use Series.str.extract to extract these values from your column. Finally use Series.map to map the values with your dict:

regex = '|'.join(postal_code.keys())
df['Region'] = df['Postal Code'].str.extract(f"({regex})")[0].map(postal_code)

  Postal Code  Region
0     SW4 7SS  London
1     SW4 6QD  London
2     SW4 7UD  London


问:
How to select different values in a column with the same ID and then delete them PHP SQL Server
I am new to the world of programming. I am in need of help in this sentence. what I want to do is select the 0.1,2 values from the CardIndex column and then be able to delete them. Rows must be removed as long as the condition is met. Or what would be the best way to do it.

CardIndex column must have the 3 values yes or yes to execute the delete. otherwise it will not be executed

```<code>$query = "SELECT * FROM CardData where UserIndex='$id' and CardIndex in (0,1,2) ";
$resultados = sqlsrv_query($conn,$query);

if($query1 = sqlsrv_fetch_array($resultados)){
        if($query1 == true){
        $cro =  "DELETE FROM CardData WHERE UserIndex='$id' and CardIndex in (0,1,2)";
        $query3 = sqlsrv_query($conn,$cro);
        }

    echo 'funciona';
    }

    else{
     echo 'no funciona';

}
?>
</code>```

答:
You want or, not and - otherwise you search for rows whose CardIndex has all three values at once, which, obviously, never happens:

```<code>DELETE FROM CardData
WHERE
    UserIndex = @UserIndex
    AND (CardIndex = 1 OR CardIndex = 2 OR CardIndex = 3)
</code>```

This can be shortened with IN:

```<code>DELETE FROM CardData
WHERE UserIndex = @UserIndex AND CardIndex IN (1, 2, 3)
</code>```

Note that there is no point SELECTing the values before deleting them. You can just fire the DELETE directly: if no row matches the condition, no actual deletion will happen.

Finally: do not concatenate variables in the query string; this is inefficient and exposes your code to SQL injection. Instead, you should use parameterized queries (there are plenty of online resources that explain how to this right).

Edit

You want to delete all three records only if all three cardIndex values are available for the given userIndex. Assuming that there are no duplicate (userIndex, cardIndex), one method is an updateable CTE:

```<code>with cte as (
    select count(*) over() cnt
    from cardData
    where userIndex = @UserIndex and cardIndex in (1, 2, 3)
)
delete from cte where cnt = 3
</code>```

Body:
I am new to the world of programming. I am in need of help in this sentence. what I want to do is select the 0.1,2 values from the CardIndex column and then be able to delete them. Rows must be removed as long as the condition is met. Or what would be the best way to do it.

CardIndex column must have the 3 values yes or yes to execute the delete. otherwise it will not be executed

$query = "SELECT * FROM CardData where UserIndex='$id' and CardIndex in (0,1,2) ";
$resultados = sqlsrv_query($conn,$query);

if($query1 = sqlsrv_fetch_array($resultados)){
        if($query1 == true){
        $cro =  "DELETE FROM CardData WHERE UserIndex='$id' and CardIndex in (0,1,2)";
        $query3 = sqlsrv_query($conn,$cro);
        }

    echo 'funciona';
    }

    else{
     echo 'no funciona';

}
?>

Body:
You want or, not and - otherwise you search for rows whose CardIndex has all three values at once, which, obviously, never happens:

DELETE FROM CardData
WHERE
    UserIndex = @UserIndex
    AND (CardIndex = 1 OR CardIndex = 2 OR CardIndex = 3)

This can be shortened with IN:

DELETE FROM CardData
WHERE UserIndex = @UserIndex AND CardIndex IN (1, 2, 3)

Note that there is no point SELECTing the values before deleting them. You can just fire the DELETE directly: if no row matches the condition, no actual deletion will happen.

Finally: do not concatenate variables in the query string; this is inefficient and exposes your code to SQL injection. Instead, you should use parameterized queries (there are plenty of online resources that explain how to this right).

Edit

You want to delete all three records only if all three cardIndex values are available for the given userIndex. Assuming that there are no duplicate (userIndex, cardIndex), one method is an updateable CTE:

with cte as (
    select count(*) over() cnt
    from cardData
    where userIndex = @UserIndex and cardIndex in (1, 2, 3)
)
delete from cte where cnt = 3


答:
This might work instead of document.write().</p>

```<code><html>
  <head></head>
  <body>
    <div id="Place to insert"></div>
    <script>
      var link = document.createElement('a');
      link.textContent = 'Link Title';
      link.href = Your URL;
      document.getElementById('Place to insert').appendChild(link);
    </script>
  </body>
</html>
</code>```

Body:
I have an URL stored in a variable (var URL).

I thought this would work:

document.write("LINK");

But it isn't! Any solution??

This is exactly what I'm trying to do:

(EDIT: IT'S WORKING NOW. SOLVED!)

Body:
This might work instead of document.write().

<html>
  <head></head>
  <body>
    <div id="Place to insert"></div>
    <script>
      var link = document.createElement('a');
      link.textContent = 'Link Title';
      link.href = Your URL;
      document.getElementById('Place to insert').appendChild(link);
    </script>
  </body>
</html>