问:
How do I make this substitution in Mathematica?
I'm just getting started with Mathematica, and I've got what must be a pretty basic question about making substitutions but I can't get it to work.

I'd like to find the Euler-Lagrange equations for a functional of the function phi[x,y] and then make a substitution for the function phi[x,y]

If I enter the following:

VariationalD[tau*phi[x, y]^2 - 2*phi[x, y]^4 + phi[x, y]^6 + Dot[D[phi[x, y], {{x, y}}], D[phi[x, y, {{x, y}}]]], phi[x, y], {x, y}]

I get

```<code>Plus[Times[2,tau,phi[x,y]],Times[-8,Power[phi[x,y],3]],Times[6,Power[phi[x,y],5]],Times[-2,Plus[Derivative[0,2][phi][x,y],Derivative[2,0][phi][x,y]]]]
</code>```

Now if I try % /. phi[x,y] -> phi0[x,y] + psi[x,y] it makes the substitution for all the polynomial terms, but not for the Derivative terms.

How do I force the substitution into those functions?

答:
First, you misplaced a ] in your second derivative term, it should read D[phi[x, y], {{x, y}}]] not D[phi[x, y, {{x, y}}]]].

That said, replacement in Mathematica can be tricky, as has been pointed out in other questions.  That isn't to say it is impossible, just requires some work.  In this case, the problem comes in in that phi[x,y] is different from Derivative[2, 0][phi][x, y].  So, your pattern won't match the derivative term.  The simplest thing to do is to add the rule

```<code>Derivative[a__][phi][x__]:> Derivative[a][phi0][x] + Derivative[a][psi][x]
</code>```

to your list of replacement rules.  Three things to note:  1) I use ReplaceDelayed so that both types of derivatives will match without writing multiple rules, 2) since I can use patterns, I named them so that I can refer to them on the RHS of the rule, and 3) I used a double underscore when defining a and x which will match one or more items in a sequence.

Of course, that isn't the most satisfying way to approach the problem, as it will require you to write two rules every time you wish to this sort of replacement.  It turns out a more general approach is surprisingly difficult to accomplish, and I'll have to get back to you on it.

Edit: This requires a double replacement, as follows

```<code><result> /. phi -> phi0 + psi /. a_[b__][c__] :> Through[Distribute[a[b]][c]]
</code>```

Distribute ensures that the derivative works correctly with Plus, and Through does the same with the function args c.  The key is that the Head of Derivative[2, 0][phi][x, y] is Derivative[2, 0][phi], hence the several levels of square brackets in the rule.

Body:
I'm just getting started with Mathematica, and I've got what must be a pretty basic question about making substitutions but I can't get it to work.

I'd like to find the Euler-Lagrange equations for a functional of the function phi[x,y] and then make a substitution for the function phi[x,y]

If I enter the following:

VariationalD[tau*phi[x, y]^2 - 2*phi[x, y]^4 + phi[x, y]^6 + Dot[D[phi[x, y], {{x, y}}], D[phi[x, y, {{x, y}}]]], phi[x, y], {x, y}]

I get

Plus[Times[2,tau,phi[x,y]],Times[-8,Power[phi[x,y],3]],Times[6,Power[phi[x,y],5]],Times[-2,Plus[Derivative[0,2][phi][x,y],Derivative[2,0][phi][x,y]]]]

Now if I try % /. phi[x,y] -> phi0[x,y] + psi[x,y] it makes the substitution for all the polynomial terms, but not for the Derivative terms.

How do I force the substitution into those functions?

Body:
First, you misplaced a ] in your second derivative term, it should read D[phi[x, y], {{x, y}}]] not D[phi[x, y, {{x, y}}]]].

That said, replacement in Mathematica can be tricky, as has been pointed out in other questions.  That isn't to say it is impossible, just requires some work.  In this case, the problem comes in in that phi[x,y] is different from Derivative[2, 0][phi][x, y].  So, your pattern won't match the derivative term.  The simplest thing to do is to add the rule

Derivative[a__][phi][x__]:> Derivative[a][phi0][x] + Derivative[a][psi][x]

to your list of replacement rules.  Three things to note:  1) I use ReplaceDelayed so that both types of derivatives will match without writing multiple rules, 2) since I can use patterns, I named them so that I can refer to them on the RHS of the rule, and 3) I used a double underscore when defining a and x which will match one or more items in a sequence.

Of course, that isn't the most satisfying way to approach the problem, as it will require you to write two rules every time you wish to this sort of replacement.  It turns out a more general approach is surprisingly difficult to accomplish, and I'll have to get back to you on it.

Edit: This requires a double replacement, as follows

<result> /. phi -> phi0 + psi /. a_[b__][c__] :> Through[Distribute[a[b]][c]]

Distribute ensures that the derivative works correctly with Plus, and Through does the same with the function args c.  The key is that the Head of Derivative[2, 0][phi][x, y] is Derivative[2, 0][phi], hence the several levels of square brackets in the rule.


来源: stackexchange

问:
Batch script that can find the Startup folder on any Windows 10 PC using environment variables
How do I write a batch script that, no matter which Windows 10 PC it runs on, no matter what the name of the user, will install a file in C:\Users\Mr x\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup, using environment variables?</p>

答:
The easiest way to access files no matter the username is to use the %USERNAME% variable in the file destination.

C:\Users\%USERNAME%\<<path>>

ContentLicense: CC BY-SA 3.0


问:
Launch iOS simulator from Visual Studio with Xamarian
How can I launch an iOS simulator from Visual Studio? I'm working on Windows but have Visual Studio connected to my mac so I can develop a cross platform app.

I can successfully launch the iOS app to the iPad that is plugged into the Mac but can't figure out how to launch a simulator (I just want to test everything is loading good on different screens).
When I set my Solution Platform to iPhoneSimulator and my startup project to myApp.iOS and click start I get the error message... Please select a valid device before running the application.

答: Ran into the same problem after I'd just installed the iOS simulator for Windows VS; restarted VS and the networked Mac and the drop-down filled.</p>


问:
Why does this array creation not work in php7?
This is the code I'm using to create an array for a WordPress site.

```<code>foreach ($terms as $item) {
    $location_no++;
    $term_id = $item->term_id;
    $term_name = $item->name;
    $latitude = get_field('latitud', 'term_' . $term_id);
    $longitude = get_field('longitud', 'term_' . $term_id);

    // Populate the array!
    $locations[$location_no] = array (
        'id' => $location_no,
        'lat' => $latitude,
        'long' => $longitude,
        'name' => $term_name,
    );
}
echo '```';
print_r($locations);
echo '```';
</code>```

the print_r() produces this:

```<code>Array
(
    [1] => Array
        (
            [id] => 1
            [lat] => 40.423560
            [long] => -3.702541
            [name] => Madrid
        )

    [2] => Array
        (
            [id] => 2
            [lat] => 40.423560
            [long] => -3.702541
            [name] => Madrid
        )

)

...
</code>```

However when I switch over to php7.1, the array no longer works and I get this instead:

```<code>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
</code>```

A var_dump() of $terms produces this:

```<code>array(1) {
  [0]=>
  object(WP_Term)#7136 (10) {
    ["term_id"]=>
    int(28)
    ["name"]=>
    string(6) "Madrid"
    ["slug"]=>
    string(6) "madrid"
    ["term_group"]=>
    int(0)
    ["term_taxonomy_id"]=>
    int(28)
    ["taxonomy"]=>
    string(14) "trip_locations"
    ["description"]=>
    string(0) ""
    ["parent"]=>
    int(71)
    ["count"]=>
    int(5)
    ["filter"]=>
    string(3) "raw"
  }
}
</code>```

Why oh why is this happening?

答:
It's a two dimensional array and you dont have to loop it the way you loop a one-dimensional array.
When looping you can provide index to access the inner array.
Do this:</p>

```<code>foreach($location as $key => $value){
   echo $value["id"]."<br>";
   echo $value["lat"]."<br>";
   echo $value["long"]."<br>";
   echo $value["name"]."<br>";
}
</code>```

Body:
This is the code I'm using to create an array for a WordPress site.

foreach ($terms as $item) {
    $location_no++;
    $term_id = $item->term_id;
    $term_name = $item->name;
    $latitude = get_field('latitud', 'term_' . $term_id);
    $longitude = get_field('longitud', 'term_' . $term_id);

    // Populate the array!
    $locations[$location_no] = array (
        'id' => $location_no,
        'lat' => $latitude,
        'long' => $longitude,
        'name' => $term_name,
    );
}
echo '
';
print_r($locations);
echo '
';

the print_r() produces this:

Array
(
    [1] => Array
        (
            [id] => 1
            [lat] => 40.423560
            [long] => -3.702541
            [name] => Madrid
        )

    [2] => Array
        (
            [id] => 2
            [lat] => 40.423560
            [long] => -3.702541
            [name] => Madrid
        )

)

...

However when I switch over to php7.1, the array no longer works and I get this instead:

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

A var_dump() of $terms produces this:

array(1) {
  [0]=>
  object(WP_Term)#7136 (10) {
    ["term_id"]=>
    int(28)
    ["name"]=>
    string(6) "Madrid"
    ["slug"]=>
    string(6) "madrid"
    ["term_group"]=>
    int(0)
    ["term_taxonomy_id"]=>
    int(28)
    ["taxonomy"]=>
    string(14) "trip_locations"
    ["description"]=>
    string(0) ""
    ["parent"]=>
    int(71)
    ["count"]=>
    int(5)
    ["filter"]=>
    string(3) "raw"
  }
}

Why oh why is this happening?

Body:
It's a two dimensional array and you dont have to loop it the way you loop a one-dimensional array.
When looping you can provide index to access the inner array.
Do this:

foreach($location as $key => $value){
   echo $value["id"]."<br>";
   echo $value["lat"]."<br>";
   echo $value["long"]."<br>";
   echo $value["name"]."<br>";
}

ContentLicense: CC BY-SA 4.0


问:
Python3.4 + Django + Ubuntu:
unknown encoding: raw-unicode-escape
I'm using a Django app on Ubuntu Trusty in a virtualenv with python 3.4 in chroot on Linux Deploy on Android 5.1.1 (Cyanogenmod 12.1). When I add an event and load the front-end, I get the following error:

LookupError at /: unknown encoding: raw-unicode-escape

  How do I fix this, do I have to install some codec packages to python (if yes, which packages)?

Edit: full log:
http://pastebin.com/QH32e92i

答: The problem was related to the architecture of the os - I was using a strange distro on Linux Deploy distribution, when I switched to VirtualBox and installed an amd64 one, everything worked properly with the same code.</p>


问:
Load MainActivity during Splash Screen
I currently have a splashScreenActivity that requires the User the press on a button to go to the MainActivity.

Would it be possible to load all the contents of MainActivity WITHOUT MainActivity's UI APPEARING ON TOP OF splashScreenActivity's UI so that when he does presses the button, he is redirected to the MainActivity and all the data is 100% loaded?

Thanks in advance

答:
I found an answer to my problem!

Note that in my case MainActivity can be any activity

Having a Splash Screen as a fragment instead of an activity allows you to overlay the MainActivity with the fragment, while the MainActivity data loads in the background.

At this point, whenever you are ready, simply set the visibility of the fragment to View.GONE or pop it off the fragment stack getFragmentManager().popBackStack();, and you will return (never really left) to your MainActivity with all the data loaded.

Title: Load MainActivity during Splash Screen


问:
How to create a singleton Toast in Extjs
I need to create a single toast on the screen of my application, today if I click multiple times on a button, several toasts are presented.

EDIT:

```<code>showToast: function(message) {
    var openedToast = Ext.get(document.querySelector('[id^="toast-"]'));
    if (openedToast != null) {
        var toast = Ext.getCmp(openedToast.id);
        toast.close();
    }
    Ext.defer(function() {
        Ext.toast({
            html: message,
            align: 't'
        });
    }, 80);
}
</code>```

But if the user clicks the button quickly, the toast is created several times

答:
Just give it a unique identifier and check if it already exists before creating a new one.

{
    xtype: 'button',
    handler: function(){
        if(!Ext.ComponentQuery.query('#myToast').length){
            Ext.toast({
                itemId: 'myToast',
                html: 'toast!'
            });
        }
    }
}
```

» Fiddle

Body:
I need to create a single toast on the screen of my application, today if I click multiple times on a button, several toasts are presented.

EDIT:

showToast: function(message) {
    var openedToast = Ext.get(document.querySelector('[id^="toast-"]'));
    if (openedToast != null) {
        var toast = Ext.getCmp(openedToast.id);
        toast.close();
    }
    Ext.defer(function() {
        Ext.toast({
            html: message,
            align: 't'
        });
    }, 80);
}

But if the user clicks the button quickly, the toast is created several times

Body:
Just give it a unique identifier and check if it already exists before creating a new one.

{
    xtype: 'button',
    handler: function(){
        if(!Ext.ComponentQuery.query('#myToast').length){
            Ext.toast({
                itemId: 'myToast',
                html: 'toast!'
            });
        }
    }
}

» Fiddle


问:
Python Multithreading Not Working
I am new to learning python and got an exercise to create a multithreaded script to take a list of 10 public ftp servers and connect to them anonymously and just do a directory listing. I have the following code and it works when i use the ftp connect within the run function but when i try to create an "ftp" function and utilize it keeps erroring out and then the terminal gets stuck and can't kill the program or get out, which i can't figure out why that keeps happening either?</p>

```<code>!/usr/bin/python

import threading
import Queue
import time
from ftplib import FTP

sites = ["speedtest.tele2.net", "test.rebex.net", "test.talia.net", "ftp.swfwmd.state.fl.us", "ftp.heanet.ie", "ftp.rediris.es", "ftp.ch.freebsd.org",  "ftp.mirror.nl", "ftp.ussg.iu.edu", "ftp.uni-bayreu$

class WorkerThread(threading.Thread) :

        def __init__(self, queue) :
                threading.Thread.__init__(self)
                self.queue = queue

        #def ftp(ip) :
        #       server = FTP(ip)
        #       server.login()
        #       server.retrlines('LIST')

        def run(self) :
                print "In WorkerThread"
                while True :
                        counter = self.queue.get()
                        print "Connecting to FTP Server %s" % counter
                        #self.ftp(counter)
                        #print "Ordered to sleep for %d seconds!" % counter
                        #time.sleep(counter)
                        #print "Finished sleeping for %d seconds" % counter

                        server = FTP(counter)
                        server.login()
                        server.retrlines('LIST')
                        self.queue.task_done()

queue = Queue.Queue()

for i in range(10) :
        print "Creating WorkerThread : %d" % i
        worker = WorkerThread(queue)
        worker.setDaemon(True)
        worker.start()
        print "WorkerThread %d Created!" % i

for j in sites :
        queue.put(j)

queue.join()

print "All Tasks Over!"
</code>```

答:
As suggested by:

Is there any way to kill a Thread in Python?

you should put a stop condition a make the threads check on it. Together with the join it allows for the thread to be terminated gracefully. Without entering into some other implication try the code below.

```<code>#!/usr/bin/python

import threading
import Queue
import time
from ftplib import FTP

sites = ["speedtest.tele2.net"]

class WorkerThread(threading.Thread):

        def __init__(self, queue):
                threading.Thread.__init__(self)
                self.queue = queue
                self._stop = threading.Event()

        def ftp(self, ip):
            server = FTP(ip)
            server.login()
            server.retrlines('LIST')

        def run(self):
                print "In WorkerThread"
                while not self.stopped():
                    counter = self.queue.get()
                    print "Connecting to FTP Server %s" % counter
                    self.ftp(counter)
                    self.queue.task_done()

        def stop(self):
            self._stop.set()

        def stopped(self):
            return self._stop.is_set()

if __name__ == '__main__':

    queue = Queue.Queue()

    for i in range(10):
            print "Creating WorkerThread : %d" % i
            worker = WorkerThread(queue)
            worker.setDaemon(True)
            worker.start()
            worker.stop()
            print "WorkerThread %d Created!" % i

    for j in sites:
            queue.put(j)

    queue.join()

    print "All Tasks Over!"
</code>```

Title: Python Multithreading Not Working

Body:
I am new to learning python and got an exercise to create a multithreaded script to take a list of 10 public ftp servers and connect to them anonymously and just do a directory listing. I have the following code and it works when i use the ftp connect within the run function but when i try to create an "ftp" function and utilize it keeps erroring out and then the terminal gets stuck and can't kill the program or get out, which i can't figure out why that keeps happening either?

!/usr/bin/python

import threading
import Queue
import time
from ftplib import FTP

sites = ["speedtest.tele2.net", "test.rebex.net", "test.talia.net", "ftp.swfwmd.state.fl.us", "ftp.heanet.ie", "ftp.rediris.es", "ftp.ch.freebsd.org",  "ftp.mirror.nl", "ftp.ussg.iu.edu", "ftp.uni-bayreu$

class WorkerThread(threading.Thread) :

        def __init__(self, queue) :
                threading.Thread.__init__(self)
                self.queue = queue

        #def ftp(ip) :
        #       server = FTP(ip)
        #       server.login()
        #       server.retrlines('LIST')

        def run(self) :
                print "In WorkerThread"
                while True :
                        counter = self.queue.get()
                        print "Connecting to FTP Server %s" % counter
                        #self.ftp(counter)
                        #print "Ordered to sleep for %d seconds!" % counter
                        #time.sleep(counter)
                        #print "Finished sleeping for %d seconds" % counter

                        server = FTP(counter)
                        server.login()
                        server.retrlines('LIST')
                        self.queue.task_done()

queue = Queue.Queue()

for i in range(10) :
        print "Creating WorkerThread : %d" % i
        worker = WorkerThread(queue)
        worker.setDaemon(True)
        worker.start()
        print "WorkerThread %d Created!" % i

for j in sites :
        queue.put(j)

queue.join()

print "All Tasks Over!"

Body:
As suggested by:

Is there any way to kill a Thread in Python?

you should put a stop condition a make the threads check on it. Together with the join it allows for the thread to be terminated gracefully. Without entering into some other implication try the code below.

#!/usr/bin/python

import threading
import Queue
import time
from ftplib import FTP

sites = ["speedtest.tele2.net"]

class WorkerThread(threading.Thread):

        def __init__(self, queue):
                threading.Thread.__init__(self)
                self.queue = queue
                self._stop = threading.Event()

        def ftp(self, ip):
            server = FTP(ip)
            server.login()
            server.retrlines('LIST')

        def run(self):
                print "In WorkerThread"
                while not self.stopped():
                    counter = self.queue.get()
                    print "Connecting to FTP Server %s" % counter
                    self.ftp(counter)
                    self.queue.task_done()

        def stop(self):
            self._stop.set()

        def stopped(self):
            return self._stop.is_set()

if __name__ == '__main__':

    queue = Queue.Queue()

    for i in range(10):
            print "Creating WorkerThread : %d" % i
            worker = WorkerThread(queue)
            worker.setDaemon(True)
            worker.start()
            worker.stop()
            print "WorkerThread %d Created!" % i

    for j in sites:
            queue.put(j)

    queue.join()

    print "All Tasks Over!"


问:
actionscript htmlLoader block ads
I've got an AIR app that is loading mx:HTMLs.  I would like to block the ads that show in them  just like Adblock Plus for Firefox does (see http://adblockplus.org/en/).  I subscribe to the Easylist USA filter.

```<code>var req:URLRequest = new URLRequest("http://www.google.com");
thisHtmlWindow.open();
thisHtmlWindow.htmlContent.htmlLoader.load(req);
</code>```

I don't know where to begin to interrupt the HTML GET-ting process in actionscript.  This is where I suspect I can add the HTTP filter.  It'd be nice to subscribe to the filter and periodically download it/update it to make sure the major ad networks are blocked.

答:
Good question.  I would start by intercepting the result that comes back from the request, manipulating the HTML, then load it into the HTMLLoader.  You do this by initially retrieving your content using a URLLoader rather than the HTMLLoader.  After you get and manipulate your content, set it into your HTMLLoader using HTMLLoader.loadString.  Hope that helps.

EDIT:  Here's a little code for you.

```<code>var urlLoader:URLLoader = new URLLoader();

public function loadUrl(url:String):void {
    var request:URLRequest = new URLRequest(url);
    _urlLoader.addEventListener(Event.COMPLETE, onHtmlLoaded);
    _urlLoader.load(request);
}

private function onHtmlLoaded(event:Event):void {
    _urlLoader.removeEventListener(Event.COMPLETE, onHtmlLoaded);

    // This is where you can mess with the data before setting it
    var content:String = _urlLoader.data as String;

    myHtmlComponent.htmlLoader.loadString(content);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: actionscript htmlLoader block ads

Body:
I've got an AIR app that is loading mx:HTMLs.  I would like to block the ads that show in them  just like Adblock Plus for Firefox does (see http://adblockplus.org/en/).  I subscribe to the Easylist USA filter.

var req:URLRequest = new URLRequest("http://www.google.com");
thisHtmlWindow.open();
thisHtmlWindow.htmlContent.htmlLoader.load(req);

I don't know where to begin to interrupt the HTML GET-ting process in actionscript.  This is where I suspect I can add the HTTP filter.  It'd be nice to subscribe to the filter and periodically download it/update it to make sure the major ad networks are blocked.

Body:
Good question.  I would start by intercepting the result that comes back from the request, manipulating the HTML, then load it into the HTMLLoader.  You do this by initially retrieving your content using a URLLoader rather than the HTMLLoader.  After you get and manipulate your content, set it into your HTMLLoader using HTMLLoader.loadString.  Hope that helps.

EDIT:  Here's a little code for you.

var urlLoader:URLLoader = new URLLoader();

public function loadUrl(url:String):void {
    var request:URLRequest = new URLRequest(url);
    _urlLoader.addEventListener(Event.COMPLETE, onHtmlLoaded);
    _urlLoader.load(request);
}

private function onHtmlLoaded(event:Event):void {
    _urlLoader.removeEventListener(Event.COMPLETE, onHtmlLoaded);

    // This is where you can mess with the data before setting it
    var content:String = _urlLoader.data as String;

    myHtmlComponent.htmlLoader.loadString(content);
}


问:
How to Monitor Qt Signal Event Queue Depth
There are two objects in my program. One object is emitting a signal. The other one receives the signal in a slot and processes the incoming signals one by one. Both objects are running in different threads. Now I need to measure and monitor the workload for my receiving object.

The problem is I do not know how many signals are waiting for my second object to process in the Qt signal queue. Is there a way to get the size of this queue? Or is there a work around to know how many signals have to be still proecessed?

答:
The qGlobalPostedEventsCount() is a starting point, although it only works for the current thread.

To poll an arbitrary thread, we can to use Qt's internals. The implementation is then very simple. It works even when the thread is blocked and doesn't process events.

```<code>// https://github.com/KubaO/stackoverflown/tree/master/questions/queue-poll-44440584
#include <QtCore>
#include <private/qthread_p.h>
#include <climits>

uint postedEventsCountForThread(QThread * thread) {
   if (!thread)
      return -1;
   auto threadData = QThreadData::get2(thread);
   QMutexLocker lock(&threadData->postEventList.mutex);
   return threadData->postEventList.size() - threadData->postEventList.startOffset;
}

uint postedEventsCountFor(QObject * target) {
   return postedEventsCountForThread(target->thread());
}
</code>```

If one really wishes not to use private APIs, we can have a less straightforward solution with more overhead. First, let's recall that the lowest overhead means of "doing stuff in some object's thread" is to do said "stuff" in an event's destructor - see this answer for more details. We can post the highest priority event to the target object's event queue. The event wraps a task that invokes qGlobalPostedEventsCount, updates the count variable, and releases a mutex that we then acquire. At the time of mutex acquisition, the count has a valid value that is returned. If the target thread is unresponsive and the request times out, -1 is returned.

```<code>uint qGlobalPostedEventsCount(); // exported in Qt but not declared
uint postedEventsCountForPublic(QObject * target, int timeout = 1000) {
   uint count = -1;
   QMutex mutex;
   struct Event : QEvent {
      QMutex & mutex;
      QMutexLocker lock;
      uint & count;
      Event(QMutex & mutex, uint & count) :
         QEvent(QEvent::None), mutex(mutex), lock(&mutex), count(count) {}
      ~Event() {
         count = qGlobalPostedEventsCount();
      }
   };
   QCoreApplication::postEvent(target, new Event(mutex, count), INT_MAX);
   if (mutex.tryLock(timeout)) {
      mutex.unlock();
      return count;
   }
   return -1;
}
</code>```

And a test harness:

```<code>int main(int argc, char ** argv) {
   QCoreApplication app(argc, argv);
   struct Receiver : QObject {
      bool event(QEvent *event) override {
         if (event->type() == QEvent::User)
            QThread::currentThread()->quit();
         return QObject::event(event);
      }
   } obj;
   struct Thread : QThread {
      QMutex mutex;
      Thread() { mutex.lock(); }
      void run() override {
         QMutexLocker lock(&mutex);
         QThread::run();
      }
   } thread;
   thread.start();
   obj.moveToThread(&thread);
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::User));
   auto count1 = postedEventsCountFor(&obj);
   thread.mutex.unlock();
   auto count2 = postedEventsCountForPublic(&obj);
   thread.wait();
   auto count3 = postedEventsCountFor(&obj);
   Q_ASSERT(count1 == 4);
   Q_ASSERT(count2 == 4);
   Q_ASSERT(count3 == 0);
}
</code>```

```<code>QT = core-private
CONFIG += console c++11
CONFIG -= app_bundle
TARGET = queue-poll-44440584
TEMPLATE = app
SOURCES += main.cpp
</code>```

Body:
The qGlobalPostedEventsCount() is a starting point, although it only works for the current thread.

To poll an arbitrary thread, we can to use Qt's internals. The implementation is then very simple. It works even when the thread is blocked and doesn't process events.

// https://github.com/KubaO/stackoverflown/tree/master/questions/queue-poll-44440584
#include <QtCore>
#include <private/qthread_p.h>
#include <climits>

uint postedEventsCountForThread(QThread * thread) {
   if (!thread)
      return -1;
   auto threadData = QThreadData::get2(thread);
   QMutexLocker lock(&threadData->postEventList.mutex);
   return threadData->postEventList.size() - threadData->postEventList.startOffset;
}

uint postedEventsCountFor(QObject * target) {
   return postedEventsCountForThread(target->thread());
}

If one really wishes not to use private APIs, we can have a less straightforward solution with more overhead. First, let's recall that the lowest overhead means of "doing stuff in some object's thread" is to do said "stuff" in an event's destructor - see this answer for more details. We can post the highest priority event to the target object's event queue. The event wraps a task that invokes qGlobalPostedEventsCount, updates the count variable, and releases a mutex that we then acquire. At the time of mutex acquisition, the count has a valid value that is returned. If the target thread is unresponsive and the request times out, -1 is returned.

uint qGlobalPostedEventsCount(); // exported in Qt but not declared
uint postedEventsCountForPublic(QObject * target, int timeout = 1000) {
   uint count = -1;
   QMutex mutex;
   struct Event : QEvent {
      QMutex & mutex;
      QMutexLocker lock;
      uint & count;
      Event(QMutex & mutex, uint & count) :
         QEvent(QEvent::None), mutex(mutex), lock(&mutex), count(count) {}
      ~Event() {
         count = qGlobalPostedEventsCount();
      }
   };
   QCoreApplication::postEvent(target, new Event(mutex, count), INT_MAX);
   if (mutex.tryLock(timeout)) {
      mutex.unlock();
      return count;
   }
   return -1;
}

And a test harness:

int main(int argc, char ** argv) {
   QCoreApplication app(argc, argv);
   struct Receiver : QObject {
      bool event(QEvent *event) override {
         if (event->type() == QEvent::User)
            QThread::currentThread()->quit();
         return QObject::event(event);
      }
   } obj;
   struct Thread : QThread {
      QMutex mutex;
      Thread() { mutex.lock(); }
      void run() override {
         QMutexLocker lock(&mutex);
         QThread::run();
      }
   } thread;
   thread.start();
   obj.moveToThread(&thread);
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::None));
   QCoreApplication::postEvent(&obj, new QEvent(QEvent::User));
   auto count1 = postedEventsCountFor(&obj);
   thread.mutex.unlock();
   auto count2 = postedEventsCountForPublic(&obj);
   thread.wait();
   auto count3 = postedEventsCountFor(&obj);
   Q_ASSERT(count1 == 4);
   Q_ASSERT(count2 == 4);
   Q_ASSERT(count3 == 0);
}

QT = core-private
CONFIG += console c++11
CONFIG -= app_bundle
TARGET = queue-poll-44440584
TEMPLATE = app
SOURCES += main.cpp


问:
Copy an entity in Google App Engine datastore in Python without knowing property names at 'compile' time
In a Python Google App Engine app I'm writing, I have an entity stored in the datastore that I need to retrieve, make an exact copy of it (with the exception of the key), and then put this entity back in.

How should I do this?  In particular, are there any caveats or tricks I need to be aware of when doing this so that I get a copy of the sort I expect and not something else.

ETA:  Well, I tried it out and I did run into problems.  I would like to make my copy in such a way that I don't have to know the names of the properties when I write the code.  My thinking was to do this:

```<code>#theThing = a particular entity we pull from the datastore with model Thing
copyThing = Thing(user = user)
for thingProperty in theThing.properties():
    copyThing.__setattr__(thingProperty[0], thingProperty[1])
</code>```

This executes without any errors... until I try to pull copyThing from the datastore, at which point I discover that all of the properties are set to None (with the exception of the user and key, obviously).  So clearly this code is doing something, since it's replacing the defaults with None (all of the properties have a default value set), but not at all what I want.  Suggestions?

答:
Here's the code provided by @zengabor with the if expression formatted for easier reading. It may not be PEP-8 compliant:

```<code>klass = e.__class__
props = {}
for k, v in klass.properties().iteritems():
    if not (type(v) == db.DateTimeProperty and ((
            skip_auto_now     and getattr(v, 'auto_now'    )) or (
            skip_auto_now_add and getattr(v, 'auto_now_add')))):
        if type(v) == db.ReferenceProperty:
            value = getattr(klass, k).get_value_for_datastore(e)
        else:
            value = v.__get__(e, klass)
        props[k] = value
props.update(extra_args)
return klass(**props)
</code>```

Body:
In a Python Google App Engine app I'm writing, I have an entity stored in the datastore that I need to retrieve, make an exact copy of it (with the exception of the key), and then put this entity back in.

How should I do this?  In particular, are there any caveats or tricks I need to be aware of when doing this so that I get a copy of the sort I expect and not something else.

ETA:  Well, I tried it out and I did run into problems.  I would like to make my copy in such a way that I don't have to know the names of the properties when I write the code.  My thinking was to do this:

#theThing = a particular entity we pull from the datastore with model Thing
copyThing = Thing(user = user)
for thingProperty in theThing.properties():
    copyThing.__setattr__(thingProperty[0], thingProperty[1])

This executes without any errors... until I try to pull copyThing from the datastore, at which point I discover that all of the properties are set to None (with the exception of the user and key, obviously).  So clearly this code is doing something, since it's replacing the defaults with None (all of the properties have a default value set), but not at all what I want.  Suggestions?

Body:
Here's the code provided by @zengabor with the if expression formatted for easier reading. It may not be PEP-8 compliant:

klass = e.__class__
props = {}
for k, v in klass.properties().iteritems():
    if not (type(v) == db.DateTimeProperty and ((
            skip_auto_now     and getattr(v, 'auto_now'    )) or (
            skip_auto_now_add and getattr(v, 'auto_now_add')))):
        if type(v) == db.ReferenceProperty:
            value = getattr(klass, k).get_value_for_datastore(e)
        else:
            value = v.__get__(e, klass)
        props[k] = value
props.update(extra_args)
return klass(**props)


问:
Timestamp conversion to instant in Java adds unnecessary time offset
I need to be able to convert data fetched from MySQL database that is stored in a "datetime" fields into Java ZonedDateTime object.

```<code>ZonedDateTime dt = ZonedDateTime.ofInstant(rs.getTimestamp("Start").toInstant(), UTC_ZONE_ID)
</code>```

The problem I'm having is that toInstant() adds local time offset to the Timestamp object which I don't need because the datetime is already stored in a UTC format in a database.
So when I run the following code:

```<code>ZonedDateTime startDT =
        ZonedDateTime.ofInstant(rs.getTimestamp("Start").toInstant(),Globals.LOCALZONEID);
System.out.println(rs.getTimestamp("start"));
System.out.println(rs.getTimestamp("start").toInstant());
</code>```

I get:

```<code>2017-06-08 13:15:00.0
2017-06-08T17:15:00Z
</code>```

I need the time component to stay unchanged.

I was unable to find any obvious solution to the problem so am I missing something here?

答:
The old classes like java.sql.Timestamp have quite some issues with their design. One of the things that often cause confusion is that Timestamp.toString() prints the time in the JVM’s time zone even though the time Timestamp in it just holds a point in time with no time zone. To be concrete, when a Timestamp is equal to 2017-06-08T17:15:00Z in UTC and you print it on a computer running Pittsburg time (which at this time of year has an offset of -4:00 from UTC), the Timestamp.toString() is implicitly called, it reads the JVM’s time zone and prints the time as 13:15:00.0 just because this time in Pennsylvania is equal to the UTC time in the Timestamp.

So to cut a long story short, do not worry, both your Timestamp and your Instant are correct.

Body:
I need to be able to convert data fetched from MySQL database that is stored in a "datetime" fields into Java ZonedDateTime object.

ZonedDateTime dt = ZonedDateTime.ofInstant(rs.getTimestamp("Start").toInstant(), UTC_ZONE_ID)

The problem I'm having is that toInstant() adds local time offset to the Timestamp object which I don't need because the datetime is already stored in a UTC format in a database.
So when I run the following code:

ZonedDateTime startDT =
        ZonedDateTime.ofInstant(rs.getTimestamp("Start").toInstant(),Globals.LOCALZONEID);
System.out.println(rs.getTimestamp("start"));
System.out.println(rs.getTimestamp("start").toInstant());

I get:

2017-06-08 13:15:00.0
2017-06-08T17:15:00Z

I need the time component to stay unchanged.

I was unable to find any obvious solution to the problem so am I missing something here?


答:
What happens if you try this?

```<code>$locations = [];

foreach ($terms as $location_no => $item) {

    $term_id = $item->term_id;
    $term_name = $item->name;
    $latitude = get_field('latitud', 'term_' . $term_id);
    $longitude = get_field('longitud', 'term_' . $term_id);

    // Populate the array!
    $locations[$location_no] = [
        'id' => $location_no,
        'lat' => $latitude,
        'long' => $longitude,
        'name' => $term_name,
    ];
}

echo '```';
print_r($locations);
echo '```';
</code>```

Title: Why does this array creation not work in php7?

Body:
What happens if you try this?

$locations = [];

foreach ($terms as $location_no => $item) {

    $term_id = $item->term_id;
    $term_name = $item->name;
    $latitude = get_field('latitud', 'term_' . $term_id);
    $longitude = get_field('longitud', 'term_' . $term_id);

    // Populate the array!
    $locations[$location_no] = [
        'id' => $location_no,
        'lat' => $latitude,
        'long' => $longitude,
        'name' => $term_name,
    ];
}

echo '<pre>';
print_r($locations);
echo '</pre>';


问:
Javascript append to url if not null
I want to append the values if they are not null to the link. It doesn't allow the if in the string, so what should i do instead?     </p>

```<code>    var age = $('#age').val();
    var fn = $('#fn').val();
    var ln = $('#ln').val();
    var city = $('#city').val();
    var country = $('#country').val();

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record" if(age !=null){ "&age=" + age + } "&fn=" + fn + "&ln=" + ln + "&city=" + city + "&country=" + country;
</code>```

答:
Use the ternary operator, it's as simple as (expression ? value if true : value if false)

Don't forget about Javascript's truthyness to keep your expression small!

You can also utilize a trick with truthy values to perform a null coalesce with var || default, where if var is falsy, default will be used (this can be chained to use a bunch of vars if you'd like)

Title: Javascript append to url if not null

Body:
I want to append the values if they are not null to the link. It doesn't allow the if in the string, so what should i do instead?

    var age = $('#age').val();
    var fn = $('#fn').val();
    var ln = $('#ln').val();
    var city = $('#city').val();
    var country = $('#country').val();

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record" if(age !=null){ "&age=" + age + } "&fn=" + fn + "&ln=" + ln + "&city=" + city + "&country=" + country;


问:
C# creating ".exe" with libraries
I'm using some dlls in my project. To make a '.exe' file i only used 'Released' in Solution Configurations. In my computer exe file works, but in another there's an error: "Can't load file X...". X is a dll file. How can i solve this problem? I copied all dlls into project-bin-realese.</p>

答: Copy the DLLs into the same folder as the EXE.  It you put them in a sub directory then you are going to have to use the <probing> element in an app.exe.config file so that the CLR can find them there.

Title: C# creating ".exe" with libraries


问:
How to remove outline border from input button
When I click somewhere else the border disappears, I tried to use onfocus: none, but that didn't help. How to make this ugly button border disappear when I click on it?

input[type=button] {
  width: 120px;
  height: 60px;
  margin-left: 35px;
  display: block;
  background-color: gray;
  color: white;
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="Example Button"></code>```

答:
This one worked for me</p>

```<code>button:focus {
    border: none;
    outline: none;
}
</code>```

Body:
When I click somewhere else the border disappears, I tried to use onfocus: none, but that didn't help. How to make this ugly button border disappear when I click on it?

input[type=button] {
  width: 120px;
  height: 60px;
  margin-left: 35px;
  display: block;
  background-color: gray;
  color: white;
  border: none;
}

<input type="button" value="Example Button">

Body:
This one worked for me

button:focus {
    border: none;
    outline: none;
}


问:
WRONGTYPE Operation against a key holding the wrong kind of value php
Hi I am using Laravel with Redis .When I am trying to access a key by get method then get following error "WRONGTYPE Operation against a key holding the wrong kind of value"

I am using following code to access the key value -

i use this code for get data from redis

```<code>$values = "l_messages";
$value = $redis->HGETALL($values);
print($value);
</code>```

答:
Redis supports 6 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value(s):

if value is of type string -> GET <key>

if value is of type hash -> HGET or HMGET or HGETALL <key>

if value is of type lists -> lrange <key> <start> <end>

if value is of type sets -> smembers <key>

if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

if value is of type stream -> xread count <count> streams <key> <ID>. https://redis.io/commands/xread

Use the TYPE command to check the type of value a key is mapping to:

type <key>

Body:
Hi I am using Laravel with Redis .When I am trying to access a key by get method then get following error "WRONGTYPE Operation against a key holding the wrong kind of value"

I am using following code to access the key value -

i use this code for get data from redis

$values = "l_messages";
$value = $redis->HGETALL($values);
print($value);


问:
deserializing json to embedded object in Symfony 3.2 - Expected argument of type "Acme\StoreBundle\Document\Gps", "array" given
Acme\StoreBundle\Document\Person

```<code>/**
 * @MongoDB\Document
 */

class Person
{

/**
 * @MongoDB\bool
 */

private $hasemail;

/**
 * @MongoDB\EmbedOne(targetDocument="Gps")
 */

private $gps;

/**
 * @MongoDB\Field(name="email", type="collection")
 */

private $email;

}
...
</code>```

Acme\StoreBundle\Document\Gps

```<code>/**
 * @MongoDB\EmbeddedDocument
 */

class Gps
{

/**
 * @MongoDB\Field(type="float")
 */

private $latitude;

/**
 * @MongoDB\Field(type="float")
 */
private $longitude;

}
...
</code>```

mongo json document

```<code>{
"hasemail": true,
"gps": {
    "latitude": 42.941579990394,
    "longitude": -85.244641161525
},
"email": [
    "sdfgsdfg@sfgsdfg.org",
    "sdfgsdfg@fgsdfg.com",
    "sdfgsdfg@sdfgsdfg.com"
]
}
</code>```

serializing mongo document to json works perfect. but deserializing json to document throws an error: "Expected argument of type 'Acme\StoreBundle\Document\Gps', 'array' given"

deserialize code:

```<code>$post = $request->getContent();
$serializer = $this->get('serializer');
$person = $serializer->deserialize($post, Person::class, 'json');
</code>```

答:
Your $post is likely an array and not a raw JSON object as you're expecting.

```<code>[{
    key: value
}]
</code>```

is different from..

```<code>{
    key: value
}
</code>```

Separately, there looks to be a separate issue based on your error message and the example code you have here.

Acme\StoreBundle\Document\Gps is the expected class, while deserializing Voter::class so you may want to check your namespaces and class names as well.

Body:
Acme\StoreBundle\Document\Person

/**
 * @MongoDB\Document
 */

class Person
{

/**
 * @MongoDB\bool
 */

private $hasemail;

/**
 * @MongoDB\EmbedOne(targetDocument="Gps")
 */

private $gps;

/**
 * @MongoDB\Field(name="email", type="collection")
 */

private $email;

}
...

Acme\StoreBundle\Document\Gps

/**
 * @MongoDB\EmbeddedDocument
 */

class Gps
{

/**
 * @MongoDB\Field(type="float")
 */

private $latitude;

/**
 * @MongoDB\Field(type="float")
 */
private $longitude;

}
...

mongo json document

{
"hasemail": true,
"gps": {
    "latitude": 42.941579990394,
    "longitude": -85.244641161525
},
"email": [
    "sdfgsdfg@sfgsdfg.org",
    "sdfgsdfg@fgsdfg.com",
    "sdfgsdfg@sdfgsdfg.com"
]
}

serializing mongo document to json works perfect. but deserializing json to document throws an error: "Expected argument of type 'Acme\StoreBundle\Document\Gps', 'array' given"

deserialize code:

$post = $request->getContent();
$serializer = $this->get('serializer');
$person = $serializer->deserialize($post, Person::class, 'json');

Body:
Your $post is likely an array and not a raw JSON object as you're expecting.

[{
    key: value
}]

is different from..

{
    key: value
}

Separately, there looks to be a separate issue based on your error message and the example code you have here.

Acme\StoreBundle\Document\Gps is the expected class, while deserializing Voter::class so you may want to check your namespaces and class names as well.


问:
How to tell if a string contains a certain character in JavaScript?
I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code.  I used maxlength to limit the user to entering 24 characters.

The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.

How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?

答:
To find "hello" in your_string

```<code>if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}
</code>```

For the alpha numeric you can use a regular expression:

http://www.regular-expressions.info/javascript.html

Alpha Numeric Regular Expression

Body:
To find "hello" in your_string

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}

For the alpha numeric you can use a regular expression:

http://www.regular-expressions.info/javascript.html

Alpha Numeric Regular Expression


问:
SysInternal's WinObj device listing mechanism
SysInternals's WinObj can list all device objects.

I wonder how it can list the devices.

Is there any open source we can read?(or a code snippet)

What is the most significant function I should know?

答:
As per the answer from user1575778 you can use NtOpenDirectoryObject and NtQueryDirectoryObject (which from user mode are identical to ZwOpenDirectoryObject and ZwQueryDirectoryObject respectively) to list the objects inside the object manager namespace.

Have a look at objmgr.hpp of NT Objects aka ntobjx, in particular at the class NtObjMgr::Directory (or DirectoryT). It provides the same functionality nicely wrapped into a C++ class. The whole utility is open source under a liberal license (dual-licensed due to WTL-use: MIT and MS-PL), so bits and pieces can be reused however you please, provided you comply with the license terms.

But here's a simple C++ code example catering just your use case:

```<code>#include <Windows.h>
#include <tchar.h>
#include <cstdio>
#include <winternl.h>

NTSTATUS (NTAPI* NtOpenDirectoryObject)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES);
NTSTATUS (NTAPI* NtQueryDirectoryObject)(HANDLE, PVOID, ULONG, BOOLEAN, BOOLEAN, PULONG, PULONG);
VOID (NTAPI* RtlInitUnicodeString_)(PUNICODE_STRING, PCWSTR);
NTSTATUS (NTAPI* NtClose_)(HANDLE);

#define DIRECTORY_QUERY                 (0x0001)
#define DIRECTORY_TRAVERSE              (0x0002)

typedef struct _OBJECT_DIRECTORY_INFORMATION {
    UNICODE_STRING Name;
    UNICODE_STRING TypeName;
} OBJECT_DIRECTORY_INFORMATION, *POBJECT_DIRECTORY_INFORMATION;

#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS                   ((NTSTATUS)0x00000000L) // ntsubauth
#endif // STATUS_SUCCESS
#ifndef STATUS_MORE_ENTRIES
#define STATUS_MORE_ENTRIES              ((NTSTATUS)0x00000105L)
#endif // STATUS_MORE_ENTRIES
#ifndef STATUS_NO_MORE_ENTRIES
#define STATUS_NO_MORE_ENTRIES           ((NTSTATUS)0x8000001AL)
#endif // STATUS_NO_MORE_ENTRIES

int PrintDevices()
{
    NTSTATUS ntStatus;
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING objname;
    HANDLE hDeviceDir = NULL;
    RtlInitUnicodeString_(&objname, L"\\Device");
    InitializeObjectAttributes(&oa, &objname, 0, NULL, NULL);
    ntStatus = NtOpenDirectoryObject(&hDeviceDir, DIRECTORY_QUERY | DIRECTORY_TRAVERSE, &oa);
    if(NT_SUCCESS(ntStatus))
    {
        size_t const bufSize = 0x10000;
        BYTE buf[bufSize] = {0};
        ULONG start = 0, idx = 0, bytes;
        BOOLEAN restart = TRUE;
        for(;;)
        {
            ntStatus = NtQueryDirectoryObject(hDeviceDir, PBYTE(buf), bufSize, FALSE, restart, &idx, &bytes);
            if(NT_SUCCESS(ntStatus))
            {
                POBJECT_DIRECTORY_INFORMATION const pdilist = reinterpret_cast<POBJECT_DIRECTORY_INFORMATION>(PBYTE(buf));
                for(ULONG i = 0; i < idx - start; i++)
                {
                    if(0 == wcsncmp(pdilist[i].TypeName.Buffer, L"Device", pdilist[i].TypeName.Length / sizeof(WCHAR)))
                    {
                        _tprintf(_T("%s\n"), pdilist[i].Name.Buffer);
                    }
                }
            }
            if(STATUS_MORE_ENTRIES == ntStatus)
            {
                start = idx;
                restart = FALSE;
                continue;
            }
            if((STATUS_SUCCESS == ntStatus) || (STATUS_NO_MORE_ENTRIES == ntStatus))
            {
                break;
            }
        }
        (void)NtClose_(hDeviceDir);
        return 0;
    }
    _tprintf(_T("Failed NtOpenDirectoryObject with 0x%08X"), ntStatus);
    return 1;
}

int _tmain(int /*argc*/, _TCHAR** /*argv*/)
{
    HMODULE hNtDll = ::GetModuleHandle(_T("ntdll.dll"));
    *(FARPROC*)&NtOpenDirectoryObject = ::GetProcAddress(hNtDll, "NtOpenDirectoryObject");
    *(FARPROC*)&NtQueryDirectoryObject = ::GetProcAddress(hNtDll, "NtQueryDirectoryObject");
    *(FARPROC*)&RtlInitUnicodeString_ = ::GetProcAddress(hNtDll, "RtlInitUnicodeString");
    *(FARPROC*)&NtClose_ = ::GetProcAddress(hNtDll, "NtClose");
    if (!NtOpenDirectoryObject || !NtQueryDirectoryObject || !RtlInitUnicodeString_ || !NtClose_)
    {
        _tprintf(_T("Failed to retrieve ntdll.dll function pointers\n"));
        return 1;
    }
    return PrintDevices();
}
</code>```

Some remarks: This will not delve into subdirectories, it will not list any types other than Device and it will not resolve symbolic links, if any. For any of those features, please look at the aforementioned utility's source code and adjust as needed. winternl.h should be available in any recent Windows SDK.

The functions RtlInitUnicodeString_ and NtClose_ have a trailing underscore to avoid clashes with these native API functions, which are declared in winternl.h, but use __declspec(dllimport).

Disclosure: I am the author of ntobjx.

Body:
As per the answer from user1575778 you can use NtOpenDirectoryObject and NtQueryDirectoryObject (which from user mode are identical to ZwOpenDirectoryObject and ZwQueryDirectoryObject respectively) to list the objects inside the object manager namespace.

Have a look at objmgr.hpp of NT Objects aka ntobjx, in particular at the class NtObjMgr::Directory (or DirectoryT). It provides the same functionality nicely wrapped into a C++ class. The whole utility is open source under a liberal license (dual-licensed due to WTL-use: MIT and MS-PL), so bits and pieces can be reused however you please, provided you comply with the license terms.

But here's a simple C++ code example catering just your use case:

#include <Windows.h>
#include <tchar.h>
#include <cstdio>
#include <winternl.h>

NTSTATUS (NTAPI* NtOpenDirectoryObject)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES);
NTSTATUS (NTAPI* NtQueryDirectoryObject)(HANDLE, PVOID, ULONG, BOOLEAN, BOOLEAN, PULONG, PULONG);
VOID (NTAPI* RtlInitUnicodeString_)(PUNICODE_STRING, PCWSTR);
NTSTATUS (NTAPI* NtClose_)(HANDLE);

#define DIRECTORY_QUERY                 (0x0001)
#define DIRECTORY_TRAVERSE              (0x0002)

typedef struct _OBJECT_DIRECTORY_INFORMATION {
    UNICODE_STRING Name;
    UNICODE_STRING TypeName;
} OBJECT_DIRECTORY_INFORMATION, *POBJECT_DIRECTORY_INFORMATION;

#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS                   ((NTSTATUS)0x00000000L) // ntsubauth
#endif // STATUS_SUCCESS
#ifndef STATUS_MORE_ENTRIES
#define STATUS_MORE_ENTRIES              ((NTSTATUS)0x00000105L)
#endif // STATUS_MORE_ENTRIES
#ifndef STATUS_NO_MORE_ENTRIES
#define STATUS_NO_MORE_ENTRIES           ((NTSTATUS)0x8000001AL)
#endif // STATUS_NO_MORE_ENTRIES

int PrintDevices()
{
    NTSTATUS ntStatus;
    OBJECT_ATTRIBUTES oa;
    UNICODE_STRING objname;
    HANDLE hDeviceDir = NULL;
    RtlInitUnicodeString_(&objname, L"\\Device");
    InitializeObjectAttributes(&oa, &objname, 0, NULL, NULL);
    ntStatus = NtOpenDirectoryObject(&hDeviceDir, DIRECTORY_QUERY | DIRECTORY_TRAVERSE, &oa);
    if(NT_SUCCESS(ntStatus))
    {
        size_t const bufSize = 0x10000;
        BYTE buf[bufSize] = {0};
        ULONG start = 0, idx = 0, bytes;
        BOOLEAN restart = TRUE;
        for(;;)
        {
            ntStatus = NtQueryDirectoryObject(hDeviceDir, PBYTE(buf), bufSize, FALSE, restart, &idx, &bytes);
            if(NT_SUCCESS(ntStatus))
            {
                POBJECT_DIRECTORY_INFORMATION const pdilist = reinterpret_cast<POBJECT_DIRECTORY_INFORMATION>(PBYTE(buf));
                for(ULONG i = 0; i < idx - start; i++)
                {
                    if(0 == wcsncmp(pdilist[i].TypeName.Buffer, L"Device", pdilist[i].TypeName.Length / sizeof(WCHAR)))
                    {
                        _tprintf(_T("%s\n"), pdilist[i].Name.Buffer);
                    }
                }
            }
            if(STATUS_MORE_ENTRIES == ntStatus)
            {
                start = idx;
                restart = FALSE;
                continue;
            }
            if((STATUS_SUCCESS == ntStatus) || (STATUS_NO_MORE_ENTRIES == ntStatus))
            {
                break;
            }
        }
        (void)NtClose_(hDeviceDir);
        return 0;
    }
    _tprintf(_T("Failed NtOpenDirectoryObject with 0x%08X"), ntStatus);
    return 1;
}

int _tmain(int /*argc*/, _TCHAR** /*argv*/)
{
    HMODULE hNtDll = ::GetModuleHandle(_T("ntdll.dll"));
    *(FARPROC*)&NtOpenDirectoryObject = ::GetProcAddress(hNtDll, "NtOpenDirectoryObject");
    *(FARPROC*)&NtQueryDirectoryObject = ::GetProcAddress(hNtDll, "NtQueryDirectoryObject");
    *(FARPROC*)&RtlInitUnicodeString_ = ::GetProcAddress(hNtDll, "RtlInitUnicodeString");
    *(FARPROC*)&NtClose_ = ::GetProcAddress(hNtDll, "NtClose");
    if (!NtOpenDirectoryObject || !NtQueryDirectoryObject || !RtlInitUnicodeString_ || !NtClose_)
    {
        _tprintf(_T("Failed to retrieve ntdll.dll function pointers\n"));
        return 1;
    }
    return PrintDevices();
}

Some remarks: This will not delve into subdirectories, it will not list any types other than Device and it will not resolve symbolic links, if any. For any of those features, please look at the aforementioned utility's source code and adjust as needed. winternl.h should be available in any recent Windows SDK.

The functions RtlInitUnicodeString_ and NtClose_ have a trailing underscore to avoid clashes with these native API functions, which are declared in winternl.h, but use __declspec(dllimport).

Disclosure: I am the author of ntobjx.


答:
One option is to use ternary if.

var age = $('#age').val();
var fn = $('#fn').val();
var ln = $('#ln').val();
var city = $('#city').val();
var country = $('#country').val();

var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-penis-record" + (age != undefined ? "&age=" + age : '') + (fn != undefined ? "&fn=" + fn : '')  + (ln != undefined ? "&ln=" + ln : '') + (city != undefined ? "&city=" + city : '') + (country != undefined ? "&country=" + country : '');

console.log(link);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Javascript append to url if not null

Body:
One option is to use ternary if.

var age = $('#age').val();
var fn = $('#fn').val();
var ln = $('#ln').val();
var city = $('#city').val();
var country = $('#country').val();

var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-penis-record" + (age != undefined ? "&age=" + age : '') + (fn != undefined ? "&fn=" + fn : '')  + (ln != undefined ? "&ln=" + ln : '') + (city != undefined ? "&city=" + city : '') + (country != undefined ? "&country=" + country : '');

console.log(link);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Spring 5 "No LookupPath attribute" exception
Having a Spring rest controller which use Spring 5 router functions
When I use Postman client to make a request, every thing works fine.
However making a request from another origin which is Angular 4 application cause this exception.

java.lang.IllegalStateException: No LookupPath attribute.
      at org.springframework.web.server.support.LookupPath.lambda$getCurrent$1(LookupPath.java:106) ~[spring-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
      at java.util.Optional.orElseThrow(Optional.java:290) ~[na:1.8.0_72]
      at org.springframework.web.server.support.LookupPath.getCurrent(LookupPath.java:106) ~[spring-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
      at org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource.getCorsConfiguration(UrlBasedCorsConfigurationSource.java:84) ~[spring-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
      at org.springframework.web.reactive.handler.AbstractHandlerMapping.lambda$getHandler$1(AbstractHandlerMapping.java:163) ~[spring-webflux-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]

```<code>@RestController
public class AdminRest {
public RouterFunction<ServerResponse> route() {
    return RouterFunctions
            .route(RequestPredicates.GET("/admin/orgnaizationUsers"), this::getOrgnaizationUsers)
}

private Mono<ServerResponse> getOrgnaizationUsers(ServerRequest request) {
    return Mono
            .just(request)
            .then(
                    Flux.from(organizationUserPostgresCollection.executeQuery("SELECT * FROM organization_user"))
                    .map(OrganizationUserDTO::convert)
                    .collectList()
                    .map(OrganizationUsersDTOView::new))
            .flatMap(
                    organizationUsersDTOView -> ServerResponse.ok().header("Access-Control-Allow-Origin", "*")
                            .body(Mono.just(organizationUsersDTOView), OrganizationUsersDTOView.class))
            .switchIfEmpty(ServerResponse.notFound().header("Access-Control-Allow-Origin", "*").build());
}
}
</code>```

Please check
https://github.com/spring-projects/spring-framework/commit/cf1bc8119999e2bf3f41ae572f5b83536685ce5e

答:
It seems that the issue arises when UrlBasedCorsConfigurationSource tries to retrieve the LookupPath before it has been initialized. You can get around of this, for now at least, by adding a new Webfilter in your application that creates the lookup path.

This can be done like this for example:

```<code>@Component
public class SomeFilter extends WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        LookupPath.getOrCreate(exchange, new HttpRequestPathHelper());
        return chain.filter(exchange);
    }
 }
</code>```

Body:
Having a Spring rest controller which use Spring 5 router functions
When I use Postman client to make a request, every thing works fine.
However making a request from another origin which is Angular 4 application cause this exception.

java.lang.IllegalStateException: No LookupPath attribute.
      at org.springframework.web.server.support.LookupPath.lambda$getCurrent$1(LookupPath.java:106) ~[spring-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
      at java.util.Optional.orElseThrow(Optional.java:290) ~[na:1.8.0_72]
      at org.springframework.web.server.support.LookupPath.getCurrent(LookupPath.java:106) ~[spring-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
      at org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource.getCorsConfiguration(UrlBasedCorsConfigurationSource.java:84) ~[spring-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
      at org.springframework.web.reactive.handler.AbstractHandlerMapping.lambda$getHandler$1(AbstractHandlerMapping.java:163) ~[spring-webflux-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]

@RestController
public class AdminRest {
public RouterFunction<ServerResponse> route() {
    return RouterFunctions
            .route(RequestPredicates.GET("/admin/orgnaizationUsers"), this::getOrgnaizationUsers)
}

private Mono<ServerResponse> getOrgnaizationUsers(ServerRequest request) {
    return Mono
            .just(request)
            .then(
                    Flux.from(organizationUserPostgresCollection.executeQuery("SELECT * FROM organization_user"))
                    .map(OrganizationUserDTO::convert)
                    .collectList()
                    .map(OrganizationUsersDTOView::new))
            .flatMap(
                    organizationUsersDTOView -> ServerResponse.ok().header("Access-Control-Allow-Origin", "*")
                            .body(Mono.just(organizationUsersDTOView), OrganizationUsersDTOView.class))
            .switchIfEmpty(ServerResponse.notFound().header("Access-Control-Allow-Origin", "*").build());
}
}

Please check
https://github.com/spring-projects/spring-framework/commit/cf1bc8119999e2bf3f41ae572f5b83536685ce5e

Body:
It seems that the issue arises when UrlBasedCorsConfigurationSource tries to retrieve the LookupPath before it has been initialized. You can get around of this, for now at least, by adding a new Webfilter in your application that creates the lookup path.

This can be done like this for example:

@Component
public class SomeFilter extends WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        LookupPath.getOrCreate(exchange, new HttpRequestPathHelper());
        return chain.filter(exchange);
    }
 }


问:
Freeing memory of ThreeJS application
I am currently having issues with freeing memory in my ThreeJS application.

I am aware there are already several questions about this problem:

freeing memory in three.js

Freeing memory with threejs

Three.js Collada - What's the proper way to dispose() and release memory (garbage collection)?

I do dispose my objects using the following Typescript function I've made :

```<code>function dispose( object3D: THREE.Object3D ): void
{
    // Dispose children first
    for ( let childIndex = 0; childIndex < object3D.children.length; ++childIndex )
    {
        this.dispose( object3D.children[childIndex] );
    }

    object3D.children = [];

    if ( object3D instanceof THREE.Mesh )
    {
        // Geometry
        object3D.geometry.dispose();

        // Material(s)
        if ( object3D.material instanceof THREE.MultiMaterial )
        {
            for ( let matIndex = 0; matIndex < object3D.material.materials.length; ++matIndex )
            {
                object3D.material.materials[matIndex].dispose();
                object3D.material.materials[matIndex] = null;
            }
            object3D.material.materials = [];
        }

        if ( object3D.material.dispose )
        {
            object3D.material.dispose();
            object3D.material = null;
        }
    }

    // Remove from parent
    if ( object3D.parent )
        object3D.parent.remove( object3D );

    object3D = null;
}
</code>```

However, when I do heap snapshots using Chrome Dev Tools, I still have tons and tons of :

Arrays

Vector2 (uvs in __directGeometry , ... )

Vector3 (vertices in geometry, normal in faces, vertexColors in faces, ...)

Face3 (faces in geometry)

Color (colors in __directGeometry, ...)

JSArrayBufferData (color, normal, in attributes of geometry, ...)

Because of all the data in memory, my application gets killed by Jetsam on iOS, see : Jetsam kills WebGL application on iOS

I suspect some data inside the library is not freed up when I ask it to.

答:
Try to dispose just everything. I'm using this snippet for a while. It disposes  materials, textures, 3d objects. It iterates over arrays and plain objects.

let dispose = function(o) {
    try {
        if (o && typeof o === 'object') {
            if (Array.isArray(o)) {
                o.forEach(dispose);
            } else
            if (o instanceof THREE.Object3D) {
                dispose(o.geometry);
                dispose(o.material);
                if (o.parent) {
                    o.parent.remove(o);
                }
                dispose(o.children);
            } else
            if (o instanceof THREE.Geometry) {
                o.dispose();
            } else
            if (o instanceof THREE.Material) {
                o.dispose();
                dispose(o.materials);
                dispose(o.map);
                dispose(o.lightMap);
                dispose(o.bumpMap);
                dispose(o.normalMap);
                dispose(o.specularMap);
                dispose(o.envMap);
            } else
            if (typeof o.dispose === 'function') {
                o.dispose();
            } else {
                Object.values(o).forEach(dispose);
            }
        }
    } catch (error) {
        console.log(error);
    }
};
```

Title: Freeing memory of ThreeJS application

Body:
I am currently having issues with freeing memory in my ThreeJS application.

I am aware there are already several questions about this problem:

freeing memory in three.js

Freeing memory with threejs

Three.js Collada - What's the proper way to dispose() and release memory (garbage collection)?

I do dispose my objects using the following Typescript function I've made :

function dispose( object3D: THREE.Object3D ): void
{
    // Dispose children first
    for ( let childIndex = 0; childIndex < object3D.children.length; ++childIndex )
    {
        this.dispose( object3D.children[childIndex] );
    }

    object3D.children = [];

    if ( object3D instanceof THREE.Mesh )
    {
        // Geometry
        object3D.geometry.dispose();

        // Material(s)
        if ( object3D.material instanceof THREE.MultiMaterial )
        {
            for ( let matIndex = 0; matIndex < object3D.material.materials.length; ++matIndex )
            {
                object3D.material.materials[matIndex].dispose();
                object3D.material.materials[matIndex] = null;
            }
            object3D.material.materials = [];
        }

        if ( object3D.material.dispose )
        {
            object3D.material.dispose();
            object3D.material = null;
        }
    }

    // Remove from parent
    if ( object3D.parent )
        object3D.parent.remove( object3D );

    object3D = null;
}

However, when I do heap snapshots using Chrome Dev Tools, I still have tons and tons of :

Arrays

Vector2 (uvs in __directGeometry , ... )

Vector3 (vertices in geometry, normal in faces, vertexColors in faces, ...)

Face3 (faces in geometry)

Color (colors in __directGeometry, ...)

JSArrayBufferData (color, normal, in attributes of geometry, ...)

Because of all the data in memory, my application gets killed by Jetsam on iOS, see : Jetsam kills WebGL application on iOS

I suspect some data inside the library is not freed up when I ask it to.


问:
Prawn PDF Compression, compress content streams, what does it do
The prawn gem has an initialize option :compress, which is described here.

Apparently it "Compresses content streams before rendering them".

With and without compress: true I generated the same 14 page pdf twice. Each page has 2 photos and all sorts of text. The resulting file size was the exact same.

So my question is: in production with larger quantities of photos will I see a difference in file sizes? Or maybe compress: true eats more or less RAM during processing? What is its purpose?

答:
A more effective way to compress PDFs is to postprocess using Ghostscript, using a command such as:

```<code>ghostscript -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dUseCIEColor -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile=<output.pdf> <input.pdf>
</code>```

This typically reduces the size of my Prawn-generated PDFs by 50% or more. The dPDFSETTINGS option can be set to different values to change the amount of compression - see the Ghostscript docs.

Body:
A more effective way to compress PDFs is to postprocess using Ghostscript, using a command such as:

ghostscript -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dUseCIEColor -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile=<output.pdf> <input.pdf>

This typically reduces the size of my Prawn-generated PDFs by 50% or more. The dPDFSETTINGS option can be set to different values to change the amount of compression - see the Ghostscript docs.


问:
The "SlowCheetah.Xdt.TransformXml" task could not be loaded from the assembly
After installing Slow Cheeath (v. 2.5.10.3) to two projects in my solution, I am receiving the following error:

```<code>"The "SlowCheetah.Xdt.TransformXml" task could not be loaded from the assembly C:\Users
\User\AppData\Local\Microsoft\MSBuild\SlowCheetah\v2.5.10.2\SlowCheetah.Xdt.dll. Could
not load file or assembly 'file:///C:\Users\User\AppData\Local\Microsoft\MSBuild
\SlowCheetah\v2.5.10.2\SlowCheetah.Xdt.dll' or one of its dependencies. The system cannot
find the file specified. Confirm that the <UsingTask> declaration is correct, that the
assembly and all its dependencies are available, and that the task contains a public
class that implements Microsoft.Build.Framework.ITask.  ISA.IMPD.FalseAlarm.Web.Portal"
</code>```

I have removed both projects in their entirety (along with Slow Cheetah), re-installed both projects (along with Slow Cheetah), and Rebuilt the solution to no avail.  Can anyone help with this type of error?

答:
They've released a new version which brings the installation procedure up to date:

https://blogs.msdn.microsoft.com/visualstudio/2017/05/25/whats-new-and-improved-with-the-slowcheetah-extension/

Tired of having to install your NuGet packages manually to get
  SlowCheetah to work? We’ve added automatic NuGet installation to help
  streamline your process. All you need to install is the latest
  extension and SlowCheetah will take care of the rest. When you use
  SlowCheetah for the first time in a project, it will prompt you to
  install or update NuGet packages. Agree and you’re ready to go!

Close Visual Studio

Install the VISX extension

Open your project.

This version detects if you already have it installed and offers to upgrade.

I would recommend checking in to source control and then doing a compare of your .csproj file to see what changes it made.

Body:
After installing Slow Cheeath (v. 2.5.10.3) to two projects in my solution, I am receiving the following error:

"The "SlowCheetah.Xdt.TransformXml" task could not be loaded from the assembly C:\Users
\User\AppData\Local\Microsoft\MSBuild\SlowCheetah\v2.5.10.2\SlowCheetah.Xdt.dll. Could
not load file or assembly 'file:///C:\Users\User\AppData\Local\Microsoft\MSBuild
\SlowCheetah\v2.5.10.2\SlowCheetah.Xdt.dll' or one of its dependencies. The system cannot
find the file specified. Confirm that the <UsingTask> declaration is correct, that the
assembly and all its dependencies are available, and that the task contains a public
class that implements Microsoft.Build.Framework.ITask.  ISA.IMPD.FalseAlarm.Web.Portal"

I have removed both projects in their entirety (along with Slow Cheetah), re-installed both projects (along with Slow Cheetah), and Rebuilt the solution to no avail.  Can anyone help with this type of error?


问:
How do I get Visual Studio Intellisense tooltips to show descriptions for .NET Framework 3.5?
I need to use .NET framework 3.5 for my project because it uses some older functionality.

The tooltips in Visual Studio aren't showing descriptions like they do when targeting a later framework. I just see basic information like method signatures and data types. Is there a way to fix this?

I looked for the xml files in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5 and it looks like it just has the files for the 3.5 Client Profile.

I tried reinstalling the 3.5 framework from this link: https://www.microsoft.com/en-us/download/details.aspx?id=21

I have no idea if it's working or not. When I run the executable nothing happens. I tried running as administrator. When I run it from command prompt there is no output.

I noticed the file is a hundred times smaller that the download for the latest .NET framework. Does that mean it doesn't include the files it's supposed to?

I'm guessing if there's a fix, it's either getting the correct xml files for .NET 3.5 or getting Visual Studio to use the xml files for .NET 4.6 even though my project is targeting 3.5.

Thanks in advance!

答:
I don't think the earlier versions of .net provide the level of tooltips that your after unfortunately. One last thing you could try is to ensure you have all of the elements in the "Add windows programs and features" enabled. Not sure what version of windows your running on but this should explain what I mean:

https://learn.microsoft.com/en-us/dotnet/framework/install/dotnet-35-windows-10

You can enable the .NET Framework 3.5 through the Windows Control Panel. This option requires an Internet connection.

Press the Windows key Windows Windows logo on your keyboard, type "Windows Features", and press Enter. The Turn Windows features on or off dialog box appears.

Select the .NET Framework 3.5 (includes .NET 2.0 and 3.0)
  check box, select OK, and reboot your computer if prompted.


问:
excel won't close after procedure is run
I run this code and excel session won't destroy or close.  I know that I am not using sheets.add or ws.delete because it says With Validation and I don't know how to use the single lines declaring my objects.  I don't know the syntax I guess.  Here is the code.  Can someone point out how to fix it?

```<code>Public Function ComboLists()
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim MyFileName As String
Dim bfile As String
Dim MyList(1) As String
Dim lRow As Long

bfile = "S:\_Reports\KSMS\Designated Letter\KSMS Designated Letter - "

MyFileName = bfile & Format(Date, "mm-dd-yyyy") & ".xls"

On Error Resume Next
Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0

Set wb = xlApp.Workbooks.Open(MyFileName)
Set ws = wb.Sheets(1)
ws.Activate
xlApp.DisplayAlerts = False

MyList(0) = "Approve Location"
MyList(1) = "Delete Location"

lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

i = 2

For Each c In wb.Sheets(1).Range("M" & lRow)

If ws.Cells(i, 12).Value = "US" Then
rng = "M" & i '& ":" & "Z" & i

With Range(rng).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
     Operator:=xlBetween, Formula1:=Join(MyList, ",")
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
End With
Else
rng = "A" & i & ":" & "L" & i
With xlApp.Range(rng).Validation
ws.Delete
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
'wb.Close savechanges:=False
End With
End If

i = i + 1

Next c

Set ws = wb.Sheets(1)
ws.Activate

ws.Cells.Rows("1:1").Select

wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
wb.Close savechanges:=False

xlApp.Quit
xlApp.Quit
xlApp.Quit
xlApp.Quit

Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing

Exit Function

End Function
</code>```

I would appreciate any help on this.

答:
```<code>Public Function ComboLists()
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim MyFileName As String
Dim bfile As String
Dim MyList(1) As String
Dim lRow As Long

bfile = "S:\_Reports\KSMS\Designated Letter\KSMS Designated Letter - "

MyFileName = bfile & Format(Date, "mm-dd-yyyy") & ".xls"

On Error Resume Next
Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0

Set wb = xlApp.Workbooks.Open(MyFileName)
Set ws = wb.Sheets(1)
ws.Activate
xlApp.DisplayAlerts = False

MyList(0) = "Approve Location"
MyList(1) = "Delete Location"

lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

MsgBox lRow

i = 2

'For Each c In wb.Sheets(1).Range("M2:M1000") '" & Range("V" & Rows.count).End(xlUp).Row)
For Each c In wb.Sheets(1).Range("M" & lRow)

If ws.Cells(i, 12).Value = "US" Then
rng = "M" & i '& ":" & "Z" & i

With xlApp.Range(rng).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
     Operator:=xlBetween, Formula1:=Join(MyList, ",")
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
DoEvents
End With
Else
rng = "A" & i & ":" & "L" & i
With xlApp.Range(rng).Validation
ws.Delete
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
DoEvents
End With
DoEvents
End If

i = i + 1

Next c

DoEvents

Set ws = wb.Sheets(1)
ws.Activate

ws.Cells.Rows("1:1").Select

wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
wb.Close savechanges:=False
DoEvents
MsgBox "quit"
xlApp.Quit

Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing

Exit Function

End Function
</code>```

I add the lrow lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row I added ws. in front of cells and ws in front of rows and that helped destroy the session

Body:
I run this code and excel session won't destroy or close.  I know that I am not using sheets.add or ws.delete because it says With Validation and I don't know how to use the single lines declaring my objects.  I don't know the syntax I guess.  Here is the code.  Can someone point out how to fix it?

Public Function ComboLists()
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim MyFileName As String
Dim bfile As String
Dim MyList(1) As String
Dim lRow As Long

bfile = "S:\_Reports\KSMS\Designated Letter\KSMS Designated Letter - "

MyFileName = bfile & Format(Date, "mm-dd-yyyy") & ".xls"

On Error Resume Next
Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0

Set wb = xlApp.Workbooks.Open(MyFileName)
Set ws = wb.Sheets(1)
ws.Activate
xlApp.DisplayAlerts = False

MyList(0) = "Approve Location"
MyList(1) = "Delete Location"

lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

i = 2

For Each c In wb.Sheets(1).Range("M" & lRow)

If ws.Cells(i, 12).Value = "US" Then
rng = "M" & i '& ":" & "Z" & i

With Range(rng).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
     Operator:=xlBetween, Formula1:=Join(MyList, ",")
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
End With
Else
rng = "A" & i & ":" & "L" & i
With xlApp.Range(rng).Validation
ws.Delete
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
'wb.Close savechanges:=False
End With
End If

i = i + 1

Next c

Set ws = wb.Sheets(1)
ws.Activate

ws.Cells.Rows("1:1").Select

wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
wb.Close savechanges:=False

xlApp.Quit
xlApp.Quit
xlApp.Quit
xlApp.Quit

Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing

Exit Function

End Function

I would appreciate any help on this.

Body:
Public Function ComboLists()
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim MyFileName As String
Dim bfile As String
Dim MyList(1) As String
Dim lRow As Long

bfile = "S:\_Reports\KSMS\Designated Letter\KSMS Designated Letter - "

MyFileName = bfile & Format(Date, "mm-dd-yyyy") & ".xls"

On Error Resume Next
Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0

Set wb = xlApp.Workbooks.Open(MyFileName)
Set ws = wb.Sheets(1)
ws.Activate
xlApp.DisplayAlerts = False

MyList(0) = "Approve Location"
MyList(1) = "Delete Location"

lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

MsgBox lRow

i = 2

'For Each c In wb.Sheets(1).Range("M2:M1000") '" & Range("V" & Rows.count).End(xlUp).Row)
For Each c In wb.Sheets(1).Range("M" & lRow)

If ws.Cells(i, 12).Value = "US" Then
rng = "M" & i '& ":" & "Z" & i

With xlApp.Range(rng).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
     Operator:=xlBetween, Formula1:=Join(MyList, ",")
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
DoEvents
End With
Else
rng = "A" & i & ":" & "L" & i
With xlApp.Range(rng).Validation
ws.Delete
wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
DoEvents
End With
DoEvents
End If

i = i + 1

Next c

DoEvents

Set ws = wb.Sheets(1)
ws.Activate

ws.Cells.Rows("1:1").Select

wb.CheckCompatibility = False
wb.Save
wb.CheckCompatibility = True
wb.Close savechanges:=False
DoEvents
MsgBox "quit"
xlApp.Quit

Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing

Exit Function

End Function

I add the lrow lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row I added ws. in front of cells and ws in front of rows and that helped destroy the session


问:
Which files to edit for HTML/CSS in my application (ruby)
I made my application with the following introduction:
http://guides.rubyonrails.org/getting_started.html

Now I want to make it more colourful etc (CSS f.eg).
I found now the JavaScript and CSS files, but I dont know which file are responsible for the editing.

[![enter image description here][1]][1]

Which file should I use for editing the websites?

答: You can also add some custom.css.scss file in app/assets/stylesheets and add your code there. In this file you can use custom styles, as far as application.css is concerned it will style the complete application. I hope this helps.</p>


问:
Why does an XML attribute without explicitely specified namespace not get assigned to the default namespace
I am parsing this XML document:

```<code><?xml version='1.0' encoding='UTF-8'?>
<team xmlns='http://www.example.com/default' xmlns:ns1='http://www.example.com/ns1'>
    <ns1:coach ns1:coachAttr="ABC"/>
    <player playerAttr="XYZ"/>
</team>
</code>```

I would expect player and playAttr to be in the http://www.example.com/default namespace, while coach and coachAttr would be in the http://www.example.com/ns1 namespace.

Turns out playerAttr has no namespace at all. Here is the code:

```<code>String xml="...";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));

Element team = doc.getDocumentElement();
Element player = (Element) team.getChildNodes().item(...);
Element coach = (Element) team.getChildNodes().item(...);
Attr playerAttr = (Attr) player.getAttributes().item(...);
Attr coachAttr = (Attr) coach.getAttributes().item(...);

System.out.println("coach: Name=" + coach.getLocalName() + " NS=" + coach.getNamespaceURI());
System.out.println("coachAttr: Name=" + coachAttr.getLocalName() + " NS=" + coachAttr.getNamespaceURI());
System.out.println("player: Name=" + player.getLocalName() + " NS=" + player.getNamespaceURI());
System.out.println("playerAttr: Name=" + playerAttr.getLocalName() + " NS=" + playerAttr.getNamespaceURI());
</code>```

This prints out 4 lines. The first 3 make sense to me. I do not understand the last line, where NS is null.

```<code>coach: Name=coach NS=http://www.example.com/ns1
coachAttr: Name=coachAttr NS=http://www.example.com/ns1
player: Name=player NS=http://www.example.com/default
playerAttr: Name=playerAttr NS=null
</code>```

Why is playerAttr treated differently? Is this in some kind of spec? What does it even mean that an items has no namespace?

答:
Every XML parser behaves like this. Since your question is 'why', I would guess that this is simply an easier approach for most practical purposes.

More details here:

https://stackoverflow.com/a/3313538/80911

Body:
I am parsing this XML document:

<?xml version='1.0' encoding='UTF-8'?>
<team xmlns='http://www.example.com/default' xmlns:ns1='http://www.example.com/ns1'>
    <ns1:coach ns1:coachAttr="ABC"/>
    <player playerAttr="XYZ"/>
</team>

I would expect player and playAttr to be in the http://www.example.com/default namespace, while coach and coachAttr would be in the http://www.example.com/ns1 namespace.

Turns out playerAttr has no namespace at all. Here is the code:

String xml="...";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));

Element team = doc.getDocumentElement();
Element player = (Element) team.getChildNodes().item(...);
Element coach = (Element) team.getChildNodes().item(...);
Attr playerAttr = (Attr) player.getAttributes().item(...);
Attr coachAttr = (Attr) coach.getAttributes().item(...);

System.out.println("coach: Name=" + coach.getLocalName() + " NS=" + coach.getNamespaceURI());
System.out.println("coachAttr: Name=" + coachAttr.getLocalName() + " NS=" + coachAttr.getNamespaceURI());
System.out.println("player: Name=" + player.getLocalName() + " NS=" + player.getNamespaceURI());
System.out.println("playerAttr: Name=" + playerAttr.getLocalName() + " NS=" + playerAttr.getNamespaceURI());

This prints out 4 lines. The first 3 make sense to me. I do not understand the last line, where NS is null.

coach: Name=coach NS=http://www.example.com/ns1
coachAttr: Name=coachAttr NS=http://www.example.com/ns1
player: Name=player NS=http://www.example.com/default
playerAttr: Name=playerAttr NS=null

Why is playerAttr treated differently? Is this in some kind of spec? What does it even mean that an items has no namespace?


问:
Paging in Entity Framework
In Entity Framework, using LINQ to Entities, database paging is usually done in following manner:

```<code>int totalRecords = EntityContext.Context.UserSet.Count;
var list     = EntityContext.Context.UserSet
                 .Skip(startingRecordNumber)
                 .Take(pageSize)
                 .ToList();
</code>```

This results in TWO database calls.

Please tell, how to reduce it to ONE database call.

Thank You.

答:
This queries are too small for DBManager and I can not understand why you want to do this, anyway for reduce it to ONE database call use this:</p>

```<code>var list     = EntityContext.Context.UserSet
                 .Skip(startingRecordNumber)
                 .Take(pageSize)
                 .ToList();
int totalRecords = list.Count;
</code>```

Title: Paging in Entity Framework

Body:
In Entity Framework, using LINQ to Entities, database paging is usually done in following manner:

int totalRecords = EntityContext.Context.UserSet.Count;
var list     = EntityContext.Context.UserSet
                 .Skip(startingRecordNumber)
                 .Take(pageSize)
                 .ToList();

This results in TWO database calls.

Please tell, how to reduce it to ONE database call.

Thank You.

Body:
This queries are too small for DBManager and I can not understand why you want to do this, anyway for reduce it to ONE database call use this:

var list     = EntityContext.Context.UserSet
                 .Skip(startingRecordNumber)
                 .Take(pageSize)
                 .ToList();
int totalRecords = list.Count;


问:
Adding a third line to a twoord plot
I have a twoord plot produced with the plotrix package and would like to add a horizontal line representing a particular value to it. The plot is all set up but I need help adding the line.

Here is some sample code:

```<code>fake <- matrix(c(1, 2, 3, 4, 5, 22, 30, 47, 98, 62, 20, 40, 10, 15, 15), nrow = 5)
fake <- as.data.frame(m)

horizontallineat <- 50

twrd.p <- twoord.plot(fake$V1,fake$V3,fake$V1,fake$V2, xlab="Bin",
                  lylim=c(0,100),rylim=c(0,100),type=c("bar","l"),
                  ylab="Exposure Percentage",rylab="Bin Average PP",
                  lytickpos=seq(0,100, by = 10),
                  rytickpos=seq(0,100, by = 10),
                  ylab.at=50,rylab.at=50,
                  main="Variable Name",
                  lcol=3,rcol=4)
</code>```

This is the plot

Thank you in advance for any insight you are able to offer.

答:
I am not sure whether this is what you want, but you can simply add line with the R-base lines function. Use code like this

```<code>library(plotrix) # added library

## your code
fake <- matrix(c(1, 2, 3, 4, 5, 22, 30, 47, 98, 62, 20, 40, 10, 15, 15), nrow = 5)
fake <- as.data.frame(fake)  # changed "m" to "fake"

twrd.p <- twoord.plot(fake$V1,fake$V3,fake$V1,fake$V2, xlab="Bin",
                      lylim=c(0,100),rylim=c(0,100),type=c("bar","l"),
                      ylab="Exposure Percentage",rylab="Bin Average PP",
                      lytickpos=seq(0,100, by = 10),
                      rytickpos=seq(0,100, by = 10),
                      ylab.at=50,rylab.at=50,
                      main="Variable Name",
                      lcol=3,rcol=4)

## simple lines() function with x an y coordinates
## we'll add 2 lines for fun
## 1. dashed, thicker, and red
## 2. dots, thicker and black
lines(x = c(1, 2, 3, 4), y= c(40, 60, 40, 70), lty = 2, lwd = 2, col = "red")
lines(x = c(1.25 , 4.75), y = c(95, 25), lty = 3, lwd=2, col = "black")
</code>```

This yields the following plot

Adding a short or long horizontal line should be simple now, I hope.

Please let me know whether this is what you had in mind.

Title: Adding a third line to a twoord plot

Body:
I have a twoord plot produced with the plotrix package and would like to add a horizontal line representing a particular value to it. The plot is all set up but I need help adding the line.

Here is some sample code:

fake <- matrix(c(1, 2, 3, 4, 5, 22, 30, 47, 98, 62, 20, 40, 10, 15, 15), nrow = 5)
fake <- as.data.frame(m)

horizontallineat <- 50

twrd.p <- twoord.plot(fake$V1,fake$V3,fake$V1,fake$V2, xlab="Bin",
                  lylim=c(0,100),rylim=c(0,100),type=c("bar","l"),
                  ylab="Exposure Percentage",rylab="Bin Average PP",
                  lytickpos=seq(0,100, by = 10),
                  rytickpos=seq(0,100, by = 10),
                  ylab.at=50,rylab.at=50,
                  main="Variable Name",
                  lcol=3,rcol=4)

This is the plot

Thank you in advance for any insight you are able to offer.

Body:
I am not sure whether this is what you want, but you can simply add line with the R-base lines function. Use code like this

library(plotrix) # added library

## your code
fake <- matrix(c(1, 2, 3, 4, 5, 22, 30, 47, 98, 62, 20, 40, 10, 15, 15), nrow = 5)
fake <- as.data.frame(fake)  # changed "m" to "fake"

twrd.p <- twoord.plot(fake$V1,fake$V3,fake$V1,fake$V2, xlab="Bin",
                      lylim=c(0,100),rylim=c(0,100),type=c("bar","l"),
                      ylab="Exposure Percentage",rylab="Bin Average PP",
                      lytickpos=seq(0,100, by = 10),
                      rytickpos=seq(0,100, by = 10),
                      ylab.at=50,rylab.at=50,
                      main="Variable Name",
                      lcol=3,rcol=4)

## simple lines() function with x an y coordinates
## we'll add 2 lines for fun
## 1. dashed, thicker, and red
## 2. dots, thicker and black
lines(x = c(1, 2, 3, 4), y= c(40, 60, 40, 70), lty = 2, lwd = 2, col = "red")
lines(x = c(1.25 , 4.75), y = c(95, 25), lty = 3, lwd=2, col = "black")

This yields the following plot

Adding a short or long horizontal line should be simple now, I hope.

Please let me know whether this is what you had in mind.


问:
Fastest way to check whether the cursor returned by a template helper is empty?
I often do something like this, using the items helper twice:

```<code>{{#if items}}
<h1>Items</h1>
  {{#each items}}
    {{> item}}
  {{/each}}
{{/if}}

Template.foo.helpers
  items: ->
    Items.find
      bar: true
    ,
      sort: created: -1
      transform: (item) ->
        i.good = true
        i
</code>```

Is Meteor doing extra work in this scenario? Would it be more efficient to switch the if to use something like areItems?

```<code>areItems: ->
  Items.find
    bar: true
  .count() > 0
</code>```

答:
I found that simply {{#if items.count}} was sufficient.

```<code>{{#if items.count}}
  <h2>Below there are items</h2>
{{/if}}

{{#each items}}
  <div class="item-name">{{this.name}}</div>
{{else}}
  <h2>There are no items</h2>
{{else}}
</code>```

Body:
I often do something like this, using the items helper twice:

{{#if items}}

Items

  {{#each items}}
    {{> item}}
  {{/each}}
{{/if}}

Template.foo.helpers
  items: ->
    Items.find
      bar: true
    ,
      sort: created: -1
      transform: (item) ->
        i.good = true
        i

Is Meteor doing extra work in this scenario? Would it be more efficient to switch the if to use something like areItems?

areItems: ->
  Items.find
    bar: true
  .count() > 0

Body:
I found that simply {{#if items.count}} was sufficient.

{{#if items.count}}
  <h2>Below there are items</h2>
{{/if}}

{{#each items}}
  <div class="item-name">{{this.name}}</div>
{{else}}
  <h2>There are no items</h2>
{{else}}


问:
Is it possible to export saved passwords from Toad
I'm looking for a way to export saved usernames/passwords from Toad for Oracle (9.5.0.31).  It doesn't have to be in a usable format for importing - even a plaintext format would be fine.

I believe the passwords are stored encrypted in CONNECTIONPWDS.INI, but from what I've read, that file doesn't transfer from one machine to another.  There doesn't seem to be anything in the Quest site or the Yahoo groups about this, other than "That's a very good suggestion...".

Has anyone had any luck accomplishing this?  Or am I stuck with having to dig up the passwords for each of my accounts?

Thanks

答: i've always used the copy user files from utilities .. copy user files and then I do an export.  when I reinstall on a new machine/laptop after lease rollout, I then import my user settings using the zip file created and everything is populated.  passwords, settings, connection information etc. </p>


问:
Javascript append to url if not null
I want to append the values if they are not null to the link. It doesn't allow the if in the string, so what should i do instead?     </p>

```<code>    var age = $('#age').val();
    var fn = $('#fn').val();
    var ln = $('#ln').val();
    var city = $('#city').val();
    var country = $('#country').val();

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record" if(age !=null){ "&age=" + age + } "&fn=" + fn + "&ln=" + ln + "&city=" + city + "&country=" + country;
</code>```

答:
Lacking the fields themselves, I wonder if this might not do what you're trying for.

 var myFields = {
   age: $("#age").val,
   fn : $("#fn").val,
   ln : $("#ln").val,
   city: $("#city").val(),
   country: $("#country").val()
  }

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record";

    $.each(myFields, function(key, value){
      if(value){
        link += "&"+key+"="+value;
      }
    }```

Title: Javascript append to url if not null

Body:
I want to append the values if they are not null to the link. It doesn't allow the if in the string, so what should i do instead?

    var age = $('#age').val();
    var fn = $('#fn').val();
    var ln = $('#ln').val();
    var city = $('#city').val();
    var country = $('#country').val();

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record" if(age !=null){ "&age=" + age + } "&fn=" + fn + "&ln=" + ln + "&city=" + city + "&country=" + country;