问:
Im using InAppWebView. How to listen url changes and get url?
this is my code. I have to navigate my screen. For excemple: if url x.com, navigate to x screen and etc.</p>
```<code>InAppWebView(

  initialUrlRequest:
      URLRequest(url: new Uri.dataFromString(url, mimeType: 'text/html')),
  initialOptions:
      InAppWebViewGroupOptions(crossPlatform: InAppWebViewOptions(),
      ),
)
</code>```

答:
You can use onUpdateVisitedHistory property in InAppWebView widget

```<code>    InAppWebView(
              key: webViewKey,
              onWebViewCreated: (controller) {
                webViewController = controller;
                _loadHtmlFromAssets();
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                if (url!.host.contains("google.com")) {
   //Prevent that url works
                  webViewController?.goBack();
                  //You can do anything
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen1()),
                  );

                  return;
                } else if (url.host.contains("yahoo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen3()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("duckduckgo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen2()),
                  );
                }
              })
</code>```

here webcontroller.goback() used for preventing jump to the site instead of new screen
It may like this:

Sample Code:

```<code>class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  WebViewController? _controller;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  late PullToRefreshController pullToRefreshController;
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  @override
  void initState() {
    super.initState();

    pullToRefreshController = PullToRefreshController(
      options: PullToRefreshOptions(
        color: Colors.blue,
      ),
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            webViewController?.goBack();
          },
          child: Icon(Icons.arrow_back),
        ),
        appBar: AppBar(
          backgroundColor: Colors.black87,
          title: Text(widget.title),
        ),
        body: Center(
          child: InAppWebView(
              key: webViewKey,
              onWebViewCreated: (controller) {
                webViewController = controller;
                _loadHtmlFromAssets();
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                if (url!.host.contains("google.com")) {
                  webViewController?.goBack();
                  //You can do anything
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen1()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("yahoo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen3()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("duckduckgo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen2()),
                  );
                }
              }),
        ));
  }

  _loadHtmlFromAssets() {
    var fileText =
        "<!DOCTYPE html> <html> <head> <title>HTML, CSS and JavaScript demo</title> <style> .rotate { transform: rotate(1700deg) ; } .rotate2 { transform: rotate(90deg) ; } .bg { background: url(https://picsum.photos/2000/1000?image=1069) center/cover; height: 50vh; width: 50vh; } body { margin:0; overflow:hidden; } </style> </head> "
        "<!-- Start your code here --> <ul> <li> <a href ='http://duckduckgo.com/' /><p> duckduckgo.com</a> </li>  <li> <a href='http://www.google.com'>google.com </a> </li>    <li> <a href='http://www.yahoo.com/'> yahoo.com </a> </li></ul> </html>";
    // return Uri.dataFromString(fileText,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString();
    webViewController!.loadUrl(
        urlRequest: URLRequest(
            url: new Uri.dataFromString(fileText, mimeType: 'text/html')));

    // _controller?.loadUrl(Uri.dataFromString(fileText,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString());
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class Screen1 extends StatelessWidget {
  const Screen1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Text("Screen 1 google.com"),
      ),
    );
  }
}

class Screen2 extends StatelessWidget {
  const Screen2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: MaterialApp(
        home: Container(
          child: Text("Screen 2 yahoo.com"),
        ),
      ),
    );
  }
}

class Screen3 extends StatelessWidget {
  const Screen3({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Text("Screen 3 duck.com"),
      ),
    );
  }
}
</code>```

Body:
this is my code. I have to navigate my screen. For excemple: if url x.com, navigate to x screen and etc.

InAppWebView(

  initialUrlRequest:
      URLRequest(url: new Uri.dataFromString(url, mimeType: 'text/html')),
  initialOptions:
      InAppWebViewGroupOptions(crossPlatform: InAppWebViewOptions(),
      ),
)

Body:
You can use onUpdateVisitedHistory property in InAppWebView widget

    InAppWebView(
              key: webViewKey,
              onWebViewCreated: (controller) {
                webViewController = controller;
                _loadHtmlFromAssets();
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                if (url!.host.contains("google.com")) {
   //Prevent that url works
                  webViewController?.goBack();
                  //You can do anything
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen1()),
                  );

                  return;
                } else if (url.host.contains("yahoo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen3()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("duckduckgo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen2()),
                  );
                }
              })

here webcontroller.goback() used for preventing jump to the site instead of new screen
It may like this:

Sample Code:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  WebViewController? _controller;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  late PullToRefreshController pullToRefreshController;
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  @override
  void initState() {
    super.initState();

    pullToRefreshController = PullToRefreshController(
      options: PullToRefreshOptions(
        color: Colors.blue,
      ),
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            webViewController?.goBack();
          },
          child: Icon(Icons.arrow_back),
        ),
        appBar: AppBar(
          backgroundColor: Colors.black87,
          title: Text(widget.title),
        ),
        body: Center(
          child: InAppWebView(
              key: webViewKey,
              onWebViewCreated: (controller) {
                webViewController = controller;
                _loadHtmlFromAssets();
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                if (url!.host.contains("google.com")) {
                  webViewController?.goBack();
                  //You can do anything
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen1()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("yahoo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen3()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("duckduckgo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen2()),
                  );
                }
              }),
        ));
  }

  _loadHtmlFromAssets() {
    var fileText =
        "<!DOCTYPE html> <html> <head> <title>HTML, CSS and JavaScript demo</title> <style> .rotate { transform: rotate(1700deg) ; } .rotate2 { transform: rotate(90deg) ; } .bg { background: url(https://picsum.photos/2000/1000?image=1069) center/cover; height: 50vh; width: 50vh; } body { margin:0; overflow:hidden; } </style> </head> "
        "<!-- Start your code here --> <ul> <li> <a href ='http://duckduckgo.com/' /><p> duckduckgo.com</a> </li>  <li> <a href='http://www.google.com'>google.com </a> </li>    <li> <a href='http://www.yahoo.com/'> yahoo.com </a> </li></ul> </html>";
    // return Uri.dataFromString(fileText,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString();
    webViewController!.loadUrl(
        urlRequest: URLRequest(
            url: new Uri.dataFromString(fileText, mimeType: 'text/html')));

    // _controller?.loadUrl(Uri.dataFromString(fileText,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString());
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class Screen1 extends StatelessWidget {
  const Screen1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Text("Screen 1 google.com"),
      ),
    );
  }
}

class Screen2 extends StatelessWidget {
  const Screen2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: MaterialApp(
        home: Container(
          child: Text("Screen 2 yahoo.com"),
        ),
      ),
    );
  }
}

class Screen3 extends StatelessWidget {
  const Screen3({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Text("Screen 3 duck.com"),
      ),
    );
  }
}


来源: stackexchange

问:
Difference in days between two dates in Java?
I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

```<code>  int age=calculateDifference(agingDate, today);
</code>```

Here calculateDifference is a private method, agingDate and today are Date objects, just for your clarification. I've followed two articles from a Java forum, Thread 1 / Thread 2.

It works fine in a standalone program although when I include this into my logic to read from the report I get an unusual difference in values.

Why is it happening and how can I fix it?

EDIT :

I'm getting a greater number of days compared to the actual amount of Days.

```<code>public static int calculateDifference(Date a, Date b)
{
    int tempDifference = 0;
    int difference = 0;
    Calendar earlier = Calendar.getInstance();
    Calendar later = Calendar.getInstance();

    if (a.compareTo(b) < 0)
    {
        earlier.setTime(a);
        later.setTime(b);
    }
    else
    {
        earlier.setTime(b);
        later.setTime(a);
    }

    while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))
    {
        tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))
    {
        tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    return difference;
}
</code>```

Note :

Unfortunately, none of the answers helped me solve the problem. I've accomplished this problem with the help of Joda-time library.

答: Look at the getFragmentInDays methods in this apache commons-lang class DateUtils.

ContentLicense: CC BY-SA 3.0

Body:
I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

  int age=calculateDifference(agingDate, today);

Here calculateDifference is a private method, agingDate and today are Date objects, just for your clarification. I've followed two articles from a Java forum, Thread 1 / Thread 2.

It works fine in a standalone program although when I include this into my logic to read from the report I get an unusual difference in values.

Why is it happening and how can I fix it?

EDIT :

I'm getting a greater number of days compared to the actual amount of Days.

public static int calculateDifference(Date a, Date b)
{
    int tempDifference = 0;
    int difference = 0;
    Calendar earlier = Calendar.getInstance();
    Calendar later = Calendar.getInstance();

    if (a.compareTo(b) < 0)
    {
        earlier.setTime(a);
        later.setTime(b);
    }
    else
    {
        earlier.setTime(b);
        later.setTime(a);
    }

    while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))
    {
        tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))
    {
        tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    return difference;
}

Note :

Unfortunately, none of the answers helped me solve the problem. I've accomplished this problem with the help of Joda-time library.


问:
Blender arms are seetrough in unity
So I'm trying to animate fps hands but the leather gloves models that I use are see through on one side. I've tried every tutorial but at this model I can't select the side to make it good in unity too.
The tutorial video that I tried: https://www.youtube.com/watch?v=9iV9wnvpQ1U.
The model that I use: https://gamebanana.com/models/4315.</p>

答: In blender, select the arms/arm > edit mode > face select mode > select all the faces on the object > mesh > normals > i think its render outside or face outside</p>

ContentLicense: CC BY-SA 4.0

Title: Blender arms are seetrough in unity


问:
About Warning Option "incompatible-pointer-types"
My program(https://godbolt.org/z/Y93eG7K7s):

int main(){
    int temp = 0;
    int* tempp = &temp;
    int** temppp = &tempp;
    int*** tempppp = &temppp;

    const int* intp0;
    intp0 = tempp;    // A

    const int** intp1;
    intp1 = temppp;   // B
}
```

Either GCC or Clang can compile, but both raise the same "incompatible-pointer-types" warning in line B. I have no problem with that warning, because const int ** and int ** are definitely two incompatible pointer types. However (in my opinions), const int * and int * are also two incompatible pointer types(line A).

Therefore My Question is: Why const int * and int * are considered as compatible pointer types?

答:
The GCC warning message is incorrectly phrased; the rule violated by intp1 = temppp is not that the operands of = must be compatible but that they must conform to certain constraints. Compatibility is one factor in those constraints, but it is not the factor at issue here, so the message is misleading. Although the question states Clang raises an “incompatible-pointer-types” warning, I do not see this; every version of Clang available on Compiler Explorer reports a correct error message, “assigning to 'const int **' from 'int **' discards qualifiers in nested pointer types.”

An int * may be assigned to a const int * because the rules for simple assignment allow adding qualifiers to the directly pointed-to type. C 2018 6.5.16.1 says:

One of the following shall hold:

…

— the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right; …

The unqualified type that const int * points to is int, and the unqualified type that int * points to is also int, and int is compatible with itself. Further, the type const int * points to, const int, has all the qualifiers of the type that int * points to, int.

In contrast, the unqualified type that const int ** points to is const int *, and the unqualified type that int ** points to is int *, and const int * is not compatible with int *. (Note that while const int * points to a qualified type, it is itself unqualified; a object of type const int * may be changed to point to a different const int; it is not const-qualified.) So intp1 = temppp does not satisfy this constraint, so the compiler warns about it.

The reason this is not allowed is it could result in a pointer to a qualified type pointing to an object without that qualifier. C 2018 6.5.16.1 6 gives an example, shown here modified slightly and with my comments:

```<code>const int *ipp;
int *p;
const int i = 1;

/*  The next line violates the constraints because `&p` is an `int **`, and
    it is assigned to a `const int **`.
    For illustration, suppose we suspend the constraint and allow it.
*/
ipp = &p;

/*  In the following, both `*ipp` and `&i` are `const int *`, so this is
    an ordinary assignment of identical types.
*/
*ipp = &i;

/*  In the following, `*p` is an `int`, to which an `int` is assigned. So
    this is an ordinary assignment of identical types. However, `p` points
    to `i`, which is `const`, so this assignment would change the value of
    a `const` object. The assignment `ipp = &p` above enabled this, so it
    is unsafe and should be disallowed.
*/
*p = 0;
</code>```

Therefore My Question is: Why const int * and int * are considered as compatible pointer types?

They are not compatible pointer types. As explained above, the reason the assignment is not allowed is because of rules about qualifiers, not about compatible types.

The notion of compatible types in C is not about whether one type may be assigned to another type but about whether two types are actually the same except for the parts we do not know about them. For example, an array of three int and an array of an unspecified number of int are compatible—all the parts we know about these two types are the same. They could be the same if the unspecified part is completed. Similarly, a function returning void * that takes unknown parameters is compatible with a function returning void * that takes certain declared parameters. This issue of compatibility is not related to the issue of qualifiers in assignments.

Body:
My program(https://godbolt.org/z/Y93eG7K7s):

int main(){
    int temp = 0;
    int* tempp = &temp;
    int** temppp = &tempp;
    int*** tempppp = &temppp;

    const int* intp0;
    intp0 = tempp;    // A

    const int** intp1;
    intp1 = temppp;   // B
}

Either GCC or Clang can compile, but both raise the same "incompatible-pointer-types" warning in line B. I have no problem with that warning, because const int ** and int ** are definitely two incompatible pointer types. However (in my opinions), const int * and int * are also two incompatible pointer types(line A).

Therefore My Question is: Why const int * and int * are considered as compatible pointer types?

Body:
The GCC warning message is incorrectly phrased; the rule violated by intp1 = temppp is not that the operands of = must be compatible but that they must conform to certain constraints. Compatibility is one factor in those constraints, but it is not the factor at issue here, so the message is misleading. Although the question states Clang raises an “incompatible-pointer-types” warning, I do not see this; every version of Clang available on Compiler Explorer reports a correct error message, “assigning to 'const int **' from 'int **' discards qualifiers in nested pointer types.”

An int * may be assigned to a const int * because the rules for simple assignment allow adding qualifiers to the directly pointed-to type. C 2018 6.5.16.1 says:

One of the following shall hold:

…

— the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right; …

The unqualified type that const int * points to is int, and the unqualified type that int * points to is also int, and int is compatible with itself. Further, the type const int * points to, const int, has all the qualifiers of the type that int * points to, int.

In contrast, the unqualified type that const int ** points to is const int *, and the unqualified type that int ** points to is int *, and const int * is not compatible with int *. (Note that while const int * points to a qualified type, it is itself unqualified; a object of type const int * may be changed to point to a different const int; it is not const-qualified.) So intp1 = temppp does not satisfy this constraint, so the compiler warns about it.

The reason this is not allowed is it could result in a pointer to a qualified type pointing to an object without that qualifier. C 2018 6.5.16.1 6 gives an example, shown here modified slightly and with my comments:

const int *ipp;
int *p;
const int i = 1;

/*  The next line violates the constraints because `&p` is an `int **`, and
    it is assigned to a `const int **`.
    For illustration, suppose we suspend the constraint and allow it.
*/
ipp = &p;

/*  In the following, both `*ipp` and `&i` are `const int *`, so this is
    an ordinary assignment of identical types.
*/
*ipp = &i;

/*  In the following, `*p` is an `int`, to which an `int` is assigned. So
    this is an ordinary assignment of identical types. However, `p` points
    to `i`, which is `const`, so this assignment would change the value of
    a `const` object. The assignment `ipp = &p` above enabled this, so it
    is unsafe and should be disallowed.
*/
*p = 0;

Therefore My Question is: Why const int * and int * are considered as compatible pointer types?

They are not compatible pointer types. As explained above, the reason the assignment is not allowed is because of rules about qualifiers, not about compatible types.

The notion of compatible types in C is not about whether one type may be assigned to another type but about whether two types are actually the same except for the parts we do not know about them. For example, an array of three int and an array of an unspecified number of int are compatible—all the parts we know about these two types are the same. They could be the same if the unspecified part is completed. Similarly, a function returning void * that takes unknown parameters is compatible with a function returning void * that takes certain declared parameters. This issue of compatibility is not related to the issue of qualifiers in assignments.


问:
How can I take comma separated inputs for python AnyTree module?
Community. I need to accept multiple comma-separated inputs to produce a summary of information ( specifically, how many different employees participated in each group/project)? The program takes employees, managers and groups in the form of strings.

I'm using anytree python library to be able to search/count the occurrence of each employee per group. However, this program is only accepting one value/cell at a time instead of multiple values.

Here is the tree structure and how I accept input values?

```<code>Press q to exit, Enter your data: Joe
Press q to exit, Enter your data: Manager1
Press q to exit, Enter your data: Group1
Press q to exit, Enter your data: Charles
Press q to exit, Enter your data: Manager1
Press q to exit, Enter your data: Group2
Press q to exit, Enter your data: Joe
Press q to exit, Enter your data: Manager3
Press q to exit, Enter your data: Group1
Press q to exit, Enter your data: Charles
Press q to exit, Enter your data: Manager3
Press q to exit, Enter your data: Group1
Press q to exit, Enter your data: Joe
Press q to exit, Enter your data: Manager5
Press q to exit, Enter your data: Group2
Press q to exit, Enter your data: q
Employee   No of groups
   JOE       2
   CHARLES       2
Group
├── GROUP1
│   ├── JOE
│   │   └── MANAGER1
│   ├── JOE
│   │   └── MANAGER3
│   └── CHARLES
│       └── MANAGER3
└── GROUP2
    ├── CHARLES
    │   └── MANAGER1
    └── JOE
        └── MANAGER5
</code>```

I need help with this code so that It can accept comma-separated values; for example, to enter Joe, Manager1, Group1 at a time.

```<code>import anytree

from anytree import Node, RenderTree, LevelOrderIter, LevelOrderGroupIter, PreOrderIter

import sys

# user input
io=''
lst_input = []
while (io!='q'):
    io=input('Press q to exit, Enter your data: ')
    if io!='q':
        lst_input.append(io.upper())

# change list in to matrix
lst=[]
for i in range(0, len(lst_input), 3):
    lst.append(lst_input[i:i + 3])

lst

# create tree structure from lst
group = Node('Group')
storeGroup = {}
for i in range(len(lst)):
    if lst[i][2] in [x.name for x in group.children]: # parent already exist, append childrens
        storeGroup[lst[i][0]] = Node(lst[i][0], parent=storeGroup[lst[i][2]])
        storeGroup[lst[i][1]] = Node(lst[i][1], parent=storeGroup[lst[i][0]])
    else: # create parent and append childreds
        storeGroup[lst[i][2]] = Node(lst[i][2], parent=group)
        storeGroup[lst[i][0]] = Node(lst[i][0], parent=storeGroup[lst[i][2]])
        storeGroup[lst[i][1]] = Node(lst[i][1], parent=storeGroup[lst[i][0]])

store = {}
for children in LevelOrderIter(group, maxlevel=3):
    if children.parent!=None and children.parent.name!='Group':
        if children.name not in store:
            store[children.name] = {children.parent.name}
        else:
            store[children.name] = store[children.name] | {children.parent.name}

print('Employee', '  No of groups')
for i in store:
    print('   '+i+'      ', len(store[i]))

for pre,fill, node in RenderTree(group):
    print('{}{}'.format(pre,node.name))
</code>```

 Thank you! Any thoughts are welcomed.

答:
I believe one way to go about it is:

name, role, grp = io.upper().split(',')
```
<p>which for an input such as <code>Joe, Manager1, Group1</code></p>
```Python 3.7.9 (v3.7.9:13c94747c7, Aug 15 2020, 01:31:08)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> name, role, grp = input("Press q to exit, Enter your data:").split(",")
Press q to exit, Enter your data:Joe, Manager1, Group1
>>> name
'Joe'
>>> role
' Manager1'
>>> grp
' Group1'
```

Would that work for you ?

Body:
Community. I need to accept multiple comma-separated inputs to produce a summary of information ( specifically, how many different employees participated in each group/project)? The program takes employees, managers and groups in the form of strings.

I'm using anytree python library to be able to search/count the occurrence of each employee per group. However, this program is only accepting one value/cell at a time instead of multiple values.

Here is the tree structure and how I accept input values?

Press q to exit, Enter your data: Joe
Press q to exit, Enter your data: Manager1
Press q to exit, Enter your data: Group1
Press q to exit, Enter your data: Charles
Press q to exit, Enter your data: Manager1
Press q to exit, Enter your data: Group2
Press q to exit, Enter your data: Joe
Press q to exit, Enter your data: Manager3
Press q to exit, Enter your data: Group1
Press q to exit, Enter your data: Charles
Press q to exit, Enter your data: Manager3
Press q to exit, Enter your data: Group1
Press q to exit, Enter your data: Joe
Press q to exit, Enter your data: Manager5
Press q to exit, Enter your data: Group2
Press q to exit, Enter your data: q
Employee   No of groups
   JOE       2
   CHARLES       2
Group
├── GROUP1
│   ├── JOE
│   │   └── MANAGER1
│   ├── JOE
│   │   └── MANAGER3
│   └── CHARLES
│       └── MANAGER3
└── GROUP2
    ├── CHARLES
    │   └── MANAGER1
    └── JOE
        └── MANAGER5

I need help with this code so that It can accept comma-separated values; for example, to enter Joe, Manager1, Group1 at a time.

import anytree

from anytree import Node, RenderTree, LevelOrderIter, LevelOrderGroupIter, PreOrderIter

import sys

# user input
io=''
lst_input = []
while (io!='q'):
    io=input('Press q to exit, Enter your data: ')
    if io!='q':
        lst_input.append(io.upper())

# change list in to matrix
lst=[]
for i in range(0, len(lst_input), 3):
    lst.append(lst_input[i:i + 3])

lst

# create tree structure from lst
group = Node('Group')
storeGroup = {}
for i in range(len(lst)):
    if lst[i][2] in [x.name for x in group.children]: # parent already exist, append childrens
        storeGroup[lst[i][0]] = Node(lst[i][0], parent=storeGroup[lst[i][2]])
        storeGroup[lst[i][1]] = Node(lst[i][1], parent=storeGroup[lst[i][0]])
    else: # create parent and append childreds
        storeGroup[lst[i][2]] = Node(lst[i][2], parent=group)
        storeGroup[lst[i][0]] = Node(lst[i][0], parent=storeGroup[lst[i][2]])
        storeGroup[lst[i][1]] = Node(lst[i][1], parent=storeGroup[lst[i][0]])

store = {}
for children in LevelOrderIter(group, maxlevel=3):
    if children.parent!=None and children.parent.name!='Group':
        if children.name not in store:
            store[children.name] = {children.parent.name}
        else:
            store[children.name] = store[children.name] | {children.parent.name}

print('Employee', '  No of groups')
for i in store:
    print('   '+i+'      ', len(store[i]))

for pre,fill, node in RenderTree(group):
    print('{}{}'.format(pre,node.name))

 Thank you! Any thoughts are welcomed.

Body:
I believe one way to go about it is:

name, role, grp = io.upper().split(',')

which for an input such as Joe, Manager1, Group1

Python 3.7.9 (v3.7.9:13c94747c7, Aug 15 2020, 01:31:08)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> name, role, grp = input("Press q to exit, Enter your data:").split(",")
Press q to exit, Enter your data:Joe, Manager1, Group1
>>> name
'Joe'
>>> role
' Manager1'
>>> grp
' Group1'

Would that work for you ?


问:
Creating your own header file in C
Can anyone explain how to create a header file in C with a simple example from beginning to end.</p>

答:
myfile.h

```<code>#ifndef _myfile_h
#define _myfile_h

void function();

#endif
</code>```

myfile.c

```<code>#include "myfile.h"

void function() {

}
</code>```

Title: Creating your own header file in C

Body:
myfile.h

#ifndef _myfile_h
#define _myfile_h

void function();

#endif

myfile.c

#include "myfile.h"

void function() {

}


问:
How can I submit just filled inputs of a form in ASP.NET Core?
I like to know if it possible to submit just filled inputs of a form and show their name and value in url in browser.

Example:

```<code><form method="get">
   <input name="firstname" value="a" />
   <input name="lastname" value="" />
</form>
</code>```

I like to show in url as:

```<code>?firstname=a
</code>```

not as:

```<code>?firstname=a&lastname=
</code>```

Thanks.

答:
You'll have to use javascript to achieve this result. For example you can make empty inputs disabled so browser doesn't send their values

Form

```<code><form method="get" id="the-form">
    <input name="firstname" value="a" />
    <input name="lastname" value="" />

    <button type="submit">Submit</button>
</form>
</code>```

Javascript

```<code><script>
    let form = document.querySelector('#the-form');
    form.addEventListener('submit', () => {
        let inputs = form.querySelectorAll('input');
        for (let input of inputs) {
            if (!input.value) {
                input.disabled = true;
            }
        }
    })
</script>
</code>```

Body:
I like to know if it possible to submit just filled inputs of a form and show their name and value in url in browser.

Example:

<form method="get">
   <input name="firstname" value="a" />
   <input name="lastname" value="" />
</form>

I like to show in url as:

?firstname=a

not as:

?firstname=a&lastname=

Thanks.

Body:
You'll have to use javascript to achieve this result. For example you can make empty inputs disabled so browser doesn't send their values

Form

<form method="get" id="the-form">
    <input name="firstname" value="a" />
    <input name="lastname" value="" />

    <button type="submit">Submit</button>
</form>

Javascript

<script>
    let form = document.querySelector('#the-form');
    form.addEventListener('submit', () => {
        let inputs = form.querySelectorAll('input');
        for (let input of inputs) {
            if (!input.value) {
                input.disabled = true;
            }
        }
    })
</script>


问:
How to Remove Minimum Value from a Data frame
I'm a novice in Data Science, but I think I have a doubt here.
I have attached the image below.

Image of Described one

In the Dataframe above in the Columns ===> the Humidity, Wind Speed (km/h), Visibility (km), and Pressure (millibars), there are min values which are zero. I don't feel that they should be zero, if am right how can I replace those min values with the next min value using pandas in my data frame. Or please correct me.

答:
If I understand your question correctly, following will do the trick:

```<code>cols = ['Humidity','Wind Speed (km/h)', 'Visibility (km)', 'Pressure (millibars)']
df_train.loc[:, cols] = df_train.loc[:,cols].apply(lambda X: applymin(X))
</code>```

where applymin(X)

```<code>def applymin(X):
    X[X==X.min()] = sorted(X.unique().tolist())[1]
    return X
</code>```

i.e. wherever a column is minimum, we replace it by 2nd smallest value.

Body:
If I understand your question correctly, following will do the trick:

cols = ['Humidity','Wind Speed (km/h)', 'Visibility (km)', 'Pressure (millibars)']
df_train.loc[:, cols] = df_train.loc[:,cols].apply(lambda X: applymin(X))

where applymin(X)

def applymin(X):
    X[X==X.min()] = sorted(X.unique().tolist())[1]
    return X

i.e. wherever a column is minimum, we replace it by 2nd smallest value.


问:
How to access Json Object which has space in its name in MVC Controller Post method
```<code>{
  "Info": "",
  "ContactId": "6850R1644495860425",
  "Retailer Name": "Grow Retailer Shop One",
  "Contact Person": "Retailer One",
  "Mobile number": "8000000001",
  "Google Address": "Bait ul Kashif, Plot no 21, H no 13-6-823/A/9, Mehdi Colony, Langar Houz, Hyderabad, Telangana 50000",
  "SAP Address": "",
  "State*": "TELANGANA",
  "District*": "HYDERABAD",
  "Mandal": "Golconda",
  "Village": "Golconda",
  "RT": "",
  "Latitude": "17.3759033",
  "Longitude": "78.4266764",
  "Preferred Distributor": "",
  "PreferredSource1": "",
  "Territory": "HYDERABAD",
  "CreatedDate": "11/02/2022 05:26:28 AM",
  "CreatedBy": "GoIndigo FO",
  "Print": ""
}
</code>```

this is my Json data which is coming from Ajax Post request to mvc controller which is having spaces in Properties i used  [JsonProperty("Retailer Name")] also while deserializing but data coming null.

答:
try to use a Newtonsoft.Json serializer since you are using  [JsonProperty] attribute. This attribute doesn't work for System.Text.Json.

```<code>Data data = JsonConvert.DeserializeObject<Data>(json);
</code>```

and class

```<code>    public partial class Data
    {

        public string Info { get; set; }

        public string ContactId { get; set; }

        [JsonProperty("Retailer Name")]
        public string RetailerName { get; set; }

        [JsonProperty("Contact Person")]
        public string ContactPerson { get; set; }

        [JsonProperty("Mobile number")]
        public string MobileNumber { get; set; }

        [JsonProperty("Google Address")]
        public string GoogleAddress { get; set; }

        [JsonProperty("SAP Address")]
        public string SapAddress { get; set; }

        public string State { get; set; }

        public string District { get; set; }

        public string Mandal { get; set; }

        public string Village { get; set; }

        public string Rt { get; set; }

        public string Latitude { get; set; }

        public string Longitude { get; set; }

        [JsonProperty("Preferred Distributor")]
        public string PreferredDistributor { get; set; }

        public string PreferredSource1 { get; set; }

        public string Territory { get; set; }

        public string CreatedDate { get; set; }

        public string CreatedBy { get; set; }

        public string Print { get; set; }
    }
</code>```

Body:
{
  "Info": "",
  "ContactId": "6850R1644495860425",
  "Retailer Name": "Grow Retailer Shop One",
  "Contact Person": "Retailer One",
  "Mobile number": "8000000001",
  "Google Address": "Bait ul Kashif, Plot no 21, H no 13-6-823/A/9, Mehdi Colony, Langar Houz, Hyderabad, Telangana 50000",
  "SAP Address": "",
  "State*": "TELANGANA",
  "District*": "HYDERABAD",
  "Mandal": "Golconda",
  "Village": "Golconda",
  "RT": "",
  "Latitude": "17.3759033",
  "Longitude": "78.4266764",
  "Preferred Distributor": "",
  "PreferredSource1": "",
  "Territory": "HYDERABAD",
  "CreatedDate": "11/02/2022 05:26:28 AM",
  "CreatedBy": "GoIndigo FO",
  "Print": ""
}

this is my Json data which is coming from Ajax Post request to mvc controller which is having spaces in Properties i used  [JsonProperty("Retailer Name")] also while deserializing but data coming null.

Body:
try to use a Newtonsoft.Json serializer since you are using  [JsonProperty] attribute. This attribute doesn't work for System.Text.Json.

Data data = JsonConvert.DeserializeObject<Data>(json);

and class

    public partial class Data
    {

        public string Info { get; set; }

        public string ContactId { get; set; }

        [JsonProperty("Retailer Name")]
        public string RetailerName { get; set; }

        [JsonProperty("Contact Person")]
        public string ContactPerson { get; set; }

        [JsonProperty("Mobile number")]
        public string MobileNumber { get; set; }

        [JsonProperty("Google Address")]
        public string GoogleAddress { get; set; }

        [JsonProperty("SAP Address")]
        public string SapAddress { get; set; }

        public string State { get; set; }

        public string District { get; set; }

        public string Mandal { get; set; }

        public string Village { get; set; }

        public string Rt { get; set; }

        public string Latitude { get; set; }

        public string Longitude { get; set; }

        [JsonProperty("Preferred Distributor")]
        public string PreferredDistributor { get; set; }

        public string PreferredSource1 { get; set; }

        public string Territory { get; set; }

        public string CreatedDate { get; set; }

        public string CreatedBy { get; set; }

        public string Print { get; set; }
    }


问:
Coming from OO languages to C, how can I avoid circular dependencies?
When I say "Entity" below, I'm not specifically referring to anything relating to the ECS pattern, I just mean a general game entity.

I'm trying my hand at game development in C, after having done previous game dev in TypeScript. I'm looking for a C idiomatic way to reuse a pattern with which I'm familiar: each tick, the game iterates through a list of entities, telling each one to update itself, then draw itself. Each entity knows how to update itself, but requires information about the game as a whole to make this update.

// Game.ts
import Entity from './Entity.js'
class Game {
  entities: List<Entity>;

  tick(dt: number) {
    entities.forEach(e => e.tick(dt));
    entities.forEach(e => e.draw());
  }
}

// Entity.ts
import Game from './Game.ts'
class Entity {
  game: Game;

  constructor(g: Game) {
    this.game = g;
  }

  tick(dt: number) {
    this.move(dt);
    this.collide(this.game);
  }
  draw() { /* snip */}
}
```
<p>In C, I would like to have a big Game struct that has a list of all Entities inside it, and each Entity contains a function pointer for how to update itself.</p>
<pre class="lang-c prettyprint-override"><code>// game.h
#include "entity.h"
typedef struct Game {
  Entity *entities;
} Game;

// entity.h
#include "game.h"
typedef struct Entity Entity;

typedef void (*tick) (Entity*);

struct Entity {
  Game *game;
  char* name;
  int x, y;
  tick* t;
};
</code>```

This, however, requires a circular reference to Game in Entity and Entity in Game, which I've gathered that one is not supposed to do. The only way I've thought of to make this work is to put a tick_entity(Game *game, Entity *e) function in game.h, but my OO brain wants to separate my concerns some more to avoid making Game responsible for everything, especially once I have different kinds of Entities. Is there a more idiomatic way to do what I'm trying to do here?

答:
Don't #include "entity.h" from game.h and vice versa. Just forward declare what you need a pointer to. Also add header guards if you haven't already.

Example:

// game.h
#ifndef GAME_H                 // header guard
#define GAME_H

//#include "entity.h"          // remove this
typedef struct Entity Entity;  // forward declare

typedef struct Game {
    Entity* entities;
} Game;

#endif
```
<pre class="lang-c prettyprint-override"><code>// entity.h
#ifndef ENTITY_H               // header guard
#define ENTITY_H

//#include "game.h"            // remove this
typedef struct Game Game;      // forward declare
typedef struct Entity Entity;

typedef void (*tick)(Entity*);

struct Entity {
    Game* game;
    char* name;
    int x, y;
    tick* t;
};

#endif
</code>```

Body:
When I say "Entity" below, I'm not specifically referring to anything relating to the ECS pattern, I just mean a general game entity.

I'm trying my hand at game development in C, after having done previous game dev in TypeScript. I'm looking for a C idiomatic way to reuse a pattern with which I'm familiar: each tick, the game iterates through a list of entities, telling each one to update itself, then draw itself. Each entity knows how to update itself, but requires information about the game as a whole to make this update.

// Game.ts
import Entity from './Entity.js'
class Game {
  entities: List<Entity>;

  tick(dt: number) {
    entities.forEach(e => e.tick(dt));
    entities.forEach(e => e.draw());
  }
}

// Entity.ts
import Game from './Game.ts'
class Entity {
  game: Game;

  constructor(g: Game) {
    this.game = g;
  }

  tick(dt: number) {
    this.move(dt);
    this.collide(this.game);
  }
  draw() { /* snip */}
}

In C, I would like to have a big Game struct that has a list of all Entities inside it, and each Entity contains a function pointer for how to update itself.

// game.h
#include "entity.h"
typedef struct Game {
  Entity *entities;
} Game;

// entity.h
#include "game.h"
typedef struct Entity Entity;

typedef void (*tick) (Entity*);

struct Entity {
  Game *game;
  char* name;
  int x, y;
  tick* t;
};

This, however, requires a circular reference to Game in Entity and Entity in Game, which I've gathered that one is not supposed to do. The only way I've thought of to make this work is to put a tick_entity(Game *game, Entity *e) function in game.h, but my OO brain wants to separate my concerns some more to avoid making Game responsible for everything, especially once I have different kinds of Entities. Is there a more idiomatic way to do what I'm trying to do here?

Body:
Don't #include "entity.h" from game.h and vice versa. Just forward declare what you need a pointer to. Also add header guards if you haven't already.

Example:

// game.h
#ifndef GAME_H                 // header guard
#define GAME_H

//#include "entity.h"          // remove this
typedef struct Entity Entity;  // forward declare

typedef struct Game {
    Entity* entities;
} Game;

#endif

// entity.h
#ifndef ENTITY_H               // header guard
#define ENTITY_H

//#include "game.h"            // remove this
typedef struct Game Game;      // forward declare
typedef struct Entity Entity;

typedef void (*tick)(Entity*);

struct Entity {
    Game* game;
    char* name;
    int x, y;
    tick* t;
};

#endif


问:
Is it possible to share and see a link using ShareKit in iOS(need the exact way as Web)
I have an app and I am using ShareKit for sharing in Facebook. I am able to share URLs, images and texts to FB using that. But why did the link/url share do not work the same way as when I share a url from Web Facebook. I have got many contents like image in my url and while doing the Share through web I am able to see the image and a small portion of content, but while I am doing it from iPhone using ShareKit, it just gives the heading/title and we need to click on that link(no images or contents).

If anyone know the solution, please help.

答: When you share a link on the Facebook site it will automatically fetch the URL and display some appropriate images that you can choose from. However, when directly interacting with the API this won't happen. You must provide the image yourself (or Facebook may use the image associated with your application). ShareKit may abstract this away from you, so you might want to look into using the Facebook SDK and Graph APIs directly.</p>


问:
TortoiseGit amend merge commit: "show diff to last commit" checkbox is disabled
I'm trying to commit --amend to a merge commit with TortoiseGit 2.13.0.1.

For a repository where the last commit is a merge commit, the "show diff to last commit" checkbox is disabled (greyed) and checked after i check the amend checkbox; it doesn't let me uncheck it:

With other repositories, the checkbox isn't disabled and not checked automatically after i check the amend checkbox.

Is this per design or is there some hidden setting to enable the checkbox for this situation?

答:
Seems like this is per design in TortoiseGit and there's no way to enable the checkbox with builtin functionality. I don't know if it always have been this way; i couldn't find much "amend" mentioned in the docs or the releasenotes.

There are two options i can see:

use another tool which doesn't have this restriction

use zDump to enable the checkbox at runtime


问:
Most efficient way to remove an item from array?
I have two arrays. If a user adds a product, we put it in the ProductArray. If they remove that product, we add it to the ProductArrayRemove array as well as remove it from the product array.  (We need to know products that have been added as well as products that have been removed. This requires redundancy.)

```<code>ProductArray = JSON.parse(ProductArray);
ProductArrayRemove = JSON.parse(ProductArrayRemove);
</code>```

When I add and item to the array, I simply do this:

```<code> ProductArray.push(ItemID);
 ProductArrayRemove.push(ItemID);
</code>```

But when I remove it, I have to do this:

```<code>var len = ProductArray.length;
for (i = 0; i < len; i++) {
    ProductID = ProductArray[i];
    if (ProductID == ItemID) {
        ProductArray.splice(i,1);
        break;
    }
}
</code>```

It seems that there should be a better way of accomplishing this task.

Is there a more efficient means of getting rid of a single item (that will always be an integer) from an array?

答:
Array.prototype.filter() should do the trick. ref

Array.filter() goes through each array element (this case product) and returns a new modified array based on your needs (this case, returns an array without the deleted product)

It would look like something like this:

```<code>  ProductArray = ProductArray.filter(function(product) {
        return product !== ItemID
    })
</code>```

the product is each array element in your ProductArray.

You even make it smaller with arrow function which is almost the same function() but more compact and limited.

```<code>  ProductArray = ProductArray.filter(product => product !== ItemID)
</code>```

Now the ProductArray doesn't have the deleted product and it's a one-liner solution

Body:
I have two arrays. If a user adds a product, we put it in the ProductArray. If they remove that product, we add it to the ProductArrayRemove array as well as remove it from the product array.  (We need to know products that have been added as well as products that have been removed. This requires redundancy.)

ProductArray = JSON.parse(ProductArray);
ProductArrayRemove = JSON.parse(ProductArrayRemove);

When I add and item to the array, I simply do this:

 ProductArray.push(ItemID);
 ProductArrayRemove.push(ItemID);

But when I remove it, I have to do this:

var len = ProductArray.length;
for (i = 0; i < len; i++) {
    ProductID = ProductArray[i];
    if (ProductID == ItemID) {
        ProductArray.splice(i,1);
        break;
    }
}

It seems that there should be a better way of accomplishing this task.

Is there a more efficient means of getting rid of a single item (that will always be an integer) from an array?

Body:
Array.prototype.filter() should do the trick. ref

Array.filter() goes through each array element (this case product) and returns a new modified array based on your needs (this case, returns an array without the deleted product)

It would look like something like this:

  ProductArray = ProductArray.filter(function(product) {
        return product !== ItemID
    })

the product is each array element in your ProductArray.

You even make it smaller with arrow function which is almost the same function() but more compact and limited.

  ProductArray = ProductArray.filter(product => product !== ItemID)

Now the ProductArray doesn't have the deleted product and it's a one-liner solution


问:
OAuth redirect flow server to server token generation for client
I have a rest API service that enables API calls for some resources.
The API calls can be done from an API server using a secret, or from a web client using a bearer token.
In order to get to the web client flow, a URL must be generated by the API server call:

https://www.someapi.com/somelink

The response will be a link with a token I call "action token". This token is passed with the link, for example:

https://www.somepage.com/?action_token=somejwttoken

By entering the link, the action token will be exchanged with an access token, that enables a client to access some pre-defined resources.

I wonder if there is a best practice for such flow.

答:
ONE TIME TOKENS

If using tokens in URLs you should also ensure that:

The token has a one time use

The token is short lived

The token is not guessable - eg make it a UUID

The final access token returned has limited privileges and also a short lifetime

The one time action token may then be available in the browser history or server logs, so be aware of that. Make the actual swap for the proper token a JSON to JSON POST operation, after the page has loaded.

Typically each action token issued would also be stored by the API in a database along with its expiry time, then used to verify links later.

This type of URL solution is sometimes used in operations such as verify email or to enable magic links, where users can quickly access limited data.

OAUTH FLOWS

One time tokens should not be overused and they are of course no substitute for signing the user in properly via OpenID Connect standards, then running an authenticated user session.

SCOPES AND API TO API FLOWS

A more secure option may be to forward JWTs from the original client to downstream APIs, as described in Scopes Best Practices. This enables user context to flow securely and also simplifies code. This may eliminate or reduce the need for any token exchange operations.


问:
Number of Rows and Columns in Julia DataFrames
I have a Julia DataFrame:

```<code>df = DataFrame(a=1:4,b=5:8, c=["a", "b", "c", "d"])

4×3 DataFrame
 Row │ a      b      c
     │ Int64  Int64  String
─────┼──────────────────────
   1 │     1      5  a
   2 │     2      6  b
   3 │     3      7  c
   4 │     4      8  d
</code>```

How do I get the number of rows an columns?

答:
Soultion 1

```<code>nrow(df)
4

ncol(df)
3
</code>```

Solution 2

```<code>size(df,1)
4

size(df,2)
3
</code>```

Body:
I have a Julia DataFrame:

df = DataFrame(a=1:4,b=5:8, c=["a", "b", "c", "d"])

4×3 DataFrame
 Row │ a      b      c
     │ Int64  Int64  String
─────┼──────────────────────
   1 │     1      5  a
   2 │     2      6  b
   3 │     3      7  c
   4 │     4      8  d

How do I get the number of rows an columns?

Body:
Soultion 1

nrow(df)
4

ncol(df)
3

Solution 2

size(df,1)
4

size(df,2)
3


问:
How should I change currentIndex property of BottomNavigationBar on Navigating to another screen?
I have a bottom navigation bar widget for my Flutter app. On tapping specific item it is navigating to another screen. However, I don't know how to update current index in this case so that selected tab gets highlighted. Here is my code:

```<code>        BottomNavigationBar(
          backgroundColor: const Color(0xffFF7B19),
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(
                Icons.calendar_today_rounded,
                size: lh / 25,
              ),
              label: 'Events',
            ),
            BottomNavigationBarItem(
              icon: Icon(
                Icons.people_alt_outlined,
                size: lh / 25,
              ),
              label: 'Councils',
            ),
          ],
          currentIndex: 0,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
            if (index == 0) {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AllEventsScreen()));
            } else {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Councils()));
            }
          })
</code>```

I have tried creating a variable _selectedIndex for this which I was updating inside the function I have provided for onTap as shown:

```<code>          currentIndex: _selectedIndex,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
            if (index == 0) {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AllEventsScreen()));
              _selectedIndex = 0;
            } else {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Councils()));
              _selectedIndex = 1;
            }
</code>```

But this doesn't seems to work. I couldn't figure out how to do this.

答:
Use the _selectedIndex with a PageView and set the onTap like this :

```<code>          currentIndex: _selectedIndex,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
              setState(()=>_selectedIndex=index);
            }
</code>```

Reading this article would be helpful

Edit: This is a full example

```<code>class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;
  late PageController _pageController;
  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      initialPage: _selectedIndex,
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _selectedIndex,
          onTap: (index) {
            setState(() {
              _selectedIndex = index;
              _pageController.animateToPage(index,
                  duration: Duration(milliseconds: 500), curve: Curves.ease);
            });
          },
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: "Home",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.search),
              label: "Search",
            ),
          ],
        ),
        appBar: AppBar(
          title: Text('Test App'),
        ),
        body: PageView(
          controller: _pageController,
          onPageChanged: (index) {
            setState(() {
              _selectedIndex = index;
            });
          },
          children: [
            Container(
              color: Colors.red,
              child: Center(
                child: Text("Home"),
              ),
            ),
            Container(
              color: Colors.green,
              child: Center(
                child: Text("Search"),
              ),
            ),
          ],
        ));
  }
}
</code>```

Body:
I have a bottom navigation bar widget for my Flutter app. On tapping specific item it is navigating to another screen. However, I don't know how to update current index in this case so that selected tab gets highlighted. Here is my code:

        BottomNavigationBar(
          backgroundColor: const Color(0xffFF7B19),
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(
                Icons.calendar_today_rounded,
                size: lh / 25,
              ),
              label: 'Events',
            ),
            BottomNavigationBarItem(
              icon: Icon(
                Icons.people_alt_outlined,
                size: lh / 25,
              ),
              label: 'Councils',
            ),
          ],
          currentIndex: 0,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
            if (index == 0) {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AllEventsScreen()));
            } else {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Councils()));
            }
          })

I have tried creating a variable _selectedIndex for this which I was updating inside the function I have provided for onTap as shown:

          currentIndex: _selectedIndex,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
            if (index == 0) {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AllEventsScreen()));
              _selectedIndex = 0;
            } else {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Councils()));
              _selectedIndex = 1;
            }

But this doesn't seems to work. I couldn't figure out how to do this.

Body:
Use the _selectedIndex with a PageView and set the onTap like this :

          currentIndex: _selectedIndex,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
              setState(()=>_selectedIndex=index);
            }

Reading this article would be helpful

Edit: This is a full example

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;
  late PageController _pageController;
  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      initialPage: _selectedIndex,
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _selectedIndex,
          onTap: (index) {
            setState(() {
              _selectedIndex = index;
              _pageController.animateToPage(index,
                  duration: Duration(milliseconds: 500), curve: Curves.ease);
            });
          },
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: "Home",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.search),
              label: "Search",
            ),
          ],
        ),
        appBar: AppBar(
          title: Text('Test App'),
        ),
        body: PageView(
          controller: _pageController,
          onPageChanged: (index) {
            setState(() {
              _selectedIndex = index;
            });
          },
          children: [
            Container(
              color: Colors.red,
              child: Center(
                child: Text("Home"),
              ),
            ),
            Container(
              color: Colors.green,
              child: Center(
                child: Text("Search"),
              ),
            ),
          ],
        ));
  }
}


问:
Laravel migration: Multiple primary key defined (SQL: alter table `mediables` add primary key

Error: Illuminate\Database\QueryException SQLSTATE[42000]: Syntax
error or access violation: 1068 Multiple primary key defined (SQL:
alter table mediables add primary key
mediables_media_id_mediable_type_mediable_id_tag_primary(media_id,
mediable_type, mediable_id, tag))

my migration :

```<code>  if (!Schema::hasTable('media')) {
            Schema::create(
                'media',
                function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->string('disk', 32);
                    $table->string('directory');
                    $table->string('filename');
                    $table->string('mime_type');
                    $table->string('aggregate_type');

                    $table->string('extension', 32);
                    $table->integer('size')->nullable(false);
                    $table->timestamps();
                    $table->unique(['disk', 'directory', 'filename', 'extension']);
                }
            );
        }

        if (!Schema::hasTable('mediables')) {
            Schema::create(
                'mediables',
                function (Blueprint $table) {
                    $table->increments('media_id');
                    $table->string('mediable_type');
                    $table->integer('mediable_id')->unsigned();
                    $table->string('tag');
                    $table->integer('order')->unsigned();
                    $table->primary(['media_id', 'mediable_type', 'mediable_id', 'tag']);
                    $table->index(['mediable_id', 'mediable_type']);
                    $table->index('tag');
                    $table->index('order');
                    $table->foreign('media_id')
                        ->references('id')->on('media')
                        ->cascadeOnDelete();
                }
            );
        }
</code>```

答:
You cant use increments for foreign_key. Use unsignedBigIntger instead:

```<code>if (!Schema::hasTable('media')) {
            Schema::create(
                'media',
                function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->string('disk', 32);
                    $table->string('directory');
                    $table->string('filename');
                    $table->string('mime_type');
                    $table->string('aggregate_type');

                    $table->string('extension', 32);
                    $table->integer('size')->nullable(false);
                    $table->timestamps();
                    $table->unique(['disk', 'directory', 'filename', 'extension']);
                }
            );
        }

        if (!Schema::hasTable('mediables')) {
            Schema::create(
                'mediables',
                function (Blueprint $table) {
                    $table->unsignedBigInteger('media_id');
                    $table->string('mediable_type');
                    $table->integer('mediable_id')->unsigned();
                    $table->string('tag');
                    $table->integer('order')->unsigned();
                    $table->primary(['media_id', 'mediable_type', 'mediable_id', 'tag']);
                    $table->index(['mediable_id', 'mediable_type']);
                    $table->index('tag');
                    $table->index('order');
                    $table->foreign('media_id')
                        ->references('id')->on('media')
                        ->cascadeOnDelete();
                }
            );
        }
</code>```

Body:
Error: Illuminate\Database\QueryException SQLSTATE[42000]: Syntax
error or access violation: 1068 Multiple primary key defined (SQL:
alter table mediables add primary key
mediables_media_id_mediable_type_mediable_id_tag_primary(media_id,
mediable_type, mediable_id, tag))

my migration :

  if (!Schema::hasTable('media')) {
            Schema::create(
                'media',
                function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->string('disk', 32);
                    $table->string('directory');
                    $table->string('filename');
                    $table->string('mime_type');
                    $table->string('aggregate_type');

                    $table->string('extension', 32);
                    $table->integer('size')->nullable(false);
                    $table->timestamps();
                    $table->unique(['disk', 'directory', 'filename', 'extension']);
                }
            );
        }

        if (!Schema::hasTable('mediables')) {
            Schema::create(
                'mediables',
                function (Blueprint $table) {
                    $table->increments('media_id');
                    $table->string('mediable_type');
                    $table->integer('mediable_id')->unsigned();
                    $table->string('tag');
                    $table->integer('order')->unsigned();
                    $table->primary(['media_id', 'mediable_type', 'mediable_id', 'tag']);
                    $table->index(['mediable_id', 'mediable_type']);
                    $table->index('tag');
                    $table->index('order');
                    $table->foreign('media_id')
                        ->references('id')->on('media')
                        ->cascadeOnDelete();
                }
            );
        }

Body:
You cant use increments for foreign_key. Use unsignedBigIntger instead:

if (!Schema::hasTable('media')) {
            Schema::create(
                'media',
                function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->string('disk', 32);
                    $table->string('directory');
                    $table->string('filename');
                    $table->string('mime_type');
                    $table->string('aggregate_type');

                    $table->string('extension', 32);
                    $table->integer('size')->nullable(false);
                    $table->timestamps();
                    $table->unique(['disk', 'directory', 'filename', 'extension']);
                }
            );
        }

        if (!Schema::hasTable('mediables')) {
            Schema::create(
                'mediables',
                function (Blueprint $table) {
                    $table->unsignedBigInteger('media_id');
                    $table->string('mediable_type');
                    $table->integer('mediable_id')->unsigned();
                    $table->string('tag');
                    $table->integer('order')->unsigned();
                    $table->primary(['media_id', 'mediable_type', 'mediable_id', 'tag']);
                    $table->index(['mediable_id', 'mediable_type']);
                    $table->index('tag');
                    $table->index('order');
                    $table->foreign('media_id')
                        ->references('id')->on('media')
                        ->cascadeOnDelete();
                }
            );
        }


问:
Multiple inputs In Laravel 8
I am new to Laravel and I am trying to add an input from where it lets the user add multiple languages and saves them as a list.

for example, the user can enter English, Spanish, Arabic and saves each input as a list to the same field
Something similar to the tags field in Stack Overflow when adding tags enter image description here

答:
if you want to send multiple options , you can use select 2 js plugin :
[https://select2.org/getting-started/basic-usage][1]

use  script src in your template , and then :

```<code><script>
    $('.multi-select').select2();
</script>
</code>```

and then , in your html code do something like this :

```<code> <select class='multi-select form-control' multiple=''
 data-placeholder='Enter Tags' aria-hidden='true'  name='tags[]'>
 <option value="1">tag 1</option>
 <option value="2">tag 2</option>
 <option value="3">tag 3</option>
</select>
</code>```

notice that the key is your select element's name should be an array ;

hope that would work .

Title: Multiple inputs In Laravel 8

Body:
if you want to send multiple options , you can use select 2 js plugin :
[https://select2.org/getting-started/basic-usage][1]

use  script src in your template , and then :

<script>
    $('.multi-select').select2();
</script>

and then , in your html code do something like this :

 <select class='multi-select form-control' multiple=''
 data-placeholder='Enter Tags' aria-hidden='true'  name='tags[]'>
 <option value="1">tag 1</option>
 <option value="2">tag 2</option>
 <option value="3">tag 3</option>
</select>

notice that the key is your select element's name should be an array ;

hope that would work .


问:
Map and filter an array at the same time
I have an array of objects that I want to iterate over to produce a new filtered array. But also, I need to filter out some of the objects from the new array depending of a parameter. I'm trying this:

```<code>function renderOptions(options) {
    return options.map(function (option) {
        if (!option.assigned) {
            return (someNewObject);
        }
    });
}
</code>```

Is that a good approach? Is there a better method? I'm open to use any library such as lodash.

答:
Hey I've just worked on this project and wanted to share my solution based on Array.prototype.flatMap() in MDN docs:

const places=[{latitude:40,longitude:1},{latitude:41,longitude:2},{latitude:44,longitude:2},{latitude:NaN,longitude:NaN},{latitude:45,longitude:4},{latitude:48,longitude:3},{latitude:44,longitude:5},{latitude:39,longitude:13},{latitude:40,longitude:8},{latitude:38,longitude:4}];

let items = places?.map((place) => [{
  latitude: (place.latitude),

  longitude: (place.longitude),
}, ]);

console.log("Items: ", items);

//Remove elements with NaN latitude and longitude

let newItems = places?.flatMap((o) =>
  Number(o.longitude, o.latitude) ?
  {
    lng: Number(o.longitude),
    lat: Number(o.latitude)
  } :
  []
);

console.log("Coordinates after NaN values removed: ", newItems);```

Body:
I have an array of objects that I want to iterate over to produce a new filtered array. But also, I need to filter out some of the objects from the new array depending of a parameter. I'm trying this:

function renderOptions(options) {
    return options.map(function (option) {
        if (!option.assigned) {
            return (someNewObject);
        }
    });
}

Is that a good approach? Is there a better method? I'm open to use any library such as lodash.


问:
Hard file on the server or binary for sound and image files in SQL with ASP.Net application
I am building an ASP.Net C# web application that will be using lots of sound files and image files. Considering performance, would it be best to store all files in SQL as image data type and retrieve from the database or store/archive the hard file on the server and store the path in sql? Im curious about the pros and cons - other than the obvious of storage space and manageability.</p>

答: From a performance perspective you should be better off storing the sounds/images as files and just keeping a reference to the location in the database.  This will save you from having to transfer the data from the database to the web server and reconstitute the "file" via a handler whenever it is referenced.  Of course, caching could help this but you'd still pay the penalty on each cache miss.   This solution is also, for my money, somewhat less complicated in terms of the code that needs to be developed though you do have issues with collisions and some extra security setup (potentially) to do if you are enabling upload.</p>

OwnerDisplayName: Jukeman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: tvanfosson


问:
Neural Networks
I want to learn more about AI and neural networks.  I have some basic idea what it is and how it works, but I want to find a good book or tutorial with good explanations.

Anyone know of some good material ( that is not too technically written ) to read on the subject?

C# implementations are also helpful.

答: You may like to try using FANN, it has bindings for C# (I use the C library) and comes with examples to help get you started.</p>

Title: Neural Networks


问:
Using for and if loops in Google Apps Script
Dear programming Community,

at first I need to state, that I am not quite experienced in VBA and programming in general.

What is my problem? I have created a topic list in google sheets in order to collect topics for our monthly meeting among members in a little dance club. That list has a few columns (A: date of creation of topic; B: topic; C: Name of creator; ...). Since it is hard to force all the people to use the same format for the date (column A; some use the year, others not, ...), I decided to lock the entire column A (read-only) and put a formular there in all cells that looks in the adjacent cell in column B and sets the current date, if someone types in a new topic (=if(B2="";"";Now()). Here the problem is, that google sheets (and excel) does then always update the date, when you open the file a few days later again. I tried to overcome this problem by using a circular reference, but that doesn't work either. So now I am thinking of creating a little function (macro) that gets triggered when the file is closed.

Every cell in Column B (Topic) in the range from row 2 to 1000 (row 1 is headline) shall be checked if someone created a new topic (whether or not its empty). If it is not empty, the Date in the adjacent cell (Column A) shall be copied and reinserted just as the value (to get rid of the formular in that cell). Since it also can happen, that someone has created a topic, but a few days later decides to delete it again, in that case the formular for the date shall be inserted again. I thought to solve this with an If-Then-Else loop (If B is not empty, then copy/paste A, else insert formula in A) in a For loop (checking rows 1 - 1000). This is what I have so far, but unfortunately does not work. Could someone help me out here?

Thanks in advance and best regards,
Harry

```<code> function NeuerTest () {
  var ss=SpreadsheetApp.getActive();
  var s=ss.getSheetByName('Themenspeicher');
  var thema = s.getCell(i,2);
  var datum = s.getCell(i,1);
    for (i=2;i<=100;i++) {
     if(thema.isBlank){
          }
      else {
        datum.copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      }}
  }
</code>```

答:
Basically it could be something like this:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Themenspeicher');
  var range = sheet.getRange('A2:B1000');
  var data = range.getValues(); // <---- or: range.getDisplayValues();

  for (let row in data) {
    var formula = '=if(B' + (+row+2) + '="";"";Now())';
    if (data[row][1] == '') data[row][0] = formula;
  }

  range.setValues(data);
}
```

But actual answer depends on what exactly you have, how your formula looks like, etc. It would be better if you show a sample of your sheet (a couple of screenshots would be enough) 'before the script' and 'after the script'.

Body:
Dear programming Community,

at first I need to state, that I am not quite experienced in VBA and programming in general.

What is my problem? I have created a topic list in google sheets in order to collect topics for our monthly meeting among members in a little dance club. That list has a few columns (A: date of creation of topic; B: topic; C: Name of creator; ...). Since it is hard to force all the people to use the same format for the date (column A; some use the year, others not, ...), I decided to lock the entire column A (read-only) and put a formular there in all cells that looks in the adjacent cell in column B and sets the current date, if someone types in a new topic (=if(B2="";"";Now()). Here the problem is, that google sheets (and excel) does then always update the date, when you open the file a few days later again. I tried to overcome this problem by using a circular reference, but that doesn't work either. So now I am thinking of creating a little function (macro) that gets triggered when the file is closed.

Every cell in Column B (Topic) in the range from row 2 to 1000 (row 1 is headline) shall be checked if someone created a new topic (whether or not its empty). If it is not empty, the Date in the adjacent cell (Column A) shall be copied and reinserted just as the value (to get rid of the formular in that cell). Since it also can happen, that someone has created a topic, but a few days later decides to delete it again, in that case the formular for the date shall be inserted again. I thought to solve this with an If-Then-Else loop (If B is not empty, then copy/paste A, else insert formula in A) in a For loop (checking rows 1 - 1000). This is what I have so far, but unfortunately does not work. Could someone help me out here?

Thanks in advance and best regards,
Harry

 function NeuerTest () {
  var ss=SpreadsheetApp.getActive();
  var s=ss.getSheetByName('Themenspeicher');
  var thema = s.getCell(i,2);
  var datum = s.getCell(i,1);
    for (i=2;i<=100;i++) {
     if(thema.isBlank){
          }
      else {
        datum.copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      }}
  }

Body:
Basically it could be something like this:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Themenspeicher');
  var range = sheet.getRange('A2:B1000');
  var data = range.getValues(); // <---- or: range.getDisplayValues();

  for (let row in data) {
    var formula = '=if(B' + (+row+2) + '="";"";Now())';
    if (data[row][1] == '') data[row][0] = formula;
  }

  range.setValues(data);
}

But actual answer depends on what exactly you have, how your formula looks like, etc. It would be better if you show a sample of your sheet (a couple of screenshots would be enough) 'before the script' and 'after the script'.


问:
Problem with clicking OK in alert python selenium
i have problem with clicking "OK" in alert, driver switch to alert not working. I think that extension open new widow with alert.

I tried:

```<code>try:
    alert = driver.switch_to_alert()
    alert.accept()
except:
    pass
</code>```

答:
Try this instead:</p>
```<code>try:
    alert = driver.switch_to.alert
    alert.accept()
except:
    pass
</code>```

Body:
i have problem with clicking "OK" in alert, driver switch to alert not working. I think that extension open new widow with alert.

I tried:

try:
    alert = driver.switch_to_alert()
    alert.accept()
except:
    pass

Body:
Try this instead:

try:
    alert = driver.switch_to.alert
    alert.accept()
except:
    pass


答:
The line $table->increments('media_id'); creates an autoincrementing id column and a primary key. So your subsequent primary key declaration attempts to create another primary key, which is not allowed.

An autoincrementing id column does not have to be the primary key, but it must be an index.

Try this:

    function (Blueprint $table) {
      $table->increments('media_id');
      $table->string('mediable_type');
      $table->integer('mediable_id')->unsigned();
      $table->string('tag');
      $table->integer('order')->unsigned();

      /* create an index for the autoincrement column */
      $table->unique('media_id');
      /* drop the primary key */
      $table->dropPrimary();
      /* add your new primary key */
      $table->primary(['media_id', 'mediable_type', 'mediable_id', 'tag']);

      $table->index(['mediable_id', 'mediable_type']);
      $table->index('tag');
      $table->index('order');
      $table->foreign('media_id')
                  ->references('id')->on('media')
                  ->cascadeOnDelete();
  }
```
<p>I haven't tested this however.</p>
<p>If you can't get Laravel to cooperate with using a different PK than the autoincrement column, you may have to use an ordinary index. You can alter the indexes later with SQL statements if you really need your compound primary key.  Something like this should work.</p>
```ALTER TABLE mediables
     ADD UNIQUE INDEX media_id (media_id),
     DROP PRIMARY KEY,
     ADD PRIMARY KEY (media_id, mediable_type, mediable_id, tag);
```
<p>Do this all in one statement.</p>
<p>Because your new primary key starts with the autoincrementing column, you actually can omit the UNIQUE index, giving</p>
```ALTER TABLE mediables
     DROP PRIMARY KEY,
     ADD PRIMARY KEY (media_id, mediable_type, mediable_id, tag);
```

Title: Laravel migration: Multiple primary key defined (SQL: alter table `mediables` add primary key

Body:
The line $table->increments('media_id'); creates an autoincrementing id column and a primary key. So your subsequent primary key declaration attempts to create another primary key, which is not allowed.

An autoincrementing id column does not have to be the primary key, but it must be an index.

Try this:

    function (Blueprint $table) {
      $table->increments('media_id');
      $table->string('mediable_type');
      $table->integer('mediable_id')->unsigned();
      $table->string('tag');
      $table->integer('order')->unsigned();

      /* create an index for the autoincrement column */
      $table->unique('media_id');
      /* drop the primary key */
      $table->dropPrimary();
      /* add your new primary key */
      $table->primary(['media_id', 'mediable_type', 'mediable_id', 'tag']);

      $table->index(['mediable_id', 'mediable_type']);
      $table->index('tag');
      $table->index('order');
      $table->foreign('media_id')
                  ->references('id')->on('media')
                  ->cascadeOnDelete();
  }

I haven't tested this however.

If you can't get Laravel to cooperate with using a different PK than the autoincrement column, you may have to use an ordinary index. You can alter the indexes later with SQL statements if you really need your compound primary key.  Something like this should work.

ALTER TABLE mediables
     ADD UNIQUE INDEX media_id (media_id),
     DROP PRIMARY KEY,
     ADD PRIMARY KEY (media_id, mediable_type, mediable_id, tag);

Do this all in one statement.

Because your new primary key starts with the autoincrementing column, you actually can omit the UNIQUE index, giving

ALTER TABLE mediables
     DROP PRIMARY KEY,
     ADD PRIMARY KEY (media_id, mediable_type, mediable_id, tag);


问:
error:a hook ('orm') failed to load when lifting sails app using mongo DB
I get this error: a hook ('orm') failed to load when trying to lift a sails app using mongoDB. This my connections.js file:

```<code>module.exports.connections = {
  mongodb: {
    adapter   : 'sails-mongo',
    host      : 'localhost',
    port      : 27017,
    database  : 'mydb1'
  }
};
</code>```

And this is my models.js file:

```<code>module.exports.models = {
  connection: 'mongodb'
};
</code>```

And this is my local.js file:

```<code>module.exports = {
  connections: {
    mongodb: {
      host      : 'localhost',
      port      : 27017,
      database  : 'mydb1'
    }
  }
}
</code>```

Sails v 0.10.1

Any idea why this could be happening?

Thanks

答:
For those if it didn't work in heroku after deploying, try to change the node js, sails, sails-mongo versions and check.

It worked for me after changing the versions to the below:

1.nodejs - 14.15.1

2.sails  - ^1.5.2

3.sails-mongo -  ^2.0.0

Body:
I get this error: a hook ('orm') failed to load when trying to lift a sails app using mongoDB. This my connections.js file:

module.exports.connections = {
  mongodb: {
    adapter   : 'sails-mongo',
    host      : 'localhost',
    port      : 27017,
    database  : 'mydb1'
  }
};

And this is my models.js file:

module.exports.models = {
  connection: 'mongodb'
};

And this is my local.js file:

module.exports = {
  connections: {
    mongodb: {
      host      : 'localhost',
      port      : 27017,
      database  : 'mydb1'
    }
  }
}

Sails v 0.10.1

Any idea why this could be happening?

Thanks


问:
AttributeError: module 'object_detection.protos.faster_rcnn_pb2' has no attribute 'AttentionPosition' - upon resuming training
I am following this tutorial https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10.

System - Windows 10, Anaconda Prompt, Python 3.6, tensorflow 1.15.0

Initial setup and training are successful. Upon pausing the training and resuming I get the error message from the title. Any help would be greatly appreciated.

答:
I realized that every time I reenter the environment from the anaconda prompt I should reset the python path. This solved the problem:

set PYTHONPATH=C:\tensorflow1\models;C:\tensorflow1\models\research;C:\tensorflow1\models\research\slim


问:
Inheritance problem in C#
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

```<code>public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}
</code>```

ISvdPredictor uses ISvdModel:

```<code>public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}
</code>```

Now I want to implement another variation:

```<code>public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}
</code>```

Which uses IBiasSvdModel which derives from ISvdModel:

```<code>public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}
</code>```

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.

答:
The interface should have one method, PredictRating.  I wouldn't have two interfaces that have the same method to implement.  Confusing.

Create an abstract class that implements your interface.  Make PredictRating a virtual method so inheritors can override as they see fit.  You could even do a default implementation on the abstract class.

One interface, One abstract class.  N concrete class that implement PredictRating as they see fit.

```<code> public interface Demo
    {
        int PredictRating(int param1);
    }

    public abstract class AbstractDemo : Demo
    {
        public virtual int PredictRating(int param1)
        {
            return param1 + 1;
        }
    }

    public class ClassDemo1 : AbstractDemo
    {
        //This guy uses AbstractDemo Predict Rating
        public override int PredictRating(int param1)
        {
            return base.PredictRating(param1);
        }
    }

    public class ClassDemo2 : AbstractDemo
    {
        //This guy overrides the predict rating behavior
        public override int PredictRating(int param1)
        {
            return param1 + 2;
        }
    }
</code>```

Title: Inheritance problem in C#

Body:
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}

ISvdPredictor uses ISvdModel:

public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}

Now I want to implement another variation:

public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}

Which uses IBiasSvdModel which derives from ISvdModel:

public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.

Body:
The interface should have one method, PredictRating.  I wouldn't have two interfaces that have the same method to implement.  Confusing.

Create an abstract class that implements your interface.  Make PredictRating a virtual method so inheritors can override as they see fit.  You could even do a default implementation on the abstract class.

One interface, One abstract class.  N concrete class that implement PredictRating as they see fit.

 public interface Demo
    {
        int PredictRating(int param1);
    }

    public abstract class AbstractDemo : Demo
    {
        public virtual int PredictRating(int param1)
        {
            return param1 + 1;
        }
    }

    public class ClassDemo1 : AbstractDemo
    {
        //This guy uses AbstractDemo Predict Rating
        public override int PredictRating(int param1)
        {
            return base.PredictRating(param1);
        }
    }

    public class ClassDemo2 : AbstractDemo
    {
        //This guy overrides the predict rating behavior
        public override int PredictRating(int param1)
        {
            return param1 + 2;
        }
    }


问:
How to group a list of list that matches certain condition
I have a list of list.

```<code>[
  [4, 5, 6],
  [5, 6, 7],
  [8, 9, 10],
  [20, 21, 22],
  [22,23,24]
]
</code>```

if the upper_bound(5) of [5,6,7] is less than or equal to lower_bound(6) of [4,5,6] then grp them together and the final list should look like this.

```<code>[
  [
    [4, 5, 6],
    [5, 6, 7]
  ],
  [8, 9, 10],
  [
    [20, 21, 22],
    [22,23,24]
  ]

]
</code>```

How can i do this?

答:
Assuming the number of resulting lists is less than 32, grouping by Range would work.

input
|> Enum.reduce(%{}, fn list, acc ->
  {min, max} = Enum.min_max(list)

  acc |> Map.keys() |> Enum.reduce_while(nil, fn
    mn..mx, _ when min >= mn and min <= mx and max >= mn and max <= mx ->
      {:halt, Map.update(acc, mn..mx, & [list | &1])}
    mn..mx, _ when min >= mn and min <= mx ->
      {:halt, acc |> Map.delete(mn..mx) |> Map.put(mn..max, [list | Map.get(acc, mn..mx)])}
    mn..mx, _ when max >= mn and max <= mx ->
      {:halt, acc |> Map.delete(mn..mx) |> Map.put(min..mx, [list | Map.get(acc, mn..mx)])}
    _, _ -> {:cont, nil}
  end) || Map.put(acc, min..max, [list])
end)
|> Map.values()
|> Enum.map(&Enum.reverse/1)
```

If the expected number of lists is greater than 32 and the sorting must be preserved, the solution would be way more cumbersome.

Body:
I have a list of list.

[
  [4, 5, 6],
  [5, 6, 7],
  [8, 9, 10],
  [20, 21, 22],
  [22,23,24]
]

if the upper_bound(5) of [5,6,7] is less than or equal to lower_bound(6) of [4,5,6] then grp them together and the final list should look like this.

[
  [
    [4, 5, 6],
    [5, 6, 7]
  ],
  [8, 9, 10],
  [
    [20, 21, 22],
    [22,23,24]
  ]

]

How can i do this?

Body:
Assuming the number of resulting lists is less than 32, grouping by Range would work.

input
|> Enum.reduce(%{}, fn list, acc ->
  {min, max} = Enum.min_max(list)

  acc |> Map.keys() |> Enum.reduce_while(nil, fn
    mn..mx, _ when min >= mn and min <= mx and max >= mn and max <= mx ->
      {:halt, Map.update(acc, mn..mx, & [list | &1])}
    mn..mx, _ when min >= mn and min <= mx ->
      {:halt, acc |> Map.delete(mn..mx) |> Map.put(mn..max, [list | Map.get(acc, mn..mx)])}
    mn..mx, _ when max >= mn and max <= mx ->
      {:halt, acc |> Map.delete(mn..mx) |> Map.put(min..mx, [list | Map.get(acc, mn..mx)])}
    _, _ -> {:cont, nil}
  end) || Map.put(acc, min..max, [list])
end)
|> Map.values()
|> Enum.map(&Enum.reverse/1)

If the expected number of lists is greater than 32 and the sorting must be preserved, the solution would be way more cumbersome.


问:
Is there an OpenSSL for windows?
I'm trying to generate OpenSSL certificates on Windows OS. But I find most of the commands related to OpenSSL are for *nix OS.

Is there an OpenSSL for Windows OS? If yes, from where can I get it? Is this official OpenSSL build for Windows?

答:
I am using this version https://slproweb.com/products/Win32OpenSSL.html and install it with

Essentials

```<code>winget install -e ShiningLight.OpenSSL.Light
</code>```

Full

```<code>winget install -e ShiningLight.OpenSSL
</code>```

Title: Is there an OpenSSL for windows?

Body:
I am using this version https://slproweb.com/products/Win32OpenSSL.html and install it with

Essentials

winget install -e ShiningLight.OpenSSL.Light

Full

winget install -e ShiningLight.OpenSSL