问:
Can initialize booking.com form 1 time but not again with ngOnInit
So I am using angular materials with angular4 and I have put html for a booking.com form inside an MdDialogue component. I want this dialogue to popup with the form inside of it when somebody pushes a button. It works as expected 1 time after the app has loaded, but not again. I would like it to work every time. There is no error message so it is unclear to me why this is happening. The logic inside booking() initializes the form.

The html for the booking.com form looks like this.

```<code><ins class="bookingaff" data-aid="1179852" data-target_aid="1179846" data-prod="nsb" data-width="100%" data-height="auto">
  <!-- Anything inside will go away once widget is loaded. -->
  <a href="//www.booking.com?aid=1179846">Booking.com</a>
</ins>
</code>```

Here is what the booking.com component looks like...

```<code>...
     openBookings(){
        let dialogRef = this.dialog.open(Booking_com);
        dialogRef.afterClosed().subscribe(result => {
        });
      }

      debug(data){
        console.log(data);
      }

    }

    @Component({
      selector: 'Booking_com',
      templateUrl: 'Booking_com.html',
      styleUrls: ['Booking_com.sass']
    })
    export class Booking_com implements AfterViewInit{

      ngAfterViewInit(): void {
        this.booking();
      }

      constructor(public dialogRef: MdDialogRef<Booking_com>) {}

      booking(){
        (function(d, sc, u) {
          var s:any =  d.createElement(sc);
          var p:any =  d.getElementsByTagName(sc)[0];
          s.type = 'text/javascript';
          s.async = true;
          s.src = u + '?v=' + (+new Date());
          p.parentNode.insertBefore(s,p);
        })(document, 'script', '//aff.bstatic.com/static/affiliate_base/js/flexiproduct.js');
      }
    }
</code>```

The images show that it works the first time but not he second time.... Any idea as to why this is happening and how to solve this issue would be great.

答:
Examining affiliate script we can see, that when this script is loaded, it calls once BookingAff.run() function, which looks like:

```<code>function u() {
  if (_i_("5fc:14"), u.already_ran) return _r_();
  u.already_ran = !0;
</code>```

it exits if already_ran flag is already set. So we will need to unset it on every modal open:

```<code>// reset already_ran flag
if (window.BookingAff && window.BookingAff.run.already_ran) {
  window.BookingAff.run.already_ran = false;
}
</code>```

Because of these 2 reasons, booking form is rendered only once at the very first modal open.

also there is an origin check, which allows only booking.com or bstatic.com origins:

```<code>var r, i = new RegExp("(booking|bstatic).com$");
if (!e.origin.match(i)) return _r_();
</code>```

so we cannot just run BookingAff.run() on each modal open from our domain.

The easiest solution would be to call booking() function on each modal open (of course, after resetting already_ran flag).

plunker: https://plnkr.co/edit/IlAa7XJDjQIxd6IgKXIe?p=preview

there is a JS error in my plunker saying

ERROR Error: The selector "dialog-overview-example-dialog" did not match any elements

it comes from the original Google's example at https://material.angular.io/components/component/dialog and their plunker link

Body:
So I am using angular materials with angular4 and I have put html for a booking.com form inside an MdDialogue component. I want this dialogue to popup with the form inside of it when somebody pushes a button. It works as expected 1 time after the app has loaded, but not again. I would like it to work every time. There is no error message so it is unclear to me why this is happening. The logic inside booking() initializes the form.

The html for the booking.com form looks like this.

  Booking.com

Here is what the booking.com component looks like...

...
     openBookings(){
        let dialogRef = this.dialog.open(Booking_com);
        dialogRef.afterClosed().subscribe(result => {
        });
      }

      debug(data){
        console.log(data);
      }

    }

    @Component({
      selector: 'Booking_com',
      templateUrl: 'Booking_com.html',
      styleUrls: ['Booking_com.sass']
    })
    export class Booking_com implements AfterViewInit{

      ngAfterViewInit(): void {
        this.booking();
      }

      constructor(public dialogRef: MdDialogRef<Booking_com>) {}

      booking(){
        (function(d, sc, u) {
          var s:any =  d.createElement(sc);
          var p:any =  d.getElementsByTagName(sc)[0];
          s.type = 'text/javascript';
          s.async = true;
          s.src = u + '?v=' + (+new Date());
          p.parentNode.insertBefore(s,p);
        })(document, 'script', '//aff.bstatic.com/static/affiliate_base/js/flexiproduct.js');
      }
    }

The images show that it works the first time but not he second time.... Any idea as to why this is happening and how to solve this issue would be great.

Body:
Examining affiliate script we can see, that when this script is loaded, it calls once BookingAff.run() function, which looks like:

function u() {
  if (_i_("5fc:14"), u.already_ran) return _r_();
  u.already_ran = !0;

it exits if already_ran flag is already set. So we will need to unset it on every modal open:

// reset already_ran flag
if (window.BookingAff && window.BookingAff.run.already_ran) {
  window.BookingAff.run.already_ran = false;
}

Because of these 2 reasons, booking form is rendered only once at the very first modal open.

also there is an origin check, which allows only booking.com or bstatic.com origins:

var r, i = new RegExp("(booking|bstatic).com$");
if (!e.origin.match(i)) return _r_();

so we cannot just run BookingAff.run() on each modal open from our domain.

The easiest solution would be to call booking() function on each modal open (of course, after resetting already_ran flag).

plunker: https://plnkr.co/edit/IlAa7XJDjQIxd6IgKXIe?p=preview

there is a JS error in my plunker saying

ERROR Error: The selector "dialog-overview-example-dialog" did not match any elements

it comes from the original Google's example at https://material.angular.io/components/component/dialog and their plunker link


来源: stackexchange

问:
How to Fix Visual Studio 2012 error LNK2019: unresolved external symbol "__declspec(dllimport) public: class std::basic_string?
How to fix a Visual Studio 2012 error LNK2019: unresolved external symbol "__declspec(dllimport) public: class std::basic_string?

I've been compiling a solution containing one exe and several static lib projects
on which the exe depends fine with Visual Studio 2008.  The static libs include:

TCL: tcl84tsx.lib

wxWidgets: wxbase.lib

zlib.lib

ws2_32.lib

xerces-c_2.lib

SNMP Research EMANATE: subagent.lib,agent.lib,emanate.lib,pack.lib,mibtable.lib,devkit.lib

etc.

I loaded the solution into Visual Studio 2012 and have compiled all the projects in the solution but when I try to link the exe, I'm getting errors about unresolved symbols for stuff in the standard C++ library like the output below.

I've found lots of people with unresolved symbols like this one but none of the fixes are working for me.  Fixes I've tried so far include

Updating the EXE project by manually adding references to static lib projects on which the exe project depends

Toggling the "treat wchar_t as built-in type" linker option

Output from Visual Studio 2012 linker...

```<code> 1>ace_funcs.obj : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:LBR' specification
 1>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
 1>ComponentX-Win32.lib(MyOrgConsoleSktServer.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentY-Win32.lib(ORBSingleton.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentY-Win32.lib(OrbException.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(ExceptionHelper.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(ComponentCCheckpointImpl.obj) : warning LNK4217: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported in function "public: __thiscall std::logic_error::logic_error(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0logic_error@std@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@1@@Z)
 1>ComponentX-Win32.lib(MyOrgConsole.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentX-Win32.lib(MyOrgThreadFactory.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(PersistenceServiceProxy.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(ComponentBServiceImpl.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(XmlPreferencesHelper.obj) : warning LNK4217: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported in function "private: void __thiscall _CORBA_Sequence_String::copybuffer(unsigned long)" (?copybuffer@_CORBA_Sequence_String@@AAEXK@Z)
 1>ComponentZ-Win32.lib(XmlHelper.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : warning LNK4217: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported in function "public: __thiscall std::logic_error::logic_error(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0logic_error@std@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@1@@Z)
 1>ComponentA-Win32.lib(propertyutil.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentA-Win32.lib(SystemEnvironment.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(PersistenceClient.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentY-Win32.lib(OrbException.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 1>ComponentX-Win32.lib(MyOrgConsole.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 1>ComponentX-Win32.lib(MyOrgThreadFactory.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 1>ComponentX-Win32.lib(MyOrgConsoleSktServer.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 1>ComponentY-Win32.lib(ORBSingleton.obj) : warning LNK4217: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported in function "public: virtual __thiscall OrbException::~OrbException(void)" (??1OrbException@@UAE@XZ)
 1>ComponentZ-Win32.lib(XmlPreferencesHelper.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 -- snip --
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::substr(unsigned int,unsigned int)const " (__imp_?substr@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBE?AV12@II@Z) referenced in function "private: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall ServiceBootstrap::trimmed(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (?trimmed@ServiceBootstrap@@AAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV23@PBD@Z)
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: unsigned int __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::find_last_not_of(char const *,unsigned int,unsigned int)const " (__imp_?find_last_not_of@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEIPBDII@Z) referenced in function "private: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall ServiceBootstrap::trimmed(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (?trimmed@ServiceBootstrap@@AAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV23@PBD@Z)
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: unsigned int __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::find_first_not_of(char const *,unsigned int,unsigned int)const " (__imp_?find_first_not_of@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEIPBDII@Z) referenced in function "private: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall ServiceBootstrap::trimmed(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (?trimmed@ServiceBootstrap@@AAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV23@PBD@Z)
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::operator+<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (__imp_??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@PBD@Z) referenced in function "private: void __thiscall ServiceBootstrap::verifyBootstrapProperties(void)" (?verifyBootstrapProperties@ServiceBootstrap@@AAEXXZ)
 1>ComponentZ-Win32.lib(PersistenceServiceProxy.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::operator+<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (__imp_??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@PBD@Z)
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::operator+<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (__imp_??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@0@Z) referenced in function "public: class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,struct std::less<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > > __thiscall ServiceBootstrap::getBootstrapProperties(void)" (?getBootstrapProperties@ServiceBootstrap@@QAE?AV?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V12@U?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V12@@std@@@2@@std@@XZ)
 1>ComponentZ-Win32.lib(PersistenceServiceProxy.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::operator+<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (__imp_??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@0@Z)
 1>ComponentA-Win32.lib(propertyutil.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::_Mutex::_Lock(void)" (__imp_?_Lock@_Mutex@std@@QAEXXZ) referenced in function "public: __thiscall std::basic_ostream<char,struct std::char_traits<char> >::_Sentry_base::_Sentry_base(class std::basic_ostream<char,struct std::char_traits<char> > &)" (??0_Sentry_base@?$basic_ostream@DU?$char_traits@D@std@@@std@@QAE@AAV12@@Z)
 1>ComponentZ-Win32.lib(XmlHelper.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::_Mutex::_Lock(void)" (__imp_?_Lock@_Mutex@std@@QAEXXZ)
 -- snip --
 1>.\Debug/sComponentC.exe : fatal error LNK1120: 22 unresolved externals
 ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

答:
If you have already tried below options:

Updating the EXE project by manually adding references to static lib projects on which the exe project depends

Toggling the "treat wchar_t as built-in type" option

Try configuring your project to x64 by following steps:

Right click on Solution 'ProjectName'

Select Configuration Manager...

Change the platform of the project which you are trying to link .lib file to x64 from Win32 (or vise versa)

Rebuild the solution

This actually resolved my problem. I wasn't aware if my external lib is compiled for 32-bit or 64-bit.

ContentLicense: CC BY-SA 3.0

Body:
How to fix a Visual Studio 2012 error LNK2019: unresolved external symbol "__declspec(dllimport) public: class std::basic_string?

I've been compiling a solution containing one exe and several static lib projects
on which the exe depends fine with Visual Studio 2008.  The static libs include:

TCL: tcl84tsx.lib

wxWidgets: wxbase.lib

zlib.lib

ws2_32.lib

xerces-c_2.lib

SNMP Research EMANATE: subagent.lib,agent.lib,emanate.lib,pack.lib,mibtable.lib,devkit.lib

etc.

I loaded the solution into Visual Studio 2012 and have compiled all the projects in the solution but when I try to link the exe, I'm getting errors about unresolved symbols for stuff in the standard C++ library like the output below.

I've found lots of people with unresolved symbols like this one but none of the fixes are working for me.  Fixes I've tried so far include

Updating the EXE project by manually adding references to static lib projects on which the exe project depends

Toggling the "treat wchar_t as built-in type" linker option

Output from Visual Studio 2012 linker...

 1>ace_funcs.obj : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:LBR' specification
 1>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
 1>ComponentX-Win32.lib(MyOrgConsoleSktServer.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentY-Win32.lib(ORBSingleton.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentY-Win32.lib(OrbException.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(ExceptionHelper.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(ComponentCCheckpointImpl.obj) : warning LNK4217: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported in function "public: __thiscall std::logic_error::logic_error(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0logic_error@std@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@1@@Z)
 1>ComponentX-Win32.lib(MyOrgConsole.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentX-Win32.lib(MyOrgThreadFactory.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(PersistenceServiceProxy.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(ComponentBServiceImpl.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(XmlPreferencesHelper.obj) : warning LNK4217: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported in function "private: void __thiscall _CORBA_Sequence_String::copybuffer(unsigned long)" (?copybuffer@_CORBA_Sequence_String@@AAEXK@Z)
 1>ComponentZ-Win32.lib(XmlHelper.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : warning LNK4217: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported in function "public: __thiscall std::logic_error::logic_error(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0logic_error@std@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@1@@Z)
 1>ComponentA-Win32.lib(propertyutil.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentA-Win32.lib(SystemEnvironment.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentZ-Win32.lib(PersistenceClient.obj) : warning LNK4049: locally defined symbol ??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)) imported
 1>ComponentY-Win32.lib(OrbException.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 1>ComponentX-Win32.lib(MyOrgConsole.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 1>ComponentX-Win32.lib(MyOrgThreadFactory.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 1>ComponentX-Win32.lib(MyOrgConsoleSktServer.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 1>ComponentY-Win32.lib(ORBSingleton.obj) : warning LNK4217: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported in function "public: virtual __thiscall OrbException::~OrbException(void)" (??1OrbException@@UAE@XZ)
 1>ComponentZ-Win32.lib(XmlPreferencesHelper.obj) : warning LNK4049: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported
 -- snip --
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::substr(unsigned int,unsigned int)const " (__imp_?substr@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBE?AV12@II@Z) referenced in function "private: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall ServiceBootstrap::trimmed(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (?trimmed@ServiceBootstrap@@AAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV23@PBD@Z)
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: unsigned int __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::find_last_not_of(char const *,unsigned int,unsigned int)const " (__imp_?find_last_not_of@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEIPBDII@Z) referenced in function "private: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall ServiceBootstrap::trimmed(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (?trimmed@ServiceBootstrap@@AAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV23@PBD@Z)
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: unsigned int __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::find_first_not_of(char const *,unsigned int,unsigned int)const " (__imp_?find_first_not_of@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEIPBDII@Z) referenced in function "private: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall ServiceBootstrap::trimmed(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (?trimmed@ServiceBootstrap@@AAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV23@PBD@Z)
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::operator+<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (__imp_??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@PBD@Z) referenced in function "private: void __thiscall ServiceBootstrap::verifyBootstrapProperties(void)" (?verifyBootstrapProperties@ServiceBootstrap@@AAEXXZ)
 1>ComponentZ-Win32.lib(PersistenceServiceProxy.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::operator+<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (__imp_??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@PBD@Z)
 1>ComponentA-Win32.lib(ServiceBootstrap.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::operator+<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (__imp_??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@0@Z) referenced in function "public: class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,struct std::less<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > > __thiscall ServiceBootstrap::getBootstrapProperties(void)" (?getBootstrapProperties@ServiceBootstrap@@QAE?AV?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V12@U?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V12@@std@@@2@@std@@XZ)
 1>ComponentZ-Win32.lib(PersistenceServiceProxy.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::operator+<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (__imp_??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@ABV10@0@Z)
 1>ComponentA-Win32.lib(propertyutil.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::_Mutex::_Lock(void)" (__imp_?_Lock@_Mutex@std@@QAEXXZ) referenced in function "public: __thiscall std::basic_ostream<char,struct std::char_traits<char> >::_Sentry_base::_Sentry_base(class std::basic_ostream<char,struct std::char_traits<char> > &)" (??0_Sentry_base@?$basic_ostream@DU?$char_traits@D@std@@@std@@QAE@AAV12@@Z)
 1>ComponentZ-Win32.lib(XmlHelper.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::_Mutex::_Lock(void)" (__imp_?_Lock@_Mutex@std@@QAEXXZ)
 -- snip --
 1>.\Debug/sComponentC.exe : fatal error LNK1120: 22 unresolved externals
 ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


问:
Count the number of likert scale results from multiple column questions in pandas
I have the following dataframe:

```<code>       Question1        Question2         Question3          Question4
User1  Agree            Agree          Disagree         Strongly Disagree
User2  Disagree         Agree          Agree            Disagree
User3  Agree            Agree          Agree            Agree
</code>```

Is there a way to convert the dataframe listed above to the following?

```<code>              Agree         Disagree         Strongly Disagree
 Question1    2               1                  0

 Question2    2               1                  0

 Question3    2               1                  0
 Question4    1               1                  1
</code>```

This is similar to my previous question: Make a dataframe with grouped questions from three columns

I tried looking at previous questions with stack/pivot but could not figure it out.  The actual dataframe has 20+ questions and a likert scale from strongly agree, agree, neutral, disagree, strongly disagree.

答:
```<code>df.apply(lambda x:x.value_counts()).fillna(0).astype(int)
#                   Question1  Question2  Question3  Question4
#Agree                      2          3          2          1
#Disagree                   1          0          1          1
#Strongly Disagree          0          0          0          1
</code>```

Body:
I have the following dataframe:

       Question1        Question2         Question3          Question4
User1  Agree            Agree          Disagree         Strongly Disagree
User2  Disagree         Agree          Agree            Disagree
User3  Agree            Agree          Agree            Agree

Is there a way to convert the dataframe listed above to the following?

              Agree         Disagree         Strongly Disagree
 Question1    2               1                  0

 Question2    2               1                  0

 Question3    2               1                  0
 Question4    1               1                  1

This is similar to my previous question: Make a dataframe with grouped questions from three columns

I tried looking at previous questions with stack/pivot but could not figure it out.  The actual dataframe has 20+ questions and a likert scale from strongly agree, agree, neutral, disagree, strongly disagree.


问:
How do I check if an object's type is a particular subclass in C++?
I was thinking along the lines of using typeid() but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)

答:
I was thinking along the lines of using typeid()...

Well, yes, it could be done by comparing: typeid().name(). If we take the already described situation, where:

```<code>class Base;
class A : public Base {...};
class B : public Base {...};

void foo(Base *p)
{
  if(/* p is A */) /* do X */
  else /* do Y */
}
</code>```

A possible implementation of foo(Base *p) would be:

```<code>#include <typeinfo>

void foo(Base *p)
{
    if(typeid(*p) == typeid(A))
    {
        // the pointer is pointing to the derived class A
    }
    else if (typeid(*p).name() == typeid(B).name())
    {
        // the pointer is pointing to the derived class B
    }
}
</code>```

OwnerDisplayName: Chad

LastEditorDisplayName: Oddthinking

Body:
I was thinking along the lines of using typeid()...

Well, yes, it could be done by comparing: typeid().name(). If we take the already described situation, where:

class Base;
class A : public Base {...};
class B : public Base {...};

void foo(Base *p)
{
  if(/* p is A */) /* do X */
  else /* do Y */
}

A possible implementation of foo(Base *p) would be:

#include <typeinfo>

void foo(Base *p)
{
    if(typeid(*p) == typeid(A))
    {
        // the pointer is pointing to the derived class A
    }
    else if (typeid(*p).name() == typeid(B).name())
    {
        // the pointer is pointing to the derived class B
    }
}


问:
object not stopping at target location
I have a game where you click and the object moves to it. It stops at the target sometimes but other times keep going... I'm really confused to what might be causing this issue. Hopefully its not something easy xD as I've been coding for a while now. Any ideas/tips feel free to leave in the comments. ;)

Mouse

```<code>@Override
public void mousePressed(MouseEvent e) {
    c.x = e.getX();
    c.y = e.getY();

    if (unit == false) {
        if (s == false) {
            for (Hazmat h1 : outbreak.hazmat) {
                if (c.getBounds().intersects(h1.bounds) || c.contains(h1.bounds)) {
                    selected = h1;
                    s = true;
                    unit = true;
                    Info.log("Selected unit. (First)");

                }
            }
        }
    } else {
        selected.re = true;

        Info.log("Sending unit to location!");
        targetX = e.getX();
        targetY = e.getY();
        selected.targetX = e.getX();
        selected.targetY = e.getY();

        float xSpeed = (targetX - (float) selected.x) / .1f;
        float ySpeed = (targetY - (float) selected.y) / .1f;
        float factor = (float) (1.0f / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed));
        xSpeed *= factor;
        ySpeed *= factor;
        selected.velx = xSpeed;
        selected.vely = ySpeed;
        s = false;
        unit = false;
        Info.log("-----------------");
        Info.log("xSpeed: " + xSpeed);
        Info.log("ySpeed: " + ySpeed);
        Info.log("Factor: " + factor);
        Info.log("TargetX: " + targetX);
        Info.log("TargetY: " + targetY);
        Info.log("-----------------");
    }
}
</code>```

Object

```<code>x += velx;
y += vely;
bounds.x = (int) x;
bounds.y = (int) y;

if (re == true) {
    if (bounds.x == targetX && bounds.y == targetY) {
        velx = 0;
        vely = 0;
        Info.log("[!] Target Point Reached [!]");
        re = false;
    }
}
</code>```

答:
Checking if two floating point values are equal oftentimes runs into problems of very small precision errors. The values bounds.x and targetX might be 0.00000001 points apart, but your check bounds.x == targetX would fail.

Instead, try something like this:

```<code>if ((bounds.x - targetX) < 0.0001 && (bounds.y - targetY) < 0.0001)
</code>```

Title: object not stopping at target location

Body:
I have a game where you click and the object moves to it. It stops at the target sometimes but other times keep going... I'm really confused to what might be causing this issue. Hopefully its not something easy xD as I've been coding for a while now. Any ideas/tips feel free to leave in the comments. ;)

Mouse

@Override
public void mousePressed(MouseEvent e) {
    c.x = e.getX();
    c.y = e.getY();

    if (unit == false) {
        if (s == false) {
            for (Hazmat h1 : outbreak.hazmat) {
                if (c.getBounds().intersects(h1.bounds) || c.contains(h1.bounds)) {
                    selected = h1;
                    s = true;
                    unit = true;
                    Info.log("Selected unit. (First)");

                }
            }
        }
    } else {
        selected.re = true;

        Info.log("Sending unit to location!");
        targetX = e.getX();
        targetY = e.getY();
        selected.targetX = e.getX();
        selected.targetY = e.getY();

        float xSpeed = (targetX - (float) selected.x) / .1f;
        float ySpeed = (targetY - (float) selected.y) / .1f;
        float factor = (float) (1.0f / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed));
        xSpeed *= factor;
        ySpeed *= factor;
        selected.velx = xSpeed;
        selected.vely = ySpeed;
        s = false;
        unit = false;
        Info.log("-----------------");
        Info.log("xSpeed: " + xSpeed);
        Info.log("ySpeed: " + ySpeed);
        Info.log("Factor: " + factor);
        Info.log("TargetX: " + targetX);
        Info.log("TargetY: " + targetY);
        Info.log("-----------------");
    }
}

Object

x += velx;
y += vely;
bounds.x = (int) x;
bounds.y = (int) y;

if (re == true) {
    if (bounds.x == targetX && bounds.y == targetY) {
        velx = 0;
        vely = 0;
        Info.log("[!] Target Point Reached [!]");
        re = false;
    }
}

Body:
Checking if two floating point values are equal oftentimes runs into problems of very small precision errors. The values bounds.x and targetX might be 0.00000001 points apart, but your check bounds.x == targetX would fail.

Instead, try something like this:

if ((bounds.x - targetX) < 0.0001 && (bounds.y - targetY) < 0.0001)


问:
NodeSet exception while using agilitypack
```<code>private void ShowStatistics_Click(object sender, RoutedEventArgs e)
    {
        HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();
        HtmlWeb hw = new HtmlWeb();
        doc = hw.Load("http://www.gamerankings.com/browse.html");
        HtmlNodeCollection nodes= doc.DocumentNode.SelectNodes("//a/");
        string result = "";
        foreach (var item in nodes)
        {
            result += item.InnerText+Environment.NewLine;
        }
        Info.ItemsSource = result;

    }
</code>```

By pressing the button i want to get information from the webpage in a textbox called Info.
After pressing the button I get an exception saying that the result of expression should be NodeSet, what should I do? I'm using agility pack

答:
Your XPATH is wrong. You can use this instead if you want to get all hyperlink elements</p>

```<code>var nodes = doc.DocumentNode.Descendants("a");
</code>```

Body:
private void ShowStatistics_Click(object sender, RoutedEventArgs e)
    {
        HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();
        HtmlWeb hw = new HtmlWeb();
        doc = hw.Load("http://www.gamerankings.com/browse.html");
        HtmlNodeCollection nodes= doc.DocumentNode.SelectNodes("//a/");
        string result = "";
        foreach (var item in nodes)
        {
            result += item.InnerText+Environment.NewLine;
        }
        Info.ItemsSource = result;

    }

By pressing the button i want to get information from the webpage in a textbox called Info.
After pressing the button I get an exception saying that the result of expression should be NodeSet, what should I do? I'm using agility pack

Body:
Your XPATH is wrong. You can use this instead if you want to get all hyperlink elements

var nodes = doc.DocumentNode.Descendants("a");


问:
if statement including hover() and window width
i'm certain new with all this, i have this for now:

```<code>$( document ).ready(function() {

   $('.item').hover(
      function(){
          $(this).find('.hola').slideDown(250); //.fadeIn(250)
      },
      function(){
          $(this).find('.hola').stop(true, false).slideUp(250); //.fadeOut(205)
      }
   );

});
</code>```

i need this code to be disabled on small screens, this is my code that i want it to work:

You can watch my code in codepen

IMAGE OF DISPLAY IN SMALL SCREEN

i dont want to this to happen, i need to disable ".hola" neither in hover.

i try and try to disable it but i dont achieve it

答:
You need to move the if statement before the event </p>

```<code>$(document).ready(function(){

  if ($(window).width() > 480) {
    $(".item").hover(function(){
      function(){
          $(this).find('.hello').slideDown(250); //.fadeIn(250)
      },
      function(){
          $(this).find('.hello').slideUp(250); //.fadeOut(205)
      }
    });
  }

});
</code>```

Body:
i'm certain new with all this, i have this for now:

$( document ).ready(function() {

   $('.item').hover(
      function(){
          $(this).find('.hola').slideDown(250); //.fadeIn(250)
      },
      function(){
          $(this).find('.hola').stop(true, false).slideUp(250); //.fadeOut(205)
      }
   );

});

i need this code to be disabled on small screens, this is my code that i want it to work:

You can watch my code in codepen

IMAGE OF DISPLAY IN SMALL SCREEN

i dont want to this to happen, i need to disable ".hola" neither in hover.

i try and try to disable it but i dont achieve it

Body:
You need to move the if statement before the event

$(document).ready(function(){

  if ($(window).width() > 480) {
    $(".item").hover(function(){
      function(){
          $(this).find('.hello').slideDown(250); //.fadeIn(250)
      },
      function(){
          $(this).find('.hello').slideUp(250); //.fadeOut(205)
      }
    });
  }

});


问:
Non-static variable cannot be referenced from a static context
I've written this test code:

```<code>class MyProgram
{
    int count = 0;
    public static void main(String[] args)
    {
        System.out.println(count);
    }
}
</code>```

But it gives the following error:

```<code>Main.java:6: error: non-static variable count cannot be referenced from a static context
        System.out.println(count);
                           ^
</code>```

How do I get my methods to recognize my class variables?

答:
This is bit diff to explain about static key word for all beginners.

You wil get to know it clearly when you work more with Classes and Objects.

|*| Static : Static items can be called with Class Name

If you observe in codes, Some functions are directly called with Class names like

```<code>NamCls.NamFnc();

System.out.println();
</code>```

This is because NamFnc and println wil be declared using key word static before them.

|*| Non Static :Non Static items can be called with Class Variable

If its not static, you need a variable of the class,

put dot after the class variable and

then call function.

```<code>NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
</code>```

Below code explains you neatly

|*| Static and non Static function in class :

```<code>public class NamCls
{
    public static void main(String[] args)
    {
        PlsPrnFnc("Tst Txt");

        NamCls NamObjVar = new NamCls();
        NamObjVar.PrnFnc("Tst Txt");
    }

    static void PlsPrnFnc(String SrgPsgVal)
    {
        System.out.println(SrgPsgVal);
    }

    void PrnFnc(String SrgPsgVal)
    {
        System.out.println(SrgPsgVal);
    }
}
</code>```

|*| Static and non Static Class inside a Class :

```<code>public class NamCls
{
    public static void main(String[] args)
    {
        NamTicCls NamTicVaj = new NamTicCls();
        NamTicVaj.PrnFnc("Tst Txt");

        NamCls NamObjVar = new NamCls();
        NamNicCls NamNicVar = NamObjVar.new NamNicCls();
        NamNicVar.PrnFnc("Tst Txt");
    }

    static class NamTicCls
    {
        void PrnFnc(String SrgPsgVal)
        {
            System.out.println(SrgPsgVal);
        }
    }

    class NamNicCls
    {
        void PrnFnc(String SrgPsgVal)
        {
            System.out.println(SrgPsgVal);
        }
    }
}
</code>```

Body:
I've written this test code:

class MyProgram
{
    int count = 0;
    public static void main(String[] args)
    {
        System.out.println(count);
    }
}

But it gives the following error:

Main.java:6: error: non-static variable count cannot be referenced from a static context
        System.out.println(count);
                           ^

How do I get my methods to recognize my class variables?

Body:
This is bit diff to explain about static key word for all beginners.

You wil get to know it clearly when you work more with Classes and Objects.

|*| Static : Static items can be called with Class Name

If you observe in codes, Some functions are directly called with Class names like

NamCls.NamFnc();

System.out.println();

This is because NamFnc and println wil be declared using key word static before them.

|*| Non Static :Non Static items can be called with Class Variable

If its not static, you need a variable of the class,

put dot after the class variable and

then call function.

NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();

Below code explains you neatly

|*| Static and non Static function in class :

public class NamCls
{
    public static void main(String[] args)
    {
        PlsPrnFnc("Tst Txt");

        NamCls NamObjVar = new NamCls();
        NamObjVar.PrnFnc("Tst Txt");
    }

    static void PlsPrnFnc(String SrgPsgVal)
    {
        System.out.println(SrgPsgVal);
    }

    void PrnFnc(String SrgPsgVal)
    {
        System.out.println(SrgPsgVal);
    }
}

|*| Static and non Static Class inside a Class :

public class NamCls
{
    public static void main(String[] args)
    {
        NamTicCls NamTicVaj = new NamTicCls();
        NamTicVaj.PrnFnc("Tst Txt");

        NamCls NamObjVar = new NamCls();
        NamNicCls NamNicVar = NamObjVar.new NamNicCls();
        NamNicVar.PrnFnc("Tst Txt");
    }

    static class NamTicCls
    {
        void PrnFnc(String SrgPsgVal)
        {
            System.out.println(SrgPsgVal);
        }
    }

    class NamNicCls
    {
        void PrnFnc(String SrgPsgVal)
        {
            System.out.println(SrgPsgVal);
        }
    }
}


问:
In JMeter how can I capture multiple (varying) values of a regular expression?
I need to parse a html page that can contain multiple (unspecified how many) links.
Here an example (pseudo html):

```<code><a href="../entrygroups/GROUPIDENTIFIER/3">edit</a>
[...]
<a href="../entrygroups/GROUPIDENTIFIER/7">edit</a>
[...]
<a href="../entrygroups/GROUPIDENTIFIER/12">edit</a>
[...]
<a href="../entrygroups/GROUPIDENTIFIER/16">edit</a>
</code>```

I am basically just interested in the numbers 3,7,12,16 of the url.

Is there a way to put those values into some sort of array and loop over them (in a for each kind of way).

Is this possible and if so, how would I do this?
I looked at the regular expression extractor but it seems that that one can only assign a fixed set of groups to a fixed set of variables.

答:
Actually RegEx extractor is able to do exactly what you want, if you specify Match No. field with less than 0, e.g. -1:

As a result, you will get N variables (using your input as example):

```<code>id_1=3
id_2=7
id_3=12
id_4=16
</code>```

There also will be variable which has a count of matches:

```<code>id_matchNr=4
</code>```

Body:
I need to parse a html page that can contain multiple (unspecified how many) links.
Here an example (pseudo html):

edit
[...]
edit
[...]
edit
[...]
edit

I am basically just interested in the numbers 3,7,12,16 of the url.

Is there a way to put those values into some sort of array and loop over them (in a for each kind of way).

Is this possible and if so, how would I do this?
I looked at the regular expression extractor but it seems that that one can only assign a fixed set of groups to a fixed set of variables.

Body:
Actually RegEx extractor is able to do exactly what you want, if you specify Match No. field with less than 0, e.g. -1:

As a result, you will get N variables (using your input as example):

id_1=3
id_2=7
id_3=12
id_4=16

There also will be variable which has a count of matches:

id_matchNr=4


问:
Bulk Procedure Call Node MySQL
This is similar to insert multiple rows into mysql through node.js but is about procedures instead.

I'd like to call a procedure in bulk (over 10k times).

Doing this all in separate calls in incredibly slow (at about 20 inserts per second, as the procedure inserts things).

How do I call a procedure multiple times, efficiently using a single database call?

I could just build up a string of CALL procedure(args...); and call that but is there a better, more quick and efficient way?

答:
You can do it by executing multiple statements in a single query.

First of all you should create your connection using mysql module with the multipleStatements option enabled:

```<code>var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db',
  multipleStatements: true
});
</code>```

Then you need to concatenate each of your procedure calls into a single string. Don't forget the semicolon ; .

```<code>var procCalls = "CALL procedure(arg1a, arg1b);" +
    "CALL procedure(arg2a, arg2b);" +
    "CALL procedure(arg3a, arg3b);" +
    "CALL procedure(arg4a, arg4b);" +
    "CALL procedure(arg5a, arg5b);" +
    "CALL procedure(arg6a, arg6b);" +
    "CALL procedure(arg7a, arg7b);";
// You might want to do it in a loop
</code>```

Finally, just execute your concatenated string query using the multiple-statement enabled connection:

```<code>connection.query(procCalls , function (error, results, fields) {
  if (error) throw error;
  // Success!
});
</code>```

Title: Bulk Procedure Call Node MySQL

Body:
You can do it by executing multiple statements in a single query.

First of all you should create your connection using mysql module with the multipleStatements option enabled:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db',
  multipleStatements: true
});

Then you need to concatenate each of your procedure calls into a single string. Don't forget the semicolon ; .

var procCalls = "CALL procedure(arg1a, arg1b);" +
    "CALL procedure(arg2a, arg2b);" +
    "CALL procedure(arg3a, arg3b);" +
    "CALL procedure(arg4a, arg4b);" +
    "CALL procedure(arg5a, arg5b);" +
    "CALL procedure(arg6a, arg6b);" +
    "CALL procedure(arg7a, arg7b);";
// You might want to do it in a loop

Finally, just execute your concatenated string query using the multiple-statement enabled connection:

connection.query(procCalls , function (error, results, fields) {
  if (error) throw error;
  // Success!
});


问:
LREM a "big" string or SET/GET + LREM a "small" string
I hope this doesn't come up as too much an open-ended question.

I'm using RPOPLPUSH to implement a reliable queue and I'm trying to evaluate the tradeoffs between having the (possibly big) string value (e.g. JSON) directly in the list or by having only a "key" in the list and storing/retrieving the value using SET/GET (i.e. 2 extra calls), in this case, LREM is still O(N), but the string being smaller, should perform better.

Something I have not considered ?

答:
You should test it yourself.

That said, memory allocation/deallocation is faster than network so a large string will probably perform better.


问:
How to use url with parameter in blade Laravel
I try to use different stylesheets in my master.blade.php for different pages. When I use simple routes it works.

@if ( Request::path() == 'videos/alpes')
   <link rel="stylesheet" href="{{ URL::asset('/css/style-vid.css') }}" type="text/css" media="all">
@elseif (Request::path() == 'texts')
   <link rel="stylesheet" href="{{ URL::asset('/css/style-lir.css') }}" type="text/css" media="all">
@else
   <link rel="stylesheet" href="{{ URL::asset('/css/style-all-together.css') }}" type="text/css" media="all">
```

<p>But I can't find the way to use in <code>@if</code> statement a route with parameters i.e.</p>

```Route::get('/videos/{video}', 'VideoController@show');
```

I try to do it for all videos, not just for one of them (alpes). Is  there a simple way to do this?

答:
Try use action helper:

The action function generates a URL for the given controller action. You do not need to pass the full namespace to the controller. Instead, pass the controller class name relative to the  App\Http\Controllers namespace:

$url = action('HomeController@getIndex');

If the method accepts route parameters, you may pass them as the second argument to the method:

$url = action('UserController@profile', ['id' => 1]);

In your variant:

```<code>@if(Request::url() == action('VideoController@show', ['video' => $video]))
    //some code
@endif
</code>```

You can change your code Request::path() == 'videos/alpes' to Request::is('video/alpes')

Body:
I try to use different stylesheets in my master.blade.php for different pages. When I use simple routes it works.

@if ( Request::path() == 'videos/alpes')
   <link rel="stylesheet" href="{{ URL::asset('/css/style-vid.css') }}" type="text/css" media="all">
@elseif (Request::path() == 'texts')
   <link rel="stylesheet" href="{{ URL::asset('/css/style-lir.css') }}" type="text/css" media="all">
@else
   <link rel="stylesheet" href="{{ URL::asset('/css/style-all-together.css') }}" type="text/css" media="all">

But I can't find the way to use in @if statement a route with parameters i.e.

Route::get('/videos/{video}', 'VideoController@show');

I try to do it for all videos, not just for one of them (alpes). Is  there a simple way to do this?

Body:
Try use action helper:

The action function generates a URL for the given controller action. You do not need to pass the full namespace to the controller. Instead, pass the controller class name relative to the  App\Http\Controllers namespace:

$url = action('HomeController@getIndex');

If the method accepts route parameters, you may pass them as the second argument to the method:

$url = action('UserController@profile', ['id' => 1]);

In your variant:

@if(Request::url() == action('VideoController@show', ['video' => $video]))
    //some code
@endif

You can change your code Request::path() == 'videos/alpes' to Request::is('video/alpes')


问:
Google Spreadsheet API v4 In Java. Trying to have unprotected cell range on a document that can be viewed to anyone with link
So I want to be able to create a sheet, populate it with some data, and create a column used for input, but I want to protect all other cells. I am using Java / eclipse to run the API.

The issue I am having seems to be a bug of some kind. When I open the document, it notifies me that I (the owner) am the only one who can edit the range, but when logged into an incognito window it states that "You and one other user can edit this sheet". Anyone with the link can edit any cell in the document, despite it stating that "Sheet1 except A1:A18" in the protected ranges.

Strange thing I noticed also, if I as owner go into Protected Ranges, click on my generated range and click Permissions -> Done, it finalizes my range to how it should behave. Problem is in the final product I cannot be going into these files manually.

The order I am going in is:
Create File -> Add Data -> Set Unprotected range -> Set view able by anyone with link.

After adding the range, it looks on the sheet itself exactly how it would if I were to add it in myself, but it doesn't behave the same way. Has anyone had any luck with this process? I have included my request for the protected range below.

If you need any more information I will try and respond as soon as possible.

```<code>public Request unProtectRange(String id, GridRange range) {
    List<GridRange> grids = new ArrayList<GridRange>();
    grids.add(range);
    return new Request()
        .setAddProtectedRange(new AddProtectedRangeRequest()
            .setProtectedRange(new ProtectedRange()
                .setRequestingUserCanEdit(false)
                    .setRange(new GridRange())
                        .setUnprotectedRanges(grids)));
}
</code>```

答:
There's a few issues here.  Per the ProtectedRange docs...

The requestingUserCanEdit field is read only, so setting that had no impact.

The editors field is not set, so the protected range is not actually being protected. It defaults to the same access controls as the spreadsheet itself. You must set editors to a valid Editors object.

The GridRange doesn't have a sheetId set on it. That means it will default to the sheet id 0.  You probably want to explicitly set the sheet ID.

Body:
So I want to be able to create a sheet, populate it with some data, and create a column used for input, but I want to protect all other cells. I am using Java / eclipse to run the API.

The issue I am having seems to be a bug of some kind. When I open the document, it notifies me that I (the owner) am the only one who can edit the range, but when logged into an incognito window it states that "You and one other user can edit this sheet". Anyone with the link can edit any cell in the document, despite it stating that "Sheet1 except A1:A18" in the protected ranges.

Strange thing I noticed also, if I as owner go into Protected Ranges, click on my generated range and click Permissions -> Done, it finalizes my range to how it should behave. Problem is in the final product I cannot be going into these files manually.

The order I am going in is:
Create File -> Add Data -> Set Unprotected range -> Set view able by anyone with link.

After adding the range, it looks on the sheet itself exactly how it would if I were to add it in myself, but it doesn't behave the same way. Has anyone had any luck with this process? I have included my request for the protected range below.

If you need any more information I will try and respond as soon as possible.

public Request unProtectRange(String id, GridRange range) {
    List<GridRange> grids = new ArrayList<GridRange>();
    grids.add(range);
    return new Request()
        .setAddProtectedRange(new AddProtectedRangeRequest()
            .setProtectedRange(new ProtectedRange()
                .setRequestingUserCanEdit(false)
                    .setRange(new GridRange())
                        .setUnprotectedRanges(grids)));
}


Title: Difference in output between numpy linspace and numpy logspace

Body:
Numpy linspace returns evenly spaced numbers over a specified interval. Numpy logspace return numbers spaced evenly on a log scale.

I don't understand why numpy logspace often returns values "out of range" from the bounds I set. Take numbers between 0.02 and 2.0:

import numpy as np
print np.linspace(0.02, 2.0, num=20)
print np.logspace(0.02, 2.0, num=20)

The output for the first is:

[ 0.02        0.12421053  0.22842105  0.33263158  0.43684211  0.54105263
  0.64526316  0.74947368  0.85368421  0.95789474  1.06210526  1.16631579
  1.27052632  1.37473684  1.47894737  1.58315789  1.68736842  1.79157895
  1.89578947  2.        ]

That looks correct. However, the output for np.logspace() is wrong:

[   1.04712855    1.33109952    1.69208062    2.15095626    2.73427446
    3.47578281    4.41838095    5.61660244    7.13976982    9.07600522
   11.53732863   14.66613875   18.64345144   23.69937223   30.12640904
   38.29639507   48.68200101   61.88408121   78.6664358   100.        ]

Why does it output 1.047 to 100.0?

Body:
2017 update: The numpy 1.12 includes a function that does exactly what the original question asked, i.e. returns a range between two values evenly sampled in log space.

The function is numpy.geomspace

>>> np.geomspace(0.02, 2.0, 20)
array([ 0.02      ,  0.0254855 ,  0.03247553,  0.04138276,  0.05273302,
        0.06719637,  0.08562665,  0.1091119 ,  0.13903856,  0.17717336,
        0.22576758,  0.28768998,  0.36659614,  0.46714429,  0.59527029,
        0.75853804,  0.96658605,  1.23169642,  1.56951994,  2.        ])


问:
Finding the greatest amount of consecutive values in an array (JS)
I'm trying to solve a problem that I can't seem to wrap my head around and was hoping I could get a little bit of insight from someone more experienced than I am. Basically, I have an array that has anywhere from 10 to 500 values. These values are all either true or false, but they are in a random order. I need to know the greatest amount of times that false appears in a row. For example:

```<code>[false, false, true, false, true, false, true, false, false, false]
</code>```

Should return 3, since it appears 3 times in a row at the most. This seems like a potentially common problem to solve but I couldn't find a solution through searching. Any help would be greatly appreciated!

答:
You can use one value to keep count of consecutive false values and if that value is larger then current max set max value to that value. If value is true you reset counter to 0.

var arr = [false, false, true, false, true, false, true, false, false, false]
var c = 0, max = 0;

arr.forEach(function(e) {
  e == false ? c++ : c = 0;
  if (c > max) max = c;
})

console.log(max)```

Body:
I'm trying to solve a problem that I can't seem to wrap my head around and was hoping I could get a little bit of insight from someone more experienced than I am. Basically, I have an array that has anywhere from 10 to 500 values. These values are all either true or false, but they are in a random order. I need to know the greatest amount of times that false appears in a row. For example:

[false, false, true, false, true, false, true, false, false, false]

Should return 3, since it appears 3 times in a row at the most. This seems like a potentially common problem to solve but I couldn't find a solution through searching. Any help would be greatly appreciated!


问:
Wordpress template files in subdirectory's
A while ago i started a new Wordpress project. But i got into an issue. Since there are multiple designs i need to create multiple templates for pages, posts and text format outputs for on the different page-templates.

So since the're are so many template files i wanted to create some subdirectory's. i know that since Wordpress 3.4 and higher you're able to use the subdirectory name page-templates for all the page templates but how could i use that for the format files and for the post files.

Yes i did try to add functions like:

```<code> get_template_part('/template-parts/page-templates' , 'page');
</code>```

And

```<code>require( get_template_directory() . '/template-parts/template-tags.php' );
</code>```

The ideal directory structure i would like to create is as follows:

```<code>wp-content/themes/mytheme
- archive
- 404
- CSS
- JS
- Images
- template-parts (dir)
-- page-templates (dir for page-template files.)
-- format-templates (dir for format-templates.)
-- post-templates (dir for post-templates.)
- header
- footer
</code>```

So to be clear. I want to create the structure for template files like above. Don't mind the folders like CSS etc. Those are set the correct way. The intention is, after i've succesfully created the structure, to be able to select the templates like a page temple from the /wp-admin edit page section.

答:
WP_Theme class contains the method get_page_templates() that offers this filter:

apply_filters( "theme_{$post_type}_templates", $post_templates, $this, $post, $post_type );

line 1103 of class-wp-theme.php

Keeping in mind that in wordpress post and page are post_types,

add_filter( "theme_post_templates", ... and add_filter( "theme_page_templates",...
should be valid.

Under the codex's "Used By" section for that method, it states:

wp-admin/includes/template.php: page_template_dropdown()

wp-admin/includes/meta-boxes.php: page_attributes_meta_box()

Which leads me to believe it would make them available on the /wp-admin/ edit page section.

Info from core files regarding the filter:

```<code> * Filters list of page templates for a theme.
 *
 * The dynamic portion of the hook name, `$post_type`, refers to the post type.
 * @since 4.7.0 Added the `$post_type` parameter.
 *
 * @param array        $post_templates Array of page templates. Keys are filenames,
 *                                     values are translated names.
 * @param WP_Theme     $this           The theme object.
 * @param WP_Post|null $post           The post being edited, provided for context, or null.
 * @param string       $post_type      Post type to get the templates for.
</code>```

I'm unsure if a relative uri works here or if you need get_theme_file_path(), but am assuming the former.

```<code>function deep_templates( $post_templates, $theme, $post, $post_type )
   $post_templates['/folder/folder/folder/file.php'] = "Page Style One";
   $post_templates['/folder/other-folder/file.php']  = "Page Style Two";
   return $post_templates;
add_filter( 'theme_page_templates', 'deep_templates' );
</code>```

AND/OR

```<code>add_filter( 'theme_post_templates', 'deep_templates' );
add_filter( 'theme_my-custom-cpt_templates', 'deep_templates' );
</code>```

Body:
A while ago i started a new Wordpress project. But i got into an issue. Since there are multiple designs i need to create multiple templates for pages, posts and text format outputs for on the different page-templates.

So since the're are so many template files i wanted to create some subdirectory's. i know that since Wordpress 3.4 and higher you're able to use the subdirectory name page-templates for all the page templates but how could i use that for the format files and for the post files.

Yes i did try to add functions like:

 get_template_part('/template-parts/page-templates' , 'page');

And

require( get_template_directory() . '/template-parts/template-tags.php' );

The ideal directory structure i would like to create is as follows:

wp-content/themes/mytheme
- archive
- 404
- CSS
- JS
- Images
- template-parts (dir)
-- page-templates (dir for page-template files.)
-- format-templates (dir for format-templates.)
-- post-templates (dir for post-templates.)
- header
- footer

So to be clear. I want to create the structure for template files like above. Don't mind the folders like CSS etc. Those are set the correct way. The intention is, after i've succesfully created the structure, to be able to select the templates like a page temple from the /wp-admin edit page section.

Body:
WP_Theme class contains the method get_page_templates() that offers this filter:

apply_filters( "theme_{$post_type}_templates", $post_templates, $this, $post, $post_type );

line 1103 of class-wp-theme.php

Keeping in mind that in wordpress post and page are post_types,

add_filter( "theme_post_templates", ... and add_filter( "theme_page_templates",...
should be valid.

Under the codex's "Used By" section for that method, it states:

wp-admin/includes/template.php: page_template_dropdown()

wp-admin/includes/meta-boxes.php: page_attributes_meta_box()

Which leads me to believe it would make them available on the /wp-admin/ edit page section.

Info from core files regarding the filter:

 * Filters list of page templates for a theme.
 *
 * The dynamic portion of the hook name, `$post_type`, refers to the post type.
 * @since 4.7.0 Added the `$post_type` parameter.
 *
 * @param array        $post_templates Array of page templates. Keys are filenames,
 *                                     values are translated names.
 * @param WP_Theme     $this           The theme object.
 * @param WP_Post|null $post           The post being edited, provided for context, or null.
 * @param string       $post_type      Post type to get the templates for.

I'm unsure if a relative uri works here or if you need get_theme_file_path(), but am assuming the former.

function deep_templates( $post_templates, $theme, $post, $post_type )
   $post_templates['/folder/folder/folder/file.php'] = "Page Style One";
   $post_templates['/folder/other-folder/file.php']  = "Page Style Two";
   return $post_templates;
add_filter( 'theme_page_templates', 'deep_templates' );

AND/OR

add_filter( 'theme_post_templates', 'deep_templates' );
add_filter( 'theme_my-custom-cpt_templates', 'deep_templates' );


问:
Coding in Emacs shell?
I am  using shell in my emacs version 22.2.1 (debian stable repos) and it has some kind of broken coding. For example, if I run `ls' command, output is

```<code>[0m[01;34margouml-0.30.2[0m
</code>```

not "argouml-0.30.2" as normal. I have tried commands C-x RET p utf-8 and so others but without any effect. I have properly generated utf-8 locales and everywhere else in emacs coding works perfect. Does anybody knows what may be wrong with it?

答:
You can also try M-x ansi-term, or even download Multi term and try that too.

Links:

Ansi Term

Multi Term

Title: Coding in Emacs shell?

Body:
I am  using shell in my emacs version 22.2.1 (debian stable repos) and it has some kind of broken coding. For example, if I run `ls' command, output is

[0m[01;34margouml-0.30.2[0m

not "argouml-0.30.2" as normal. I have tried commands C-x RET p utf-8 and so others but without any effect. I have properly generated utf-8 locales and everywhere else in emacs coding works perfect. Does anybody knows what may be wrong with it?

ContentLicense: CC BY-SA 2.5


问:
How to override null and blank field attributes of an abstract model
I want to set null and blank to true on all the fields inherited from an abstract model.

My current attempt follows similar SO questions, e.g. overriding the 'default' attribute on ABC and overriding parent model's attribute, which say it is possible. I get the required runtime behaviour, when initialising objects from the python console, but it is not reflected in the migrations file or database.

Context:

I have a System model where I want to be able to create client specific overrides on certain data. I have the following models:

abstract BaseSystem - defining the overridable fields

concrete SystemOverride - containing the partially overridden records

concrete System - containing the 'full' System records.

It is important to make all the fields in SystemOverride null/blank = True so that only the fields that are initialised (by the client) will override the related System object.

Code:

```<code>class BaseSystem(models.Model):

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        super(BaseSystem, self).__init__(args, kwargs)

        # Mark all fields with 'override' attribute
        for field in self._meta.get_fields():
            field.override = True

    name = models.CharField(max_length=128)

class System(BaseSystem):
    pass

class SystemOverride(BaseSystem):

    def __init__(self, *args, **kwargs):
        super(SystemOverride, self).__init__(args, kwargs)

        # Set all overridable fields to null/blank = True.
        for field in self._meta.get_fields():
            if(hasattr(field, 'override') and field.override):
                field.null = True
                field.blank = True

    # Override-specific fields
    system = models.ForeignKey(System)
</code>```

The result of makemigrations:

```<code>class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='System',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=128)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SystemOverride',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=128)),
                ('system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='overide.System')),
            ],
            options={
                'abstract': False,
            },
        ),
    ]
</code>```

null=True and blank=True have not been added to the name field in SystemOveride.

答: This can't be done in the init of the class. The makemigrations will never see it. You need to do it at the metaclass level.

Body:
I want to set null and blank to true on all the fields inherited from an abstract model.

My current attempt follows similar SO questions, e.g. overriding the 'default' attribute on ABC and overriding parent model's attribute, which say it is possible. I get the required runtime behaviour, when initialising objects from the python console, but it is not reflected in the migrations file or database.

Context:

I have a System model where I want to be able to create client specific overrides on certain data. I have the following models:

abstract BaseSystem - defining the overridable fields

concrete SystemOverride - containing the partially overridden records

concrete System - containing the 'full' System records.

It is important to make all the fields in SystemOverride null/blank = True so that only the fields that are initialised (by the client) will override the related System object.

Code:

class BaseSystem(models.Model):

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        super(BaseSystem, self).__init__(args, kwargs)

        # Mark all fields with 'override' attribute
        for field in self._meta.get_fields():
            field.override = True

    name = models.CharField(max_length=128)

class System(BaseSystem):
    pass

class SystemOverride(BaseSystem):

    def __init__(self, *args, **kwargs):
        super(SystemOverride, self).__init__(args, kwargs)

        # Set all overridable fields to null/blank = True.
        for field in self._meta.get_fields():
            if(hasattr(field, 'override') and field.override):
                field.null = True
                field.blank = True

    # Override-specific fields
    system = models.ForeignKey(System)

The result of makemigrations:

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='System',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=128)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SystemOverride',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=128)),
                ('system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='overide.System')),
            ],
            options={
                'abstract': False,
            },
        ),
    ]

null=True and blank=True have not been added to the name field in SystemOveride.


答:
```<code>var yourArray=[false,true,true,false,false,false,true];
arrayLength = yourArray.length;
var maxCount=0;
var currentCount=0;
var lastElement;

for(var i = 0;i<arrayLength;i++){
    if(lastElement === yourArray[i]){
        currentCount++;
    }
    else{
        if(currentCount>maxCount){
            maxCount=currentCount;
        }
        currentCount=1;
    }
    lastElement=yourArray[i];
}
console.log(maxCount);
</code>```

This should suit your needs

Title: Finding the greatest amount of consecutive values in an array (JS)

Body:
var yourArray=[false,true,true,false,false,false,true];
arrayLength = yourArray.length;
var maxCount=0;
var currentCount=0;
var lastElement;

for(var i = 0;i<arrayLength;i++){
    if(lastElement === yourArray[i]){
        currentCount++;
    }
    else{
        if(currentCount>maxCount){
            maxCount=currentCount;
        }
        currentCount=1;
    }
    lastElement=yourArray[i];
}
console.log(maxCount);

This should suit your needs


问:
ERR_EMPTY_RESPONSE for localhost when running Docker
Here's my Dockerfile:

```<code># CentOs base image
FROM centos:centos6.8

# install python, pip, apache and other packages
RUN yum -y update; yum clean all
RUN yum -y install epel-release; yum clean all
RUN yum -y install centos-release-scl; yum clean all
RUN yum -y install python27; yum clean all
RUN yum -y install python-devel.x86_64; yum clean all
RUN yum -y install python-pip; yum clean all
RUN yum -y install gcc; yum clean all
RUN yum -y install httpd httpd-devel mod_ssl; yum clean all

# Make a non root user so I can run mod_wsgi without root
# USER adm

# install Python modules needed by the Python app
COPY requirements.txt /usr/src/app/
RUN pip install --no-cache-dir -r /usr/src/app/requirements.txt

# copy files required for the app to run
COPY . /usr/src/app/

# tell the port number the container should expose
EXPOSE 80

# run the application
# CMD ["mod_wsgi", "start-server run_apache_server.wsgi"]
# CMD ["cat", "/etc/passwd"]
# CMD ["cat", "/etc/group"]
# CMD ["find", "/"]
CMD ["/bin/sh", "-c", "/usr/bin/mod_wsgi-express start-server run_apache_server.wsgi --user adm --group apache"]
</code>```

I can run the app:

```<code>$ docker run -d -P --name myapp jacobirr/pleromatest
</code>```

And see tcp port 80:

```<code>$ docker port myapp
80/tcp -> 0.0.0.0:32769
</code>```

Here's my requirements.txt:

```<code>Flask==0.10.1
Flask-Restless==0.13.1
Flask-SQLAlchemy==0.16
Jinja2==2.7
MarkupSafe==0.18
SQLAlchemy==0.8.2
Werkzeug==0.9.2
gunicorn==17.5
itsdangerous==0.22
mimerender==0.5.4
python-dateutil==2.1
python-mimeparse==0.1.4
requests==1.2.3
six==1.3.0
wsgiref==0.1.2
setuptools==5.4.2
mod_wsgi==4.5.15
</code>```

Why can't I get to localhost:32769 in the browser? I suspect this is related to:

•the user/group running apache?

•the fact that I'm installing mod_wsgi but it's nowhere on the docker "filesystem" so I have to use mod_wsgi-express?

Update:

'1' Netstat shows:

```<code>[root@9003b0d64916 app]# netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 *:irdmi                     *:*                         LISTEN
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node Path
unix  2      [ ACC ]     STREAM     LISTENING     113181 /tmp/mod_wsgi-localhost:8000:0/wsgi.1.0.1.sock
</code>```

'2' httpd seems to be running in my container:

```<code>[root@9003b0d64916 mod_wsgi-localhost:8000:0]# ps aux | grep httpd
root         1  0.0  0.2  64060  5084 ?        Ss   21:17   0:00 httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8000:0/httpd.conf -k start -DFOREGROUND
adm          6  0.0  0.6 350928 13936 ?        Sl   21:17   0:00 (wsgi:localhost:8000:0)  -f /tmp/mod_wsgi-localhost:8000:0/httpd.conf -k start -DFOREGROUND
adm          7  0.0  0.1  64192  3248 ?        S    21:17   0:00 httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8000:0/httpd.conf -k start -DFOREGROUND
</code>```

答:
From all your outputs, your httpd / uwsgi process is definitely bound to 8000, and this is the port you need to expose on the container.

This line in netstat, is showing a bind on 8000, and nothing else.

```<code>tcp        0      0 *:irdmi                     *:*                         LISTEN
</code>```

It is not obvious here, but if you use the --numeric-ports argument, it will not convert the 8000 into its known port.

In your docker file, again you should

```<code>EXPOSE 8000
</code>```

When launching your container, you can also specify the port to use on the host machine:

```<code>docker run -p 8080:8000 --name ...
</code>```

After this, you should be able to use your browser to hit

```<code>localhost:8080  ->  container:8000
</code>```

Body:
Here's my Dockerfile:

# CentOs base image
FROM centos:centos6.8

# install python, pip, apache and other packages
RUN yum -y update; yum clean all
RUN yum -y install epel-release; yum clean all
RUN yum -y install centos-release-scl; yum clean all
RUN yum -y install python27; yum clean all
RUN yum -y install python-devel.x86_64; yum clean all
RUN yum -y install python-pip; yum clean all
RUN yum -y install gcc; yum clean all
RUN yum -y install httpd httpd-devel mod_ssl; yum clean all

# Make a non root user so I can run mod_wsgi without root
# USER adm

# install Python modules needed by the Python app
COPY requirements.txt /usr/src/app/
RUN pip install --no-cache-dir -r /usr/src/app/requirements.txt

# copy files required for the app to run
COPY . /usr/src/app/

# tell the port number the container should expose
EXPOSE 80

# run the application
# CMD ["mod_wsgi", "start-server run_apache_server.wsgi"]
# CMD ["cat", "/etc/passwd"]
# CMD ["cat", "/etc/group"]
# CMD ["find", "/"]
CMD ["/bin/sh", "-c", "/usr/bin/mod_wsgi-express start-server run_apache_server.wsgi --user adm --group apache"]

I can run the app:

$ docker run -d -P --name myapp jacobirr/pleromatest

And see tcp port 80:

$ docker port myapp
80/tcp -> 0.0.0.0:32769

Here's my requirements.txt:

Flask==0.10.1
Flask-Restless==0.13.1
Flask-SQLAlchemy==0.16
Jinja2==2.7
MarkupSafe==0.18
SQLAlchemy==0.8.2
Werkzeug==0.9.2
gunicorn==17.5
itsdangerous==0.22
mimerender==0.5.4
python-dateutil==2.1
python-mimeparse==0.1.4
requests==1.2.3
six==1.3.0
wsgiref==0.1.2
setuptools==5.4.2
mod_wsgi==4.5.15

Why can't I get to localhost:32769 in the browser? I suspect this is related to:

•the user/group running apache?

•the fact that I'm installing mod_wsgi but it's nowhere on the docker "filesystem" so I have to use mod_wsgi-express?

Update:

'1' Netstat shows:

[root@9003b0d64916 app]# netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 *:irdmi                     *:*                         LISTEN
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node Path
unix  2      [ ACC ]     STREAM     LISTENING     113181 /tmp/mod_wsgi-localhost:8000:0/wsgi.1.0.1.sock

'2' httpd seems to be running in my container:

[root@9003b0d64916 mod_wsgi-localhost:8000:0]# ps aux | grep httpd
root         1  0.0  0.2  64060  5084 ?        Ss   21:17   0:00 httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8000:0/httpd.conf -k start -DFOREGROUND
adm          6  0.0  0.6 350928 13936 ?        Sl   21:17   0:00 (wsgi:localhost:8000:0)  -f /tmp/mod_wsgi-localhost:8000:0/httpd.conf -k start -DFOREGROUND
adm          7  0.0  0.1  64192  3248 ?        S    21:17   0:00 httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8000:0/httpd.conf -k start -DFOREGROUND

Body:
From all your outputs, your httpd / uwsgi process is definitely bound to 8000, and this is the port you need to expose on the container.

This line in netstat, is showing a bind on 8000, and nothing else.

tcp        0      0 *:irdmi                     *:*                         LISTEN

It is not obvious here, but if you use the --numeric-ports argument, it will not convert the 8000 into its known port.

In your docker file, again you should

EXPOSE 8000

When launching your container, you can also specify the port to use on the host machine:

docker run -p 8080:8000 --name ...

After this, you should be able to use your browser to hit

localhost:8080  ->  container:8000


问:
I have to add .aar files as a library in a sub project in Android studio. It gives me an error.
I have added the .aar files to libs folder in the sub-project.
And have given the repositories as:

```<code>repositories {
 mavenCentral()
    mavenLocal()
    flatDir {
        dirs 'libs'
    }
</code>```

in the build.gradle of this sub-project.
Do I need to add dependencies in Main project's build.gradle also?
If yes, how should that be done?

答:
For filename.aar

```<code>repositories {
   flatDir {
        dirs 'libs'
    }
}

dependencies {
    compile(name:'filename', ext:'aar')
}
</code>```

Body:
I have added the .aar files to libs folder in the sub-project.
And have given the repositories as:

repositories {
 mavenCentral()
    mavenLocal()
    flatDir {
        dirs 'libs'
    }

in the build.gradle of this sub-project.
Do I need to add dependencies in Main project's build.gradle also?
If yes, how should that be done?

Body:
For filename.aar

repositories {
   flatDir {
        dirs 'libs'
    }
}

dependencies {
    compile(name:'filename', ext:'aar')
}