问:
How to use ChangeNotifier with Navigator
In my app, I have a model that store the user logged in my app.

```<code>class AuthenticationModel extends ChangeNotifier {
  User _user;
  User get user => _user;

  void authenticate(LoginData loginData) async {
    // _user = // get user from http call
    notifyListeners();
  }

  void restoreUser() async {
    //_user = // get user from shared prefs
    notifyListeners();
  }
}
</code>```

The model is registered at the top of the widget tree :

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthenticationModel(),
      child: MaterialApp(
        title: 'My App',
        initialRoute: '/',
        routes: {
          '/': (context) => PrehomeScreen(),
          '/home': (context) => HomeScreen()
        },
      ),
    );
  }
}
</code>```

Somewhere down the widget tree, I have a button that calls the Model :

```<code>          child: Consumer<AuthenticationModel>(
            builder: (context, authModel, child) {
              return MyCustomButton(
                text: 'Connect',
                onPressed: () {
                  authModel.authenticate(...)
                },
              );
            },
          ),
</code>```

Now, I would like, somewhere, listen to the changes on the AuthenticationModel to trigger a Navigator.pushReplacmentNamed('/home') when the user is not null in the model.

I tried to do it in the builder of Prehome :

```<code>class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<AuthenticationModel>(
      builder: (context, authModel, child) {
        if (authModel.user != null) {
          Navigator.of(context).pushReplacementNamed("/home")
        }
        return Container(
          child: // Prehome UI
        );
      },
    );
  }
}
</code>```

but I have a error when doing it like this :

```<code>════════ (2) Exception caught by widgets library ═══════════════════════════════════════════════════
setState() or markNeedsBuild() called during build.
The relevant error-causing widget was:
  Consumer<AuthenticationModel> file:///Users/pierre.degand/Projects/cdc/course_du_coeur/lib/Prehome.dart:13:12
═══════════════════════════════════════════════════════════════════════════════
</code>```

How can I setup such a listener ? Is it a good practice to trigger navigation on model changes like this ?

Thanks

EDIT: I found a way to make this work. Instead of using Consumer inside the PrehomeScreen builder, I used the following code :

```<code>class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    Provider.of<AuthenticationModel>(context).addListener(() {
      Navigator.of(context).pushReplacementNamed("/home");
    });

    return Container(
      child: // UI
    );
  }
}
</code>```

It works fine, the navigation is executed when the model changes. But there is an error message in the console (printed 3 times) :

```<code>════════ (4) Exception caught by foundation library ════════════════════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
════════════════════════════════════════════════════════════════════════════════════════════════════
</code>```

The app does not crash so, for now, I'm ok with this.
I still want to know if this is a good approach or not.

答:
I prefer to use Stream or rxdart PublishSubject BehaviourSubject for listening to any activity or to manage global app data.

I implement it using bloc pattern. Basically bloc pattern is just like redux for react means creating a central dataset that contains all app data and you don't have to do prop drilling.

You can create Stream like this.

```<code>import 'package:rxdart/rxdart.dart';

class AbcBloc {
  BehaviorSubject<bool> _connectivity;
  AbcBloc() {
    _connectivity = BehaviorSubject<bool>();
  }
  // stream
  Stream<bool> get connectivity => _connectivity.stream;
  // sink
  Function(bool) get updateConnectivity => _connectivity.sink.add;
dispose(){
    _connectivity.close();
}
}

void createAbcBloc() {
  if (abcBloc != null) {
    abcBloc.dispose();
  }
  abcBloc = AbcBloc();
}

AbcBloc abcBloc = AbcBloc();

</code>```

now you can access that abcBloc variable from anywhere and listen to connectivity variable like this

```<code>import './abcBloc.dart';
void listenConnectivity(){

abcBloc.connectivity.listen((bool connectivety){

here you can perform your operations
});
}

</code>```

and you can update connectivity from abcBloc.updateConnectivity(false);
every time you perform any changes that listener will get called.

remember you have to call listenConnectivity() one time to get it activated;

Body:
In my app, I have a model that store the user logged in my app.

class AuthenticationModel extends ChangeNotifier {
  User _user;
  User get user => _user;

  void authenticate(LoginData loginData) async {
    // _user = // get user from http call
    notifyListeners();
  }

  void restoreUser() async {
    //_user = // get user from shared prefs
    notifyListeners();
  }
}

The model is registered at the top of the widget tree :

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthenticationModel(),
      child: MaterialApp(
        title: 'My App',
        initialRoute: '/',
        routes: {
          '/': (context) => PrehomeScreen(),
          '/home': (context) => HomeScreen()
        },
      ),
    );
  }
}

Somewhere down the widget tree, I have a button that calls the Model :

          child: Consumer<AuthenticationModel>(
            builder: (context, authModel, child) {
              return MyCustomButton(
                text: 'Connect',
                onPressed: () {
                  authModel.authenticate(...)
                },
              );
            },
          ),

Now, I would like, somewhere, listen to the changes on the AuthenticationModel to trigger a Navigator.pushReplacmentNamed('/home') when the user is not null in the model.

I tried to do it in the builder of Prehome :

class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<AuthenticationModel>(
      builder: (context, authModel, child) {
        if (authModel.user != null) {
          Navigator.of(context).pushReplacementNamed("/home")
        }
        return Container(
          child: // Prehome UI
        );
      },
    );
  }
}

but I have a error when doing it like this :

════════ (2) Exception caught by widgets library ═══════════════════════════════════════════════════
setState() or markNeedsBuild() called during build.
The relevant error-causing widget was:
  Consumer<AuthenticationModel> file:///Users/pierre.degand/Projects/cdc/course_du_coeur/lib/Prehome.dart:13:12
═══════════════════════════════════════════════════════════════════════════════

How can I setup such a listener ? Is it a good practice to trigger navigation on model changes like this ?

Thanks

EDIT: I found a way to make this work. Instead of using Consumer inside the PrehomeScreen builder, I used the following code :

class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    Provider.of<AuthenticationModel>(context).addListener(() {
      Navigator.of(context).pushReplacementNamed("/home");
    });

    return Container(
      child: // UI
    );
  }
}

It works fine, the navigation is executed when the model changes. But there is an error message in the console (printed 3 times) :

════════ (4) Exception caught by foundation library ════════════════════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
════════════════════════════════════════════════════════════════════════════════════════════════════

The app does not crash so, for now, I'm ok with this.
I still want to know if this is a good approach or not.

Body:
I prefer to use Stream or rxdart PublishSubject BehaviourSubject for listening to any activity or to manage global app data.

I implement it using bloc pattern. Basically bloc pattern is just like redux for react means creating a central dataset that contains all app data and you don't have to do prop drilling.

You can create Stream like this.

import 'package:rxdart/rxdart.dart';

class AbcBloc {
  BehaviorSubject<bool> _connectivity;
  AbcBloc() {
    _connectivity = BehaviorSubject<bool>();
  }
  // stream
  Stream<bool> get connectivity => _connectivity.stream;
  // sink
  Function(bool) get updateConnectivity => _connectivity.sink.add;
dispose(){
    _connectivity.close();
}
}

void createAbcBloc() {
  if (abcBloc != null) {
    abcBloc.dispose();
  }
  abcBloc = AbcBloc();
}

AbcBloc abcBloc = AbcBloc();

now you can access that abcBloc variable from anywhere and listen to connectivity variable like this

import './abcBloc.dart';
void listenConnectivity(){

abcBloc.connectivity.listen((bool connectivety){

here you can perform your operations
});
}

and you can update connectivity from abcBloc.updateConnectivity(false);
every time you perform any changes that listener will get called.

remember you have to call listenConnectivity() one time to get it activated;


来源: stackexchange

问:
Overloading on R-value references and code duplication
Consider the following:

```<code>struct vec
{
    int v[3];

    vec() : v() {};
    vec(int x, int y, int z) : v{x,y,z} {};
    vec(const vec& that) = default;
    vec& operator=(const vec& that) = default;
    ~vec() = default;

    vec& operator+=(const vec& that)
    {
        v[0] += that.v[0];
        v[1] += that.v[1];
        v[2] += that.v[2];
        return *this;
    }
};

vec operator+(const vec& lhs, const vec& rhs)
{
    return vec(lhs.v[0] + rhs.v[0], lhs.v[1] + rhs.v[1], lhs.v[2] + rhs.v[2]);
}
vec&& operator+(vec&& lhs, const vec& rhs)
{
    return move(lhs += rhs);
}
vec&& operator+(const vec& lhs, vec&& rhs)
{
    return move(rhs += lhs);
}
vec&& operator+(vec&& lhs, vec&& rhs)
{
    return move(lhs += rhs);
}
</code>```

Thanks to r-value references, with these four overloads of operator+ I can minimize the number of objects created, by reusing temporaries. But I don't like the duplication of code this introduces. Can I achieve the same with less repetition?

答:
Recycling temporaries is an interesting idea and you're not the only one who wrote functions that return rvalue references for this reason. In an older C++0x draft operator+(string&&,string const&) was also declared to return an rvalue reference. But this changed for good reasons. I see three issues with this kind of overloading and choice of return types. Two of them are independent of the actual type and the third argument refers to the kind of type that vec is.

Safety issues. Consider code like this:

```<code>vec a = ....;
vec b = ....;
vec c = ....;
auto&& x = a+b+c;
</code>```

If your last operator returns an rvalue reference, x will be a dangling reference. Otherwise, it won't. This is not an artificial example. For example, the auto&& trick is used in the for-range loop internally to avoid unnecessary copies. But since the life-time extension rule for temporaries during reference binding does not apply in case of a function call that simply returns a reference, you'll get a dangling reference.

```<code>string source1();
string source2();
string source3();

....

int main() {
  for ( char x : source1()+source2()+source3() ) {}
}
</code>```

If the last operator+ returned an rvalue reference to the temporary that is created during the first concatenation, this code would invoke undefined behaviour because the string temporary would not exist long enough.

In generic code, functions that return rvalue references force you to write

```<code>typename std::decay<decltype(a+b+c)>::type
</code>```

instead of

```<code>decltype(a+b+c)
</code>```

simply because the last op+ might return an rvalue reference. This is getting ugly, in my humble opinion.

Since your type vec is both "flat" and small, these op+ overloads are hardly useful. See FredOverflow's answer.

Conclusion: Functions with an rvalue reference return type should be avoided especially if these references may refer to short-lived temporary objects. std::move and std::forward are special-purpose exceptions to this rule of thumb.

ContentLicense: CC BY-SA 3.0

Body:
Consider the following:

struct vec
{
    int v[3];

    vec() : v() {};
    vec(int x, int y, int z) : v{x,y,z} {};
    vec(const vec& that) = default;
    vec& operator=(const vec& that) = default;
    ~vec() = default;

    vec& operator+=(const vec& that)
    {
        v[0] += that.v[0];
        v[1] += that.v[1];
        v[2] += that.v[2];
        return *this;
    }
};

vec operator+(const vec& lhs, const vec& rhs)
{
    return vec(lhs.v[0] + rhs.v[0], lhs.v[1] + rhs.v[1], lhs.v[2] + rhs.v[2]);
}
vec&& operator+(vec&& lhs, const vec& rhs)
{
    return move(lhs += rhs);
}
vec&& operator+(const vec& lhs, vec&& rhs)
{
    return move(rhs += lhs);
}
vec&& operator+(vec&& lhs, vec&& rhs)
{
    return move(lhs += rhs);
}

Thanks to r-value references, with these four overloads of operator+ I can minimize the number of objects created, by reusing temporaries. But I don't like the duplication of code this introduces. Can I achieve the same with less repetition?

Body:
Recycling temporaries is an interesting idea and you're not the only one who wrote functions that return rvalue references for this reason. In an older C++0x draft operator+(string&&,string const&) was also declared to return an rvalue reference. But this changed for good reasons. I see three issues with this kind of overloading and choice of return types. Two of them are independent of the actual type and the third argument refers to the kind of type that vec is.

Safety issues. Consider code like this:

vec a = ....;
vec b = ....;
vec c = ....;
auto&& x = a+b+c;

If your last operator returns an rvalue reference, x will be a dangling reference. Otherwise, it won't. This is not an artificial example. For example, the auto&& trick is used in the for-range loop internally to avoid unnecessary copies. But since the life-time extension rule for temporaries during reference binding does not apply in case of a function call that simply returns a reference, you'll get a dangling reference.

string source1();
string source2();
string source3();

....

int main() {
  for ( char x : source1()+source2()+source3() ) {}
}

If the last operator+ returned an rvalue reference to the temporary that is created during the first concatenation, this code would invoke undefined behaviour because the string temporary would not exist long enough.

In generic code, functions that return rvalue references force you to write

typename std::decay<decltype(a+b+c)>::type

instead of

decltype(a+b+c)

simply because the last op+ might return an rvalue reference. This is getting ugly, in my humble opinion.

Since your type vec is both "flat" and small, these op+ overloads are hardly useful. See FredOverflow's answer.

Conclusion: Functions with an rvalue reference return type should be avoided especially if these references may refer to short-lived temporary objects. std::move and std::forward are special-purpose exceptions to this rule of thumb.


问:
where to run commands on mysql
I work on a java project using mysql as database, at some level I needed to increase  the value of max_allowed_packet variable, I checked in the net but I can't find my.cnf or my.ini.
So I need to run some recommended command such as set global max_allowed_packet=33554432 but I do not know where to find the terminal to do that.
I am using mySql 8.0 on windows 10

答:
First you would need to log into your MySQL instance, typically you would do this from the command line...
mysql -u root -p

That gets you to a MySQL prompt.  From there you can run a SET command

https://dev.mysql.com/doc/refman/8.0/en/set-variable.html

```<code>SET variable = expr [, variable = expr] ...

variable: {
    user_var_name
  | param_name
  | local_var_name
  | {GLOBAL | @@GLOBAL.} system_var_name
  | [SESSION | @@SESSION. | @@] system_var_name
}
</code>```

In your case that command would be SET global max_allowed_packet=33554432;

ContentLicense: CC BY-SA 4.0

Title: where to run commands on mysql

Body:
First you would need to log into your MySQL instance, typically you would do this from the command line...
mysql -u root -p

That gets you to a MySQL prompt.  From there you can run a SET command

https://dev.mysql.com/doc/refman/8.0/en/set-variable.html

SET variable = expr [, variable = expr] ...

variable: {
    user_var_name
  | param_name
  | local_var_name
  | {GLOBAL | @@GLOBAL.} system_var_name
  | [SESSION | @@SESSION. | @@] system_var_name
}

In your case that command would be SET global max_allowed_packet=33554432;


问:
Google DataStudio how to make Pie from two filtered Scorecards?
I tried everything and it's not possible or i don't know how to make it.

I have event-action lets say "color"

This event-action has data containing different labels and it contains  rather  "black" or "white" text in the label.

I made  1 filter to extract the total number of blacks  and 1 more filter  to get the total number of whites.

How to show in my Data Studio  a Pie with  how many % include black and how many include white in the labels?
Is it possible to blend data between 2 filter results?

答:
The method you a trying can't be used as pie charts can only have one metrics. You could possibly manage that with a stacked bar chart?

If "event-action" can't include black AND white then create a dimension with a case statement along the lines of:

```<code>CASE
WHEN REGEXP_MATCH(event-action,"black") THEN "black"
WHEN REGEXP_MATCH(event-action,"white") THEN "white"
ELSE "other"
END
</code>```

You can then use this (filtering out the "other" if necessary) as the dimension in the pie chart with a suitable sum/count metric.

Body:
The method you a trying can't be used as pie charts can only have one metrics. You could possibly manage that with a stacked bar chart?

If "event-action" can't include black AND white then create a dimension with a case statement along the lines of:

CASE
WHEN REGEXP_MATCH(event-action,"black") THEN "black"
WHEN REGEXP_MATCH(event-action,"white") THEN "white"
ELSE "other"
END

You can then use this (filtering out the "other" if necessary) as the dimension in the pie chart with a suitable sum/count metric.


问:
More Efficient method to split overlapped intervals, then merge duplicates
So I'm trying to figure out the most efficient method to split overlapped intervals, then merge duplicates. Two conditions specific to my situation are that if the start of a merged interval was an end of an original interval, it is incremented by 1. If the end of a merged interval was a start of an original interval, it is decremented by 1. Here is some sample data, and the expected result:

```<code>interface Interval {
    start: number;
    end: number;
    type: Array<number>;
}

// starting data
const arr: Array<Interval> = [
    { start: 0, end: 16, type: [42] },
    { start: 6, end: 30, type: [95] },
    { start: 11, end: 24, type: [126] },
    { start: 32, end: 47, type: [42] }
].sort((a, b) => a.start - b.start);

// magic splitting code here

// what we expect to end up with
const end_arr: Array<Interval> = [
    { start: 0, end: 5, type: [42] },
    { start: 6, end: 10, type: [42, 95] },
    { start: 11, end: 16, type: [42, 95, 126] },
    { start: 17, end: 24, type: [95, 126] },
    { start: 25, end: 30, type: [95] },
    { start: 32, end: 47, type: [42] },
];
</code>```

I've already technically got an answer for this, but it is not very efficient - involving 3 nested for/forEach loops. Surely there is a more efficient way? Here is the code for that:

```<code>let startIndexArray: Array<number> = [];

let endIndexArray: Array<number> = [];

for (let i = 0; i < arr.length; i++) {
    startIndexArray.push(arr[i].start);
    endIndexArray.push(arr[i].end);
}

startIndexArray = startIndexArray.sort((a, b) => a - b);
endIndexArray = endIndexArray.sort((a, b) => a - b);

const indexArray = [...startIndexArray, ...endIndexArray].sort((a, b) => a - b);

const result: Array<Interval> = [];

arr.forEach((currentInterval) => {
    for (let i = currentInterval.start; i < currentInterval.end; i++) {
        if (indexArray.includes(i)) {
            const position = indexArray.indexOf(i);

            if (position !== indexArray.length - 1) {
                let start = i;
                let next = indexArray[position + 1];

                if (endIndexArray.includes(start)) {
                    start = start + 1;
                }

                if (startIndexArray.includes(next)) {
                    next = next - 1;
                }

                let in_result = false;
                result.forEach((mergedInterval) => {
                    if (mergedInterval.start === start && mergedInterval.end === next) {
                        mergedInterval.type = [...mergedInterval.type, ...currentInterval.type];
                        in_result = true;
                    }
                });
                if (!in_result) {
                    result.push({ start: start, end: next, type: [...currentInterval.type]});
                }
            }
        }
    }
});

// output is my expected, correct outcome
console.log(result);
</code>```

答:
The following algorithm is the cleanest one I can come up with which has reasonable performance.  I expect that, with the particular example array you gave, this code and the one you gave above will be of similar performance levels, but if you start using larger arrays you will see performance gains here compared to yours.  Without a suite of test cases it's hard to tell for sure.

Anyway, the general idea looks like this. Let's call a Partition a sorted array of non-overlapping intervals that covers all integers from -Infinity to Infinity.

```<code>type Partition = Array<Interval>;
</code>```

If we have a value partition of type Partition, we know that partition[0].start === -Infinity, partition[partition.length-1].end === Infinity, and for any index i < partition.length - 1, partition[i].end + 1 === partition[i+1].start.

One good thing about a partition is that it will always contain exactly one interval that covers any given position.  This eliminates a class of edge cases.  So, given a partition: Partition and a position: number, let's find the index of the interval inside partition that contains it:

```<code>// binary search of the partition to find the index of the interval containing position
// startIndex is a hint, where partition[startIndex].start <= position
// endIndex is a hint, where partition[startIndex].end > position
function findIndex(
    partition: Partition,
    position: number,
    startIndex: number = 0,
    endIndex: number = partition.length
) {
    while (true) {
        let i = (startIndex + endIndex) >> 1;
        let cur = partition[i];
        if (cur.end <= position) {
            startIndex = i;
        } else if (cur.start > position) {
            endIndex = i;
        } else {
            return i;
        }
    }
}
</code>```

This algorithm is a binary search, and it allows you to give it hints about start and end index if you happen to already have some knowledge about where in the partition the right interval might be.  If the partition is of length  then this algorithm should be ( ).

Another useful operation is to split a partition at a particular position.  If the partition already contains an interval starting at the position, you don't have to do anything.  Otherwise you need to find the interval that spans the position and split it into two:

```<code>// ensure that the partition contains an interval starting at position
// startIndex is a hint, where partition[startIndex].start <= position
// return the index of the interval starting at position
function splitAt(partition: Partition, position: number, startIndex: number = 0) {

    let i = findIndex(partition, position, startIndex);
    let cur = partition[i];
    if (cur.start < position) {
        partition.splice(i, 1,
            { start: cur.start, end: position - 1, type: cur.type.slice() },
            { start: position, end: cur.end, type: cur.type }
        )
        i++;
    }
    return i;
}
</code>```

This algorithm uses findIndex() so it should also be ( ). (edit... I guess this depends on splice(), so it's possibly just ()).

Given a partition: Partition and an interval: Interval, how can we merge the interval into the partition?  We need to split the partition at the interval's start and just after the interval's end positions, and then walk through the affected intervals and add the new interval's type array to them:

```<code>// merge interval into partition
function merge(partition: Partition, interval: Interval) {
    // split partition at interval's start, get index of starting interval in partition
    let startIndex = splitAt(partition, interval.start);
    // split partition at interval's end, get index of interval after ending interval
    let endIndex = splitAt(partition, interval.end + 1, startIndex);
    // add types to each interval between start and end
    for (let i = startIndex; i < endIndex; i++) {
        partition[i].type.push(...interval.type);
    }
}
</code>```

This is a pair of binary searches plus a walk through affected intervals.  In the worst case each interval in the partition needs to be modified, so this would be ().

Finally, all we need to do to convert an arbitrary array of intervals into the format you'd like is to start with an empty Partition (which has exactly one interval from -Infinity to Infinity and with an empty type array), merge each interval into it, and then return the final Partition without any intervals whose type array is empty.  This will automatically suppress the ones that touch Infinity or -Infinity, as well as any holes in the middle:

```<code>// denormalize array into non-overlapping intervals
function denormalize(arr: Array<Interval>) {

    // empty partition
    const partition: Partition = [{ start: -Infinity, end: Infinity, type: [] }];
    arr.forEach(interval => merge(partition, interval));
    // turn partition into normal array by removing "empty" intervals
    return partition.filter(i => i.type.length !== 0);
}
</code>```

Since this runs merge() for each interval, this will end up being (²) in the worst case.  I think that's probably the best you can do for the algorithm; this implies that you shouldn't need three nested loops but I'd be surprised if you can avoid having two.

You can verify that it produces the same output as your version. There may be edge cases but I'm more confident with an algorithm that operates on Partitions since I don't have to keep asking "what if the position I'm looking at doesn't have an interval associated with it"?

Notes:

You might want to consider having your intervals be half-open as in [start, end).  That is, start should be the smallest position contained by the interval and end should be the smallest position greater than the interval.  Half-open intervals are much easier to compose and reason about.  The length of [start, end) is end - start.  If you join intervals [a, b) and [b, c) you get [a, c). If you ever decide that you need to switch from whole number positions to fractions, a half-open interval won't require any code changes.  Conversely, closed intervals require careful math to add or subtract 1 (or whatever the step size is) in the right places and are therefore susceptible to fence-post errors.

As I said before, performance is often important but it might not be as important as correctness.  The only way to know exactly how important performance is in your case is to test it against load and see how it fares.  Quite often a simple algorithm is preferable to a complicated one that is a little faster, especially if you have to maintain and/or debug the code in the future.

All right, hope that helps; good luck!

Playground link to code

Body:
So I'm trying to figure out the most efficient method to split overlapped intervals, then merge duplicates. Two conditions specific to my situation are that if the start of a merged interval was an end of an original interval, it is incremented by 1. If the end of a merged interval was a start of an original interval, it is decremented by 1. Here is some sample data, and the expected result:

interface Interval {
    start: number;
    end: number;
    type: Array<number>;
}

// starting data
const arr: Array<Interval> = [
    { start: 0, end: 16, type: [42] },
    { start: 6, end: 30, type: [95] },
    { start: 11, end: 24, type: [126] },
    { start: 32, end: 47, type: [42] }
].sort((a, b) => a.start - b.start);

// magic splitting code here

// what we expect to end up with
const end_arr: Array<Interval> = [
    { start: 0, end: 5, type: [42] },
    { start: 6, end: 10, type: [42, 95] },
    { start: 11, end: 16, type: [42, 95, 126] },
    { start: 17, end: 24, type: [95, 126] },
    { start: 25, end: 30, type: [95] },
    { start: 32, end: 47, type: [42] },
];

I've already technically got an answer for this, but it is not very efficient - involving 3 nested for/forEach loops. Surely there is a more efficient way? Here is the code for that:

let startIndexArray: Array<number> = [];

let endIndexArray: Array<number> = [];

for (let i = 0; i < arr.length; i++) {
    startIndexArray.push(arr[i].start);
    endIndexArray.push(arr[i].end);
}

startIndexArray = startIndexArray.sort((a, b) => a - b);
endIndexArray = endIndexArray.sort((a, b) => a - b);

const indexArray = [...startIndexArray, ...endIndexArray].sort((a, b) => a - b);

const result: Array<Interval> = [];

arr.forEach((currentInterval) => {
    for (let i = currentInterval.start; i < currentInterval.end; i++) {
        if (indexArray.includes(i)) {
            const position = indexArray.indexOf(i);

            if (position !== indexArray.length - 1) {
                let start = i;
                let next = indexArray[position + 1];

                if (endIndexArray.includes(start)) {
                    start = start + 1;
                }

                if (startIndexArray.includes(next)) {
                    next = next - 1;
                }

                let in_result = false;
                result.forEach((mergedInterval) => {
                    if (mergedInterval.start === start && mergedInterval.end === next) {
                        mergedInterval.type = [...mergedInterval.type, ...currentInterval.type];
                        in_result = true;
                    }
                });
                if (!in_result) {
                    result.push({ start: start, end: next, type: [...currentInterval.type]});
                }
            }
        }
    }
});

// output is my expected, correct outcome
console.log(result);

Body:
The following algorithm is the cleanest one I can come up with which has reasonable performance.  I expect that, with the particular example array you gave, this code and the one you gave above will be of similar performance levels, but if you start using larger arrays you will see performance gains here compared to yours.  Without a suite of test cases it's hard to tell for sure.

Anyway, the general idea looks like this. Let's call a Partition a sorted array of non-overlapping intervals that covers all integers from -Infinity to Infinity.

type Partition = Array<Interval>;

If we have a value partition of type Partition, we know that partition[0].start === -Infinity, partition[partition.length-1].end === Infinity, and for any index i < partition.length - 1, partition[i].end + 1 === partition[i+1].start.

One good thing about a partition is that it will always contain exactly one interval that covers any given position.  This eliminates a class of edge cases.  So, given a partition: Partition and a position: number, let's find the index of the interval inside partition that contains it:

// binary search of the partition to find the index of the interval containing position
// startIndex is a hint, where partition[startIndex].start <= position
// endIndex is a hint, where partition[startIndex].end > position
function findIndex(
    partition: Partition,
    position: number,
    startIndex: number = 0,
    endIndex: number = partition.length
) {
    while (true) {
        let i = (startIndex + endIndex) >> 1;
        let cur = partition[i];
        if (cur.end <= position) {
            startIndex = i;
        } else if (cur.start > position) {
            endIndex = i;
        } else {
            return i;
        }
    }
}

This algorithm is a binary search, and it allows you to give it hints about start and end index if you happen to already have some knowledge about where in the partition the right interval might be.  If the partition is of length  then this algorithm should be ( ).

Another useful operation is to split a partition at a particular position.  If the partition already contains an interval starting at the position, you don't have to do anything.  Otherwise you need to find the interval that spans the position and split it into two:

// ensure that the partition contains an interval starting at position
// startIndex is a hint, where partition[startIndex].start <= position
// return the index of the interval starting at position
function splitAt(partition: Partition, position: number, startIndex: number = 0) {

    let i = findIndex(partition, position, startIndex);
    let cur = partition[i];
    if (cur.start < position) {
        partition.splice(i, 1,
            { start: cur.start, end: position - 1, type: cur.type.slice() },
            { start: position, end: cur.end, type: cur.type }
        )
        i++;
    }
    return i;
}

This algorithm uses findIndex() so it should also be ( ). (edit... I guess this depends on splice(), so it's possibly just ()).

Given a partition: Partition and an interval: Interval, how can we merge the interval into the partition?  We need to split the partition at the interval's start and just after the interval's end positions, and then walk through the affected intervals and add the new interval's type array to them:

// merge interval into partition
function merge(partition: Partition, interval: Interval) {
    // split partition at interval's start, get index of starting interval in partition
    let startIndex = splitAt(partition, interval.start);
    // split partition at interval's end, get index of interval after ending interval
    let endIndex = splitAt(partition, interval.end + 1, startIndex);
    // add types to each interval between start and end
    for (let i = startIndex; i < endIndex; i++) {
        partition[i].type.push(...interval.type);
    }
}

This is a pair of binary searches plus a walk through affected intervals.  In the worst case each interval in the partition needs to be modified, so this would be ().

Finally, all we need to do to convert an arbitrary array of intervals into the format you'd like is to start with an empty Partition (which has exactly one interval from -Infinity to Infinity and with an empty type array), merge each interval into it, and then return the final Partition without any intervals whose type array is empty.  This will automatically suppress the ones that touch Infinity or -Infinity, as well as any holes in the middle:

// denormalize array into non-overlapping intervals
function denormalize(arr: Array<Interval>) {

    // empty partition
    const partition: Partition = [{ start: -Infinity, end: Infinity, type: [] }];
    arr.forEach(interval => merge(partition, interval));
    // turn partition into normal array by removing "empty" intervals
    return partition.filter(i => i.type.length !== 0);
}

Since this runs merge() for each interval, this will end up being (²) in the worst case.  I think that's probably the best you can do for the algorithm; this implies that you shouldn't need three nested loops but I'd be surprised if you can avoid having two.

You can verify that it produces the same output as your version. There may be edge cases but I'm more confident with an algorithm that operates on Partitions since I don't have to keep asking "what if the position I'm looking at doesn't have an interval associated with it"?

Notes:

You might want to consider having your intervals be half-open as in [start, end).  That is, start should be the smallest position contained by the interval and end should be the smallest position greater than the interval.  Half-open intervals are much easier to compose and reason about.  The length of [start, end) is end - start.  If you join intervals [a, b) and [b, c) you get [a, c). If you ever decide that you need to switch from whole number positions to fractions, a half-open interval won't require any code changes.  Conversely, closed intervals require careful math to add or subtract 1 (or whatever the step size is) in the right places and are therefore susceptible to fence-post errors.

As I said before, performance is often important but it might not be as important as correctness.  The only way to know exactly how important performance is in your case is to test it against load and see how it fares.  Quite often a simple algorithm is preferable to a complicated one that is a little faster, especially if you have to maintain and/or debug the code in the future.

All right, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgIJSnAngHgCoB8yA3gFDIXKgIA2ArgCYQDOAFMxHFAgBYCiNCAFsI4AFzI8AGmQwoAeyEBJEEwAeAfgkg6QgEbQAlBL3z5guCADcpUgF9SoSLEQoVzgG5waJcpWZgXGDaugZQNpTIogwh+tARlGBYAA4QEuiYuDpxUAQ2DqQA9IXIAUGgAObIDHCBpAjyIAHIXFDpGNg47tBeNEQAvMgA2n4UxKWBUMHIAAwy0RIAjABsMkmpEkMALABMALrIdlKjJBNBEjvzqksAHGspacO7MwdHJ+NlUxKrUdfIAMxzZDrR5DACcAFZXsdIh9JtNFosrjFkDstvcNsNFjtltD3mcvgDLr8UVsAOwY0G7PGwgnTf4Q5EXLZAkGbbE0yhw87IRYzIELVEQ1kPTY3G6vWx7GxFEpMEDyKBCbzAABeKFa2Co4HkyAVIAAtPIPNAaHBkslKtrPN5mKQYHQQAgwMBGtVRIrlTQ1RBWK12pkuuAet4CIZfCditbRNM4MhkuUXW7gMwWqVFZAGC0OlhkPIYHrGkaTVAzRarU4QzRU5GSg0S1bvD5KxVoKm5IpkAaVDBQMAksDdT2+0kTiDkAAFROukDIQYZTrdKC9PK2SJRvSgLi5jhcXh5gtgHgoBNTfszweyUBZo8oa8QNQH4HH6PL7zIBrgOB9kBVZLyZhz0aWs6RUdQqFTOMeCcGQAHdjygE9p0aIZPjAMCHz2AA6NDkBwQZ-0ApMQBA6IMMfFM02g8A4IQpCz2I1D4XI7DomQIhCKAkjIgdJ1iKvVRyNYE5IlPF1iIkKcGJnGFIkoTiJL1UJoFkuTQNUB9YjCOdZlUuSyI0tQtOgHSxK4rDBF-I8TnDMg1IoeDgEEZBWDAKA6AgWyRPswQwCoHT2GYwzkAAahJcjwwIIhFgSezKF8j86CgUzkJAIZgGlby1OAAtWAQJKsLY-D4wArivLiuK0PInTgFiiq7Cias71y-KoBw+F2JKoiZ3Kiq1IM8DBlqrK5IaiAmt8Pq1MQsAktnYapsOEaHEiAp1xKURmCSlAj1qZ96PEi9P0CUBIPm4M3x8NDGz8hSZxAqrgsoqCYOQeDoAOrimKCFj2qCPCCNK4iQJmub9u1cD83BytLrpG6uq4k5eOdC9mGSb0wFQMBWDMxSpMOxoZDuxpjKgGRHvUUmdJmLyRoS4AdN7QTDJx1KiaBmT1PUQw6siBLWpS6SUIy3nKBylzWr+qY8IR4jer63GZxw9HgCQVhgBkJERri7lCUltCmVli8DV5SkJElkEcO9NXwzeRbaTQiRiZAQ3JeiM3Era8cVqmwxtbFkKQtFigfemiBZqgea6rWygoxEKBW1fXprV1RXgJ4x0UbdePW1ZoWQEktmk+8CQl16eW5KjNGMfjVKWj8mHegAclTA3kFbBvgqh67f2L5tZzT7ifPDrmHx06v+yxvOCZdvupbAHmRqrlXbrrvbG+8FuSRkDuIbHqGN58OAYGcEkKwu3o6ZHgax8GCfMexweZEPwrVFC03R7URe4qjOAGBvB4qYwC6k4PuQ+yADBgFghAUQdIWhv2iCNGAioXL03HkFdQVh-I4HCoZLBwBA4VzioPdK2FLbJDoMwHgrAsK0JfiCb+9lQ5LVIkIZIA5B4nE-M0Qehd846SGLraY3YQBM37FgQ2w4QDiI9kMV4mVIitCwsgqAfBEDUPAf0IgOdfRPz7oYRhFAowRwHnXJwuoFRKnfJqXMehcyISEMaK0AAiYQ7CsDOL7naSIoNI613zsopyzh1ZziIMALCltLIVCPMgAAhP0QYNN8i2FIAlAAcjpPk-J+QyntJnfikAAioBoBURU-YeBCD9CUiQrAjJoBzEGG0fRwxaPqYGMuoZn4ogCFASoFcEqIWYAGRcF9QwCIUZQbh5gIAROACIdWDBDGyBQawNBiT8EyzSfgwhk17KDJ0t4CofoMBLOYVMwQsyRB8FUAspZ5yZk0HkEcgAUgAZQAPJpPar038OUsCsEGQY5JpBCmYxKWUo8lSykVC3DQAAIh6Kx3p1TFNKb0yFMhnHQthS0cF6KKnOMXqC1FEKKmsHlJ6FU6pMUgAgLBXFaLylCEJTKZG-FsUgG8AiyxXofQkvxZU-0bSRlNLDLsigCUKYPgXFgYZWRlK5HGTKPm19mbqBlXKnA2QwgDGGJlJGKy1mzA2TgpRUSjzbJCkQ-wGDpU5iwhQqhxyoCkPnksyIN81AyodZQ6hrRXXRFOWuG1P1DIyvQaG9V9rmAZlYH6GQegWlEDjCbRNdVPXhsGBm6Nsb40QKTWmVNi8uGNGaPeL1OYBG0PnuRGVMhq3ZsyNhGNUw41wATQWlN+blWTNLX5QZdAaDTBlY0qsuq5F1SUSotRvA42tUQuADpNAC12Xsio1BI8GaDHnTGJd88TWewXehUZNBX4MEtda7KuVy3euoPQJgbBgAGPFfbbht0OZuiGmG+15b3kwHVsW+2YtcrOziQkveFbMgWVENEngXZeSXvtpKjqQ1g5IZHrStQfkv1RsyEMUDYVFj6qA1elyjbsBYTvYwFggUgjPtXSR+yuE74dUI2hxaMdGMUHFrRqYtaf1OnvTRzDC9EOMZEzpCTJsYr+z6pxrj9MQAAH0B1DsZraCA7GpqqbAMoxUM7qGsB0QwJdK7ZP2x48ZvdzHwO4QAGR2eQFZk9Z65zgZE2JrjFBnNNIiQ8KttCfNVj86kettCd2LpcyCCZXm4qgBUywQd2HgTuU0+Zjj6WmHupIzx2J8WdOeaAzpn1TqhESDboKETsjq0RePb56LhxstAeYRl1rTCTh2CWb42cOn8hAA" rel="nofollow noreferrer">Playground link to code


问:
How to use Raycast methods in RealityKit?
There are three ways about Detecting Intersections in RealityKit framework, but I don't know how to use it in my project.

1.

```<code>func raycast(origin: SIMD3<Float>,
          direction: SIMD3<Float>,
             length: Float,
              query: CollisionCastQueryType,
               mask: CollisionGroup,
         relativeTo: Entity?) -> [CollisionCastHit]
</code>```

2.

```<code>func raycast(from: SIMD3<Float>,
               to: SIMD3<Float>,
            query: CollisionCastQueryType,
             mask: CollisionGroup,
       relativeTo: Entity?) -> [CollisionCastHit]
</code>```

3.

```<code>func convexCast(convexShape: ShapeResource,
               fromPosition: SIMD3<Float>,
            fromOrientation: simd_quatf,
                 toPosition: SIMD3<Float>,
              toOrientation: simd_quatf,
                      query: CollisionCastQueryType,
                       mask: CollisionGroup,
                 relativeTo: Entity?) -> [CollisionCastHit]
</code>```

答:
Simple Ray-Casting

If you want to find out how to position a model made in Reality Composer into a RealityKit scene (that has a detected horizontal plane) using Ray-Casting method, use the following code:

```<code>import RealityKit
import ARKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!
    let scene = try! Experience.loadScene()

    @IBAction func onTap(_ sender: UITapGestureRecognizer) {

        scene.steelBox!.name = "Parcel"

        let tapLocation: CGPoint = sender.location(in: arView)
        let estimatedPlane: ARRaycastQuery.Target = .estimatedPlane
        let alignment: ARRaycastQuery.TargetAlignment = .horizontal

        let result: [ARRaycastResult] = arView.raycast(from: tapLocation,
                                                   allowing: estimatedPlane,
                                                  alignment: alignment)

        guard let rayCast: ARRaycastResult = result.first
        else { return }

        let anchor = AnchorEntity(world: rayCast.worldTransform)
        anchor.addChild(scene)
        arView.scene.anchors.append(anchor)

        print(rayCast)
    }
}
</code>```

Pay attention to a class ARRaycastQuery. This class comes from ARKit, not from RealityKit.

Convex-Ray-Casting

A Convex-Ray-Casting methods like raycast(from:to:query:mask:relativeTo:) is the op of swiping a convex shapes along a straight line and stopping at the very first intersection with any of the collision shape in the scene. Scene raycast() method performs a hit-tests against all entities with collision shapes in the scene. Entities without a collision shape are ignored.

You can use the following code to perform a convex-ray-cast from start position to end:

```<code>import RealityKit

let startPosition: SIMD3<Float> = [0, 0, 0]
let endPosition: SIMD3<Float> = [5, 5, 5]
let query: CollisionCastQueryType = .all
let mask: CollisionGroup = .all

let raycasts: [CollisionCastHit] = arView.scene.raycast(from: startPosition,
                                                          to: endPosition,
                                                       query: query,
                                                        mask: mask,
                                                  relativeTo: nil)

guard let rayCast: CollisionCastHit = raycasts.first
else { return }

print(rayCast.distance)      /* The distance from the ray origin to the hit */
print(rayCast.entity.name)   /* The entity's name that was hit              */
</code>```

A CollisionCastHit structure is a hit result of a collision cast and it lives in RealityKit's scene.

P.S.

When you use raycast(from:to:query:mask:relativeTo:) method for measuring a distance from camera to entity it doesn't matter what an orientation of ARCamera is, it only matters what its position is in world coordinates.

Body:
There are three ways about Detecting Intersections in RealityKit framework, but I don't know how to use it in my project.

1.

func raycast(origin: SIMD3<Float>,
          direction: SIMD3<Float>,
             length: Float,
              query: CollisionCastQueryType,
               mask: CollisionGroup,
         relativeTo: Entity?) -> [CollisionCastHit]

2.

func raycast(from: SIMD3<Float>,
               to: SIMD3<Float>,
            query: CollisionCastQueryType,
             mask: CollisionGroup,
       relativeTo: Entity?) -> [CollisionCastHit]

3.

func convexCast(convexShape: ShapeResource,
               fromPosition: SIMD3<Float>,
            fromOrientation: simd_quatf,
                 toPosition: SIMD3<Float>,
              toOrientation: simd_quatf,
                      query: CollisionCastQueryType,
                       mask: CollisionGroup,
                 relativeTo: Entity?) -> [CollisionCastHit]

Body:
Simple Ray-Casting

If you want to find out how to position a model made in Reality Composer into a RealityKit scene (that has a detected horizontal plane) using Ray-Casting method, use the following code:

import RealityKit
import ARKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!
    let scene = try! Experience.loadScene()

    @IBAction func onTap(_ sender: UITapGestureRecognizer) {

        scene.steelBox!.name = "Parcel"

        let tapLocation: CGPoint = sender.location(in: arView)
        let estimatedPlane: ARRaycastQuery.Target = .estimatedPlane
        let alignment: ARRaycastQuery.TargetAlignment = .horizontal

        let result: [ARRaycastResult] = arView.raycast(from: tapLocation,
                                                   allowing: estimatedPlane,
                                                  alignment: alignment)

        guard let rayCast: ARRaycastResult = result.first
        else { return }

        let anchor = AnchorEntity(world: rayCast.worldTransform)
        anchor.addChild(scene)
        arView.scene.anchors.append(anchor)

        print(rayCast)
    }
}

Pay attention to a class ARRaycastQuery. This class comes from ARKit, not from RealityKit.

Convex-Ray-Casting

A Convex-Ray-Casting methods like raycast(from:to:query:mask:relativeTo:) is the op of swiping a convex shapes along a straight line and stopping at the very first intersection with any of the collision shape in the scene. Scene raycast() method performs a hit-tests against all entities with collision shapes in the scene. Entities without a collision shape are ignored.

You can use the following code to perform a convex-ray-cast from start position to end:

import RealityKit

let startPosition: SIMD3<Float> = [0, 0, 0]
let endPosition: SIMD3<Float> = [5, 5, 5]
let query: CollisionCastQueryType = .all
let mask: CollisionGroup = .all

let raycasts: [CollisionCastHit] = arView.scene.raycast(from: startPosition,
                                                          to: endPosition,
                                                       query: query,
                                                        mask: mask,
                                                  relativeTo: nil)

guard let rayCast: CollisionCastHit = raycasts.first
else { return }

print(rayCast.distance)      /* The distance from the ray origin to the hit */
print(rayCast.entity.name)   /* The entity's name that was hit              */

A CollisionCastHit structure is a hit result of a collision cast and it lives in RealityKit's scene.

P.S.

When you use raycast(from:to:query:mask:relativeTo:) method for measuring a distance from camera to entity it doesn't matter what an orientation of ARCamera is, it only matters what its position is in world coordinates.


问:
Is it possible to get the file name of a pointer in Windows?
As far as I have researched on SO, in order to obtain the file name from a pointer(perhaps a memory location), we'll need to get it's File Descriptor No. which could then be used to indirectly request the OS for the file name. Maybe by navigating it's proc directory or there could be different ways OS-dependent ways to do it.

But the real question here is,

Is it possible in Windows?

I am looking for  a way to do it specifically using C, since my code is written in C.

===

Just for the sake of reference,

```<code>typedef struct  {
        int             level;          /* fill/empty level of buffer */
        unsigned        flags;          /* File status flags          */
        char            fd;             /* File descriptor            */
        unsigned char   hold;           /* Ungetc char if no buffer   */
        int             bsize;          /* Buffer size                */
        unsigned char   *buffer;        /* Data transfer buffer       */
        unsigned char   *curp;          /* Current active pointer     */
        unsigned        istemp;         /* Temporary file indicator   */
        short           token;          /* Used for validity checking */
}       FILE;
</code>```

答: It appears that you can use the GetFileInformationByHandleEx function with the argument FileNameInfo. I am not on Windows and cannot test, but it's suggested by this answer as well.

Body:
As far as I have researched on SO, in order to obtain the file name from a pointer(perhaps a memory location), we'll need to get it's File Descriptor No. which could then be used to indirectly request the OS for the file name. Maybe by navigating it's proc directory or there could be different ways OS-dependent ways to do it.

But the real question here is,

Is it possible in Windows?

I am looking for  a way to do it specifically using C, since my code is written in C.

===

Just for the sake of reference,

typedef struct  {
        int             level;          /* fill/empty level of buffer */
        unsigned        flags;          /* File status flags          */
        char            fd;             /* File descriptor            */
        unsigned char   hold;           /* Ungetc char if no buffer   */
        int             bsize;          /* Buffer size                */
        unsigned char   *buffer;        /* Data transfer buffer       */
        unsigned char   *curp;          /* Current active pointer     */
        unsigned        istemp;         /* Temporary file indicator   */
        short           token;          /* Used for validity checking */
}       FILE;


问:
DolphinDB JIT doesn't support break and continue in while-loop and for-loop?
Recently I found that DolphinDB has supported JIT from version 1.01. But I found that break and continue doesn't work in for-loop or while-loop. I tried something like this:

```<code>@jit
def foo() {
   for(i in 1..10) {
     break
   }
}
foo()
</code>```

```<code>@jit
def foo() {
    i = 0
    while(i < 100) {
       continue
    }
}
foo()
</code>```

both of them doesn't work, and throw exceptions. Since break and continue are pretty common
in my previous scripts, it's very  inconvenience if they are not supported. So my question is are there any problem with my code, or will them be supported in later releases?

答: Please checkout version 1.01.2. This version supported the use of break and continue in JIT

Body:
Recently I found that DolphinDB has supported JIT from version 1.01. But I found that break and continue doesn't work in for-loop or while-loop. I tried something like this:

@jit
def foo() {
   for(i in 1..10) {
     break
   }
}
foo()

@jit
def foo() {
    i = 0
    while(i < 100) {
       continue
    }
}
foo()

both of them doesn't work, and throw exceptions. Since break and continue are pretty common
in my previous scripts, it's very  inconvenience if they are not supported. So my question is are there any problem with my code, or will them be supported in later releases?


问:
Ruby add nil value to an array
How can I initialize an array and be able to add nil value to it? as I know Array.wrap doesn't do the job.

```<code>list = Array.wrap(nil) => []
</code>```

What I want:

```<code>list = Array.add(nil) => [nil]
</code>```

Thank you

答:
Maybe you are looking for (Rails):

```<code>list = Array.wrap([nil])
#=> [nil]
</code>```

But why not just a simple list = [nil], as per @engineersmnky's comment?

Also list = Array.new.push nil, but it's still better the easy way above.

Title: Ruby add nil value to an array

Body:
How can I initialize an array and be able to add nil value to it? as I know Array.wrap doesn't do the job.

list = Array.wrap(nil) => []

What I want:

list = Array.add(nil) => [nil]

Thank you

Body:
Maybe you are looking for (Rails):

list = Array.wrap([nil])
#=> [nil]

But why not just a simple list = [nil], as per @engineersmnky's comment?

Also list = Array.new.push nil, but it's still better the easy way above.


问:
Able to debug ONLY when running test
Using laravel/homestead vagrant box, VS Code, and PHP Debug extension, I can set breakpoints and step through code only when running a test via phpunit.

If I access the same resource via the browser, my breakpoints are never hit.

Based on the fact that I can debug when tests are running, I'm assuming that xdebug is working and configured properly.

My .env file:

```<code>APP_NAME=lms
APP_ENV=local
APP_KEY=base64:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
APP_DEBUG=true
APP_URL=https://lms.test
</code>```

My .env.testing file:

```<code>APP_NAME=lms
APP_ENV=testing
APP_KEY=base64:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
APP_DEBUG=true
APP_URL=https://lms.test
</code>```

PHP Debug config:

```<code>    "configurations": [
        {
            "name": "Listen for XDebug on Homestead",
            "type": "php",
            "request": "launch",
            "pathMappings": {
                "/home/vagrant/code/MyProject": "C:\\Users\\lemon\\source\\vagrant\\MyProject"
            },
            "port": 9000
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9000
        }
    ]
</code>```

app.php

```<code>'env' => env('APP_ENV', 'production'),
'debug' => env('APP_DEBUG', false),
</code>```

```<code>netstat -rn | grep "^0.0.0.0 " | cut -d " " -f10
10.0.2.2
</code>```

/etc/php/7.4/cli/conf.d/20-xdebug.ini

```<code>zend_extension=xdebug.so
xdebug.remote_enable = 1
xdebug.remote_autostart=1
xdebug.remote_host=10.0.2.2
xdebug.remote_connect_back = 1
xdebug.remote_port = 9000
xdebug.max_nesting_level = 512
</code>```

I've enabled xdebug logging. When I run the debugger during a test, the log is created and shows the expected entries. If I then delete the log file and make a GET from the browser, to the same controller as the test, no xdebug log is created.

Maybe some fresh eyes can identify the problem. Thanks!

答:
In desperation I deleted these lines from 20-xdebug.ini (and restarted the php service) and it worked.

```<code>xdebug.remote_connect_back = 1
xdebug.remote_port = 9000
xdebug.max_nesting_level = 512
</code>```

No idea why, but I hope this helps someone else.

Title: Able to debug ONLY when running test

Body:
Using laravel/homestead vagrant box, VS Code, and PHP Debug extension, I can set breakpoints and step through code only when running a test via phpunit.

If I access the same resource via the browser, my breakpoints are never hit.

Based on the fact that I can debug when tests are running, I'm assuming that xdebug is working and configured properly.

My .env file:

APP_NAME=lms
APP_ENV=local
APP_KEY=base64:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
APP_DEBUG=true
APP_URL=https://lms.test

My .env.testing file:

APP_NAME=lms
APP_ENV=testing
APP_KEY=base64:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
APP_DEBUG=true
APP_URL=https://lms.test

PHP Debug config:

    "configurations": [
        {
            "name": "Listen for XDebug on Homestead",
            "type": "php",
            "request": "launch",
            "pathMappings": {
                "/home/vagrant/code/MyProject": "C:\\Users\\lemon\\source\\vagrant\\MyProject"
            },
            "port": 9000
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9000
        }
    ]

app.php

'env' => env('APP_ENV', 'production'),
'debug' => env('APP_DEBUG', false),

netstat -rn | grep "^0.0.0.0 " | cut -d " " -f10
10.0.2.2

/etc/php/7.4/cli/conf.d/20-xdebug.ini

zend_extension=xdebug.so
xdebug.remote_enable = 1
xdebug.remote_autostart=1
xdebug.remote_host=10.0.2.2
xdebug.remote_connect_back = 1
xdebug.remote_port = 9000
xdebug.max_nesting_level = 512

I've enabled xdebug logging. When I run the debugger during a test, the log is created and shows the expected entries. If I then delete the log file and make a GET from the browser, to the same controller as the test, no xdebug log is created.

Maybe some fresh eyes can identify the problem. Thanks!

Body:
In desperation I deleted these lines from 20-xdebug.ini (and restarted the php service) and it worked.

xdebug.remote_connect_back = 1
xdebug.remote_port = 9000
xdebug.max_nesting_level = 512

No idea why, but I hope this helps someone else.


问:
ENOENT: no such file or directory .?
This is error which am getting while post data and file.
I have followed 'academind' tutorial for building Restful API services, also i have been searching answer for this type of errors but nothing works for me.

Am using "multer" to upload file

The folder 'uploads' available in the folder but it shows

ENOENT: no such file or directory, open 'D:\project\uploads\2018-01-24T07:41:21.832Zcheck.jpg'"

app.js

```<code>const express = require("express");
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const productRoutes = require("./api/routes/products");

mongoose.connect('',
(err)=>{
    if(err){console.log(err)}
    else{console.log('DB Connected')}
})
mongoose.Promise = global.Promise;

app.use(morgan("dev"));
app.use('/uploads', express.static('uploads'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
    return res.status(200).json({});
  }
  next();
});

// Routes which should handle requests
app.use("/products", productRoutes);

app.use((req, res, next) => {
  const error = new Error("Not found");
  error.status = 404;
  next(error);
});

app.use((error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  });
});

module.exports = app;
</code>```

product.js

```<code>const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

router.post("/", checkAuth, upload.single('productImage'), (req, res, next) => {
  const product = new Product({
    _id: new mongoose.Types.ObjectId(),
    name: req.body.name,
    price: req.body.price,
    productImage: req.file.path
  });
  product
    .save()
    .then(result => {
      console.log(result);
      res.status(201).json({
        message: "Created product successfully",
        createdProduct: {
            name: result.name,
            price: result.price,
            _id: result._id,
            request: {
                type: 'GET',
                url: "http://localhost:3000/products/" + result._id
            }
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

module.exports = router;
</code>```

答:
So the answer is in the tutorials comments section on youtube.
Instead of:

```<code>cb(null, new Date().toISOString() + file.originalname);
</code>```

do:

```<code>cb(null, Date.now() + file.originalname);
</code>```

Simple as.

Title: ENOENT: no such file or directory .?

Body:
This is error which am getting while post data and file.
I have followed 'academind' tutorial for building Restful API services, also i have been searching answer for this type of errors but nothing works for me.

Am using "multer" to upload file

The folder 'uploads' available in the folder but it shows

ENOENT: no such file or directory, open 'D:\project\uploads\2018-01-24T07:41:21.832Zcheck.jpg'"

app.js

const express = require("express");
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const productRoutes = require("./api/routes/products");

mongoose.connect('',
(err)=>{
    if(err){console.log(err)}
    else{console.log('DB Connected')}
})
mongoose.Promise = global.Promise;

app.use(morgan("dev"));
app.use('/uploads', express.static('uploads'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
    return res.status(200).json({});
  }
  next();
});

// Routes which should handle requests
app.use("/products", productRoutes);

app.use((req, res, next) => {
  const error = new Error("Not found");
  error.status = 404;
  next(error);
});

app.use((error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  });
});

module.exports = app;

product.js

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

router.post("/", checkAuth, upload.single('productImage'), (req, res, next) => {
  const product = new Product({
    _id: new mongoose.Types.ObjectId(),
    name: req.body.name,
    price: req.body.price,
    productImage: req.file.path
  });
  product
    .save()
    .then(result => {
      console.log(result);
      res.status(201).json({
        message: "Created product successfully",
        createdProduct: {
            name: result.name,
            price: result.price,
            _id: result._id,
            request: {
                type: 'GET',
                url: "http://localhost:3000/products/" + result._id
            }
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

module.exports = router;

Body:
So the answer is in the tutorials comments section on youtube.
Instead of:

cb(null, new Date().toISOString() + file.originalname);

do:

cb(null, Date.now() + file.originalname);

Simple as.


问:
VBA Excel Event Compile Error with MouseMove event on a command button
I am trying to use the MouseMove event with a command button, but cannot figure out how to prevent the following error:

Compile error:
     Procedure declaration does not match description of event or procedure having the same name.

The code is very simple. I used "dummy" code here because I can never enter the event handler to get to something useful.

```<code>Private Sub Button_Name_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
  Dim X as Integer
  x = x+1
End Sub
</code>```

I have taken the parameter list directly from the object browser. I get similar results with other events, including DblClick(), but not Click(). I think that I must be making some fundamental error, but have not been able to identify it. Help!

答:
I don't quite understand why you have taken the parameter list directly from the object browser. If you have the code of your user form open in the VBA window, you can select the command button in the left drop down list just above the code and the MouseMove event in the right drop down list. Then the required code is inserted automatically. It will slightly differ from your code:

```<code>Private Sub CommandButton1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal x As Single, ByVal Y As Single)

End Sub
</code>```

The next error you will run into is a duplicate declaration of X. It's already a parameter of the subroutine. So you cannot reuse it within the subroutine.

With these two things fixed, the mouse move event will fire, even on a command button.

Body:
I am trying to use the MouseMove event with a command button, but cannot figure out how to prevent the following error:

Compile error:
     Procedure declaration does not match description of event or procedure having the same name.

The code is very simple. I used "dummy" code here because I can never enter the event handler to get to something useful.

Private Sub Button_Name_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
  Dim X as Integer
  x = x+1
End Sub

I have taken the parameter list directly from the object browser. I get similar results with other events, including DblClick(), but not Click(). I think that I must be making some fundamental error, but have not been able to identify it. Help!

Body:
I don't quite understand why you have taken the parameter list directly from the object browser. If you have the code of your user form open in the VBA window, you can select the command button in the left drop down list just above the code and the MouseMove event in the right drop down list. Then the required code is inserted automatically. It will slightly differ from your code:

Private Sub CommandButton1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal x As Single, ByVal Y As Single)

End Sub

The next error you will run into is a duplicate declaration of X. It's already a parameter of the subroutine. So you cannot reuse it within the subroutine.

With these two things fixed, the mouse move event will fire, even on a command button.


问:
Powermockito with Java 8
I am using powermockito to mock static methods with params in Java 7. Recently started migrating to Java 8. Post migration the powermockito stopped mocking the static methods and started calling the original method.

Pom.xml

```<code><dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4-rule-agent</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.18.2-GA</version>
    <scope>test</scope>
</dependency>
</code>```

```<code>Test class
using spring runner with PowerMockRule
@RunWith(SpringJUnit4ClassRunner.class)

@Rule
public PowerMockRule rule = new PowerMockRule();

Below is the code used for mock/stubbing the static..

PowerMockito.stub(PowerMockito.method(ABCHelper.class, "prepareResult",Arg1.class,Arg2.class,Arg3.class,Arg4.class)).toReturn(mockedReturnedObject);
</code>```

Can somebody please help me with this issue?

答:
Below code works for me. Please give it a try with below dependencies and code in new project.

pom.xml

```<code> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>PowerMockTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4-rule</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-classloading-xstream</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>
</code>```

Test class

```<code>import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

import org.junit.Rule;
import org.junit.Test;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;

@PrepareForTest({UtilTest.class})
public class PowerMockRuleTest {

  @Rule
  public PowerMockRule powerMockRule = new PowerMockRule();

  @Test
  public void testStatic() throws Exception{
    PowerMockito.mockStatic(UtilTest.class);
    when(UtilTest.getName()).thenReturn("1234");
    System.out.println(UtilTest.getName());

    Main mainMock = mock(Main.class);

    PowerMockito.whenNew(Main.class).withAnyArguments().thenReturn(mainMock);
    when(mainMock.getMyTest()).thenReturn("12345");
    System.out.println(mainMock.getMyTest());
  }

}
</code>```

Classess:

```<code>public class UtilTest {

  public static String getName() {

    return "test";
  }

}

public class Main {

  public static void main(String[] args) {
    System.out.println("Hello World!");
  }

  public String getMyTest() {
    return "main test";
  }
}
</code>```

Title: Powermockito with Java 8

Body:
I am using powermockito to mock static methods with params in Java 7. Recently started migrating to Java 8. Post migration the powermockito stopped mocking the static methods and started calling the original method.

Pom.xml

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4-rule-agent</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.18.2-GA</version>
    <scope>test</scope>
</dependency>

Test class
using spring runner with PowerMockRule
@RunWith(SpringJUnit4ClassRunner.class)

@Rule
public PowerMockRule rule = new PowerMockRule();

Below is the code used for mock/stubbing the static..

PowerMockito.stub(PowerMockito.method(ABCHelper.class, "prepareResult",Arg1.class,Arg2.class,Arg3.class,Arg4.class)).toReturn(mockedReturnedObject);

Can somebody please help me with this issue?

Body:
Below code works for me. Please give it a try with below dependencies and code in new project.

pom.xml

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>PowerMockTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4-rule</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-classloading-xstream</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

Test class

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

import org.junit.Rule;
import org.junit.Test;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;

@PrepareForTest({UtilTest.class})
public class PowerMockRuleTest {

  @Rule
  public PowerMockRule powerMockRule = new PowerMockRule();

  @Test
  public void testStatic() throws Exception{
    PowerMockito.mockStatic(UtilTest.class);
    when(UtilTest.getName()).thenReturn("1234");
    System.out.println(UtilTest.getName());

    Main mainMock = mock(Main.class);

    PowerMockito.whenNew(Main.class).withAnyArguments().thenReturn(mainMock);
    when(mainMock.getMyTest()).thenReturn("12345");
    System.out.println(mainMock.getMyTest());
  }

}

Classess:

public class UtilTest {

  public static String getName() {

    return "test";
  }

}

public class Main {

  public static void main(String[] args) {
    System.out.println("Hello World!");
  }

  public String getMyTest() {
    return "main test";
  }
}


问:
Using split on an input string
I'm a beginner to Python 3 and when I try this code it works:

```<code>a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)
</code>```

Output:

Enter three digits separated by space:2 3 4
[2, 3, 4]
```

<p>However I get errors when I try this:</p>

```a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)
```

<blockquote>
  <p>Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'</p>
</blockquote>

<p>In fact this works as well:</p>

```list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)
```

What am I doing wrong?

答:
You might want to do exponentiation after converting to an int:

```<code>mylist = [int(i)**2 for i in list1]
</code>```

You can't raise a string to a power (do you know what the square of the string "blah" is?), but you can raise a number to a power. So you need to convert the string to a number first.

Of course, a.split() returns a list of smaller strings derived from the original string, and you have to turn them into numbers yourself, but you already figured this out.

Title: Using split on an input string

Body:
I'm a beginner to Python 3 and when I try this code it works:

a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)

Output:

Enter three digits separated by space:2 3 4
[2, 3, 4]

However I get errors when I try this:

a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)

Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

In fact this works as well:

list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)

What am I doing wrong?

Body:
You might want to do exponentiation after converting to an int:

mylist = [int(i)**2 for i in list1]

You can't raise a string to a power (do you know what the square of the string "blah" is?), but you can raise a number to a power. So you need to convert the string to a number first.

Of course, a.split() returns a list of smaller strings derived from the original string, and you have to turn them into numbers yourself, but you already figured this out.


问:
S3 Static Website Hosting Route All Paths to Index.html
I am using S3 to host a javascript app that will use HTML5 pushStates. The problem is if the user bookmarks any of the URLs, it will not resolve to anything. What I need is the ability to take all url requests and serve up the root index.html in my S3 bucket, rather than just doing a full redirect. Then my javascript application could parse the URL and serve the proper page. </p>

<p>Is there any way to tell S3 to serve the index.html for all URL requests instead of doing redirects? This would be similar to setting up apache to handle all incoming requests by serving up a single index.html as in this example: https://stackoverflow.com/a/10647521/1762614. I would really like to avoid running a web server just to handle these routes. Doing everything from S3 is very appealing. </p>

答:
You can now do this with Lambda@Edge to rewrite the paths

Here is a working lambda@Edge function:

Create a new Lambda function, but use one of the pre-existing Blueprints instead of a blank function.

Search for “cloudfront” and select cloudfront-response-generation from the search results.

After creating the function, replace the content with the below.  I also had to change the node runtime to 10.x because cloudfront didn't support node 12 at the time of writing.

'use strict';
exports.handler = (event, context, callback) => {

    // Extract the request from the CloudFront event that is sent to Lambda@Edge
    var request = event.Records[0].cf.request;

    // Extract the URI from the request
    var olduri = request.uri;

    // Match any '/' that occurs at the end of a URI. Replace it with a default index
    var newuri = olduri.replace(/\/$/, '\/index.html');

    // Log the URI as received by CloudFront and the new URI to be used to fetch from origin
    console.log("Old URI: " + olduri);
    console.log("New URI: " + newuri);

    // Replace the received URI with the URI that includes the index page
    request.uri = newuri;

    return callback(null, request);
};
```

In your cloudfront behaviors, you'll edit them to add a call to that lambda function on "Viewer Request"

Full Tutorial: https://aws.amazon.com/blogs/compute/implementing-default-directory-indexes-in-amazon-s3-backed-amazon-cloudfront-origins-using-lambdaedge/

Body:
I am using S3 to host a javascript app that will use HTML5 pushStates. The problem is if the user bookmarks any of the URLs, it will not resolve to anything. What I need is the ability to take all url requests and serve up the root index.html in my S3 bucket, rather than just doing a full redirect. Then my javascript application could parse the URL and serve the proper page.

Is there any way to tell S3 to serve the index.html for all URL requests instead of doing redirects? This would be similar to setting up apache to handle all incoming requests by serving up a single index.html as in this example: https://stackoverflow.com/a/10647521/1762614. I would really like to avoid running a web server just to handle these routes. Doing everything from S3 is very appealing.

Body:
You can now do this with Lambda@Edge to rewrite the paths

Here is a working lambda@Edge function:

Create a new Lambda function, but use one of the pre-existing Blueprints instead of a blank function.

Search for “cloudfront” and select cloudfront-response-generation from the search results.

After creating the function, replace the content with the below.  I also had to change the node runtime to 10.x because cloudfront didn't support node 12 at the time of writing.

'use strict';
exports.handler = (event, context, callback) => {

    // Extract the request from the CloudFront event that is sent to Lambda@Edge
    var request = event.Records[0].cf.request;

    // Extract the URI from the request
    var olduri = request.uri;

    // Match any '/' that occurs at the end of a URI. Replace it with a default index
    var newuri = olduri.replace(/\/$/, '\/index.html');

    // Log the URI as received by CloudFront and the new URI to be used to fetch from origin
    console.log("Old URI: " + olduri);
    console.log("New URI: " + newuri);

    // Replace the received URI with the URI that includes the index page
    request.uri = newuri;

    return callback(null, request);
};

In your cloudfront behaviors, you'll edit them to add a call to that lambda function on "Viewer Request"

Full Tutorial: https://aws.amazon.com/blogs/compute/implementing-default-directory-indexes-in-amazon-s3-backed-amazon-cloudfront-origins-using-lambdaedge/


问:
NetLogo: Neet to set the variable's value to a random number within a range
Dear NetLogo Community,

I am aiming to set a variable's value to a number between -1 and 1. I have tried the following code but in vain.

```<code>to xyz
[
set probability-of-wom compute-wom [-1 1]
if probability-wom > 0 [...]
]
end

to-report compute-wom -1 1
  report -1 + random-float (1 - -1)
end
</code>```

probablity-wom is a global variable in this case.
Appreciate your support in advance.
Thank you.

Regards,
Shreesha

答:
Shreesha

Let's say you want to generate a random number between lower and upper.  Then your compute-wom would be

```<code>to-report compute-wom [lower upper]
  report upper - random-float (upper - lower)
end
</code>```

In your case, you would

```<code>set probability-of-wom compute-wom -1 1
</code>```

But a couple of comments. First, what you are generating here is a random number between two limits (as your title suggests), so calling it a probability could be misleading to anyone reading your code. Probabilities will normally be in the range from zero to one. If you really are just looking to do something with a 50% probability, you can simply say

```<code>if random-float 1 >= 0.5 [...]
</code>```

Second, reporters should generally take variable arguments if they are to have arguments at all. Note that since you hard code -1 and 1 in the body of your to-report compute-wom reporter, passing them as arguments is redundant, and possibly misleading to anyone reading your code.

Body:
Dear NetLogo Community,

I am aiming to set a variable's value to a number between -1 and 1. I have tried the following code but in vain.

to xyz
[
set probability-of-wom compute-wom [-1 1]
if probability-wom > 0 [...]
]
end

to-report compute-wom -1 1
  report -1 + random-float (1 - -1)
end

probablity-wom is a global variable in this case.
Appreciate your support in advance.
Thank you.

Regards,
Shreesha

Body:
Shreesha

Let's say you want to generate a random number between lower and upper.  Then your compute-wom would be

to-report compute-wom [lower upper]
  report upper - random-float (upper - lower)
end

In your case, you would

set probability-of-wom compute-wom -1 1

But a couple of comments. First, what you are generating here is a random number between two limits (as your title suggests), so calling it a probability could be misleading to anyone reading your code. Probabilities will normally be in the range from zero to one. If you really are just looking to do something with a 50% probability, you can simply say

if random-float 1 >= 0.5 [...]

Second, reporters should generally take variable arguments if they are to have arguments at all. Note that since you hard code -1 and 1 in the body of your to-report compute-wom reporter, passing them as arguments is redundant, and possibly misleading to anyone reading your code.


问:
[[ -e $file ]] command in unix
I'm relatively new to unix command line and I do not really understand what this command does:

```<code>[[ ! -e "$text_file" ]] || { echo "Error: I cannot overwrite '$text_file'." >&2;}
</code>```

Does anyone have an idea?

答:
This checks a file for existence and the ! negates the expression
See a list of bash file testing</p>

Title: [[ -e $file ]] command in unix

Body:
I'm relatively new to unix command line and I do not really understand what this command does:

[[ ! -e "$text_file" ]] || { echo "Error: I cannot overwrite '$text_file'." >&2;}

Does anyone have an idea?


问:
Using tuples to remove duplicate coordinates from a list in VBA
I have two arrays filled with X and Y values. The values are pulled from text boxes the user fills.

These values (x1,y1), (y1,y2), (x_nth, y_nth) are plotted, where n is the number of points in my arrays.

I want to run through these coordinate pairs and find the ones that overlap each other. Once I find an overlapping point identified then I can change the duplicate(s) marker size to be bigger so the reader can see how often a point is repeated. Right now I just want to accomplish the former.

I’m not familiar with VBA I work mainly in Python. Below is my example code that works in python.

```<code>x = [1,2,2,4,5,5,5]
y = [1,3,3,4,5,5,5]
pts = []
for i in range(len(x)):
    cX = x[i]
    cY = y[i]
    if (cX, cY) in pts:
        print("duplicate")
        print(cX, cY)
        #plot this point on scatter
        #increase marker size for this particular point
    else:
        pts.append((cX, cY))
print(pts)
</code>```

Output

```<code>Duplicate
2 3
Duplicate
5 5
Duplicate
5 5
[(1,1), (2, 3), (4,4), (5,5)]
</code>```

答:
I just threw this together real quick, but it does the job. Python does a better job working with data than vba (more data types like lists and tuples). There are a few ways to make this happen, I just chose to use a 2 dimensional array.  </p>

```<code>Dim array_Tuple() As Variant, i As Integer, xsplit, ysplit
Dim sLength As Integer, x As String, y As String, v
Dim bool As Boolean

x = "1,2,2,4,5,5,5"
y = "1,3,3,4,5,5,5"

xsplit = Split(x, ",")
ysplit = Split(y, ",")
count = 0

On Error Resume Next
For i = 0 To UBound(xsplit)
bool = True

    For j = 0 To count
        If xsplit(i) = array_Tuple(1, j) And ysplit(i) = array_Tuple(2, j) Then
            If Not err.Number <> 0 Then
                bool = False
            End If
            err.Clear
        End If
    Next

If bool Then
    count = count + 1
    ReDim Preserve array_Tuple(1 To 2, 1 To count)
    array_Tuple(1, count) = xsplit(i)
    array_Tuple(2, count) = ysplit(i)

    Debug.Print array_Tuple(1, count) & "," & array_Tuple(2, count)
End If

Next
On Error GoTo 0
</code>```

Body:
I have two arrays filled with X and Y values. The values are pulled from text boxes the user fills.

These values (x1,y1), (y1,y2), (x_nth, y_nth) are plotted, where n is the number of points in my arrays.

I want to run through these coordinate pairs and find the ones that overlap each other. Once I find an overlapping point identified then I can change the duplicate(s) marker size to be bigger so the reader can see how often a point is repeated. Right now I just want to accomplish the former.

I’m not familiar with VBA I work mainly in Python. Below is my example code that works in python.

x = [1,2,2,4,5,5,5]
y = [1,3,3,4,5,5,5]
pts = []
for i in range(len(x)):
    cX = x[i]
    cY = y[i]
    if (cX, cY) in pts:
        print("duplicate")
        print(cX, cY)
        #plot this point on scatter
        #increase marker size for this particular point
    else:
        pts.append((cX, cY))
print(pts)

Output

Duplicate
2 3
Duplicate
5 5
Duplicate
5 5
[(1,1), (2, 3), (4,4), (5,5)]

Body:
I just threw this together real quick, but it does the job. Python does a better job working with data than vba (more data types like lists and tuples). There are a few ways to make this happen, I just chose to use a 2 dimensional array.

Dim array_Tuple() As Variant, i As Integer, xsplit, ysplit
Dim sLength As Integer, x As String, y As String, v
Dim bool As Boolean

x = "1,2,2,4,5,5,5"
y = "1,3,3,4,5,5,5"

xsplit = Split(x, ",")
ysplit = Split(y, ",")
count = 0

On Error Resume Next
For i = 0 To UBound(xsplit)
bool = True

    For j = 0 To count
        If xsplit(i) = array_Tuple(1, j) And ysplit(i) = array_Tuple(2, j) Then
            If Not err.Number <> 0 Then
                bool = False
            End If
            err.Clear
        End If
    Next

If bool Then
    count = count + 1
    ReDim Preserve array_Tuple(1 To 2, 1 To count)
    array_Tuple(1, count) = xsplit(i)
    array_Tuple(2, count) = ysplit(i)

    Debug.Print array_Tuple(1, count) & "," & array_Tuple(2, count)
End If

Next
On Error GoTo 0


问:
Need a Https endpoint for microsoft teams and python integration
I have some python scripts which perform some jobs based on the user inputs I want to host this on microsoft teams. For an outgoing webhook teams asks for a https link where and how do I get it. I am pretty new to this so do not take anything for granted.</p>

答:
You need to use bot framework to create bot that will handle that:
https://github.com/microsoft/botframework-sdk

https://github.com/microsoft/BotBuilder-Samples


问:
Fancybox 3: Disable zoom when image is clicked
I have set up a simple image slider using the Fancybox 3 plugin (http://fancyapps.com/fancybox/3/docs/) within the Kirby CMS (https://getkirby.com/). The only thing I'm not able to work out, is how to stop the slider from zooming into an image when the image is clicked on while the slider is open.

Can someone give me a hand with this?

I tried including clickSlide : 'close', in the options for the slider, but it did not work.

Here are the options I have set up for the slider globally on my site:

```<code>  <!-- Setting fancybox-options GLOBALLY -->

    <script type="text/javascript">

       $("[data-fancybox]").fancybox({

         thumbs          : false,

         hash            : false,

         loop            : true,

         keyboard        : true,

         toolbar         : false,

         animationEffect : false,

         arrows          : true,

       });

    </script>

  <!-- /////////////////////// -->
</code>```

答:
To disable click to scroll and remove zoom button from the toolbar:

$('[data-fancybox]').fancybox({
  clickContent: 'close',
  buttons: ['close']
})
```


问:
Show Data from CoreData
I have a SwiftUI project using CoreData Database with a Product entity in it. It has 2 attributes, id, and barcode.
Then I create a fetch request that seems to work but will result in an empty [Products].

When the view appears on screen I get the error

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1df9bda98) on the ForEach and no other information.

I tried to make it as simple as possible and I still have the problem.
I tried to delete the xcdatamodel file entirely and recreate it and I keep have the problem.

```<code>private struct ProductList: View {
@FetchRequest(
    entity: Product.entity(),
    sortDescriptors: []
) var products: FetchedResults<Product>

var body: some View {
    VStack {
        List{
            ForEach(products, id: \.id) { product in
                ProductRow(product: product)
            }
        }
    }

}
</code>```

}

```<code>private struct ProductRow: View {
var product: Product

var body: some View {
    Text(product.barcode ?? "No name given")
}
</code>```

}

Screencapture of the problematic code

答:
Before using @FetchRequest you must first have injected a Core Data managed object context into the environment, otherwise your products is not empty, but nil

see https://github.com/andrewcbancroft/BlogIdeaList-SwiftUI/tree/master/BlogIdeaList-SwiftUI for further details

Title: Show Data from CoreData

Body:
I have a SwiftUI project using CoreData Database with a Product entity in it. It has 2 attributes, id, and barcode.
Then I create a fetch request that seems to work but will result in an empty [Products].

When the view appears on screen I get the error

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1df9bda98) on the ForEach and no other information.

I tried to make it as simple as possible and I still have the problem.
I tried to delete the xcdatamodel file entirely and recreate it and I keep have the problem.

private struct ProductList: View {
@FetchRequest(
    entity: Product.entity(),
    sortDescriptors: []
) var products: FetchedResults<Product>

var body: some View {
    VStack {
        List{
            ForEach(products, id: \.id) { product in
                ProductRow(product: product)
            }
        }
    }

}

}

private struct ProductRow: View {
var product: Product

var body: some View {
    Text(product.barcode ?? "No name given")
}

}

Screencapture of the problematic code


问:
Best way to write a Safari 4 Extension
What is the best way to write a Safari extension? I've written a couple XUL extensions for Firefox, and now I'd like to write versions of them for Safari. Is there a way that would allow you to add buttons or forms to the browser UI, since this is not possible with an Input manager or Service menu?</p>

答:
Safari plugin development is non-trivial. The interface is written in Objective-C, and most of it is not even part of WebKit (so you can't see the source), but there's machinery to inspect and patch the object hierarchy of a running application. It requires understanding of Cocoa and Objective-C, but no lower.

Here's a high level overview I had in my bookmarks of the process http://livingcode.org/2006/tab-dumping-in-safari. It goes over creating Safari plugins using Python with working (probably outdated) code. Instead of Python you can use anything that has Objective-C bindings.

There are two major parts to it:

You need to attach your code to a running Safari. This is typically done with SIMBL http://www.culater.net/software/SIMBL/SIMBL.php.

Once you're inside, you need to figure what to patch. There's a tutorial on reversing Cocoa applications http://www.culater.net/wiki/moin.cgi/CocoaReverseEngineering, which links to the most important tool, class-dump http://www.codethecode.com/projects/class-dump/ (the link on wiki is broken). Class-dump gives you a complete hierarchy of Safari's classes, where you can guess by names what, specifically, you need to patch. This is a very trial and error mode.

Reading the links above will give you the scope of the project.

OwnerDisplayName: username

Title: Best way to write a Safari 4 Extension

ContentLicense: CC BY-SA 2.5


问:
Is there any reason to retain a scheduled NSTimer if you don't need to invalidate it?
I'm going back over some crufty code to tidy it up and I see I've been retaining NSTimers returned from scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: and storing them in a field - then releasing and nulling the field when it fires. In some cases I use the timer to send an invalidate message to it later - but in many cases not.

In more recent code I usually just schedule the timer and forget about it. I understand that the constructor method is autoreleasing and the timer is retained by the run loop while it is active - so I don't see any issue with this.

So, just to round out my understanding - is there any other reason I should be holding on to my timers, or is what I am doing now the accepted idiom?

This is all in the context of iPhone code, but I don't believe this is iPhone specific.

答: I just let the run loop handle the retention, myself - it's the run loop that owns the timer and not me. If you see what I mean.</p>

OwnerDisplayName: Phil Nash


问:
run button in xcode 4
Whenever I re-run my application by selecting the run button in xcode for, it says simulator already in use. So I have to stop it every time before re-running.
So my question is, is there any option or setting to avoid this. I want to run the application without stopping it like we used to do in xcode 3.</p>

答: The issue is that pressing the Home button, even in the simulator, does not stop your app under iOS 4. You can either stop your app in the debugger, or in the simulator, or you can modify your app such that it doesn't run in the background. See Opting Out of Background Execution.</p>

Title: run button in xcode 4