问:
Why is my paragraph popup coming outside my div with the "mousedown" event?
I need to show my paragraph inside my
 when click on the
. This is my code:

const area = document.getElementById("area");
const popup = document.getElementById("popup");

function showPopup(event) {
    let x = event.clientX;
    let y = event.clientY;
    popup.style.left = `${x}px`;
    popup.style.top = `${y}px`;
    popup.style.visibility = "visible";
}

area.addEventListener("mousedown", showPopup);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.area {
    border: 1px solid;
    position: absolute;
    height: 200px;
    width: 200px;
}

.popup {
    visibility: hidden;
    position: absolute;
    display: inline-block;
}</code>```

popup

```

Note that this is inside another main body
 (also with position: absolute).

答:
I tested your code and observed you are changing style.top property based on your ClientX value which is causing popup element to appear over random position. Use following updated code and it's should be good.

```<code>function showPopup(event) {
console.log(event.clientX, event.clientY)

    let x = event.clientX;
    let y = event.clientY;
    popup.style.left = `${x - 8}px`;
    popup.style.top = `${y - 8}px`;
    popup.style.visibility = "visible";
}
</code>```

and few CSS changes as -

```<code>.area {
    border: 1px solid;
    position: relative;
    height: 200px;
    width: 200px;
}

.popup {
    visibility: hidden;
    position: absolute;
    display: inline-block;
    margin: 0;
}
</code>```

For more close positioning of popup element.

Body:
I need to show my paragraph inside my
 when click on the
. This is my code:

const area = document.getElementById("area");
const popup = document.getElementById("popup");

function showPopup(event) {
    let x = event.clientX;
    let y = event.clientY;
    popup.style.left = `${x}px`;
    popup.style.top = `${y}px`;
    popup.style.visibility = "visible";
}

area.addEventListener("mousedown", showPopup);

.area {
    border: 1px solid;
    position: absolute;
    height: 200px;
    width: 200px;
}

.popup {
    visibility: hidden;
    position: absolute;
    display: inline-block;
}

popup

Note that this is inside another main body
 (also with position: absolute).

Body:
I tested your code and observed you are changing style.top property based on your ClientX value which is causing popup element to appear over random position. Use following updated code and it's should be good.

function showPopup(event) {
console.log(event.clientX, event.clientY)

    let x = event.clientX;
    let y = event.clientY;
    popup.style.left = `${x - 8}px`;
    popup.style.top = `${y - 8}px`;
    popup.style.visibility = "visible";
}

and few CSS changes as -

.area {
    border: 1px solid;
    position: relative;
    height: 200px;
    width: 200px;
}

.popup {
    visibility: hidden;
    position: absolute;
    display: inline-block;
    margin: 0;
}

For more close positioning of popup element.


来源: stackexchange

问:
get XY of object in wpf for this situation?
I have a Canvas with two or more objects.
Now, I put these objects in a new Canvas placed in the previous Canvas. Then, I rotate it.

Now, I want to know how to get the positions of the objects in the new Canvas, as though there were no new canvas.

答:
You can use the following extension method to get the location of one UIElement with respect to another:

```<code>  public static class ExtensionMethods
  {
    public static Point GetRelativePosition(this UIElement element, UIElement other)
    {
      return element.TransformToVisual(other)
                    .Transform(new Point(0, 0));
    }
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use the following extension method to get the location of one UIElement with respect to another:

  public static class ExtensionMethods
  {
    public static Point GetRelativePosition(this UIElement element, UIElement other)
    {
      return element.TransformToVisual(other)
                    .Transform(new Point(0, 0));
    }
  }


问:
Remove the (sub)section number from figures in LaTeX
I'm using overleaf for my thesis and I would like some help.

(document class=report)

I am using chapters, sections, and subsections. My tables are named after the chapter and increment with every table (e.g. 5.1 and 5.2 for two tables in Chapter 5). My figures are named after the chapter, including section number and subsection (e.g. a figure in Chapter 5, section 3 is called 5.3.1, even though it is the first figure in Chapter 5). I want the section and subsection number removed from my figure names and have the same counting as for the tables. Can you please help? Thanks!

答:
I already found the answer (by trial-and-error):

simply add the following code to the main.tex:

```<code>\counterwithout{figure}{section}
\counterwithin{figure}{chapter}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I already found the answer (by trial-and-error):

simply add the following code to the main.tex:

\counterwithout{figure}{section}
\counterwithin{figure}{chapter}


问:
Flutter: Method was called on null Eventhough declared
I have an error in the following code in a flutter. I have declared all the functions and there is no compile-time error. It shows an error in run time.
Error is in the following way.

```<code>NoSuchMethodError: The method 'getCurrentUser' was called on null.
Reciever: null
Tried calling: getCurrentUser()
see also: https://flutter.dev/docs/testing/errors
</code>```

This code is placed in MappingPage.dart file which will called by the main.dart file.

```<code>import 'package:flutter/material.dart';
import 'loginPage.dart';
import 'homePage.dart';
import 'authentication.dart';

class MappingPage extends StatefulWidget
{
  final AuthImplementation auth;

  MappingPage({
    this.auth
  });

  @override
  _MappingPageState createState() => new _MappingPageState();
}
enum AuthStatus
{
  notSignedIn,
  signedIn,
}

class _MappingPageState extends State<MappingPage>
{
  AuthStatus authStatus = AuthStatus.notSignedIn;

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

    widget.auth.getCurrentUser().then((firebaseUserId)
    {
      setState(() {
        authStatus = firebaseUserId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
        print("Initial state");
      });
    });
  }

  void _signedIn()
  {
    setState(() {
     authStatus = AuthStatus.signedIn;
    });
  }

  void _signedOut()
  {
    setState(() {
     authStatus = AuthStatus.notSignedIn;
    });
  }

  @override
  Widget build(BuildContext context)
  {
    switch(authStatus)
    {
      case AuthStatus.notSignedIn:
      return loginPage
      (
        auth: widget.auth,
        onSignedIn: _signedIn,
      );
      case AuthStatus.signedIn:
      return homePage
      (
        auth: widget.auth,
        onSignedOut: _signedOut,
      );
    }
    return null;
  }
}
</code>```

This code is authentication.dart file

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

abstract class AuthImplementation
{
  Future<String> SignIn(String email, String password);
  Future<String> getCurrentUser();
  Future<void> signOut();
}

class Auth implements AuthImplementation
{
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future<String> SignIn(String email, String password) async
  {
    try {

      GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
      GoogleSignInAuthentication googleAuth =
          await googleSignInAccount.authentication;

      final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      FirebaseUser user = (await _firebaseAuth.signInWithCredential(credential)).user;
      // updateUserData(user);
      print("user name: ${user.displayName}");

      // loading.add(false);
      return user.uid;
    } catch (error) {
      return error;
    }
  }
  Future<String> getCurrentUser() async
  {
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.uid;
  }

  Future<void> signOut() async
  {
    _firebaseAuth.signOut();
  }
}
</code>```

I don't know what is error in it. Please help it out!

答: widget.auth is null, you need to set it

Body:
I have an error in the following code in a flutter. I have declared all the functions and there is no compile-time error. It shows an error in run time.
Error is in the following way.

NoSuchMethodError: The method 'getCurrentUser' was called on null.
Reciever: null
Tried calling: getCurrentUser()
see also: https://flutter.dev/docs/testing/errors

This code is placed in MappingPage.dart file which will called by the main.dart file.

import 'package:flutter/material.dart';
import 'loginPage.dart';
import 'homePage.dart';
import 'authentication.dart';

class MappingPage extends StatefulWidget
{
  final AuthImplementation auth;

  MappingPage({
    this.auth
  });

  @override
  _MappingPageState createState() => new _MappingPageState();
}
enum AuthStatus
{
  notSignedIn,
  signedIn,
}

class _MappingPageState extends State<MappingPage>
{
  AuthStatus authStatus = AuthStatus.notSignedIn;

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

    widget.auth.getCurrentUser().then((firebaseUserId)
    {
      setState(() {
        authStatus = firebaseUserId == null ? AuthStatus.notSignedIn : AuthStatus.signedIn;
        print("Initial state");
      });
    });
  }

  void _signedIn()
  {
    setState(() {
     authStatus = AuthStatus.signedIn;
    });
  }

  void _signedOut()
  {
    setState(() {
     authStatus = AuthStatus.notSignedIn;
    });
  }

  @override
  Widget build(BuildContext context)
  {
    switch(authStatus)
    {
      case AuthStatus.notSignedIn:
      return loginPage
      (
        auth: widget.auth,
        onSignedIn: _signedIn,
      );
      case AuthStatus.signedIn:
      return homePage
      (
        auth: widget.auth,
        onSignedOut: _signedOut,
      );
    }
    return null;
  }
}

This code is authentication.dart file

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

abstract class AuthImplementation
{
  Future<String> SignIn(String email, String password);
  Future<String> getCurrentUser();
  Future<void> signOut();
}

class Auth implements AuthImplementation
{
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future<String> SignIn(String email, String password) async
  {
    try {

      GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
      GoogleSignInAuthentication googleAuth =
          await googleSignInAccount.authentication;

      final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      FirebaseUser user = (await _firebaseAuth.signInWithCredential(credential)).user;
      // updateUserData(user);
      print("user name: ${user.displayName}");

      // loading.add(false);
      return user.uid;
    } catch (error) {
      return error;
    }
  }
  Future<String> getCurrentUser() async
  {
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.uid;
  }

  Future<void> signOut() async
  {
    _firebaseAuth.signOut();
  }
}

I don't know what is error in it. Please help it out!

Body: widget.auth is null, you need to set it


问:
Selecting two highest values from a list, whilst keeping a record of their index positions?
I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.

For example:

```<code>a = [1,2,7,9,3,4]
</code>```

Desired output:

```<code>maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2
</code>```

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.

答:
The solution using sorted is cleanest, but for long lists this might be faster (linear complexity):</p>

```<code>a = [1,2,7,9,3,4]
index_max, maxVal = max(enumerate(a), key=lambda x:x[1])
index_secondMax, secondMax =  max([t for t in enumerate(a) if t[0] != index_max],  key=lambda x:x[1])
</code>```

Body:
I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.

For example:

a = [1,2,7,9,3,4]

Desired output:

maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.

Body:
The solution using sorted is cleanest, but for long lists this might be faster (linear complexity):

a = [1,2,7,9,3,4]
index_max, maxVal = max(enumerate(a), key=lambda x:x[1])
index_secondMax, secondMax =  max([t for t in enumerate(a) if t[0] != index_max],  key=lambda x:x[1])


问:
Can't Apache2 start erorr: Can't locate SOAP/Transport/HTTP.pm
I have a problem with apache2 start.

When I try apache start i have the message:

```<code>root@ocsi:/var/log/apache2# **systemctl start apache2.service**
Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.
</code>```

in systemctl status apache2.service

```<code>root@ocsi:/var/log/apache2# systemctl status apache2.service
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Mon 2020-06-01 07:53:07 CEST; 19s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 3142 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)

Jun 01 07:53:07 ocsi systemd[1]: Starting The Apache HTTP Server...
Jun 01 07:53:07 ocsi apachectl[3142]: Action 'start' failed.
Jun 01 07:53:07 ocsi apachectl[3142]: The Apache error log may have more information.
Jun 01 07:53:07 ocsi systemd[1]: apache2.service: Control process exited, code=exited, status=1/FAILURE
Jun 01 07:53:07 ocsi systemd[1]: apache2.service: Failed with result 'exit-code'.
Jun 01 07:53:07 ocsi systemd[1]: Failed to start The Apache HTTP Server.
</code>```

in journalctl -xe

```<code>root@ocsi:/var/log/apache2# journalctl -xe
Jun 01 07:54:31 ocsi multipathd[700]: sda: add missing path
Jun 01 07:54:31 ocsi multipathd[700]: sda: failed to get udev uid: Invalid argument
Jun 01 07:54:31 ocsi multipathd[700]: sda: failed to get sysfs uid: Invalid argument
Jun 01 07:54:31 ocsi multipathd[700]: sda: failed to get sgio uid: No such file or directory
</code>```

and in apache2 log is:

root@ocsi:/var/log/apache2# vi error.log

```<code>[Mon Jun 01 07:53:07.305344 2020] [perl:error] [pid 3149] Can't locate SOAP/Transport/HTTP.pm in @INC (you may need to install the SOAP::Transport::HTTP module) (@INC contains: /etc/perl /usr/local/lib/x86_64-linux-gnu/perl/5.30.0 /usr/local/share/perl/5.30.0 /usr/lib/x86_64-linux-gnu/perl5/5.30 /usr/share/perl5 /usr/lib/x86_64-linux-gnu/perl/5.30 /usr/share/perl/5.30 /usr/local/lib/site_perl /etc/apache2) at /usr/local/share/perl/5.30.0/Apache/Ocsinventory/Plugins/Apache.pm line 25.\nBEGIN failed--compilation aborted at /usr/local/share/perl/5.30.0/Apache/Ocsinventory/Plugins/Apache.pm line 25.\nCompilation failed in require at (eval 16) line 1.\n
[Mon Jun 01 07:53:07.305621 2020] [perl:error] [pid 3149] Can't load Perl module Apache::Ocsinventory::Plugins::Apache for server localhost:0, exiting...
</code>```

My system:

PHP Version : 7.4.3

Server version: Apache/2.4.41 (Ubuntu)

Description:    Ubuntu 20.04 LTS

Ubuntu Linux 5.4.0-33-generic x86_64

How can I fix this error?

答:
Looks like you need to install the SOAP::Lite module. That can be done by running:

```<code>$ sudo apt-get install libsoap-lite-perl
</code>```

For more details, read on.

The error message is telling you that the Perl compiler can't find the module SOAP::Transport::HTTP (which is presumably used in some code used in your Apache start-up).

This module has never been part of a standard Perl distribution (you can test that by running corelist SOAP::Transport::HTTP). It, therefore, needs to be installed separately.

Perl modules are usually installed from CPAN. If you search for the module there, you'll see it's part of the SOAP-Lite distribution. Now you could install it directly from there using cpan but, given in this case, the easier approach is probably to install the pre-built package for your operating system. And that's done by running the command above.

Body:
I have a problem with apache2 start.

When I try apache start i have the message:

root@ocsi:/var/log/apache2# **systemctl start apache2.service**
Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.

in systemctl status apache2.service

root@ocsi:/var/log/apache2# systemctl status apache2.service
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Mon 2020-06-01 07:53:07 CEST; 19s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 3142 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)

Jun 01 07:53:07 ocsi systemd[1]: Starting The Apache HTTP Server...
Jun 01 07:53:07 ocsi apachectl[3142]: Action 'start' failed.
Jun 01 07:53:07 ocsi apachectl[3142]: The Apache error log may have more information.
Jun 01 07:53:07 ocsi systemd[1]: apache2.service: Control process exited, code=exited, status=1/FAILURE
Jun 01 07:53:07 ocsi systemd[1]: apache2.service: Failed with result 'exit-code'.
Jun 01 07:53:07 ocsi systemd[1]: Failed to start The Apache HTTP Server.

in journalctl -xe

root@ocsi:/var/log/apache2# journalctl -xe
Jun 01 07:54:31 ocsi multipathd[700]: sda: add missing path
Jun 01 07:54:31 ocsi multipathd[700]: sda: failed to get udev uid: Invalid argument
Jun 01 07:54:31 ocsi multipathd[700]: sda: failed to get sysfs uid: Invalid argument
Jun 01 07:54:31 ocsi multipathd[700]: sda: failed to get sgio uid: No such file or directory

and in apache2 log is:

root@ocsi:/var/log/apache2# vi error.log

[Mon Jun 01 07:53:07.305344 2020] [perl:error] [pid 3149] Can't locate SOAP/Transport/HTTP.pm in @INC (you may need to install the SOAP::Transport::HTTP module) (@INC contains: /etc/perl /usr/local/lib/x86_64-linux-gnu/perl/5.30.0 /usr/local/share/perl/5.30.0 /usr/lib/x86_64-linux-gnu/perl5/5.30 /usr/share/perl5 /usr/lib/x86_64-linux-gnu/perl/5.30 /usr/share/perl/5.30 /usr/local/lib/site_perl /etc/apache2) at /usr/local/share/perl/5.30.0/Apache/Ocsinventory/Plugins/Apache.pm line 25.\nBEGIN failed--compilation aborted at /usr/local/share/perl/5.30.0/Apache/Ocsinventory/Plugins/Apache.pm line 25.\nCompilation failed in require at (eval 16) line 1.\n
[Mon Jun 01 07:53:07.305621 2020] [perl:error] [pid 3149] Can't load Perl module Apache::Ocsinventory::Plugins::Apache for server localhost:0, exiting...

My system:

PHP Version : 7.4.3

Server version: Apache/2.4.41 (Ubuntu)

Description:    Ubuntu 20.04 LTS

Ubuntu Linux 5.4.0-33-generic x86_64

How can I fix this error?

Body:
Looks like you need to install the SOAP::Lite module. That can be done by running:

$ sudo apt-get install libsoap-lite-perl

For more details, read on.

The error message is telling you that the Perl compiler can't find the module SOAP::Transport::HTTP (which is presumably used in some code used in your Apache start-up).

This module has never been part of a standard Perl distribution (you can test that by running corelist SOAP::Transport::HTTP). It, therefore, needs to be installed separately.

Perl modules are usually installed from CPAN. If you search for the module there, you'll see it's part of the SOAP-Lite distribution. Now you could install it directly from there using cpan but, given in this case, the easier approach is probably to install the pre-built package for your operating system. And that's done by running the command above.


问:
React - passing props up components tree through functional components
I want to pass a simple string, number or boolean up more than one level in my component tree. From what I read I need to do this with callback functions but I can't seem to get the logic right.

Here is a sample of where I pass a prop down from Parent App to grandchild Breadcrumb. I would like this prop to actually come from the last child in the tree, the "ResultsPage" component.

I realise there are better ways of doing sth like this (redux, context, different structure, etc), the point here for me is learning and to understand how to use callback functions and how to pass a prop up several more than 1 level.

Newbie friendly please - thanks for any input :)

```<code>class App extends React.Component {
  render() {
    return (
      <>
        <h1>Top level app</h1>

        {/* I import the header and pass down prop */}
        <Header currentLocation="Results Page" />

        {/* I import the main app content */}
        <ResultsPage />
      </>
    );
  }
}

function Header(props) {
  return (
    <>
      <h2>
        This is the header element. It will have some nav items and the
        breadcrumb I import
      </h2>

      {/* I import the breadcrumb accept the props from parent and pass the props down to child */}
      <Crumbs currentLocation={props.currentLocation} />
    </>
  );
}

function Crumbs(props) {
  return (
    <>
      {/* I display the props I passed down through the tree */}
      <h3>
        <small>This is the breadcrumb, you are on</small>{" "}
        {props.currentLocation}
      </h3>
    </>
  );
}

function ResultsPage() {
  return (
    <>
      <p>
        This is the actual results content. I would like this component to tell
        the header component that I have loaded so it can update the breadcrumb
        to let it know which page is currently loaded in the app.
      </p>
    </>
  );
}

export default App;
</code>```

To complete this issue I lewave the following solutions:

Codesandbox: Solution to the initial question

Codesandbox: Additional solution for the same problem using only functional components

Hope it helps the next guy :)

答:
Best way is to do this as I think keep the state inside a redux store. You can create a listener using subscribe() method in the redux to listen any dispatches from the child components from the parent component.

Also there is some easy method, You can use localstorage.  You can store value from the child component and listen it by the parent component using window.addEventListener('storage', function(e) {  } callback method. I hope you can understand what I tried to say.

Body:
I want to pass a simple string, number or boolean up more than one level in my component tree. From what I read I need to do this with callback functions but I can't seem to get the logic right.

Here is a sample of where I pass a prop down from Parent App to grandchild Breadcrumb. I would like this prop to actually come from the last child in the tree, the "ResultsPage" component.

I realise there are better ways of doing sth like this (redux, context, different structure, etc), the point here for me is learning and to understand how to use callback functions and how to pass a prop up several more than 1 level.

Newbie friendly please - thanks for any input :)

class App extends React.Component {
  render() {
    return (
      <>

Top level app

        {/* I import the header and pass down prop */}

        {/* I import the main app content */}
        <ResultsPage />
      </>
    );
  }
}

function Header(props) {
  return (
    <>

        This is the header element. It will have some nav items and the
        breadcrumb I import

      {/* I import the breadcrumb accept the props from parent and pass the props down to child */}
      <Crumbs currentLocation={props.currentLocation} />
    </>
  );
}

function Crumbs(props) {
  return (
    <>
      {/* I display the props I passed down through the tree */}

        This is the breadcrumb, you are on{" "}
        {props.currentLocation}

    </>
  );
}

function ResultsPage() {
  return (
    <>

        This is the actual results content. I would like this component to tell
        the header component that I have loaded so it can update the breadcrumb
        to let it know which page is currently loaded in the app.

    </>
  );
}

export default App;

To complete this issue I lewave the following solutions:

Codesandbox: Solution to the initial question

Codesandbox: Additional solution for the same problem using only functional components

Hope it helps the next guy :)


问:
The view 'Edit' or its master was not found or no view engine supports the searched locations
I want to edit blogs. I have Edit view in View folder in BlogAdmin folder.

```<code> <a  href="/BlogAdmin/Edit/@item.id" class=" btn btn-sm btn-primary float-right"> Edit </a>
</code>```

Controller:

```<code>  public ActionResult Edit(int? id)
         {
        if (id == null)
        {
            return HttpNotFound();
        }
        List<Blog> EditBg = db.Blogs.Where(i => i.id==id).ToList();
        if (EditBg== null)
        {
            return HttpNotFound();
        }
        var vm = new VmBlog
        {
            blogcatg = db.BlogCategories.ToList(),
            Blog = db.Blogs.Where(i => i.id == id).ToList(),
            Content=db.Blogs.FirstOrDefault(i=>i.id==id).posttext

        };

        return View(vm);

    }
</code>```

Get method is working. There is no error here:

Everything seems correctly. But I am getting this error:

The view 'Edit' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/BlogAdmin/Edit.aspx

~/Views/BlogAdmin/Edit.ascx

~/Views/Shared/Edit.aspx

~/Views/Shared/Edit.ascx

~/Views/BlogAdmin/Edit.cshtml

~/Views/BlogAdmin/Edit.vbhtml

~/Views/Shared/Edit.cshtml

~/Views/Shared/Edit.vbhtml

Why does error happen?

答:
@Aytac,

In the MVC pattern the default routing puts controllers into a folder at "/controllers".  Views are stored in a folder at "/Views/{ControllerBaseName}/{ActionName}".

The default folder structure (routing) should look like the following (tagged as c# so assuming c# extensions):

/Controllers/BlogAdminController.cs

/Views/BlogAdmin/Edit.cshtml

Body:
I want to edit blogs. I have Edit view in View folder in BlogAdmin folder.

  Edit

Controller:

  public ActionResult Edit(int? id)
         {
        if (id == null)
        {
            return HttpNotFound();
        }
        List<Blog> EditBg = db.Blogs.Where(i => i.id==id).ToList();
        if (EditBg== null)
        {
            return HttpNotFound();
        }
        var vm = new VmBlog
        {
            blogcatg = db.BlogCategories.ToList(),
            Blog = db.Blogs.Where(i => i.id == id).ToList(),
            Content=db.Blogs.FirstOrDefault(i=>i.id==id).posttext

        };

        return View(vm);

    }

Get method is working. There is no error here:

Everything seems correctly. But I am getting this error:

The view 'Edit' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/BlogAdmin/Edit.aspx

~/Views/BlogAdmin/Edit.ascx

~/Views/Shared/Edit.aspx

~/Views/Shared/Edit.ascx

~/Views/BlogAdmin/Edit.cshtml

~/Views/BlogAdmin/Edit.vbhtml

~/Views/Shared/Edit.cshtml

~/Views/Shared/Edit.vbhtml

Why does error happen?


问:
Function not call when button click
i have create a UIBUtton

```<code>editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
        [editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
        editButton.hidden = YES;
        [editButton setTag:tag];
        [backView addSubview:editButton];
</code>```

But control not jump to its definition where i check if button give its tag value on click or not.

-

```<code>(void)deleteObjectViewImage
{

    NSInteger index = editButton.tag;
    editButton.hidden = YES;
}
</code>```

Can anyone tell me why it not work please.

答:
```<code>[editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
</code>```

expects the function deleteObjectViewImage: to have one argument. But the function definition doesnt has any.

UPDATE:

```<code>-(void)deleteObjectViewImage: (id) sender
    {
    UIButton *clickedButton = (UIButton *) sender;
        NSInteger index = clickedButton.tag;
        editButton.hidden = YES;
    }
</code>```

and use

```<code>[editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
</code>```

Title: Function not call when button click

Body:
i have create a UIBUtton

editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
        [editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
        editButton.hidden = YES;
        [editButton setTag:tag];
        [backView addSubview:editButton];

But control not jump to its definition where i check if button give its tag value on click or not.

-

(void)deleteObjectViewImage
{

    NSInteger index = editButton.tag;
    editButton.hidden = YES;
}

Can anyone tell me why it not work please.

Body:
[editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];

expects the function deleteObjectViewImage: to have one argument. But the function definition doesnt has any.

UPDATE:

-(void)deleteObjectViewImage: (id) sender
    {
    UIButton *clickedButton = (UIButton *) sender;
        NSInteger index = clickedButton.tag;
        editButton.hidden = YES;
    }

and use

[editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];


问:
Corda nodes role or nodes categorization
I have a requirement of identifying a pool/set of nodes in the Flow on basis of their assigned role, So that the transactions can be sent to all nodes of a particular role/type.

For example:

A node (Type 1)

B node (Type 1)

C node (Type 2)

D node (Type 2)

Than, if I pass Type 2 in the flow, than I should be able to get the List of Parties/Node with that Type (i.e. C,D).

Is it possible? If yes, how? and where can I define the nodes type, maybe as some suffix in node name?

One possible hacky way I have in mind is, set prefix in every node and
  then get List of nodes, extract name and identify according to it. But
  it will be required in every flow initiation.

Thanks for any help.

答:
There is no better solution to serve your purpose with the fewer overheads.

If you are expecting the no. of nodes and roles to be changed dynamically, a proper way would be to retrieves the roles (whether using an oracle or not) and cache it.
Then write a separate flow to trigger updates it.

If not, you can just hardcode it in the config file.


问:
Unique values of Dictionary comprehension, return dictionary instread of string
this is my data:

```<code>data = [{'id': 1, 'name': 'The Musical Hop', 'city': 'San Francisco', 'state': 'CA'},
{'id': 2, 'name': 'The Dueling Pianos Bar', 'city': 'New York', 'state': 'NY'},
{'id': 3, 'name': 'Park Square Live Music & Coffee', 'city': 'San Francisco', 'state': 'CA'}]
</code>```

I want to find out the unique values (thats why I use a set) of "city" and return them like this:

```<code>cities = set([x.get("city") for x in data])
cities ´

{'New York', 'San Francisco'}
</code>```

However, I also want to return the corresponding state, like this:

```<code>[{"city": "New York", "state": "NY"}, {"city":  "San Francisco", "state": "CA"}]
</code>```

Is there a way to do this?

答:
You can use dict-comprehension for the task:

```<code>out = list({x['city']:{'city':x['city'], 'state':x['state']} for x in data}.values())

print(out)
</code>```

Prints:

```<code>[{'city': 'San Francisco', 'state': 'CA'}, {'city': 'New York', 'state': 'NY'}]
</code>```

Body:
this is my data:

data = [{'id': 1, 'name': 'The Musical Hop', 'city': 'San Francisco', 'state': 'CA'},
{'id': 2, 'name': 'The Dueling Pianos Bar', 'city': 'New York', 'state': 'NY'},
{'id': 3, 'name': 'Park Square Live Music & Coffee', 'city': 'San Francisco', 'state': 'CA'}]

I want to find out the unique values (thats why I use a set) of "city" and return them like this:

cities = set([x.get("city") for x in data])
cities ´

{'New York', 'San Francisco'}

However, I also want to return the corresponding state, like this:

[{"city": "New York", "state": "NY"}, {"city":  "San Francisco", "state": "CA"}]

Is there a way to do this?

Body:
You can use dict-comprehension for the task:

out = list({x['city']:{'city':x['city'], 'state':x['state']} for x in data}.values())

print(out)

Prints:

[{'city': 'San Francisco', 'state': 'CA'}, {'city': 'New York', 'state': 'NY'}]


问:
Include files from function
I am trying to include a file from a function. This function doesn't return anything, it is just initializing many things.

This function also apply the language so I need to include the language file. But it seems like the scope isn't the same.

How can I include a file from a function as global ?

Ex :

```<code>function StartUp() {
    include('test.php'); // I want to make the vars in test.php available in a Global Scope.
}
</code>```

答:
You cannot include external files in the function and make all the vars global in it because if you do so they remain the in scope of that function only, better way you just include them by a simple way without any function.

Or you can just add a global keyword in front of your all variables to make them global all over.

Title: Include files from function

Body:
I am trying to include a file from a function. This function doesn't return anything, it is just initializing many things.

This function also apply the language so I need to include the language file. But it seems like the scope isn't the same.

How can I include a file from a function as global ?

Ex :

function StartUp() {
    include('test.php'); // I want to make the vars in test.php available in a Global Scope.
}


问:
How To Click A Link Within An Email
Im testing my website with Selenium. After a user registers, they must click a link emailed to them in order to log in. I am able to get the email, but do not know how to click the link.

This selects the email

```<code>confirmation_email = mail.outbox[0]
</code>```

Now I just need to find a link within it and press it.
The email link will be something like:

```<code>http://localhost:52348/accounts/confirm-email/MQ:1jfhcf:4ZqeOcmY4fdfh1lhA0feBl7eeUBk3440/
</code>```

Thank you.

答:
You can use the driver.get() method for navigating with the provided email link and you will get the result you needed.</p>

```<code>driver.get("http://localhost:52348/accounts/confirm-email/MQ:1jfhcf:4ZqeOcmY4fdfh1lhA0feBl7eeUBk3440/");
</code>```

Title: How To Click A Link Within An Email

Body:
Im testing my website with Selenium. After a user registers, they must click a link emailed to them in order to log in. I am able to get the email, but do not know how to click the link.

This selects the email

confirmation_email = mail.outbox[0]

Now I just need to find a link within it and press it.
The email link will be something like:

http://localhost:52348/accounts/confirm-email/MQ:1jfhcf:4ZqeOcmY4fdfh1lhA0feBl7eeUBk3440/

Thank you.

Body:
You can use the driver.get() method for navigating with the provided email link and you will get the result you needed.

driver.get("http://localhost:52348/accounts/confirm-email/MQ:1jfhcf:4ZqeOcmY4fdfh1lhA0feBl7eeUBk3440/");


问:
Using both Opengl CORE functions along with Comptability profile - GLFW
I have this visual studio project where i can use both core and compat profile at the same time ,
by using : glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_ANY_PROFILE) ; but weirdly it doesn't work on another projects.

答:
There are only two different types of profiles (at least in OpenGL 3.2+): A core profile supports only core functionality. A compatibility profile supports core functionality + all deprecated functionality. There is no profile that doesn't allow for core functionality.

GLFW_OPENGL_ANY_PROFILE means that you will get a profile type at random. This will either be a core or a compatibility profile (but it might be a different profile on different machines/drivers/applications). There is no way to predict which profile it will be.

From what you state, you simply want to use a compatibility profile.


问:
Kill Service After BootUp Start android
Hello

How can i kill my service when my Mobile Boot ups.

For example i want to achieve that my service starts on Boot up and after doing all its Task it should be Exit/Killed/Removed.

PLease guide.!

答:
```<code>stopSelf();
stopForground(true);
</code>```

both works for me!

Thanks to capDroid!

Title: Kill Service After BootUp Start android

Body:
stopSelf();
stopForground(true);

both works for me!

Thanks to capDroid!


问:
How to "naturally sort" files that end with a number (png0 to png188) via Python's natsort?
I have a folder that has plots in PNGs like earthquake0, earthquake1, earthquake2, and so on. These photos are converted to GIF via moviepy but Python's sorting results to 1, 10, 100 instead of 1, 2, 3.

Here's the moviepy code

```<code>import os
os.chdir(r'path')
from moviepy.editor import *

image_list = 'exports' # folder
my_clip = ImageSequenceClip(image_list, fps=0.75)
my_clip.write_gif('eqph_gif.gif')
</code>```

I have tried adding this but Python says it can't find the folder

```<code>image_list = natsort.natsorted(image_list)
</code>```

答:
Solved it!

```<code>def gif():
    os.chdir(r'C:\Users\imper\Documents\new_GISfiles\earthquakesPH\exports')
    imgs = humansorted(os.listdir('.'))
    my_clip = ImageSequenceClip(imgs, fps=1.5)
    my_clip.write_videofile('eqph.mp4', fps=15)
</code>```

Someone from r/learnpython pointed out that I can't just write imgs = 'exports' even if I already set up the working directory os.chdir(r'path').
https://www.reddit.com/r/learnpython/comments/guabw3/the_humansorted_function_work_when_ran_in_the/

Body:
I have a folder that has plots in PNGs like earthquake0, earthquake1, earthquake2, and so on. These photos are converted to GIF via moviepy but Python's sorting results to 1, 10, 100 instead of 1, 2, 3.

Here's the moviepy code

import os
os.chdir(r'path')
from moviepy.editor import *

image_list = 'exports' # folder
my_clip = ImageSequenceClip(image_list, fps=0.75)
my_clip.write_gif('eqph_gif.gif')

I have tried adding this but Python says it can't find the folder

image_list = natsort.natsorted(image_list)

Body:
Solved it!

def gif():
    os.chdir(r'C:\Users\imper\Documents\new_GISfiles\earthquakesPH\exports')
    imgs = humansorted(os.listdir('.'))
    my_clip = ImageSequenceClip(imgs, fps=1.5)
    my_clip.write_videofile('eqph.mp4', fps=15)

Someone from r/learnpython pointed out that I can't just write imgs = 'exports' even if I already set up the working directory os.chdir(r'path').
https://www.reddit.com/r/learnpython/comments/guabw3/the_humansorted_function_work_when_ran_in_the/


问:
How to find rows of a dataframe containing a date value?
There is a huge dataframe containing multiple data types in different columns. I want to find rows that contain date values in different columns.
Here a test dataframe:

```<code>   dt = pd.Series(['abc', datetime.now(), 12, '', None, np.nan, '2020-05-05'])
   dt1 = pd.Series([3, datetime.now(), 'sam', '', np.nan, 'abc-123', '2020-05-25'])
   dt3 = pd.Series([1,2,3,4,5,6,7])
   df = pd.DataFrame({"A":dt.values, "B":dt1.values, "C":dt3.values})
</code>```

Now, I want to create a new dataframe that contains only dates in both columns A and B, here rows 2nd and last.

Expected output:

```                            A                           B  C
1  2020-06-01 16:58:17.274311  2020-06-01 17:13:20.391394  2
6                  2020-05-05                  2020-05-25  7
```

What is the best way to do that? Thanks.

P.S.> Dates can be in any standard format.

Body:
There is a huge dataframe containing multiple data types in different columns. I want to find rows that contain date values in different columns.
Here a test dataframe:

   dt = pd.Series(['abc', datetime.now(), 12, '', None, np.nan, '2020-05-05'])
   dt1 = pd.Series([3, datetime.now(), 'sam', '', np.nan, 'abc-123', '2020-05-25'])
   dt3 = pd.Series([1,2,3,4,5,6,7])
   df = pd.DataFrame({"A":dt.values, "B":dt1.values, "C":dt3.values})

Now, I want to create a new dataframe that contains only dates in both columns A and B, here rows 2nd and last.

Expected output:

                            A                           B  C
1  2020-06-01 16:58:17.274311  2020-06-01 17:13:20.391394  2
6                  2020-05-05                  2020-05-25  7

What is the best way to do that? Thanks.

P.S.> Dates can be in any standard format.

Body:
Use:

m = df[['A', 'B']].transform(pd.to_datetime, errors='coerce').isna().any(axis=1)
df = df[~m]

Result:

# print(df)
                            A                           B  C
1  2020-06-01 17:54:16.377722  2020-06-01 17:54:16.378432  2
6                  2020-05-05                  2020-05-25  7


问:
Static website I am hosting cannot be reached and the server IP cannot be found
I recently used Google Domains to register a domain and have connected it to Google Cloud Console to manage a static website. I followed the Google Codelabs guide to set it up and faced no issues. However, when refreshing my website, it still doesn't load and my browser (Chrome) gives me the following error message:

This site can’t be reached

carbonfootprint.dev’s server IP address could not be found."

As well, going to www.carbonfootprint.dev gives me another error message:

Your connection is not private

Attackers might be trying to steal your information from www.carbonfootprint.dev (for example, passwords, messages, or credit cards).

NET::ERR_CERT_COMMON_NAME_INVALID

...Which is confusing, because I was under the impression that a .dev domain suffix gives SSL certification by default.

However, in my Google Domains settings, the website content appears as it should in the minimized preview that exists in both the Domain Overview panel and Website panel. It has been over 48 hours, so it should have updated by now if it were just a delay issue.

For reference, this is what my Custom resource records look like, this is what my synthetic records look like, and these are my bucket details in Google Cloud Console. As well, here is a preview of the website, as shown in the Google Domains console.

Any help is much appreciated!

答:
Ended up finding the answer thanks to @IshRaj on ServerFault.

For future reference to anyone else viewing, Google Cloud Storage only supports HTTP connections when hosting a static website through CNAME resource records. To serve content through a custom domain over SSL, you will need to either:

Set up an external HTTPS load balancer (instructions here),
potentially with Google Cloud CDN (set-up documentation here)

Connect a third-party Content Delivery Network to your Google Cloud

Storage (guide here)

Host your static website on Google App Engine with Python (guide
here)

Serve static website content through Google Firebase rather than

Google Cloud Platform (tutorial here/additional support)

Personally, I went with Google Firebase (the last option), which automatically upgrades websites to https. It was simple and quick to set up and content is now directly deployable from my files. As well, with Firestore's automatic scalability and powerful queries, Firebase becomes a viable alternative, especially with its other features (user authentication, realtime data synchronization, machine-learning, extensions).


问:
Mutable state update in react
For example, we have a state defined like this which is having some todos and we want to change done of that todo if they are completed

```<code>this.state = {
  // store an array of todo objects
  todos: [
    { task: 'do the dishes', done: false, id: 1 },
    { task: 'vacuum the floor', done: true, id: 2 }
  ]
};
</code>```

For that, we can do this away.

```<code>  const theTodo = this.state.todos.find(t => t.id === id);
  theTodo.done = true; // NOOOOO

  this.setState({
    todos: this.state.todos
  });
</code>```

}

But I am a little confused that find method on the array will return us the element which matches the condition inside it and we store it in a different variable and then access done to change it to true.
But still, we haven't changed the original state value as this was a copy one.

Then how come we can use this to save it?

```<code> this.setState({
    todos: this.state.todos // bad
  });
</code>```

答: This is not an issue or something related to React framework. It's a basic understanding of JavaScript. Of course you will get a match, the find method is applicable to any array and your todo is an array. The find method returns a new object not a reference to it. If you want to update just that, create a copy of your todo, then use any method to update the right todo item, and then add the copied todo to the new state. You could use immer, or use spread operators, there's several ways to do this.

Title: Mutable state update in react

Body:
For example, we have a state defined like this which is having some todos and we want to change done of that todo if they are completed

this.state = {
  // store an array of todo objects
  todos: [
    { task: 'do the dishes', done: false, id: 1 },
    { task: 'vacuum the floor', done: true, id: 2 }
  ]
};

For that, we can do this away.

  const theTodo = this.state.todos.find(t => t.id === id);
  theTodo.done = true; // NOOOOO

  this.setState({
    todos: this.state.todos
  });

}

But I am a little confused that find method on the array will return us the element which matches the condition inside it and we store it in a different variable and then access done to change it to true.
But still, we haven't changed the original state value as this was a copy one.

Then how come we can use this to save it?

 this.setState({
    todos: this.state.todos // bad
  });


问:
TFDMemTable filter not responding to my TEdit OnChangeTracking
I have TFDMemTable data from API. The TFDMemTable is livebinded with TListView. The tricky part here is that, I want to show in the TListView the filtered data only using OnChangeTracking event of TEdit control.

Here's the code that I am working with to effect my intended result but, unfortunately, it is not returning anything.

```<code>procedure TformMain.edtSearchBoxChangeTracking(Sender: TObject);
var
  metastr : string;
begin
  metastr := edtSearchBox.text;   //edtSearchBox is my TEdit control
  with dmMain_u.dmMain do
  begin
    mtbMeta.Active := False;      //mtbMeta is my TFDMemTable
    mtbMeta.Filtered := False;
    mtbMeta.Filter := 'meta LIKE ' + QuotedStr('%' + metastr + '%');
    mtbMeta.Filtered := True;
    mtbMeta.Active := True;
  end;
end;
</code>```

Can anyone here try to check my code if it is correct? Or I might need to do something else?

答:
I would remove the .Active := False and .Active := True. They are the same as calls to .Close and .Open, and the Close will cause mtbMeta to lose its data.

As for the slowness you mentioned in your comment, the usual way around that is to to something like this:

```<code>procedure TformMain.edtSearchBoxChangeTracking(Sender: TObject);
var
  metastr : string;
begin
  Timer1.Enabled := True;
end;
</code>```

and put your remaining code from your q into Timer1's OnTimer event. With its time interval set to say, 150 or 200 (millseconds), using the timer this way effectively waits until your typing "pauses for breath" as it were, rather than trying to update the gui on every keypress.

Body:
I have TFDMemTable data from API. The TFDMemTable is livebinded with TListView. The tricky part here is that, I want to show in the TListView the filtered data only using OnChangeTracking event of TEdit control.

Here's the code that I am working with to effect my intended result but, unfortunately, it is not returning anything.

procedure TformMain.edtSearchBoxChangeTracking(Sender: TObject);
var
  metastr : string;
begin
  metastr := edtSearchBox.text;   //edtSearchBox is my TEdit control
  with dmMain_u.dmMain do
  begin
    mtbMeta.Active := False;      //mtbMeta is my TFDMemTable
    mtbMeta.Filtered := False;
    mtbMeta.Filter := 'meta LIKE ' + QuotedStr('%' + metastr + '%');
    mtbMeta.Filtered := True;
    mtbMeta.Active := True;
  end;
end;

Can anyone here try to check my code if it is correct? Or I might need to do something else?

Body:
I would remove the .Active := False and .Active := True. They are the same as calls to .Close and .Open, and the Close will cause mtbMeta to lose its data.

As for the slowness you mentioned in your comment, the usual way around that is to to something like this:

procedure TformMain.edtSearchBoxChangeTracking(Sender: TObject);
var
  metastr : string;
begin
  Timer1.Enabled := True;
end;

and put your remaining code from your q into Timer1's OnTimer event. With its time interval set to say, 150 or 200 (millseconds), using the timer this way effectively waits until your typing "pauses for breath" as it were, rather than trying to update the gui on every keypress.


问:
Error fetching custom collections: Error in Watson Visual Recognition service: Recieved invalid status 403 response
I am using IBM Watson Visual Recognition for a custom model. I have uploaded my dataset as .zip files, which is fine so far. However, I cannot test  already trained model and  I cannot label new images. When I go on my Watson services, it says:

```<code>Error fetching custom collections: Error in Watson Visual Recognition service: Recieved invalid status 403 in getAllCollections response for guid crn:v1:bluemix:public:watson-vision-combined:us-south:a/649b0335a5a44f6d80d1fd6909e466f9:8a71daa3-b0be-42ac-bb72-1473de835c19:: at endpoint https://gateway.watsonplatform.net/visual-recognition/api/
</code>```

When I try to label new images , it says: Error in Watson Visual Recognition service: Received empty image data response

To the best of my knowledge, I have checked Google and StackOverflow for solutions, but didn't find any. I am using the Lite version. I only have one project, and one Visual Recognition instance. Please note that it worked for a different Visual Recognition model before, but later I could not use or access that model.

答: Another thing to consider, since you mentioned you were using a lite plan, is that once you have exhausted the monthly quota of resources for this free plan, you will get 403 error codes.</p>

Body:
I am using IBM Watson Visual Recognition for a custom model. I have uploaded my dataset as .zip files, which is fine so far. However, I cannot test  already trained model and  I cannot label new images. When I go on my Watson services, it says:

Error fetching custom collections: Error in Watson Visual Recognition service: Recieved invalid status 403 in getAllCollections response for guid crn:v1:bluemix:public:watson-vision-combined:us-south:a/649b0335a5a44f6d80d1fd6909e466f9:8a71daa3-b0be-42ac-bb72-1473de835c19:: at endpoint https://gateway.watsonplatform.net/visual-recognition/api/

When I try to label new images , it says: Error in Watson Visual Recognition service: Received empty image data response

To the best of my knowledge, I have checked Google and StackOverflow for solutions, but didn't find any. I am using the Lite version. I only have one project, and one Visual Recognition instance. Please note that it worked for a different Visual Recognition model before, but later I could not use or access that model.


问:
grouping continuous data with specific pattern
I have a data frame with a column like this (I am not posting other columns)

```<code>Value
1
1
1
0
0
1
0
0
1
1
2
2
0
0
1
0
0
1
1
1
0
0
2
2
1
1
2
0
0
1
0
</code>```

I am trying to group it based on a specific condition. Grouping has to be done when I have 1 and 2. But conditions like these are one group :

```<code>1 1 0 0 1 1 0 0
</code>```

Basically I need to group occurrences of 1 but in between 0s are allowed

Expected output:

```<code>Value   Group
    1   1
    1   1
    1   1
    0   1
    0   1
    1   1
    0   1
    0   1
    1   1
    1   1
    2   2
    2   2
    0   2
    0   2
    1   3
    0   3
    0   3
    1   3
    1   3
    1   3
    0   3
    0   3
    2   4
    2   4
    1   5
    1   5
    2   6
    0   6
    0   6
    1   7
    0   7
    2   8
    0   8
    2   8
    1   9
</code>```

答:
Here is another option using data.table:

```<code>DT[, Group := .GRP, .(date, rleid(nafill(replace(Value, Value==0L, NA_integer_), "locf")))]
</code>```

Body:
I have a data frame with a column like this (I am not posting other columns)

Value
1
1
1
0
0
1
0
0
1
1
2
2
0
0
1
0
0
1
1
1
0
0
2
2
1
1
2
0
0
1
0

I am trying to group it based on a specific condition. Grouping has to be done when I have 1 and 2. But conditions like these are one group :

1 1 0 0 1 1 0 0

Basically I need to group occurrences of 1 but in between 0s are allowed

Expected output:

Value   Group
    1   1
    1   1
    1   1
    0   1
    0   1
    1   1
    0   1
    0   1
    1   1
    1   1
    2   2
    2   2
    0   2
    0   2
    1   3
    0   3
    0   3
    1   3
    1   3
    1   3
    0   3
    0   3
    2   4
    2   4
    1   5
    1   5
    2   6
    0   6
    0   6
    1   7
    0   7
    2   8
    0   8
    2   8
    1   9

Body:
Here is another option using data.table:

DT[, Group := .GRP, .(date, rleid(nafill(replace(Value, Value==0L, NA_integer_), "locf")))]


问:
How to convert the file with multiple delimiter to dataframe
I have a text file as below

```<code>1234_4567_DigitalDoc_XRay-01.pdf
2345_5678_DigitalDoc_CTC-03.png
1234_5684_DigitalDoc_XRay-05.pdf
1234_3345_DigitalDoc_XRay-02.pdf
</code>```

I am expecting the output as

```<code>| catg|sub_catg|      doc_name        |revision_label|extension|
|1234|     4567|DigitalDoc_XRay-01.pdf|   01         |pdf      |
</code>```

I have created a custom schema

```<code> val customSchema = StructType(
      StructField("catg", StringType, true)
        :: StructField("sub_catg", StringType, true)
        :: StructField("doc_name", StringType, true)
        :: StructField("revision_label", StringType, true)
        :: StructField("extension", StringType, true)
        :: Nil
    )
</code>```

I am trying to create a dataframe as

```<code>val df = sparkSession.read
  .format("csv")
  .schema(customSchema)
  .option("delimiter", "_")
  .load("src/main/resources/data/sample.txt")

df.show()
</code>```

I am wondering how to break that each line by custom record

I could probably write a java code something of this kind, can someone please help me with the spark. I am new to spark.

```<code>String word[] = line.split("_");

            String filenName[] = word[3].split("-");
            String revision = filenName[1];
            word[0]+","+word[1]+","+ word[2]+"_"+word[3]+","+revision.replace(".", " ");
</code>```

答:
since all columns are string type, no need to define a schema in your case. You can write code as below</p>

```<code>import org.apache.spark.sql.functions.{col,split,regexp_extract}

val data = spark.read.option("delimiter","_").csv(src/main/resources/data/sample.txt").toDF("catg","sub_catg","doc_name","no_name")

val df2 = data.withColumn("revision_label",regexp_extract(col("no_name"),".*-(\\w+)\\.",1)).withColumn("extension",split(col("no_name"),"\\.")(1)).drop("no_name")
</code>```

Body:
I have a text file as below

1234_4567_DigitalDoc_XRay-01.pdf
2345_5678_DigitalDoc_CTC-03.png
1234_5684_DigitalDoc_XRay-05.pdf
1234_3345_DigitalDoc_XRay-02.pdf

I am expecting the output as

| catg|sub_catg|      doc_name        |revision_label|extension|
|1234|     4567|DigitalDoc_XRay-01.pdf|   01         |pdf      |

I have created a custom schema

 val customSchema = StructType(
      StructField("catg", StringType, true)
        :: StructField("sub_catg", StringType, true)
        :: StructField("doc_name", StringType, true)
        :: StructField("revision_label", StringType, true)
        :: StructField("extension", StringType, true)
        :: Nil
    )

I am trying to create a dataframe as

val df = sparkSession.read
  .format("csv")
  .schema(customSchema)
  .option("delimiter", "_")
  .load("src/main/resources/data/sample.txt")

df.show()

I am wondering how to break that each line by custom record

I could probably write a java code something of this kind, can someone please help me with the spark. I am new to spark.

String word[] = line.split("_");

            String filenName[] = word[3].split("-");
            String revision = filenName[1];
            word[0]+","+word[1]+","+ word[2]+"_"+word[3]+","+revision.replace(".", " ");

Body:
since all columns are string type, no need to define a schema in your case. You can write code as below

import org.apache.spark.sql.functions.{col,split,regexp_extract}

val data = spark.read.option("delimiter","_").csv(src/main/resources/data/sample.txt").toDF("catg","sub_catg","doc_name","no_name")

val df2 = data.withColumn("revision_label",regexp_extract(col("no_name"),".*-(\\w+)\\.",1)).withColumn("extension",split(col("no_name"),"\\.")(1)).drop("no_name")


问:
why isnt line "print("guys listen")" not working?
```<code>def amn(func):
    def inner():
        print("guys listen")
    func()
    return inner

@amn
def damn():
    print("hey")
</code>```

amn is a decorator. The function inner() is supposed to be called when amn is executed. But for some reason, it is not working

答:
```<code>@amn
def foo():
    pass
</code>```

Is the same as

def foo():
    pass

foo = amn(foo)
```

Your amn calls the original damn as func(), and then the @ operator assigns the return value of amn back to damn, making it inner.

You shouldn't invoke func in the outer part of amn but as part of inner. You should also look at functools.wraps.

Body:
def amn(func):
    def inner():
        print("guys listen")
    func()
    return inner

@amn
def damn():
    print("hey")

amn is a decorator. The function inner() is supposed to be called when amn is executed. But for some reason, it is not working

Body:
@amn
def foo():
    pass

Is the same as

def foo():
    pass

foo = amn(foo)

Your amn calls the original damn as func(), and then the @ operator assigns the return value of amn back to damn, making it inner.

You shouldn't invoke func in the outer part of amn but as part of inner. You should also look at functools.wraps.


问:
Use variable inside Hugo content
I'm trying to use a variable within the content of a Hugo statically generated site. For example, the content looks like the following:

Go to your site's url ({{ .Site.BaseURL }})

Enter your credentials

.....(blah blah blah)

When this gets rendered, the {{ .... }} part doesn't get processed...it stays the same as I put above. I've tried it with a $ in front as well. Variables within templates seem to work just fine. Do I need to create a shortcode to use within content pages?

答:
I had the same problem, and this post helped me.

I wanted to display a site param in my site content, and discovered you cannot use regular templating inside content files.

In the end I created a shortcode to load the requested site param. Who knows this information might help someone.

/config.yml

```<code>params:
  appName: My app
</code>```

/content/about.html

```<code><p>My app's name is {{< param "appName" >}}</p>
</code>```

/layouts/shortcodes/param.html

```<code>{{/* Usage: {{< param "siteParamName" }} */}}
{{ index .Site.Params (.Get 0) }}
</code>```

Result

```<code><p>My app's name is My app</p>
</code>```

Title: Use variable inside Hugo content

Body:
I had the same problem, and this post helped me.

I wanted to display a site param in my site content, and discovered you cannot use regular templating inside content files.

In the end I created a shortcode to load the requested site param. Who knows this information might help someone.

/config.yml

params:
  appName: My app

/content/about.html

<p>My app's name is {{< param "appName" >}}</p>

/layouts/shortcodes/param.html

{{/* Usage: {{< param "siteParamName" }} */}}
{{ index .Site.Params (.Get 0) }}

Result

<p>My app's name is My app</p>


问:
Failed to build project with react-Native-firebase
The project used to built but recently broke. Diagnostic:

```<code>:@react-native-firebase_app:reactNativeAndroidDir
/<PATH>/node_modules/react-native/android

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':@react-native-firebase_app'.
> Failed to notify project evaluation listener.
   > 'org.gradle.api.file.RegularFileProperty org.gradle.api.file.ProjectLayout.fileProperty(org.gradle.api.provider.Provider)'
</code>```

Gradle 6.4.1,
"@react-native-firebase/app": "^7.1.4",

答:
The issue is resolved by updating to </p>

```<code>classpath 'com.android.tools.build:gradle:4.0.0'
</code>```

Body:
The project used to built but recently broke. Diagnostic:

:@react-native-firebase_app:reactNativeAndroidDir
/<PATH>/node_modules/react-native/android

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':@react-native-firebase_app'.
> Failed to notify project evaluation listener.
   > 'org.gradle.api.file.RegularFileProperty org.gradle.api.file.ProjectLayout.fileProperty(org.gradle.api.provider.Provider)'

Gradle 6.4.1,
"@react-native-firebase/app": "^7.1.4",

Body:
The issue is resolved by updating to

classpath 'com.android.tools.build:gradle:4.0.0'


问:
Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class in angular 8
ERROR in node_modules/@angular/common/http/http.d.ts:2801:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class</p>

```<code>2801 export declare class HttpClientModule {
</code>```

答: Setting "aot": false inside angular.json file worked for me.</p>

Body:
ERROR in node_modules/@angular/common/http/http.d.ts:2801:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

2801 export declare class HttpClientModule {


问:
Using the spread operator on an array with objects
I got a Javascript object which looks like this:

```<code>{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   }
}
</code>```

I also got an array to which I push items like this:

```<code>myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items
</code>```

I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:

```<code>{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   },
   key3: { //the object that was added },
   key4: { //the object that was added }
}
</code>```

I tried doing it with the spread operator:

```<code>return {...object, ...myArr}
</code>```

But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).

How do I concatenate the object and the array the way I want?

答:
What you're looking to achieve here is not possible with the spread operator; it's working exactly as intended and the functionality cannot be changed as JS doesn't allow operator overloading. Your best bet is to loop through myArr and add each item in the array to the object using your own code. </p>

<p>P.S. As the comments suggest, in the future you should really provide more examples of your input, the current output, and your intended output; it was quite difficult to follow without it. </p>

Body:
I got a Javascript object which looks like this:

{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   }
}

I also got an array to which I push items like this:

myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items

I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:

{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   },
   key3: { //the object that was added },
   key4: { //the object that was added }
}

I tried doing it with the spread operator:

return {...object, ...myArr}

But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).

How do I concatenate the object and the array the way I want?

Body:
What you're looking to achieve here is not possible with the spread operator; it's working exactly as intended and the functionality cannot be changed as JS doesn't allow operator overloading. Your best bet is to loop through myArr and add each item in the array to the object using your own code.

P.S. As the comments suggest, in the future you should really provide more examples of your input, the current output, and your intended output; it was quite difficult to follow without it.


问:
KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'
I tried to get query from database but failed by KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'.
My code is

```<code>@app.route("/users/<int:id>")
def users(id):
result = Account.query.get(id)
return render_template("users.html",username=result.username).
</code>```

I think syntax on query is mistake. Need suggestions !!!

答:
Major problem is not instantiating of session object
Now code is

```<code>@app.route("/users/<int:id>")
def users(id):
    session = Session()
    result = session.query(Account).filter_by(id=id).first()
    return render_template("users.html", result = result)`
</code>```

in users.html is

```<code><ul>
    <li>id: {{ result.id }} </li>
    <li>username: {{ result.username }} </li>
    <li>password: {{ result.password }} </li>
</ul>`
</code>```

Body:
I tried to get query from database but failed by KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'.
My code is

@app.route("/users/<int:id>")
def users(id):
result = Account.query.get(id)
return render_template("users.html",username=result.username).

I think syntax on query is mistake. Need suggestions !!!

Body:
Major problem is not instantiating of session object
Now code is

@app.route("/users/<int:id>")
def users(id):
    session = Session()
    result = session.query(Account).filter_by(id=id).first()
    return render_template("users.html", result = result)`

in users.html is

<ul>
    <li>id: {{ result.id }} </li>
    <li>username: {{ result.username }} </li>
    <li>password: {{ result.password }} </li>
</ul>`


问:
launchnavigator plugin building with error in phonegap buid
Today the phonegap build issue an error with launchnavigator plugin,the following error is displayed on the build log:
Failed to install 'uk.co.workingedge.phonegap.plugin.launchnavigator': Error: Variable(s) missing: GOOGLE_API_KEY_FOR_ANDROID, any thought?</p>

答:
Worth to try this command line to include in your project as well

$ cordova plugin add uk.co.workingedge.phonegap.plugin.launchnavigator --variable GOOGLE_API_KEY_FOR_ANDROID="{your_api_key}"


问:
Adding SPA to .NET Core Web API
I want to add a separately developed Vue-based SPA to a .NET Core Web API project.

How do I bundle my Vue app with the Web API project?

答: The question has already been answered, though with a different focus, here: What is the difference between UseStaticFiles, UseSpaStaticFiles, and UseSpa in ASP.NET Core 2.1?</p>

Title: Adding SPA to .NET Core Web API


问:
Access dom element with vuejs and vuetify dialog
I have a div tag with an 'id="meet"' into v-dialog.

I need to access the node of this tag after I open the dialog.
I am using

```<code>let node=document.querySelector("#meet").
</code>```

My problem is that it always returns "null".
Here is the codepen: https://codepen.io/luizalves/pen/NWxKbXQ

What is wrong here?

答:
According to your CodePen, it returns null only on first open.

The content of the component is loaded dynamically by default, only after the first opening of the v-dialog.

You could add eager prop to v-dialog element to force it.

```<code><v-dialog
    v-model="dialog"
    max-width="290"
    eager
>
...
</code>```

Body:
I have a div tag with an 'id="meet"' into v-dialog.

I need to access the node of this tag after I open the dialog.
I am using

let node=document.querySelector("#meet").

My problem is that it always returns "null".
Here is the codepen: https://codepen.io/luizalves/pen/NWxKbXQ

What is wrong here?

Body:
According to your CodePen, it returns null only on first open.

The content of the component is loaded dynamically by default, only after the first opening of the v-dialog.

You could add eager prop to v-dialog element to force it.

<v-dialog
    v-model="dialog"
    max-width="290"
    eager
>
...


问:
How to animate images onslide of ViewPager?
How do I animate objects on swipe of fragments in Viewpager? I want to achieve something like this.

答:
you can achieve this effect by attaching OnPageChangeListener on your viewPager.

```<code>@Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // use positionOffset and position to zoom in-out of your image
            //For ex you have to zoom images on fragment on 1st index.
           // zoom the images in when you get position = 0 and set zoom level according to positionOffsetPixels
        }
</code>```

I hope you will get ahead with answer. If you have any doubt ask away. Giving you a small example for the above explanation:

```<code> @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            if (position==0){
                fragment1.setZoomImage(positionOffset);
            }
        }
</code>```

Method in fragment1:

```<code>public void setZoomImage(float zoom){
    if (zoomImage!=null){
        zoomImage.setPadding((int)(padding-(zoom*padding)),(int)(padding-(zoom*padding)),(int)(padding-(zoom*padding)),(int)(padding-(zoom*padding)));
    //padding is the max padding you want for the image.
    }
}
</code>```

Body:
you can achieve this effect by attaching OnPageChangeListener on your viewPager.

@Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // use positionOffset and position to zoom in-out of your image
            //For ex you have to zoom images on fragment on 1st index.
           // zoom the images in when you get position = 0 and set zoom level according to positionOffsetPixels
        }

I hope you will get ahead with answer. If you have any doubt ask away. Giving you a small example for the above explanation:

 @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            if (position==0){
                fragment1.setZoomImage(positionOffset);
            }
        }

Method in fragment1:

public void setZoomImage(float zoom){
    if (zoomImage!=null){
        zoomImage.setPadding((int)(padding-(zoom*padding)),(int)(padding-(zoom*padding)),(int)(padding-(zoom*padding)),(int)(padding-(zoom*padding)));
    //padding is the max padding you want for the image.
    }
}


问:
Moving props data to state to generate forms
I'm planning to add a prefilled form with React. I have the actual data on props. This is what I came up with.

```<code>@connect(...)
class Some extends React.Component {
   state = {
      ...this.props.auth.user
   }

   render() {
     // Create a form using the data on state
   }
}
</code>```

It looks not correct since I'm not using a react lifecycle hook here. I would like to ask if there is a better practice to achieve what I'm trying to do.

答:
So to elaborate on my previous responses you would do something like this to achieve what you want:

```<code>@connect(...)
class Some extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      value: '',
   }
}
handleChange = (event) => {
    this.setState({ value: event.target.value });
  }

   render() {
      return(
         <div>
          <input onChange={this.handleChange} id="some" type="text" value= {this.state.value|| this.props.value}/>
        </div>
     )
   }
}
</code>```

While your value is an empty string (in the state), the fields will be populated from your props and as soon as you start typing it will overwrite the prepopulated values with the ones in your state.

Best practices would be to actually have a Component that handles this logic and then passes the props to the form that should be just a dumb presentational component:

```<code>class SomeController extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
      value: '',
    }
 }
 handleChange = (event) => {
    this.setState({ value: event.target.value });
  }

  return (<Form handleChange={this.handleChange} value={this.state.value} />)
}
</code>```

And then your form component:

```<code>const Form = (props) => (
  <form>
    <input onChange={props.handleChange} value={props.value} />
  </form>
);
</code>```

Hope this explanation helps.

Body:
I'm planning to add a prefilled form with React. I have the actual data on props. This is what I came up with.

@connect(...)
class Some extends React.Component {
   state = {
      ...this.props.auth.user
   }

   render() {
     // Create a form using the data on state
   }
}

It looks not correct since I'm not using a react lifecycle hook here. I would like to ask if there is a better practice to achieve what I'm trying to do.

Body:
So to elaborate on my previous responses you would do something like this to achieve what you want:

@connect(...)
class Some extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      value: '',
   }
}
handleChange = (event) => {
    this.setState({ value: event.target.value });
  }

   render() {
      return(
         <div>
          <input onChange={this.handleChange} id="some" type="text" value= {this.state.value|| this.props.value}/>
        </div>
     )
   }
}

While your value is an empty string (in the state), the fields will be populated from your props and as soon as you start typing it will overwrite the prepopulated values with the ones in your state.

Best practices would be to actually have a Component that handles this logic and then passes the props to the form that should be just a dumb presentational component:

class SomeController extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
      value: '',
    }
 }
 handleChange = (event) => {
    this.setState({ value: event.target.value });
  }

  return (<Form handleChange={this.handleChange} value={this.state.value} />)
}

And then your form component:

const Form = (props) => (
  <form>
    <input onChange={props.handleChange} value={props.value} />
  </form>
);

Hope this explanation helps.


问:
Receiving Disparate Content In Java
The Problem:

I need to receive different types of content from a number of different sources normalize them and then make them persistent through JDO.

Naive Solution?:

Create and listen on a specific port for each data type.

OR

Do a bunch of complicated parsing

A Seemingly Ideal Solution:

Have custom URL types i.e. FOO://myhost.tld, BAR://myhost.tld. any application could then send to the URL specific to the custom type and the host would ideally use Java's URLConnection and URLStreamHandler abstract classes to create a factory that would spawn the appropriate normalization thread. Or if there is anyway other way to retrieve the connection URL I think that would be sufficient

Is this possible? I have looked through the API and other docs put cannot figure out if it is possible to use these with a Java server socket.

I should mention that in some (many? most?) cases I am not responsible for the client code.

答: The solution I ended up going with is using the java nio lib and a thread pool with a collection of ServerSocketChannels with content handlers attached</p>

OwnerDisplayName: tapi

Title: Receiving Disparate Content In Java

LastEditorDisplayName: tapi

ContentLicense: CC BY-SA 2.5


问:
kotlinx.android.synthetic unused android studio issue
I am working one project using kotlin + Rxjava + MVVM. During development facing issue of importing view ids in Fragment or viewholder.

import kotlinx.android.synthetic.main.layout.* unused with kotlin.

Normaly view id should used from kotlin synthetic layout imports but it directly import it from R.id that should not happen.

Kotlin plugin version : org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.40

My gradle file :

```<code>apply plugin: 'com.android.feature'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'idea'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 27
    baseFeature true
    defaultConfig {
        minSdkVersion 23
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    lintOptions {
        abortOnError false
    }
}

dependencies {

    api "com.android.support:design:$rootProject.support_library_version"
    api "com.android.support:appcompat-v7:$rootProject.support_library_version"
    api "com.android.support:recyclerview-v7:$rootProject.support_library_version"
    api "com.android.support:support-dynamic-animation:$rootProject.support_library_version"
    api "com.android.support:cardview-v7:$rootProject.support_library_version"
    api "com.android.support:customtabs:$rootProject.support_library_version"

    api "com.android.support.constraint:constraint-layout:1.1.0-beta5"
    api 'android.arch.lifecycle:extensions:1.1.0'

    api 'androidx.core:core-ktx:0.2'

    api "com.google.dagger:dagger:$rootProject.dagger_version"
    kapt "com.google.dagger:dagger-compiler:$rootProject.dagger_version"

    api "android.arch.persistence.room:runtime:$rootProject.room_version"
    kapt "android.arch.persistence.room:compiler:$rootProject.room_version"
    testImplementation "android.arch.persistence.room:testing:$rootProject.room_version"
    api "android.arch.persistence.room:rxjava2:$rootProject.room_version"
    androidTestImplementation "android.arch.core:core-testing:$rootProject.room_version"
    testImplementation "android.arch.core:core-testing:$rootProject.room_version"

    api "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    api "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"

    api 'com.jakewharton.timber:timber:4.5.1'

    api "com.android.support:multidex:1.0.3"

    api "com.github.bumptech.glide:glide:$rootProject.glide_version"
    api "jp.wasabeef:glide-transformations:$rootProject.glide_transformation_version"
    api 'com.github.bumptech.glide:okhttp3-integration:1.5.0@aar'

    api "io.reactivex.rxjava2:rxandroid:$rootProject.rxAndroid_version"
    api "io.reactivex.rxjava2:rxjava:$rootProject.rxJava_version"
    api "com.google.code.gson:gson:$rootProject.gson_version"

    api("com.squareup.retrofit2:retrofit:$rootProject.retrofit_version") {
        // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
        exclude module: 'okhttp'
    }

    api "com.squareup.okhttp3:okhttp:$rootProject.okhttp_version"
    api "com.squareup.okhttp3:logging-interceptor:$rootProject.okhttp_version"
    api "com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofit_version"
    api "com.squareup.retrofit2:converter-gson:$rootProject.retrofit_version"

    api 'com.jakewharton.threetenabp:threetenabp:1.0.5'

    api "com.google.firebase:firebase-invites:$rootProject.play_services_version"
    api "com.google.firebase:firebase-core:$rootProject.play_services_version"
    api "com.google.firebase:firebase-config:$rootProject.play_services_version"
    api "com.google.firebase:firebase-perf:$rootProject.play_services_version"
    api "com.google.firebase:firebase-auth:$rootProject.play_services_version"
    api "com.google.firebase:firebase-firestore:$rootProject.play_services_version"

    api("com.firebaseui:firebase-ui-auth:$rootProject.firebase_ui_version") {
        // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
        exclude module: 'play-services-auth'
        exclude module: 'firebase-auth'
    }

    // Required only if Facebook login support is required
    api('com.facebook.android:facebook-android-sdk:4.31.0')

    api "com.google.android.gms:play-services-auth:$rootProject.play_services_version"

    // Required only if Twitter login support is required
    api("com.twitter.sdk.android:twitter-core:3.0.0@aar") { transitive = true }

    api 'com.jakewharton.rxbinding2:rxbinding-kotlin:2.0.0'
    api 'com.jakewharton.rxbinding2:rxbinding-support-v4-kotlin:2.0.0'
    api 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7-kotlin:2.0.0'
    api 'com.jakewharton.rxbinding2:rxbinding-design-kotlin:2.0.0'

    api('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
        transitive = true
    }
}
</code>```

I have also tried clean build and Rebuild project.

Any idea how can i resolve this issue ?

答: I try every other solution bu no one worked for me. At the and I cloned project again and now it's working. I love android studio</p>

Body:
I am working one project using kotlin + Rxjava + MVVM. During development facing issue of importing view ids in Fragment or viewholder.

import kotlinx.android.synthetic.main.layout.* unused with kotlin.

Normaly view id should used from kotlin synthetic layout imports but it directly import it from R.id that should not happen.

Kotlin plugin version : org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.40

My gradle file :

apply plugin: 'com.android.feature'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'idea'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 27
    baseFeature true
    defaultConfig {
        minSdkVersion 23
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    lintOptions {
        abortOnError false
    }
}

dependencies {

    api "com.android.support:design:$rootProject.support_library_version"
    api "com.android.support:appcompat-v7:$rootProject.support_library_version"
    api "com.android.support:recyclerview-v7:$rootProject.support_library_version"
    api "com.android.support:support-dynamic-animation:$rootProject.support_library_version"
    api "com.android.support:cardview-v7:$rootProject.support_library_version"
    api "com.android.support:customtabs:$rootProject.support_library_version"

    api "com.android.support.constraint:constraint-layout:1.1.0-beta5"
    api 'android.arch.lifecycle:extensions:1.1.0'

    api 'androidx.core:core-ktx:0.2'

    api "com.google.dagger:dagger:$rootProject.dagger_version"
    kapt "com.google.dagger:dagger-compiler:$rootProject.dagger_version"

    api "android.arch.persistence.room:runtime:$rootProject.room_version"
    kapt "android.arch.persistence.room:compiler:$rootProject.room_version"
    testImplementation "android.arch.persistence.room:testing:$rootProject.room_version"
    api "android.arch.persistence.room:rxjava2:$rootProject.room_version"
    androidTestImplementation "android.arch.core:core-testing:$rootProject.room_version"
    testImplementation "android.arch.core:core-testing:$rootProject.room_version"

    api "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    api "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"

    api 'com.jakewharton.timber:timber:4.5.1'

    api "com.android.support:multidex:1.0.3"

    api "com.github.bumptech.glide:glide:$rootProject.glide_version"
    api "jp.wasabeef:glide-transformations:$rootProject.glide_transformation_version"
    api 'com.github.bumptech.glide:okhttp3-integration:1.5.0@aar'

    api "io.reactivex.rxjava2:rxandroid:$rootProject.rxAndroid_version"
    api "io.reactivex.rxjava2:rxjava:$rootProject.rxJava_version"
    api "com.google.code.gson:gson:$rootProject.gson_version"

    api("com.squareup.retrofit2:retrofit:$rootProject.retrofit_version") {
        // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
        exclude module: 'okhttp'
    }

    api "com.squareup.okhttp3:okhttp:$rootProject.okhttp_version"
    api "com.squareup.okhttp3:logging-interceptor:$rootProject.okhttp_version"
    api "com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofit_version"
    api "com.squareup.retrofit2:converter-gson:$rootProject.retrofit_version"

    api 'com.jakewharton.threetenabp:threetenabp:1.0.5'

    api "com.google.firebase:firebase-invites:$rootProject.play_services_version"
    api "com.google.firebase:firebase-core:$rootProject.play_services_version"
    api "com.google.firebase:firebase-config:$rootProject.play_services_version"
    api "com.google.firebase:firebase-perf:$rootProject.play_services_version"
    api "com.google.firebase:firebase-auth:$rootProject.play_services_version"
    api "com.google.firebase:firebase-firestore:$rootProject.play_services_version"

    api("com.firebaseui:firebase-ui-auth:$rootProject.firebase_ui_version") {
        // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
        exclude module: 'play-services-auth'
        exclude module: 'firebase-auth'
    }

    // Required only if Facebook login support is required
    api('com.facebook.android:facebook-android-sdk:4.31.0')

    api "com.google.android.gms:play-services-auth:$rootProject.play_services_version"

    // Required only if Twitter login support is required
    api("com.twitter.sdk.android:twitter-core:3.0.0@aar") { transitive = true }

    api 'com.jakewharton.rxbinding2:rxbinding-kotlin:2.0.0'
    api 'com.jakewharton.rxbinding2:rxbinding-support-v4-kotlin:2.0.0'
    api 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7-kotlin:2.0.0'
    api 'com.jakewharton.rxbinding2:rxbinding-design-kotlin:2.0.0'

    api('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
        transitive = true
    }
}

I have also tried clean build and Rebuild project.

Any idea how can i resolve this issue ?


问:
Is there a restriction on the no. of HERE API Calls I can make in a loop (using R)
I am trying to loop through a list of origin destination lat long locations to get the transit time. I am getting the following error when I loop. However when I do a single call (without looping), I get an output without error. I use the freemium HERE-API and I am allowed 250k transactions a month.

```<code> `for (i in 1:nrow(test))
   {
            call <- paste0("https://route.api.here.com/routing/7.2/calculateroute.json",
                           "?app_id=","appid",
                           "&app_code=","appcode",
                           "&waypoint0=geo!",y$dc_lat[i],",",y$dc_long[i],
                           "&waypoint1=geo!",y$store_lat[i],",",y$store_long[i],
                           "&mode=","fastest;truck;traffic:enabled",
                           "&trailerscount=","1",
                           "&routeattributes=","sh",
                           "&maneuverattributes=","di,sh",
                           "&limitedweight=","20")

                  response <-fromJSON(call, simplify = TRUE)
            Traffic_time = (response[["response"]][["route"]][[1]][["summary"]][["trafficTime"]]) / 60
            Base_time = (response[["response"]][["route"]][[1]][["summary"]][["baseTime"]]) / 60
            print(Traffic_time)
}`
</code>```

Error in file(con, "r"): cannot open the connection to 'https://route.api.here.com/routing/7.2/calculateroute.json?app_id=appid&app_code=appcode&waypoint0=geo!45.1005200,-93.2452000&waypoint1=geo!45.0978500,-95.0413620&mode=fastest;truck;traffic:enabled&trailerscount=1&routeattributes=sh&maneuverattributes=di,sh&limitedweight=20'
  Traceback:

答: As per the error, this suggests that there is problem with the file at your end.  it could be corrupt, good to try with changing the extension of the file. Can also try to restart your IDE. The number of API calls depend on the plans that you have opted for freemium or pro plans. You can have more details : https://developer.here.com/faqs</p>

Body:
I am trying to loop through a list of origin destination lat long locations to get the transit time. I am getting the following error when I loop. However when I do a single call (without looping), I get an output without error. I use the freemium HERE-API and I am allowed 250k transactions a month.

 `for (i in 1:nrow(test))
   {
            call <- paste0("https://route.api.here.com/routing/7.2/calculateroute.json",
                           "?app_id=","appid",
                           "&app_code=","appcode",
                           "&waypoint0=geo!",y$dc_lat[i],",",y$dc_long[i],
                           "&waypoint1=geo!",y$store_lat[i],",",y$store_long[i],
                           "&mode=","fastest;truck;traffic:enabled",
                           "&trailerscount=","1",
                           "&routeattributes=","sh",
                           "&maneuverattributes=","di,sh",
                           "&limitedweight=","20")

                  response <-fromJSON(call, simplify = TRUE)
            Traffic_time = (response[["response"]][["route"]][[1]][["summary"]][["trafficTime"]]) / 60
            Base_time = (response[["response"]][["route"]][[1]][["summary"]][["baseTime"]]) / 60
            print(Traffic_time)
}`

Error in file(con, "r"): cannot open the connection to 'https://route.api.here.com/routing/7.2/calculateroute.json?app_id=appid&app_code=appcode&waypoint0=geo!45.1005200,-93.2452000&waypoint1=geo!45.0978500,-95.0413620&mode=fastest;truck;traffic:enabled&trailerscount=1&routeattributes=sh&maneuverattributes=di,sh&limitedweight=20'
  Traceback:


问:
How to set up a health check on an individual GCE - Internal IP
I want to create an uptime health check for an application running on GCE with Internal IP.

I've noticed that Uptime checks in GCP only supports external IP and health checks only support a GCE with Load Balancer or a Managed Instance group.

Is there a any other GCP way to create a health check? I'm not sure if Cloud functions help.

答:
No need for Managed Instance Group or Load Balancer. There's a little workaround for this.

Create legacy health check (http-health-check)

$ gcloud compute http-health-checks create chk1
Created [https://www.googleapis.com/compute/v1/projects/*/global/httpHealthChecks/ch3]
NAME  HOST  PORT  REQUEST_PATH
ch3         80    /

and then create a target-pool with health check assigned

$ gcloud compute target-pools create tp1 --health-check=chk1
The --health-check flag is deprecated. Use equivalent --http-health-check=chk1 flag.
Created [https://www.googleapis.com/compute/v1/projects/*/regions/my-region1/targetPools/tp1].
NAME  REGION        SESSION_AFFINITY  BACKUP  HEALTH_CHECKS
tp1   my-region1    NONE                      ch3

Next add an instance to the target-pool (just one).

gcloud compute target-pools add-instances tp1 --instances test-inst1

Finally you can check health using gcloud compute target-pools get-health command.


问:
Navigate a URL with Query string values on click of hyperlink
I have a control with 'email' and 'password' textboxes and a 'autoLogin' checkbox. All are web form controls (not html controls). And there is a 'Login' hyperlink. When I click on heperlink, I want to move to other page using NavigateUrl property like below:

```<code>NavigateUrl="~/DoLogin.aspx?email={0}&pwd={1}&autoLogin={3}"
</code>```

how to pass and how to get the query string?

Thanks in Advance...

答: The easiest way would be to not use a hyperlink but a button (or link button) and make a postback and then use, Response.Redirect("Url") or event better, process the login directly. Otherwize you have to collect your data using javascript.

Body:
I have a control with 'email' and 'password' textboxes and a 'autoLogin' checkbox. All are web form controls (not html controls). And there is a 'Login' hyperlink. When I click on heperlink, I want to move to other page using NavigateUrl property like below:

NavigateUrl="~/DoLogin.aspx?email={0}&pwd={1}&autoLogin={3}"

how to pass and how to get the query string?

Thanks in Advance...


问:
How can one stop Safari from focussing on form fields labelled Username or Password when document loads?
Whilst it might feel that this question should have been asked before, many times, the closest solution I can find is less than helpful, referring to 'snowflakes'. There is, however, a comment that highlights where the problem is a genuine issue.

When developing a form for a site administrator to use, any page which is set up to allow that administrator to initialise the username and password for a user seems to trigger Safari's aggressive Autocomplete / Keychain behaviour, which pulls the form's focus onto the Username field once the DOM is complete. There are some solutions to this, but they are not particularly elegant - redoing the form layout, for example, so that the Username field is the very first one or so that usernames and passwords are handled on a totally separate page / tab. To my mind that's the browser dictating the page, which is the wrong way around!

In my case, I'm pulling the form's construction details from a table of constraints so that additional fields can be added later and the form for that table amended automatically without rewriting code. This approach means that javascript based solutions are not 100% compliant with the idea of having no pages that require special measures - it's nicer to fix this at HTML or CSS level. Obviously this might not be possible; just ANYTHING that works to fix this annoying habit would be good.

答:
I could kludge the effect I required by adding the following dummy input field right after the main body form tag:

```<code><input type="text" id="defeatbox" style="position:absolute; top:-1000px;" autofocus />
</code>```

And then changing the focus to it 300ms after DOM ready.

```<code>$(document).ready(function () {
                setTimeout(function () {
                    $('#defeatbox').focus();
                }, 300);
});
</code>```

This is a REALLY kludgy way of doing it. The dummy field can't be hidden, the length of the timeout has to be determined by trial and error, and is dependent on the size of the page, and presumably the browser and the CPU speed. It also caused the first "autofocussed" box to "flash" briefly on the screen.

The more generic code:

```<code>setTimeout(function() {$('form:nth-of-type(2) *:input:first').focus();},300);
</code>```

didn't work if the autofilled/autofocussed element was in that same form (mine is the second form as there's a search box on the page that's drawn first). I could autofocus the search box in the first form using this method, but couldn't pull the focus to anything 'generic' in the second form which is the one in the main body of the page.

Body:
I could kludge the effect I required by adding the following dummy input field right after the main body form tag:

<input type="text" id="defeatbox" style="position:absolute; top:-1000px;" autofocus />

And then changing the focus to it 300ms after DOM ready.

$(document).ready(function () {
                setTimeout(function () {
                    $('#defeatbox').focus();
                }, 300);
});

This is a REALLY kludgy way of doing it. The dummy field can't be hidden, the length of the timeout has to be determined by trial and error, and is dependent on the size of the page, and presumably the browser and the CPU speed. It also caused the first "autofocussed" box to "flash" briefly on the screen.

The more generic code:

setTimeout(function() {$('form:nth-of-type(2) *:input:first').focus();},300);

didn't work if the autofilled/autofocussed element was in that same form (mine is the second form as there's a search box on the page that's drawn first). I could autofocus the search box in the first form using this method, but couldn't pull the focus to anything 'generic' in the second form which is the one in the main body of the page.