text:
Q: How do I select a random row from database in grails? I am trying to make a simple Quiz Application in Grails. I am having problem that i need to select a random row from the question table and display, and each time the user submits the answer, the question must be different.
I am new to grails...
I have a controller class named QuizController.groovy
and in controller, i have
playQuiz() which should render a gsp page named playQuiz.gsp with one question at a time.
My domain for question is Question which have following
int id
    String question
    String answer1
    String answer2
    String answer3
    String answer4
    int correctAnswer
In database there may be numbers of rows populated with the datas, and i need to take one data at a time in random.
I need help with the data fetching from database in random order.
Thanks in advance!

A: Try this, was tested with Grails 2.5.3:
def randomQuestion = Question.find("from Question order by rand()")

A: It is not very difficult. Hibernate Criteria has methods to specify the first result index: setFirstResult(int firstResult) and max rows count: setMaxResults(int maxResults).
int rowsCount = getRowsCount();
int randomRowIndex = getRandomNumberLessThan(rowsCount);

criteria.setFirstResult(randomRowIndex);
criteria.setMaxResults(1);

You can use HQL as well
Query query = session.createQuery("from Question");
query.setFirstResult(randomRowIndex);
query.setMaxResults(1);

And you need to use additional restrictions to not ask a question that was asked before.


text:
Q: How do I get valid lastActivityTime and cloudToDeviceMessageCount values for an IoTHub device? When I query the device twins for my active devices, either in code (via the C# SDK or in the Device Explorer), lastActivityTime is always "0001-01-01T00:00:00Z" and cloudToDeviceMessageCount is always 0. Valid fields appear to be deviceId, the etags, status, connectionState, and lastUpdated on the properties metadata fields. Is there additional configuration or provisioning I need to do to obtain the additional information?

A: We can start to see the Device twins get updated only if we have any status updated from any particular devices, Please see the below images for a detailed steps to demonstrate the device twin updated properties. For example if your device is shutdown or disabled as explained in the below images.
Steps: VS code the easy way.
1) Go to the Azure portal-->IoT Hub -->Device and 'Disable' its connection

2) Go to VS code , right click the device and select 'Get Device Info'

3) You will see the device twin is reported as the status is "Disconnected" and even the 'StatusUpdatedTime and 'LastActivity' are also reported for the first time and will continue to keep reporting if there is an activity on the particular device.

Steps: Device Explorer, the easy way
1) Open the Device Explorer Twin, Messages to Device-->Select your device and send a Message. You can use the VS Code to Get Device info again as showed in the previous step. Here in the below image you can see the "cloudToDeviceMessageCount":1 , keep on sending further messages from Device explorer and check the message count.

More info can be obtained from Understand and use device twins in IoT Hub.
Step: Cloud to device messaging: Azure Portal
Please read more info about Cloud to device Messaging

Step: Using Azure IoT service SDK NuGet package. C# Sample App C2D

Happy Azure IoT Learning

redpajama_set_name: RedPajamaStackExchange


text:
Q: need help in flow of ajax http://www.ibm.com/developerworks/library/j-ajax1/ajax.gif
I came across this flow, i would like to know certain things over this.

*

*What does Raise - > DOM Event do?

*After creating an XMLHTTPRequest why do we create a callback function?

*Register callback... what does it do?

*Parse response into XML DOM?

*Interogate response DOM?

Finally a basic question...
What does DOM contain and What does it do actually?

A: The DOM is an object representation of the HTML code. HTML documents are just simple text files, but it is often useful to consider one like it is a tree of elements. So, if your html contains
hello

world
 then the DOM will have a "body" object that contains two "div" objects as children. It lets you examine and modify an HTML document in a program without having to do text parsing of the HTML code.

*

*A DOM event is raised when the user interacts with an element of the DOM, so it's something like an "onclick" or "onkeypress" event. It will have an event handler, which is a function containing code to execute when the event occurs.

*Because the XmlHttpRequest is asynchronous. After the request is sent, the page will not wait for the response but instead will continue executing the rest of your code. The callback function waits for the response from the server and then executes. So your code to request data from the server should go in the event handler, and the code to process the data goes in the callback.

*This just tells the system that the callback function is to be called when the XmlHttpRequest gets data back from the server. If you had multiple XmlHttpRequests with different callbacks you would need to make sure each callback is registered to the right XmlHttpRequest.

*This is the text processing that is involved in turning the HTML code into a DOM tree. It is often done automatically by the browser, so your javascript should not need to worry too much about it.

*This just means the data processing you are doing with the data you received from the server. It will depend on what data you are getting and what you want to do with it.


text:
Q: If $\lim a_n/n=a>0$ then $\lim a_n=\infty$
Prove that:
  if
  $$lim_{n\to\infty} \ \frac{a_n}{n} = a>0 \ \ \ \ \ \ \ (1)$$
  then
  $$lim_{n\to\infty} \ a_n = \infty \ \ \ \ \ \ \ (2)$$

My proof:
Using a definition of limit, (1) yields:
$$\forall\epsilon>0 \ \ \exists N \ \ \forall n>N \ \ \left|\frac{a_n}{n} - a\right|<\epsilon$$
which is equivalent to:
$$\forall\epsilon>0 \ \ \exists N \ \ \forall n>N \ \ n(a-\epsilon)<a_n<n(a+\epsilon) \ \ \ \ \ \ \ (3)$$
To prove (2) wee need to show that
$$\forall M \ \ \exists N \ \ \forall n>N \ \ a_n>M \ \ \ \ \ \ \ (4)$$
So, let $M$ be any positive real number. Then let's take $N=\frac{M}{a-\epsilon}$. From (3) we know that $a_n>n(a-\epsilon)>N(a-\epsilon)=M.$ So indeed (4) holds.
Is this proof correct?
Edit:
Ok, I rethought this once again and I think proof above is indeed wrong. So let's take a second try:
Using a definition of limit, (1) yields:
$$\forall\epsilon>0 \ \ \exists N \ \ \forall n>N \ \ \left|\frac{a_n}{n} - a\right|<\epsilon$$
which is equivalent to:
$$\forall\epsilon>0 \ \ \exists N \ \ \forall n>N \ \ n(a-\epsilon)<a_n<n(a+\epsilon) \ \ \ \ \ \ \ (3)$$
To prove (2) we need to show that
$$\forall M \ \ \exists \tilde{N} \ \ \forall n>\tilde{N} \ \ a_n>M \ \ \ \ \ \ \ (4)$$
So, let $M$ and $\epsilon$ be any positive real numbers.
From (3) we know that it exists $N$ s.t. $\forall n>N \ \ a_n>n(a-\epsilon)$.
Now let's take $\tilde{N}=max\left(N,\lceil\frac{M}{a-\epsilon}\rceil\right)$. We will show that $\forall n>\tilde{N} \ \ a_n>M$.
We have now two cases: $N\geq\lceil\frac{M}{a-\epsilon}\rceil$ or $N<\lceil\frac{M}{a-\epsilon}\rceil$.
Let's consider the first case. We have from (3)
$$\forall n>\tilde{N}=N \ \ a_n>n(a-\epsilon)>N(a-\epsilon)\geq \lceil\frac{M}{a-\epsilon}\rceil(a-\epsilon)\geq M$$
Now let's consider the second case. Because $\lceil\frac{M}{a-\epsilon}\rceil>N$, it holds from (3) that
$$\forall n>\lceil\frac{M}{a-\epsilon}\rceil \ \ a_n>n(a-\epsilon)>\lceil\frac{M}{a-\epsilon}\rceil(a-\epsilon)=M$$

A: No it is not correct. You did not define $ε$ in your proof. If you fix that you will also realize another error in your later reasoning.

A: Yes it looks more or less fine to me.
More briefly you could say something along these lines: definitely $a_n>\frac{an}{2}$ and since $b_n=n$ grows to infinity, so does $\frac{an}{2}$ and so does $a_n$.


text:
Q: Are there any negative side-effects to overriding .gitignored files using git add -f? I want to commit binaries when i create a tag, those binaries are .gitignored and git-add says "Use -f if you really want to add them." So, i wonder if this would be a safe thing to do or not.
I want to use this to checkout binaries on a target computer. The old "system" is to keep old versions in a subdirectory named by the date that version was compiled on, which is a little annoying.

A: It is safe. The only reason git warns you is because you marked them as ignored, which means that you told git that you do not want them in the tree.
Git is warning you and requiring you to make it clear that you know that you are currently adding files which are on the ignorelist before just adding them.

A: In general, it's safe to add ignored files.  Once added they will be tracked, of course.  If you want to stop tracking such a file without deleting it from your working directory, you'll have to git rm --cached <filename>.
However!  Think three times before adding binary files to your git repo;  there's a good chance there's something wrong with your workflow, or you're using git in a way that's not intended.  As soon as you start having a lot of binary files in your repository, you'll notice git getting very, very slow.
For your specific application, you might want to take a look at git annex.
Another tip:  If you temporarily need to add a binary file to your repository, do so on an orphaned branch (git checkout -b --orphan <new_branch>).  That way, once you've removed the binary again, you can run garbage collection and trim the reflog, and the binary file will be gone gone.  If you'd simply added it to your normal tree, it'd still be in a referenced commit, and hence sitting as a blob in your .git directory, slowing things down.


text:
Q: Will having two antennae at the receiver give better reception? I have a 300mbps router with two antennae (tp-link td-wd8968). I'm building a PC and looking for a wireless network card. I have seen seen cards with a single antenna (150mbps) and cards with two antennae (300mbps); I understand the latter is for 802.11n which has higher data rates, but does it have any affect on the signal range?

A: Yes, all other things being equal, multiple antennas will increase signal range. Primarily by using beamforming they increase signal strength towards the target, which means the signal to noise ratio is strong enough to still send and receive data at a longer distance. It also allows higher throughput at the distances covered by a single antenna, if the max throughput supported by the protocol hasn't been reached yet.
This increase in signal strength works both for sending and receiving.
Keep in mind that this doesn't mean more antennas are always better. It means when all else is equal, and the beamforming is correctly implemented, more antennas are always better.
Beamforming is especially useful for a stationary device (desktop) which only talks with a single other stationary device (access point), because it only ever needs to boost signal strength towards a single direction and suffers no drawbacks from the reduced signal strength in the other directions.
EDIT:
Essentially if you provide a network card with 2 antennas, there are 3 reasonable implementations:

*

*Only turn on one antenna, turn off the other one, and scam the customer. (Don't underestimate the likelihood of this possibility)

*Operate both antennas on 2 different frequencies (resp. spatial streams). This requires having a router with multiple antennas that operate on the same frequencies as the antennas of the network card. This slightly boosts effective range, by increasing the speed from intolerable to tolerable.

*Operate both antennas on the same frequency. This is always results in beamforming, intentional or not - it's the very definition of beamforming.

You'll want a card that supports 2) and 3), using the former when the signal is strong and the latter when the signal is weak.
Multi-antenna network cards that support 802.11ac are more likely to have a solid beamforming implementation than 802.11n cards, and can collaborate to help each other figure out towards which directions to boost the signal. Nevertheless, 802.11ac is not required for beamforming, and any network card with multiple antennas and a decent beamforming implementation will have better range and throughput than a single antenna network card, even if paired with a 10 year old single antenna router. Here's an article mentioning beamforming in 802.11n products back in 2009.

A: Really it depend on features supported by wireless chip.

*

*It can support beamforming, increasing receive and transmit. (I never
seen it really supported in 802.11n. May be on high-end wireless like Aruba, Ruckus ...)

*It can support diversion, increasing receive sensitivity.

*It can support Spatial streams (MIMO). If both sides has more that 1
antenna.

A: Number of antennas doesn't affect your signal range. That's just depending on the transmit power of the radio / antennas. What you get is the higher signal speed due to MIMO capability.
If you have a 802.1n device with one antenna, it can only handle one spatial stream. This gives you (theoretical) max transfer rate of 150Mb/s. Your router is 2x2 MIMO capable, as seems to be the NIC with 2 antennas. They can handle two simultaneous spatial streams thus giving you the 300Mb/s speed.


text:
Q: My app crashes on CGRectIntersectsRect My app crashes on CGRectIntersectsRect and I dont know what to do.
Here is my code :
if(CGRectIntersectsRect(player.frame,enemy.frame))
{
    loseViewController *controller = [[loseViewController alloc] initWithNibName:@"loseView" bundle:nil];

    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:NO];
    [controller release];
}

A: Expanding on @Vince's comment (I'm not sure why it wasn't an answer!) . . . .
Where does it crash if you do
CGRect playerRect = player.frame;
CGRect enemyRect = enemy.frame;
if (CGRectIntersectsRect(playerRect, enemyRect)) {

instead of
if(CGRectIntersectsRect(player.frame,enemy.frame)) {

That should tell you which (or both) object has been deallocated.


text:
Q: Issue in removing value in tooltip dynamically I want to load the values in applicationResources.properties in jsp dynamically.
ApplicationResource.properties would be like this.
message=Message for invalid password.
i did like the following code to retrive the value from property file in jsp.
<fmt:message key="message" var="msgTooltip"/>
<form:password path="password" id="password" showPassword="true" data-toggle="tooltip" data-placement="right" title="${msgTooltip}"/>

The intention of above code is to get value from property file and display value in tooltip when corresponding field is hovered.
As a result i will get value as "Message for invalid password" in tooltip.But i need to get the message as "invalid password".
I tried some solution.But nothing makes it.Please some one help me to get it.
I tried like this...
var msgTooltip="<fmt:message key="message"/>";
msgTooltip = msgTooltip.slice(12);

A: You can't have double quotes in your double quotes. I'd try something like the following:
var msgTooltip='<fmt:message key="message"/>';


text:
Q: Why CSS hover with pseudo element failed? I wrote a list item hover effect today, but the result behavior is quite strange:
When hover from Item6 to Item2, everything's ok,
but when hover from Item2 to Item6 & hover the blank area (inside
, outside of
),
it seems something is blocking the hovering.
Feels like something's wrong with the pseudo element.
Can anyone help me with it? Thanks!
Here is my code:

var li = document.querySelectorAll('li')
li.forEach((e) => {
  e.addEventListener('click', (event) => {
    li.forEach((l) => {
      l.classList.remove('active')
    })
    e.classList.add('active')
  })
})
:root {
  --el-color-primary: #409eff;
  --el-color-info: #909399;
  --el-color-primary-rgb: 64, 158, 255;
}

.categories {
  width: 200px;
}

li {
  list-style-type: none;
  box-sizing: border-box;
  height: 2.2rem;
  cursor: pointer;
  color: var(--el-color-info);
  z-index: 0;
  border-radius: .5rem;
}

li {
  margin: .3rem;
}

li p {
  font-size: 1rem;
  line-height: 1rem;
  padding: .6rem 0 .6rem .8rem;
  margin: 0;
  color: var(--el-color-info);
}

li.active p {
  font-weight: 600;
  color: var(--el-color-primary);
}

li.active {
  background-color: rgba(var(--el-color-primary-rgb), .2);
}

li:not(.active)::after {
  content: "";
  display: inline-block;
  width: 0;
  height: 2.2rem;
  position: relative;
  top: -2.2rem;
  left: 0;
  border-radius: .5rem;
  background-color: rgba(var(--el-color-primary-rgb), .1);
  z-index: -99;
  transition: width .4s ease-out;
}

li:not(.active):hover p {
  color: var(--el-color-primary);
}

li:not(.active):hover::after {
  width: 100%;
}

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

A: The problem is solved by modifying putting a display: block at li:not(.active)::after instead of an inline-block

var li = document.querySelectorAll('li')
li.forEach((e) => {
  e.addEventListener('click', (event) => {
    li.forEach((l) => {
      l.classList.remove('active')
    })
    e.classList.add('active')
  })
})
:root {
  --el-color-primary: #409eff;
  --el-color-info: #909399;
  --el-color-primary-rgb: 64, 158, 255;
}

.categories {
  width: 200px;
}

li {
  list-style-type: none;
  box-sizing: border-box;
  height: 2.2rem;
  cursor: pointer;
  color: var(--el-color-info);
  z-index: 0;
  border-radius: .5rem;
}

li {
  margin: .3rem;
}

li p {
  font-size: 1rem;
  line-height: 1rem;
  padding: .6rem 0 .6rem .8rem;
  margin: 0;
  color: var(--el-color-info);
}

li.active p {
  font-weight: 600;
  color: var(--el-color-primary);
}

li.active {
  background-color: rgba(var(--el-color-primary-rgb), .2);
}

li:not(.active)::after {
  content: "";
  display: block;
  width: 0;
  height: 2.2rem;
  position: relative;
  top: -2.2rem;
  left: 0;
  border-radius: .5rem;
  background-color: rgba(var(--el-color-primary-rgb), .1);
  z-index: -99;
  transition: width .4s ease-out;
}

li:not(.active):hover p {
  color: var(--el-color-primary);
}

li:not(.active):hover::after {
  width: 100%;
}

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

A: The problem is in top: -2.2rem because it is relative and relative position doesn't remove the element from the normal document flow (mdn link). see how it looks like when we just use top: 0:

The whole selected area shows "item 2" li element and the light-blue box is actually a part of that element and we bring it up by negative top value. That's why when we enter mouse from item 2 to 3, we think we would be on item 3 but in fact we are still hovering item 2.
I guess the better way to do this is using absolute:

var li = document.querySelectorAll('li')
li.forEach((e) => {
  e.addEventListener('click', (event) => {
    li.forEach((l) => {
      l.classList.remove('active')
    })
    e.classList.add('active')
  })
})
:root {
  --el-color-primary: #409eff;
  --el-color-info: #909399;
  --el-color-primary-rgb: 64, 158, 255;
}

.categories {
  width: 200px;
}

li {
  list-style-type: none;
  box-sizing: border-box;
  height: 2.2rem;
  cursor: pointer;
  color: var(--el-color-info);
  z-index: 0;
  border-radius: .5rem;
  position: relative; /* <----- new */
}

li {
  margin: .3rem;
}

li p {
  font-size: 1rem;
  line-height: 1rem;
  padding: .6rem 0 .6rem .8rem;
  margin: 0;
  color: var(--el-color-info);
}

li.active p {
  font-weight: 600;
  color: var(--el-color-primary);
}

li.active {
  background-color: rgba(var(--el-color-primary-rgb), .2);
}

li:not(.active)::after {
  content: "";
  display: block;
  width: 0;
  height: 2.2rem;
  position: absolute; /* <----- new */
  top: 0; /* <----- new */
  left: 0;
  border-radius: .5rem;
  background-color: rgba(var(--el-color-primary-rgb), .1);
  z-index: -99;
  transition: width .4s ease-out;
}

li:not(.active):hover p {
  color: var(--el-color-primary);
}

li:not(.active):hover::after {
  width: 100%;
}

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6


text:
Q: Find whether a partiular file is valid PHP file I want to find out whether a particular file is valid PHP file or not?
php -l filename only finds our whether it have syntactical errors or not, it is lint.
But I also want to find out, that on execution, it will run without error or not?
I am running on Ubuntu machine.
EDIT:
Actually my problem is I am allowing users to define formulas for some calculations and I have to execute those formulas, but before submission of formulas by users, I want to make sure whether they are correct or not in PHP

A: it will be really hard to know if a php script will throw an error or not.
unless formulas are well defined and that you can define a grammar in order to check if it's correct. eg: you can only add integer,
SUM -> N | N + N
N -> integer

but even like this, you will have soon problems, eg, if you allow to N1 / N2, you would have to ensure is never null.
my advice, make sure your program recover from an error. and, in case of on error, notify the user that input the formula with details about the error


text:
Q: What is the origin of "33" in "catch-33"? http://en.wikipedia.org/wiki/Catch_Thirtythree explains:

Lyrically, the album is a concept album, revolving around different kinds of paradoxes, hence the title Catch Thirtythree (see Catch-22).

I cannot understand the derivation of 33 from 22. Can someone explain it to me?

A: My reading of a catch-33 would be a situation that involves three mutually logically contradictory necessary conditions, where a catch-22 involves two.

A: I would read this as Catch-33 being just like Catch-22 except each digit is incremented, therefore it is deemed by Meshuggah to be a more (or moar) emphatic statement.
Remember Nigel Tufnel (Christopher Guest) in This Is Spın̈al Tap, talking about how his band's amps "go to 11" where ordinary amps only go to 10? "Well, it's louder, innit?"

Nigel Tufnel: The numbers all go to eleven. Look, right across the board, eleven, eleven, eleven and...
Marty DiBergi: Oh, I see. And most amps go up to ten?
Nigel Tufnel: Exactly.
Marty DiBergi: Does that mean it's louder? Is it any louder?
Nigel Tufnel: Well, it's one louder, isn't it? It's not ten. You see, most blokes, you know, will be playing at ten. You're on ten here, all the way up, all the way up, all the way up, you're on ten on your guitar. Where can you go from there? Where?
Marty DiBergi: I don't know.
Nigel Tufnel: Nowhere. Exactly. What we do is, if we need that extra push over the cliff, you know what we do?
Marty DiBergi: Put it up to eleven.
Nigel Tufnel: Eleven. Exactly. One louder.
Marty DiBergi: Why don't you just make ten louder and make ten be the top number and make that a little louder?
Nigel Tufnel: [pause] These go to eleven.

Hey, it's only rock 'n' roll ...

A: 12" vinyl albums (you know, the things from before CDs) rotate at 33⅓ RPM, often just referred to as 33 RPM (by way of contrast with 7" singles which are "45s"). So perhaps Meshuggah were thinking of this when they chose to replace Joseph Heller's 22 with 33, since it is an album we are talking about (although I imagine its main release is on CD rather than 12" vinyl).

A: Does their album involve guns? (I notice it refers to nuclear warfare)
If so, maybe it's a reference to .33 caliber guns, like Rule 303 refers to .303 caliber guns.

A: Tordendal's favorite beat signature is 3/3. Maybe this would explain the name twist on this album.


text:
Q: How to shut down all Executors when quitting an application? According to Brian Goetz's Java Concurrency in Practice JVM can't exit until all the (nondaemon) threads have terminated, so failing to shut down an Executor could prevent the JVM from exiting.
I.e. System.exit(0) doesn't necessarily work as expected if there are Executors around. It would seem necessary to put some kind of
public void stop() { exec.shutdown() }

methods to all classes that contain Executors, and then call them when the application is about to terminate. Is this the only way, or is there some kind of shortcut to shut down all the Executors?

A: By default, an Executor will create only non-daemon threads. You can override that by supplying the Executor with your own ThreadFactory. Here's an example:
class DaemonThreadFactory implements ThreadFactory {
  public Thread newThread(Runnable r) {
    Thread t = new Thread(r);
    t.setDaemon(true);
    return t;
  }
}

Be cautious, though, because the JVM will exit right away even if these threads are busy doing useful work!

A: Decorate the executor with com.google.common.util.concurrent.MoreExecutors#getExitingExecutorService
@Beta
public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor,
                                         long terminationTimeout,
                                         TimeUnit timeUnit)

Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion.
This is mainly for fixed thread pools. See Executors.newFixedThreadPool(int).

A: You can also provide an implementation of ThreadFactory that marks created threads as daemon threads. I prefer a clean shutdown mechanism (with lifecycle methods) but there are cases where you don't need guarantees about the state/completion of uncompleted tasks when this can be appropriate.

A: There's no shortcut to do them all, no. Also, you should probably call shutdownNow() rather than shutdown(), otherwise you could be waiting a while.
What you could do, I suppose, is when you create the Executor, register it in a central place. Then, when shutting down, just call shutdown() on that central object, which in turn could terminate each of the registered executors.
If you use Spring, then you can take advantage of its factory beans which create and manage the Executors for you. That includes shutting them down gracefully when the application quits, and saves you having to manage them yourself.

A: Probably he meant to say JVM can't stop on its own until nondaemon threads are finished. Its like running a simple class from command like java SomeClass and after the execution of main method JVM stops.
System.exit is a JVM termination command, even if daemon threads are running JVM will shutdown.


text:
Q: One step approach to grouping, then sorting, then echoing? Mysql or through PHP?
I have a design that calls for grouping articles by their date. The date will be a heading and all articles from the latest 10 will be grouped under each heading. The date can be anything and/or highly sporadic, the articles must be in descending order, etc.
I figure i would have to

*

*retrieve the last 10 articles and put them in a multi-dimensional array like so:
$allretrieved = array ( array ( id => a, date => b, title => c, body => d, image => e, etc.),
                        array ( id => a, date => b, title => c, body => d, image => e, etc.),
                        etc.
                );

*then group the array by using a method I don't fully understand ( extract into another array? Would someone explain this function to me?)
$date_groups[] = array();
$group = '';

foreach( $date_groups as $key=>$val ) {
    if($key == 'date'){
         $group = $val;
    }
$comment_groups[$group][] = $val;
}

*and then sort the groups?
Or should I sort beforehand?
is doing it at the MySql level faster? more efficient?
EDIT: Best Method I have found for this:
Basic PHP MySQL array grouping question

A: At some point where your dataset isn't too big, sorting with mysql should be faster if indexes are correctly added since default mysql indexes are b-tree. In your case, bringing the data and looping over it you will have a O(n) thus the sorting will take more as the data gets bigger.
I recommend you to take a look to your database schema, use explain to see how indexes are being used in the query you are running and benchmark. AGAIN: this will depend of your data.
now, for a sake of dreaming: Once your data is big enough to make the sorting too slow in mysql then you should switch something where you can sort in parallel using map-reduce or something like that, but given the nature of your post I think you are safe for now.


text:
Q: Port forwarding works on Ubuntu but doesn't work on windows I set up my wireless router to port forward 80 -> 80 (as well as 8080 -> 80) to my local http server. I have dual boot windows + ubuntu and both of them have apache installed. The problem is if I boot ubuntu the port forwarding is working fine but if I boot windows (still same IP) port forwarding doesn't work.
I've disabled firewall but it doesn't help. I tried accessing it through the proxy - still no luck. Could you tell what could be the problem on windows machine? I suspect if router config is working for Ubuntu then I shouldn't bother to change anything on the router side, isn't it?
The event logs (when in windows) is showing this warning (yellow triangle with exclamation mark):
Warning     Jul 29 22:50:57 FIREWALL rule : Protocol: TCP Src ip: 188.220.xx.xx Src port: 51522 Dst ip: 192.168.1.66 Dst port: 80 Chain: forward_host_service Rule Id: 1 Action: accept

Warning     Jul 29 22:50:56 FIREWALL rule : Protocol: TCP Src ip: 188.220.xx.xx Src port: 51521 Dst ip: 192.168.1.66 Dst port: 80 Chain: forward_host_service Rule Id: 1 Action: accept

Warning     Jul 29 22:50:56 FIREWALL rule : Protocol: TCP Src ip: 188.220.xx.xx Src port: 51520 Dst ip: 192.168.1.66 Dst port: 80 Chain: forward_host_service Rule Id: 1 Action: accept

P.S. 188.220.xx.xx is my external IP (shown by 'my ip' pages) and I can't ping to it
EDIT: And I can ping external IP from Ubuntu (but not from windows) there is the log from router when accessed from Ubuntu(still warning but works):
Warning     Jul 30 08:46:52 FIREWALL rule : Protocol: TCP Src ip: 188.220.xx.xx Src port: 32897 Dst ip: 192.168.1.66 Dst port: 80 Chain: forward_host_service Rule Id: 1 Action: accept

Warning     Jul 30 08:46:52 FIREWALL rule : Protocol: TCP Src ip: 188.220.xx.xx Src port: 32896 Dst ip: 192.168.1.66 Dst port: 80 Chain: forward_host_service Rule Id: 1 Action: accept


text:
Q: Is there a tree data type in windows libraries? Working in C#. I need a simple tree data type to store some objects.
Is there a native windows libraries tree data type?
I've looked in System.Collections.Generic but couldn't find anything.
Tried Googling it, all I see is custom built trees.

A: No, There isn't a tree data type in .Net for two reasons:

*

*Trees are almost always built specifically for a certain usage and there isn't a general case for them like, for example, a dictionary.

*It's really simple to build a basic tree. You just write a TreeNode class that references 2 or more TreeNode children. Maybe add a Tree class to hold them. That's all.


text:
Q: Reuse virtual machines from Intel laptop on AMD laptop? I have Windows, Linux and some other virtual machines (some of them are on VMWare Player, some are on VirtualBox) on my old Intel laptop.
Is it possible to just move theirs disks images on my new AMD laptop and use them there as is? Or do I have to install these machines from scratch?

A: CPUs in desktop computers are generally compatible, because they are all implementations of the same x86_64 architecture. Your VMs will probably detect that the CPU has changed, because VMWare and VirtualBox expose CPU name to the guest, but that shouldn't affect anything.
Some software may take advantage from specific x86_64 extensions, which differ between CPUs. That shouldn't be a problem though, unless you're using specialized builds for specific instruction sets, which is unlikely. Most programs are built to work on all platforms.

A: You can generally just take the Virtual Machine folder and put it on the new machine and virtual machines will work.
For the VMware machines, if they were 32-bit machines, they will still work. If you have 64-bit machines, you need to ensure Hardware Virtualization is enabled on the new machine. This is true of any Virtual Machine app.
Again for VMware, when a machine is first built, it includes a Hardware Compatibility setting. It does not always need to change when upgrading the VMware app to a newer version or when changing the physical machine to a new machine.
If you need to (or even to see if the machine works better), you can change the Hardware Compatibility level to a newer level. The machine needs to be OFF and you can change the compatibility level in the machine settings.
I have virtual machines here on this laptop that were created with VMware 1 or 2 on a Windows NT Workstation machine, so you definitely can move virtual machines to new hardware.
Here is a screen shot of the Hardware Compatibility settings.

A: This being a new computer it should have the virtualization feature of
AMD virtualization (AMD-V)
that is necessary to emulate different CPU architecture, in case you intend
running 32-bit VMs on a 64-bit host.
In case of a problem, verify that all hardware virtualization options are
enabled in the BIOS.


text:
Q: elasticsearch - there is no copy of the shard available? I have a few indices in red, after a failure of the system, caused by disk full.
But I cannot reallocate the lost shard. It says "there is no copy of the shard available"
 curl -XGET 'localhost:9200/_cluster/allocation/explain?pretty'
{
  "shard" : {
    "index" : "my_index",
    "index_uuid" : "iNY9t81wQf6wJc-KqufUrg",
    "id" : 0,
    "primary" : true
  },
  "assigned" : false,
  "shard_state_fetch_pending" : false,
  "unassigned_info" : {
    "reason" : "ALLOCATION_FAILED",
    "at" : "2017-05-30T07:33:04.192Z",
    "failed_attempts" : 5,
    "delayed" : false,
    "details" : "failed to create shard, failure FileSystemException[/data/es/storage/nodes/0/indices/iNY9t81wQf6wJc-KqufUrg/0/_state/state-13.st.tmp: Read-only file system]",
    "allocation_status" : "deciders_no"
  },
  "allocation_delay_in_millis" : 60000,
  "remaining_delay_in_millis" : 0,
  "nodes" : {
    "KvOd2vSQTOSgjgqyEnOKpA" : {
      "node_name" : "node1",
      "node_attributes" : { },
      "store" : {
        "shard_copy" : "NONE"
      },
      "final_decision" : "NO",
      "final_explanation" : "there is no copy of the shard available",
      "weight" : -3.683333,
      "decisions" : [
        {
          "decider" : "max_retry",
          "decision" : "NO",
          "explanation" : "shard has already failed allocating [5] times vs. [5] retries allowed unassigned_info[[reason=ALLOCATION_FAILED], at[2017-05-30T07:33:04.192Z], failed_attempts[5], delayed=false, details[failed to create shard, failure FileSystemException[/data/es/storage/nodes/0/indices/iNY9t81wQf6wJc-KqufUrg/0/_state/state-13.st.tmp: Read-only file system]], allocation_status[deciders_no]] - manually call [/_cluster/reroute?retry_failed=true] to retry"
        }
      ]
    },
    "pC9fL41xRgeZDAEYvNR1eQ" : {
      "node_name" : "node2",
      "node_attributes" : { },
      "store" : {
        "shard_copy" : "AVAILABLE"
      },
      "final_decision" : "NO",
      "final_explanation" : "the shard cannot be assigned because one or more allocation decider returns a 'NO' decision",
      "weight" : -2.333333,
      "decisions" : [
        {
          "decider" : "max_retry",
          "decision" : "NO",
          "explanation" : "shard has already failed allocating [5] times vs. [5] retries allowed unassigned_info[[reason=ALLOCATION_FAILED], at[2017-05-30T07:33:04.192Z], failed_attempts[5], delayed=false, details[failed to create shard, failure FileSystemException[/data/es/storage/nodes/0/indices/iNY9t81wQf6wJc-KqufUrg/0/_state/state-13.st.tmp: Read-only file system]], allocation_status[deciders_no]] - manually call [/_cluster/reroute?retry_failed=true] to retry"
        }
      ]
    },
    "1g7eCfEQS9u868lFSoo7FQ" : {
      "node_name" : "node3",
      "node_attributes" : { },
      "store" : {
        "shard_copy" : "AVAILABLE"
      },
      "final_decision" : "NO",
      "final_explanation" : "the shard cannot be assigned because one or more allocation decider returns a 'NO' decision",
      "weight" : 40.866665,
      "decisions" : [
        {
          "decider" : "max_retry",
          "decision" : "NO",
          "explanation" : "shard has already failed allocating [5] times vs. [5] retries allowed unassigned_info[[reason=ALLOCATION_FAILED], at[2017-05-30T07:33:04.192Z], failed_attempts[5], delayed=false, details[failed to create shard, failure FileSystemException[/data/es/storage/nodes/0/indices/iNY9t81wQf6wJc-KqufUrg/0/_state/state-13.st.tmp: Read-only file system]], allocation_status[deciders_no]] - manually call [/_cluster/reroute?retry_failed=true] to retry"
        }
      ]
    }
  }
}

I tried basically every option of the reroute command (documentation here). but it gives me 400 error.. like this:
curl -XPOST 'localhost:9200/_cluster/reroute?pretty' -H 'Content-Type: application/json' -d'
{
    "commands" : [

        {
          "allocate_replica" : {
                "index" : "myindex", "shard" : 0,
                "node" : "node2"
          }
        }
    ]
}'

response:
{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "[allocate_replica] trying to allocate a replica shard [myindex][0], while corresponding primary shard is still unassigned"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "[allocate_replica] trying to allocate a replica shard [myindex][0], while corresponding primary shard is still unassigned"
  },
  "status" : 400
}

A: try this:
curl -XPOST 'xx.xxx.xx:9200/_cluster/reroute' -d '{"commands" : [{"allocate_stale_primary":{"index" : "myindex", "shard" : 0, "node" : "node2","accept_data_loss" : true}}]}'


text:
Q: Answered question is identical to mine, but accepted solution doesn't work for me Here is the situation. I have a problem, and upon searching for a solution, I find that another SO user has already posted a question and accepted and answer. However, while the question perfectly describes my issue, the answer does not solve my problem.
What is the best practice in this situation? If I post a new question, it will surely get marked as duplicate, and rightfully so. If I ask follow up questions in the comments, I am potentially creating a cluttered, unhelpful comment section. I can upvote the question, but even if this gets more attention for the question, there is no reason for another user to try to answer the question, because the OP already has an answer he or she is satisfied with.
It seems like this is a situation that would arise fairly often because an accepted answer is not accurate or because there are subtle differences in the problem. As someone with a better answer, I can post that and get upvoted past the accepted answer. But as someone with the same question, do I have any recourse to get help from the community to find an answer that works for me, without posting a duplicate question?

A: You can post a new question.
However, be sure you outline that you did find and try the answer that isn't working for you- You can even link to the answer to provide context. Be sure to describe the answer and show the code in your question, though, so people aren't required to leave the question to see what you did.
Also be sure to describe why the answer doesn't work. What errors, if any, are you getting when using it? Are the outputs wrong?
Doing this helps for a couple reasons:
1) It shows you've done your homework. You've searched, tried to find your answer, and come up short.
2) It shows what you've tried, keeping potential answerers from suggesting the same solution.
3) It shows that your question is not a duplicate- there is something, perhaps subtly, different about your issue that prevents the answer to the other question from working. Since that answer does not answer your question, your question is not a duplicate.
This should be enough to prove your question is not a duplicate, and to get some help. Keep in mind that it could be that you've implemented the other answer incorrectly, and you may get comments or answers to that effect. Try to keep an open mind if this happens.


text:
Q: no test for session key if sent by application I'm writing a non browser application using rails as server.
As I understand, I need to add the received session key to any successive request.
If logged through a browser, it is indeed checked as deleting the cookie during a sesion will fail session test for any request senf afterwards.
However, in my application, I can send any request after logging in, not including the session cookie and it will pass the session test and execute.
I can point out I disabled protect_from_forgery but this should apply only to authenticity_token check, shouldn't it ?
Any help will be appreciated.
Thanks.

A: If this is a non-browser application, there's no real reason to use cookies (or the session for that matter).  Just authenticate using basic authentication by sending the credentials on every request as part of the HTTP header.  The basic authentication credentials can be something traditional like a username and password, or something more suited for your needs like an api_key or token.


text:
Q: How to pivot output in SQL Server 2012 Input:
Table1->Student  details
sno    sname     scourse    sjoindate
1    Ram         bsc        11/26/2011
2    Sham        bcom       10/06/2010
3    Krishna     ba         06/16/2012

Table2->Student marks
sno     id      marks
1       1       67
1       2       77
1       3       80
1       4       60
1       5       90

Table3->Subjectnames
id      subjectname
1       Computerscience
2       Maths
3       Satatistics
4       English
5       Hindi

Table4->Student_feedback_QuestionandAnswer
sno     Questions       Answers
1        Q1             A1
1        Q2             A2
1        Q3             A3
1        Q4             A4

Expected Output:
sno     sname       scourse     sjoindate       Computerscience      Maths      Statistics      English     Hindi       Questions       Answers
1       Ram         bsc         11/26/2011          67                  77      80               60         90          Q1              A1
                                    Q2              A2
                                    Q3              A3
                                    Q4              A4

In the above tables the rows of Table2 and Table3 can increase and decrease depending on the studentname.
I need  tabled to combine the data from all four tables into one result set but I don't know how to use pivot with dynamic header with dynamic column values:

*

*Data from Table3.Subjectname column values should be header column names e.g. Computerscience, Hindi.

*Data from Table2.marks should be the value under the header column name e.g. marks for id=1 under Computerscience.

*the Questions, Answers column from Table4  should come in result set depending on the value of `Table1.sno'

If you can provide a hint for creating a table using pivot with dynamic header with dynamic column values ,yeah using two tables.
Please let me know for more clarification.


text:
Q: is it possible to use two if/then/else below? I have this part of my query:
declare function local:accoppiamenti($snapshot){
for $ev in $snapshot/EV
let $stringa := $ev/accoppiamenti//accoppiamento/@specie
let $flag := true()
return(
    if($stringa[1]=$ev/specie/@cod and $stringa[2]!=$ev/specie/@cod and $stringa[3]=$ev/specie/@cod and $stringa[last()]=$ev/specie/@cod and $stringa[last()-1]!=$ev/specie/@cod and $stringa[last()-2]=$ev/specie/@cod)
    then(
        for $i in (4 to count($stringa)-3)
        return(
            if($stringa[$i]=$ev/specie/@cod and $stringa[$i+1]!=$ev/specie/@cod and $stringa[$i+2]=$ev/specie/@cod)
            then($flag=false())
            else()
        )
    )
    else($flag=false())
    if($flag=true())
    then(data("OK"))
    else()
)
};

The second block if/then/else in the extern cycle for don't work. How can I check the value of the variable flag? I need to see if I passed all the tests.

A: You're returning a sequence, so you just need to add a comma after else($flag=false()) to separate it from the next expression.

A: Create a sequence of booleans indicating a result for each test, and then test if any of the booleans is false.
declare function local:accoppiamenti($snapshot){
for $ev in $snapshot/EV
let $stringa := $ev/accoppiamenti//accoppiamento/@specie
let $flags :=
    if($stringa[1]=$ev/specie/@cod and $stringa[2]!=$ev/specie/@cod and $stringa[3]=$ev/specie/@cod and $stringa[last()]=$ev/specie/@cod and $stringa[last()-1]!=$ev/specie/@cod and $stringa[last()-2]=$ev/specie/@cod)
    then(
        for $i in (4 to count($stringa)-3)
        return(
            if($stringa[$i]=$ev/specie/@cod and $stringa[$i+1]!=$ev/specie/@cod and $stringa[$i+2]=$ev/specie/@cod)
            then(false())
            else(true())
        )
    )
    else(false())
return (if every $f in $flags satisfies $f then 'ok' else ())
};

This can be simplified but I have deliberately kept it close to the original.


text:
Q: Trouble Converting string to datetime? I have this strings with the format "09-FEB-21 05.19.32.871000000 AM".
import datetime
dt_string = "09-FEB-21 05.19.32.871000000 AM"
format = "%d-%m-%y %H.%M.%S.%f %p"
dt_object = datetime.datetime.strptime(dt_string, format)

The above code causes ValueError("unconverted data remains: %s" %
time data '09-FEB-21 05.19.32.871000000 AM' does not match format '%d-%m-%y %H.%M.%S.%f %p'

Any help?

A: Use %b instead of %m (doc):
dt_string = "09-FEB-21 05.19.32.871000000 AM"
print(pd.to_datetime(dt_string, format="%d-%b-%y %H.%M.%S.%f %p"))

Prints:
2021-02-09 05:19:32.871000

EDIT: Using only datetime: Remove last 000 from the fraction:
import re
import datetime

dt_string = "09-FEB-21 05.19.32.871000000 AM"
dt_string = re.sub(r"000(?=\s)", "", dt_string)

format = "%d-%b-%y %H.%M.%S.%f %p"
dt_object = datetime.datetime.strptime(dt_string, format)
print(dt_object)

Prints:
2021-02-09 05:19:32.871000


text:
Q: Magento 2.3.5p2: Uncaught Error: Create invoice with shipment issue I am getting this error on creating invoice with shipment from the admin:

Uncaught Error: Call to a member function getUrl() on null in /var/www/html/vendor/magento/module-sales/view/frontend/templates/email/shipment/track.phtml:

Any help would be appreciated.

A: <?php $_shipment = $block->getShipment() ?>
$_order = $block->getOrder() ?>
<?php if ($_shipment && $_order) : ?>
    <?php $trackCollection = $_order->getTracksCollection($_shipment->getId()) ?>
    <?php if ($trackCollection) : ?>

                <?= $block->escapeHtml(__('Shipped By')) ?>
                <?= $block->escapeHtml(__('Tracking Number')) ?>

            <?php foreach ($trackCollection as $_item) : ?>

                    <?= $block->escapeHtml($_item->getTitle()) ?>:

                        <a href="<?= $block->escapeUrl($this->helper('Magento\Shipping\Helper\Data')->getTrackingPopupUrlBySalesModel($_item)) ?>" target="_blank">
                            <?= $block->escapeHtml($_item->getNumber()) ?>

            <?php endforeach ?>

    <?php endif; ?>
<?php endif; ?>

Created a template file in the custom theme: Magento_Sales/templates/email/shipment/track.phtml


text:
Q: Can't add to a string literal in C to shift its index I was code-golfing the famous "fizzbuzz" screening question in C (The point of this question is understanding how C operators work, not code golf; don't vote me off topic ^^"), and I came up with this line:
puts(&"Fizz\0FizzBuzz"[i%15?i%3?9:0:5]));

Which seems a little unnecessary to me because I thought I could just do:
puts("Fizz\0FizzBuzz"+i%15?i%3?9:0:5));

but that segfaults on the first would-be Fizz. My question is: why can't I index a string literal by simply adding to it? I've tried casting the addend to size_t, but that does nothing useful. Given that for an arbitrary char *p (or a pointer to any type for that matter), p[n]is just syntactic sugar for (*p+n), and (I think) &*p == p.
Why, then, is &p[n] != p+n?
EDIT: Turns out I was just catching Fizz\0FizzBuzz"+i%15 in my ?:. Damned operator precedence. I'm a moron. :)

A: The problem your code is that you are missing parentheses. This works perfectly fine:
puts("Fizz\0FizzBuzz"+(i%15?i%3?9:0:5));

In your original code the condition of the first ? : operator is
"Fizz\0FizzBuzz"+i%15

which is not what you intended.
Demo.


text:
Q: Codeigniter route pattern with prefix I'm working on Codeigniter 3 route mechanism, my application is multi branch, I tried google mail url pattern like app.com/p/branch_id/controller/method/param1/param2/etc but some cases it doesn't need prefix p/branch_id/ for admin or global setting. I think my rule isn't effective.
$route['p/(:num)/(:any)'] = '$2';
$route['p/(:num)/(:any)/(:any)'] = '$2/$3';
$route['p/(:num)/(:any)/(:any)/(:any)'] = '$2/$3/$4';
$route['p/(:num)/(:any)/(:any)/(:any)/(:any)'] = '$2/$3/$4/$5';

I want achieve
/p/1/booking -> route to controller booking
/p/1/booking/create -> route to controller booking action create()
/p/1/booking/view/1 -> route to controller booking action view($id)

also same thing when user visit
/booking -> route to controller booking
/booking/create -> route to controller booking action create()
/booking/view/1 -> route to controller booking action view($id)

How i write the rule for number unknown possible of parameters, when $route['p/(:num)/(:any)'] = '$2'; just routing index controller only.

A: I am sure it will work.
$route['p/(:num)/(:any)'] = 'booking/action/$1/$2';
$route['p/(:num)/(:any)/create'] = 'booking/create/$1/$2';
$route['p/(:num)/(:any)/view/(:num)'] = 'booking/view/$1/$2/$3'; //$3 is record no.

Addition

Or if you want to make action as dynamic variable.
$route['p/(:num)/(:any)'] = 'booking/defaultAction/$1/$2';
$route['p/(:num)/(:any)/(:any)'] = 'booking/defaultAction/$1/$2'; // here in default action you need to add condition that if its create then execute create functionality. or if its view then execute view funcitonality


text:
Q: log unclosed PreparedStatement using c3p0 Using c3p0 I can log unclosed Connection by setting properties debugUnreturnedConnectionStackTraces and
unreturnedConnectionTimeout. I wonder if is there any way to find out unclosed PreparedStatement because today I found a code as below:
...
ps=dbConnection.prepareStatement(qry);
rs=ps.executeQuery();
if(!rsCandItem.next())//to check Result Set has rows
{
rs.close();
qry = "SELECT * FROM TABLE1";
ps=dbConnection.prepareStatement(qry); //same PreparedStatement object is used without closing previous instance
rs=ps.executeQuery();
}
...

I guess using same PreparedStatement object (ps) without closing it is wrong/bad practice, correct me if I am wrong. So I want to log using c3p0 (or by any other way) unclosed PreparedStatement. Is there any way?

A: Unless the driver is broken, closing a Connection should also close associated statements and ResultSets. As you said, it is bad practice to not close them even if in particular cases they might not cause problems.
Since connection pools deal with Connections (and they're the ones that will leak resources), it's unlikely that there are settings for observing anything else.


text:
Q: Tokenizer that splits up words with underscores in them but also retains a full version I'm implementing an Elasticsearch search for content that has filesnames in it, such as
"golf_master_2009.xls". I'd like a tokenizer that splits this up into at least the following tokens: "golf", "master", "golf_master_2009.xml". Now I have to use wildcards (for example "master") if I want to search for it without specifying the full filename.

A: You can apply differents analyzers using a multifield field.
See http://www.elasticsearch.org/guide/reference/mapping/multi-field-type.html
HTH

A: You can use your own analyzer with keyword tokenizer and word delimiter token filter (with options generate_word_parts and preserve_original set to true)


text:
Q: Need help about turning of Etag for specific url via htaccess I'd like to turn off Etag for all xxx.googleapis.com
http://fonts.googleapis.com/css?family=Indie+Flower&ver=3.9.1
http://fonts.googleapis.com/css?family=Raleway%3A100%2C200%2C300%2C400%2C500%2C600%2C700%2C800%2C900&ver=1406918262
http://fonts.googleapis.com/css?family=Roboto:300,400,500,700
http://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=panoramio&language=en&callback=google.loader.callbacks.maps
http://mt0.googleapis.com/mapslt/ft?hl=en&lyrs=m%40270000000%7Csalt%3A185418970&las=twutvtvvttwv,twutvtvvttww,twutvtvvtuvv,twutvtvvtuvw,twutvtvvtvut,twutvtvvtvuu,twutvtvvtvuv,twutvtvvtvuw,twutvtvvtvwt,twutvtvvtvwu,twutvtvvtvwv,twutvtvvtvww,twutvtvvtwtt,twutvtvvtwtu,twutvtvvtwtv,twutvtvvtwtw,twutvtvvtwvt,twutvtvvtwvu,twutvtvvtwvv,twutvtvvtwvw,twutvtvvvtut,twutvtvvvtuu,twutvtvvvutt,twutvtvvvutu&z=12&src=apiv3&xc=1&style=47%2C37%7Csmartmaps&apistyle=p.h%3A%23ff1a00%7Cp.il%3Atrue%7Cp.s%3A-100%7Cp.l%3A33%7Cp.g%3A0.5%2Cs.t%3A6%7Cs.e%3Ag%7Cp.c%3A%23ff2D333C&callback=_xdc_._dpwvne&token=112829

Here is what I try but it doesn't work
<FilesMatch "(/^http?:\/\/([a-zA-Z\d-]+\.){0,}googleapis\.com$/)">
Header unset ETag
FileETag None
</FilesMatch>

What's wrong with the regex?

A: You have a $ at the end of your expression, which tells the regex parser that this is the end of the line.  If you'd like to capture URL's that contain data after .com, remove the $.
Like this:
<FilesMatch "(/^http?:\/\/([a-zA-Z\d-]+\.){0,}googleapis\.com/)">
Header unset ETag
FileETag None
</FilesMatch>

A: You can use mod_setenvif here:
# set env=NO_ETAG for certain URIs
SetEnvIfNoCase Host "([a-zA-Z\d-]+\.)+googleapis\.com/" NO_ETAG

# use that env variable to set headers
Header unset ETag env=NO_ETAG


text:
Q: Swift 4.0 MapView Running Slow Ever since I updated to Xcode 9 and Swift 4.0, my mapView in my simulator has been running extremely slow. I thought this would be because code would be deprecated or because my code was extensive causing it to slow down, but I added a mapView into a blank project and that mapView is slow to navigate/zoom as well! Are there some settings I need to configure to fix this in the simulator?
This is the output produced in the console log:
2017-10-26 23:25:50.932530-0500 mapTest[7994:151068] [VKDefault] Tile 1.2.2 (256) in current unloaded state for 0.07 seconds - Polygons - Loading (ephemeral) (0.07 sec), Rivers - Loading (ephemeral) (0.07 sec), Roads - Loading (ephemeral) (0.07 sec), Point Labels - Loading (ephemeral) (0.07 sec), Polygon Labels - Loading (ephemeral) (0.07 sec), Road Labels - Loading (ephemeral) (0.07 sec), Resources - Unavailable (terminal) (2.11 sec), Attributes - Loading (ephemeral) (0.07 sec)

A: If this is just in the simulator for ios 11 or 10.3, then it is a known bug. The XCode 9 simulator is working very slowly for everyone relating to mapKit. This bug can be seen here and here. It should, however, work fine if you use the app on your phone.
Apple staff working with Swift development have acknowledged the issue. The only workaround currently is using the ios 10 simulator or changing the rendering modules (suggested by Apple staff). Supposedly, changing the modules isnt perfect, but it might just help. Type this in terminal:
defaults write com.apple.CoreSimulator.IndigoFramebufferServices FramebufferRendererHint X
Replace the X with: 0 = auto, 1 = Metal, 2 = OpenCL, 3 = OpenGL
Again, this is an official bug in the simulator so changing the rendering still won't make the simulation perfect. There have been 4-5 people who have submitted bug reports on this and it has been acknowledged, so hopefully a fix comes soon.
Edit
I tried a map kit app on iOS 11.1 simulator. It seems to be slightly smoother but the error message still pops up... waiting for a fix
Edit
A comment pointed out that this is fixed in the iOS 11.3 beta.


text:
Q: Smooth overflow:hidden This fiddle should explain my problem.
 I have a container with overflow:hidden. I want the content which is cut of, to be cut of "smoothly".
 The font should slowly become more transparent before it is cut off. I have found a solution, which you can see in my fiddle.
I would like to know if there is a more elegant solution compared to my solution. Right now there are 5 different transparency levels but i want to work with at least 10 different levels. Therefore it would get very messy. Thanks for your help!
Short HTML/CSS-Sample, which shows how much code is needed for this little effect:
HTML

CSS
    #transparencydiv{
        position:absolute;
        top:45%;
        height:10%; width:100%;
    }
    .transparencys{
        float:right;
        height:100%;width:2ex;
        background-color:black;
        z-index:5;

    }
    #transparency1{opacity:0.9;margin-right:2%;}
    #transparency2{opacity:0.7;}
    #transparency3{opacity:0.5;}
    #transparency4{opacity:0.3;}
    #transparency5{opacity:0.1;}

http://jsfiddle.net/y049jbm8/

A: Use a linear-gradient:
#scrollmenu:after {
    content:" ";
    width:15%;
    position:absolute;
    right:0;
    top:0;
    height:100%;
    background-image: linear-gradient(to right, rgba(255,255,255,0), black);
}

Check the Fiddle

Note :::
This will work on the latest Chrome, to keep compatibility use the necessary prefixes. You can check here for more info http://css-tricks.com/css3-gradients/

A: Instead of multiple divs, you can add a unique div over your text, with a gradient as background.
On this site, you will be able to configure the gradient you want to make.
http://www.colorzilla.com/gradient-editor/
Hope this helps!

A: Your approach is way too complicated! You can just use a CSS gradient instead:
HTML:

THIS CONTENT WILL SCROLL! Theres will always be a different word cut of in the end. somecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontent somecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontentsomecontent

body, html {
    height:100%;
    width:100%;
}
* {
    padding:0;
    margin:0;
}
#scrollmenu {
    position:absolute;
    top:45%;
    height:10%;
    width:100%;
    overflow:hidden;
    white-space:nowrap;
    background-color:black;
    color:white;
}
#arrow1, #arrow2 {
    position:absolute;
    top:0;
    height:100%;
    width:2%;
    z-index:2;
    background-color:red;
}
#arrow1 {
    left:0;
}
#arrow2 {
    right:0;
}
#content {
    height:100%;
    margin-left:2%;
    position:relative;
    z-index:1;
}
#transparencydiv {
    background: -moz-linear-gradient(left,  rgba(0,0,0,0) 0%, rgba(0,0,0,0) 80%, rgba(0,0,0,1) 100%);
    background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(0,0,0,0)), color-stop(80%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,1)));
    background: -webkit-linear-gradient(left,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 80%,rgba(0,0,0,1) 100%);
    background: -o-linear-gradient(left,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 80%,rgba(0,0,0,1) 100%);
    background: -ms-linear-gradient(left,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 80%,rgba(0,0,0,1) 100%);
    background: linear-gradient(to right,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 80%,rgba(0,0,0,1) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00000000', endColorstr='#000000',GradientType=1 );
    height:100%;
    left:0;
    max-height:100%;
    position:absolute;
    top:0;
    width:100%;
}

Fiddle:
Here's a JSFiddle for reference.

A: The basic gradient overlay is probably just the way to go. However, for the sake of science, I tried to answer your question literally and make a truly dynamic and transparent text overlay.
Basically, you can set a linear gradient background on the container element that fades to transparent (you can adjust these gradients to get the desired effect with a CSS Gradient Generator). In my snippet below, I put the text over an image so you can see that it's the text that is transparent, not an overlay making it look like it fades out.

body { background: url('http://i.imgur.com/I5G6HaZ.jpg'); }

.container {
  background: -webkit-linear-gradient(left, white, transparent);
  width: 50%;
  -webkit-background-clip: text;
  overflow-x: hidden;
}

p {
  width: 20em;

  font-size: 24px;
  -webkit-text-fill-color: transparent;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero.


text:
Q: Where do I see Testcafe Studio console log errors? Where do you read console log messages in testcafe studio?
I am writing this code;
 var image  = await getImageElement(
   Selector('.call-to-action__image'
 ).nth(1).nth(1).nth(1).find('a').find('img'));

 console.log(image.src);
 console.log(image.alt);
 await t.debug()
   .expect(isEmpty(image.src)).eql(true,"Ribbon does not exist")
   .expect(isEmpty(image.alt)).eql(false,"Ribbon does not exist");

This code is for trying to read which value of src or alt the element gets.
Thanks

A: At this moment, you can not read the console.log messages in TestCafe Studio. However, you can get the console.log result in your terminal if you run your testfile using the TestCafe Open Source.
Please read the following article to get more details about installation and running TestCafe Open Source:
https://devexpress.github.io/testcafe/documentation/using-testcafe/installing-testcafe.html


text:
Q: How to implement scheduled task on EF (DB first) entities? I am quite new to Asp.net and have a website using Entity Framework. Every night, I need to do some work on my Person entities.
Thus I installed Quartz.Net et tried to use it this way in Global.asax :
<%@ Application Language="C#" %>

<%@ Import Namespace="Quartz" %>
<%@ Import Namespace="Quartz.Impl" %>

<script runat="server">

    private IScheduler Scheduler { get; set; }

    void Application_Start(object sender, EventArgs e)
    {
        Scheduler = StdSchedulerFactory.GetDefaultScheduler();
        Scheduler.Start();

        IJobDetail dailyReset = JobBuilder.Create<ApplicationJobs.DailyReset>()
            .WithIdentity("dailyReset", "group1")
            .Build();

        ITrigger dailyResetTrigger = TriggerBuilder.Create()
            .WithIdentity("dailyResetTrigger", "group1")
            .StartAt(DateBuilder.DateOf(3, 0, 0))
        .WithSimpleSchedule(x => x
            .WithIntervalInHours(24)
            .RepeatForever())
        .Build()

        Scheduler.ScheduleJob(dailyReset, dailyResetTrigger);
    }
</script>

Then my ApplicationJobs class :
public class ApplicationJobs : System.Web.HttpApplication
{
    public class DailyReset : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            using (var uow = new UnitOfWork())
            {
                foreach (Person person in uof.Context.Persons)
                {
                    //do something
                }
            }
        }
    }
}

And finally the UnitOfWork :
public class UnitOfWork : IDisposable
{
    private const string _httpContextKey = "_unitOfWork";
    private MyEntities _dbContext;

    public static UnitOfWork Current
    {
        get { return (UnitOfWork)HttpContext.Current.Items[_httpContextKey]; }
    }

    public UnitOfWork()
    {
        HttpContext.Current.Items[_httpContextKey] = this;
    }

    public MyEntities Context
    {
        get
        {
            if (_dbContext == null)
                _dbContext = new MyEntities();

            return _dbContext;
        }
    }
}

But using (var uow = new UnitOfWork()) is not working because of HttpContext.Current.Items[_httpContextKey] = this; in uow's constructor ; I read that HttpContext.Current was not available in Application_Start.
In read related posts, notably this one but I don't really understand if I do need to create something like UnitOfWorkScope described here, or if there could be a way to do that as it currently is.
Then is there any clean and safe way to schedule some task which would use my UnitOfWork in order to update entities ?
Thanks a lot.

A: Your problem come from the fact that when your job will run, it wil be called by the quartz scheduller, not from an http request (even if the job is in an ASP website).
So HttpContext.Current will be most likely null.
Keep in mind when using Quartz that you shoudl see it as a totally paralle process to your website, almost like a separate service.
If you need to pass "argument" to your job, you can use the job data map
JobDataMap dataMap = jobContext.JobDetail.JobDataMap;

(see here for more info : http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/more-about-jobs.html)
If you need to access your job, just use the same key and group when creating a jobkey (the one you used in WithIdentity
Note that it is recommended for entity context to be alive only for the time of the action you need it, so you could probably just instantiate a new context at the start of the job and dispose it at the end.

A: The issue is that you're not executing the job within a web request. As in, web request starts, you check outstanding work, do work if required, request ends. Without a web request you have no context - as the context is for the lifetime of the web request and accessible via the request thread.
Another issue you're going to have is app-pool, using default settings, may end if there's no activity. So you would need a way to keep it alive.
An alternative method is to use something like win task scheduler to hit the website to kick off the work.


text:
Q: Multiple Regression: Finding which variables are non linearly related to the outcome I have a dataset with 10 predictors and 1 outcome variable. Looking at the Residual Vs Fitted Plot, I suspect a Non-Linearity that I am missing.
But how can I check out of the 10 predictors, which are linearly and which are non-linearly related to the outcome ?

A: It may not answer the question of which exact variable is non-linear, but there is a test designed for this exact type of problem in the econometrics literature called the Ramsey Reset test.
The way it works is by testing whether polynomial terms of the fitted values from the original regression are significant terms. If there is no non-linearity and the original model is correctly specified, then the polynomial terms should not be significant. This is done with an f-test.
The other thing that you can do if you are mainly concerned with fit of the regression (i.e not running a regression with the purpose of doing causal inference) is to pick a small polynomial term, say square or cube and apply it to all of your variables.
Let's say we picked cube for clarity. Run the regression with all cubic terms. Look at the coefficients of all the cubic terms and starting from the coefficients with the largest p-values (least significant so to speak although this wording is making me cringe as I write) and test the hypothesis that the more parsimonious model is an adequate simplification of the original.
Now your p-values will be different, pick the least significant cubed term that remains, eliminate it and test the hypothesis. Rinse and Repeat. Continue until you have eliminated all the non-significant terms and then proceed with the squared terms in this fashion. Eventually you will be left with a regression that cannot be adequately simplified by removing polynomial terms. If there are important non-linearities captured by a cubic they should still be included in the model. With 10 variables this is cumbersome, you could also take a guess at which variables you think might have the non-linearities and work with a subset of cubic terms instead. Again, not ideal for performing inference, your resulting p-values etc are a little strange to interpret since you are squeezing your data so much to get the model in the first place, but this can be reasonable to produce predictive values. You can inject more or less parsimony in this process by changing your significance level for the f-tests.


text:
Q: Redis session expired after 20 minutes, why? I use redis cache (azure servers)
System.Web.HttpContext.Current.Session["UserID"] = user.Id;

After 20 minutes System.Web.HttpContext.Current.Session["UserID"] returns null.
I use Microsoft.Web.RedisSessionStateProvider for my custom sesson.
What is the best way to slide the session when I call System.Web.HttpContext.Current.Session["UserID"]
<sessionState mode="Custom" customProvider="MySessionStateStore">
  <providers>
    <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="SERVER" accessKey="KEY" ssl="true" throwOnError="false" />
  </providers>
</sessionState>

A: When I call variable, then at the same time I update the session variable, like this:
var userId = System.Web.HttpContext.Current.Session["UserID"]; // Get value
System.Web.HttpContext.Current.Session["UserID"] = userId; // Refresh it immediately to increase timeout

A: you not set timeout config,the default timeout configration is 20 minutes.
try this
<sessionState mode="Custom" customProvider="MySessionStateStore" timeout="120">


text:
Q: Decrementing progress bar I'm planning to add a progress message at the top of the progress bar. However, I encountered a problem when decrementing. If all checkboxes are unchecked, the value of the checkbox stays, and it wont decrement to 0.

Here is the fiddle.

$('input').on('click', function() {
  var emptyValue = 0;
  $('input:checked').each(function() {
    emptyValue += parseInt($(this).val());
    $("p.progress_count").html("Progress: " + emptyValue + '%');
  });
  $('.progress-bar').css('width', emptyValue + '%').attr('aria-valuenow', emptyValue);
});

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

Progress: 0%

  <input id="input1" type="checkbox" name="completed1" value="20">
  <input id="input2" type="checkbox" name="completed2" value="20">
  <input id="input3" type="checkbox" name="completed3" value="20">
  <input id="input4" type="checkbox" name="completed4" value="20">
  <input id="input5" type="checkbox" name="completed5" value="20">

A: I moved $("p.progress_count").html("Progress: " + emptyValue + '%'); outside of the loop and it now goes to 0% when all boxes are unchecked.

$('input').on('click', function() {
  var emptyValue = 0;
  $('input:checked').each(function() {
    emptyValue += parseInt($(this).val());
  });
  $("p.progress_count").html("Progress: " + emptyValue + '%');
  $('.progress-bar').css('width', emptyValue + '%').attr('aria-valuenow', emptyValue);
});

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

Progress: 0%

  <input id="input1" type="checkbox" name="completed1" value="20">
  <input id="input2" type="checkbox" name="completed2" value="20">
  <input id="input3" type="checkbox" name="completed3" value="20">
  <input id="input4" type="checkbox" name="completed4" value="20">
  <input id="input5" type="checkbox" name="completed5" value="20">

A: Instead of iterating over each of the checked elements, you can get the number of checked inputs directly.

$('input').on('change', function() {
    var numInputs = $('input').length;
    var numChecked = $('input:checked').length;
    var percentageChecked = numChecked * (100/numInputs);

    $("p.progress_count").html( "Progress: " + percentageChecked  +'%');
    $('.progress-bar').css('width', percentageChecked  + '%').attr('aria-valuenow', percentageChecked);
});

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

Progress: 0%

    <input id="input1" type="checkbox" name="completed1" value="20">
    <input id="input2" type="checkbox" name="completed2" value="20">
    <input id="input3" type="checkbox" name="completed3" value="20">
    <input id="input4" type="checkbox" name="completed4" value="20">
    <input id="input5" type="checkbox" name="completed5" value="20">

A: Issue is very small, it does not get 0 value because each checkbox has value 20. I have simplified it here:

$('input').on('click', function() {
    var emptyValue = $('input:checked').length*20;
   $("p.progress_count").html( "Progress: "+ emptyValue +'%' );

    $('.progress-bar').css('width', emptyValue + '%').attr('aria-valuenow', emptyValue);
});

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

Progress: 0%

    <input id="input1" type="checkbox" name="completed1" >
    <input id="input2" type="checkbox" name="completed2" >
    <input id="input3" type="checkbox" name="completed3" >
    <input id="input4" type="checkbox" name="completed4" >
    <input id="input5" type="checkbox" name="completed5" >

Please note:  I think its not necessary to hard code values in the html instead we can write whole logic in javascript itself. With this approach there are few main advantages:

*

*You can assign real values to each checkbox.

*Maintainability will be easier.

*If you keep more/less controls then you can change your logic. e.g. 100/numberofcontrols

Cheers,
Ashok


text:
Q: Elastic Beanstalk - set .htpasswd on specific environment I have a PHP website configured within Elastic Beanstalk on two environments, a production environment and a stage environment. Within each environment I have an APPLICATION_ENV environment variable set which identifies to the code which environment it's running on. I don't want my stage website to be accessible to the public and I wanted to place a htpasswd on this environment but not on the production one.
To try to achieve this I have created a configuration within .ebextensions. The entire .ebextensions folder has three files:

*

*01stage.config
container_commands:
  command-01:
    command: "/bin/bash .ebextensions/set_stage_htpasswd.sh"
    leader_only: true

*set_stage_htpasswd.sh
#!/bin/bash
if [ "$APPLICATION_ENV" == "stage" ]; then
  cp /var/app/current/.ebextensions/.htpasswd /var/app/current/
fi

*.htpasswd
my_username:my_password

I want Elastic Beanstalk to run the config file 01stage.config which will in turn run the shell script set_stage_htpasswd.sh to copy the .htpasswd file to a specific location.
However when I try to deploy this:

*

*I get an error message in the Events log:
Instance: i-2f795c6e Module: AWSEBAutoScalingGroup ConfigSet: null Command failed on instance. Return code: 1 Output: Error occurred during build: Command command-01 failed .

*Elastic Beanstalk informs me that it has deployed the application and that it's running the new version but it hasn't actually deployed the new code and is still running the previous one.
Is this is right way to try and achieve this or is there a better alternative.

A: I think the quotes on your command: line is giving you problems. I wouldn't be surprised if the shell is looking for a very strange command... But even if that's ok, it's probably easier to use the test: directive to conditionally execute the file copy operations you want. Try something along the lines:
container_commands:
    command-01: cp .ebextensions/.htpasswd /var/app/current
    test: "[ .$APPLICATION_ENV. = .stage. ]"

(Environment variables are available to container_commands:, but I'm not sure -- and you'll need to verify -- that the they are also available in the test: part of the section.)


text:
Q: Jquery UI datepicker date format I am using jquery ui datepicker in a form in my project. I am initializing datepicker like this.
var date_lower = new Date(1910,0,1);
var year_lower = date_lower.getFullYear();
var date_upper = new Date();
var year_upper = date_upper.getFullYear();
$("#id_dob").datepicker({ dateFormat: 'mm-dd-yy',minDate: date_lower,
        maxDate: date_upper ,
        yearRange: year_lower+':'+year_upper ,
        changeYear: true,
        changeMonth: true,
        defaultDate: new Date(2000,01,01)
});

My date format is like this 'mm-dd-yy'. So datepicker does not allow me to enter date in 'mm/dd/yy' format. When I try to type '/' in datepicker input, it does nothing or I cannot type '/' in datepicker input field. I am doing this because I want to give user option to add date without using calander too (It is client's demand). I want that to set date format so that I can use any separater from [./-\s]. For example I want all these type of dates (01-01-1999, 01/01/1999, 01.01.1999 and 01 01 1999) to be accepted. Can any one tell me how I can do this?
I am using Django model formsets.

A: Check this out: jQuery Datepicker that supports multiple formats
Basically, tweak the parseDate function to allow several formats, and use the original parseDate to check each one:
$.datepicker.inputFormats = ["mm-dd-yy", "mm/dd/yy", "mm dd yy"];//list formats to be accepted here, add formats as you see fit.

$.datepicker.originalParseDate = $.datepicker.parseDate;

$.datepicker.parseDate = function (format, value, settings) {
    var date;

    function testParse(format, value, settings) {
        if ( ! date ) {
            try {
                date = $.datepicker.originalParseDate(format, value, settings);
            } catch (Error) {
            }
        }
    }

    testParse(format, value, settings);
    for(var n = 0, stop = $.datepicker.inputFormats ? $.datepicker.inputFormats.length : 0; n < stop; n++){
        testParse($.datepicker.inputFormats[n], value, settings);
    };
    return date;
};

A: Small changes i made
Your code has some problem, you set data time format to mm-dd-yyyy,
that why date time picker always get mm-dd-yyyy.
following updated code work perfectly
$("#datepicker").datepicker({
  minDate: date_lower,
  maxDate: date_upper,
  changeYear: true,
  changeMonth: true,
 });


text:
Q: Python 3 - Formatting print commands New to python and I'm trying to export some information from network devices and format it into a text file. I have the below code I'm running;
for device in (LD6AGGSW01 , LD6AGGSW02 ):
    net_connect = ConnectHandler(**device)
    output = net_connect.send_command('show hostname')
    pickle.dump(output, open("hostname.p", "wb"))
    output = net_connect.send_command('sh ver | i NXOS | i image |i file |i is:')
    output = output.strip()
    pickle.dump(output, open("IOSimage.p", "wb"))
    output = pickle.load(open("hostname.p","rb"))
    print('Hostname: ' + output)
    output = pickle.load(open("IOSimage.p","rb"))
    print(output)

I'm trying to change the output from looking like:
Hostname: LD6-AGG-SW01

NXOS image file is: bootflash:///nxos.7.0.3.I3.1.bin
Hostname: LD6-AGG-SW02

NXOS image file is: bootflash:///nxos.7.0.3.I3.1.bin

to:
Hostname: LD6-AGG-SW01
NXOS image file is: bootflash:///nxos.7.0.3.I3.1.bin

Hostname: LD6-AGG-SW02
NXOS image file is: bootflash:///nxos.7.0.3.I3.1.bin

Any ideas on how I'd go about this?

A: I'm assuming net_connect.send_command() returns a string with a trailing newline.
If that's correct,
for device in (LD6AGGSW01 , LD6AGGSW02 ):
    net_connect = ConnectHandler(**device)
    hostname = net_connect.send_command('show hostname').strip()
    ios_image = net_connect.send_command('sh ver | i NXOS | i image |i file |i is:').strip()
    print('Hostname:', hostname)
    print('Image:', ios_image)
    print()

– i.e. strip()ing the outputs – should do the trick.

A: Use .strip() to remove the unwanted \n character in your output:
for device in (LD6AGGSW01 , LD6AGGSW02 ):
    net_connect = ConnectHandler(**device)
    output = net_connect.send_command('show hostname')
    pickle.dump(output, open("hostname.p", "wb"))
    output = net_connect.send_command('sh ver | i NXOS | i image |i file |i is:')
    output = output.strip()
    pickle.dump(output, open("IOSimage.p", "wb"))
    output = pickle.load(open("hostname.p","rb"))
    output = output.strip()    # Strip output
    print('Hostname: ' + output)
    output = pickle.load(open("IOSimage.p","rb"))
    output = output.strip()   # Strip output
    print(output)
    print()    # Call print function to insert extra line


text:
Q: Strange issue with System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity We're writing a system that allows a user to change their account password through a web application on our intranet.
At first, everything appeared to be running smoothly. During development passwords for our test accounts could be changed with no problem.
When we made the system live, however, we started running into issues. Here are the symptoms:

*

*At first, everything is fine. Users
can change their passwords.

*At some
point, the following error occurs in
UserPrincipal.FindByIdentity:
"System.Runtime.InteropServices.COMException:
The authentication mechanism is
unknown. "

*From then on, trying to
change a password through the web
application results in the error:
"System.Runtime.InteropServices.COMException:
The server is not operational. "

*If I manually recycle the app pool,
    everything seems to fix itself until
    more errors begin happening... i.e.,
    the process starts all over again at
    phase 1.

Here's the relevant snippet of code:

    private static PrincipalContext CreateManagementContext() {
        return new PrincipalContext(
            ContextType.Domain,
            ActiveDirectoryDomain,
            ActiveDirectoryManagementAccountName,
            ActiveDirectoryManagementAccountPassword);
    }

    private static void ChangeActiveDirectoryPasword(string username, string password) {
        if (username == null) throw new ArgumentNullException("username");
        if (password == null) throw new ArgumentNullException("password");

        using (var context = CreateManagementContext())
        using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username)) {
            user.SetPassword(password);
        }
    }

Any clues as to why this is happening? Google searches aren't turning up anything really helpful, and neither are the docs on MSDN.

A: First thing I notice is that you are using UserPrincipal.FindByIdentity which is inherited from AuthenticablePrincipal which is inherited from Principal.  I say all this because the Principal class has a known memory leak in the FindByIdentity.  If you have a look at this MSDN entry, you will notice at the bottom that Gary Caldwell from Microsoft said the following:

This call has an unmanaged memory leak
  because the underlying implemenation
  uses DirectorySearcher and
  SearchResultsCollection but does not
  call dispose on the
  SearchResultsCollection as the
  document describes.

I would guess that this is your issue.  The memory leak causes the Application Pool to fill up and finally cause errors, until the Application Pool is reset and the memory is disposed.
When we use any active directory functions, we use the following to accomplish setting of the user's password:
Public Shared Function GetUserAccount(ByVal username As String) As DirectoryEntry
    Dim rootPath As String = GetRootPath()
    Using objRootEntry As New DirectoryEntry(rootPath)
        Using objAdSearcher As New DirectorySearcher(objRootEntry)
            objAdSearcher.Filter = "(&(objectClass=user)(samAccountName=" & username & "))"
            Dim objResult As SearchResult = objAdSearcher.FindOne()
            If objResult IsNot Nothing Then Return objResult.GetDirectoryEntry()
        End Using
    End Using
    Return Nothing
End Function

Public Shared Sub SetPassword(ByVal username As String, ByVal newPassword As String)
    Using objUser As DirectoryEntry = GetUserAccount(username)
        If objUser Is Nothing Then Throw New UserNotFoundException(username)
        Try
            objUser.Invoke("SetPassword", newPassword)
            objUser.CommitChanges()
        Catch ex As Exception
            Throw New Exception("Could not change password for " & username & ".", ex)
        End Try
    End Using
End Sub

Also, if you're wanting the users to change the passwords directly and you don't want to rely on their honesty, you might want to consider using the ChangePassword function of LDAP like this:
Public Shared Sub ChangePassword(ByVal username As String, ByVal oldPassword As String, ByVal newPassword As String)
    Using objUser As DirectoryEntry = GetUserAccount(username)
        If objUser Is Nothing Then Throw New UserNotFoundException(username)
        Try
            objUser.Invoke("ChangePassword", oldPassword, newPassword)
            objUser.CommitChanges()
        Catch ex As TargetInvocationException
            Throw New Exception("Could not change password for " & username & ".", ex)
        End Try
    End Using
End Sub

This forces the user to know the prior password before changing to the new one.
I hope this helps,
Thanks!


text:
Q: How to select rows that date is in range from ranges table I have a table1 that hold ranges
rangeId, rangeName, fromDate, toDate,cat

another table2 has rows
rowTitle,rowDate

I need to
select  all rows
from table2
that table2.rowDate is between table1.fromDate
                           and table1.toDate
and cat = 1

A: Something like :
select t2.*
from table2 t2
join table1 t1 on t2.rowdate between t1.fromDate and t1.toDate
where t1.cat = 1


text:
Q: What is the cyclic subgroup of integers(Z) generated by -1 under +? I am trying to understand cyclic, and need to know what the cyclic subgroup of integers (Z) generated by -1 under + ?

A: Keep adding $-1$ to itself; what do you get?  Then don't forget that subgroups include the inverses; what is the additive inverse of $-1$, and what do you get when you add that to itself?  That is the subgroup of $\mathbb{Z}$ you get.  (Note that subgroups don't have to be proper.)

A: The subgroup would be denoted $\langle -1 \rangle$ and the set of elements of the group is
$$\{ \dots , (-1)^{-2}, (-1)^{-1}, (-1)^0, (-1)^1, (-1)^2, \dots \}$$
where $(-1)^n=\underbrace{(-1)+\cdots +(-1)}_\text{$n$-many}$ for $n>0$.


text:
Q: How to tell Webpack not to pack a config file I am using Webpack for an Angular 4/TypeScript project and in one of my modules, I want to access a config.json file with some values that must be configurable on the server (i.e., config values that can be changed at runtime instead of being fixed at compile time).
In my source, I refer to that file using
let config = require('./../relative/path/config.json');

It works nicely but webpack packs it up and in the resulting dist the values of the config file end up along with the rest in the app.XXX.js file.
I tried to mark the file in webpack.common.js (which is referenced by the other webpack configuration files) by adding it to the externals, but that doesn't change anything. I had hoped that webpack would then simply not pack up the file but deploy it as-is to the dist directory.
Question: can I have my config.json, and have webpack not pack it but simply deploy it, so that I can modify or replace the file upon deployment instead of opening app.XXX.js and searching for the values?

A: First thing to realize is that your webpack'ed application is not running on the server, but in the client's browser. Although this require call looks like a call to read a file at runtime, it is in fact just an instruction to webpack to bundle a file and deliver it to browser embedded in the bundle. The bundle itself is served as plain file to the browser.
In light of this, simple task of reading a configuration file at runtime becomes: fetching a file from the server and parsing it at runtime. Fortunately webpack has dedicated infrastructure to do exactly this: import().
import('./../relative/path/config.json').then(config => {
  // Do something with 'config'
})

or if you are still on legacy JavaScript, you can use legacy require.ensure().
require.ensure(['./../relative/path/config.json'], function(require) {
  let config = require('./../relative/path/config.json');
  // Do something special...
});


text: Q: How to interpret bound charges geometrically? Conceptually, it makes sense to say that when there is an electric field along $E=E\hat{n}$, then given a polarization $P$, the amount that $P$ aligns with the electric field is simply the dot product $P\cdot\hat{n}$. But why does this only apply to the surface charge? Shouldn't we use the dot product to describe the extent of alignment of the dipoles within the  material as well? That's given by $-\nabla\cdot P$. But when I visualize that, I see the amount that the polarization is approaching a point $(x,y,z)$ (creating a sink). Why is this the case? And how does it describe the amount that the dipoles align with the electric field inside the material? I hope my question is not phrased in an obscure manner.


text:
Q: macOS Big Sur - how to show exact time when clicking on analog clock in the menu bar? I just upgraded to macOS Big Sur and this is my menu bar and the analog clock is at the end:

When I click on the analog clock, notifications and widgets are shown, while in Catalina, the exact time would be shown. How do I do that in Big Sur?


text:
Q: Is XACML still under maintenance Currently i'm working in a on-line payment company, i need to implement a access control system. I used XACML for experimental purpose 2 years ago, and used it in a management system(based on Balana's XACML implementation). I noticed XACML Version 3 specification hasn't been updated since Jan 2013, i wonder whether this specification is still under maintenance. If not, does anyone know any alternative?

A: What David says is correct. In addition, the OASIS XACML Technical Committee (TC) has just voted to hold a public review of Errata for XACML 3.0. The review should start within a few days. The corrections are minor, but it does show we are maintaining the documents and getting input from the field.
Although no one is currently working on them, there are several unfinished Profiles I would like to see completed. One is to extend the JSON format for XACML to cover the policy language. It currently only covers only the decision request protocol. Another is the ALFA policy language which is a more user friendly, JSON-like language originally developed by Axiomatics, and endorsed by the TC.
For people who want to use XACML, in addition to several excellent commercial products, there are at least two other open source implementations in addition the the WS02 - Balana one mentioned above. Forgerock has one and there is another originally developed in house at ATT. The later one was contributed to the Apache Incubator, but failed to gain traction and was mothballed. However the original code is still freely available under Apache license.
Finally I should mention that I have proposed various ways to integrate XACML with token-based authorization schemes such as OAuth. However this has not gone past the research stage.

A: Yes, XACML is still very much active. The standard, in version 3, is mature and right now no one is working on XACML 4.0. Given XACML 3.0 is a standard, there won't be changes made to 3.0. Either we go to 3.1 or 4.0. There are enhancements we are thinking of for a 4.0 version but this is not the focus for now.
The focus is on profiles, both technical profiles (such as the JSON profile of XACML) and business profiles (such as the Export Control profile of XACML).
Disclaimer: I work for Axiomatics, the leading XACML implementation. I am also a member of the XACML Technical Committee.
We see more and more requests for Attribute Based Access Control and XACML in the marketplace especially in financial and healthcare


text:
Q: how can we check connectivity between two virtual machine in azure I have below questions related to Azure.

*

*How can we check the latency between two virtual machine on Azure network as ICMP is not allowed there.
I have an Linux VM and one Windows Server 2016 VM with SQL standard.

*How can we check the network performance on Azure.Like to check the alloted bandwidth to a VM.
Regards,
Yugdeep

A: In Azure, we can't use ICMP to test the network, we can use tcping to test it. if we use tcping, we should open port 80.

Also we can use third party tools to test it.
Linux we can use iperf3, windows we can use Ntttcp.
Here a article talk about how to test it, and have a report about the result, please refer to it.


text:
Q: Problems reading data into an array list from a file in Java So this is my first time posting here. I am trying to read data from a file, create multiple objects from that data, and then place the created objects into an ArrayList. But every time I have tried, I just get multiple copies of the same object, instead of different objects. I am at my wits end.
Anyways, here is the code for the method to read the data in from the file. Thanks in advance for any help!
public void openShop() throws IOException{
    System.out.println("What is the name of the shop?");
    shopName = keyboard.nextLine();
    setShopFile();
    File openShop = new File(shopFile);
    if (openShop.isFile()){
        Scanner shopData = new Scanner(openShop);
            shopName = shopData.nextLine();
            shopOwner = shopData.nextLine();

            while (shopData.hasNextLine()){
                shopItem.setName(shopData.nextLine());
                shopItem.setPrice(Double.parseDouble(shopData.nextLine()));
                shopItem.setVintage(Boolean.parseBoolean(shopData.nextLine()));
                shopItem.setNumberAvailable(Integer.parseInt(shopData.nextLine()));
                shopItem.setSellerName(shopData.nextLine());
                shopInventory.add(shopItem);

            }
            setNumberOfItems();
    }
    else
        System.out.println("That shop does not exist. Please try to open" +
                          "the shop again.");
    isSaved = true;
}

A: inside your while loop you should create a new instance of an object. Else it would only end up making modifications to the exisiting instance.
Correct way :
while (shopData.hasNextLine()){
   shopItem = new ShopItem(); //This will create a new Object of type ShopItem
   shopItem.setName(shopData.nextLine());
   shopItem.setPrice(Double.parseDouble(shopData.nextLine()));
   shopItem.setVintage(Boolean.parseBoolean(shopData.nextLine()));
   shopItem.setNumberAvailable(Integer.parseInt(shopData.nextLine()));
   shopItem.setSellerName(shopData.nextLine());
   shopInventory.add(shopItem);
}

A: I cant see where you're creating the shopItem instance.
But if you're not creating a new ShopItem each time then every time you go around the loop you're just updating the one instance, and then adding it to the shopInventory.

A: You fill your ArrayList using the very same object. You should create a new instance of ShopItem:
while (shopData.hasNextLine()){
  ShopItem shopItem = new ShopItem();
  shopItem.setName(shopData.nextLine());
  ...
}


text:
Q: Does MySQL have inbuilt feature for Geo location based queries? Does MySQL have inbuilt feature for Geo location based queries?
I have found this one Spatial extension http://dev.mysql.com/doc/refman/5.1/en/spatial-extensions.html
How's it as compare to MongoDB GeoSpatial feature?? What's the difference in between them??

A: MySQL's geospatial extension implements planar, not spherical or projection, geometry in a native fashion. It is possible to use a spatial index to accelerate latitude / longitude lookup, but the spherical geometry computations need to be done in MySQL queries or stored functions provided by you, the user of the geospatial extension. Here's a writeup on that.
http://www.plumislandmedia.net/mysql/using-mysqls-geospatial-extension-location-finder/
Mongo has multiple projections supported in the geospatial projection.


text:
Q: Spring Web MVC tomcat deployment issues I am developing one Spring Web application with Intellij IDEA deployed to tomcat.
I met the issues below:
When I set the application context to the application name(my app) in the Run/Debug configuration page then run tomcat i can access the tomcat homepage and can see "myapp" in the manager page but can't access it.
The URL will be "localhost:8080/request" when clicking myapp in the manager page.
I have to add "myapp" to the URL as "localhost:8080/myapp/request".In this way the requested page can be accessed.
But if i removed "/myapp" from application context leaving it blank in the Run/Debug configuration page  then run tomcat i will access the requested page successfully.
The URL is "localhost:8080/request" now the same as before without "myapp".
If I just added the myapp.war file in /webapps folder the result is the same as the first scenario.
What i want is that I put the war file in /webapps folder and start the tomcat server then the page can be accessed.
Anything wrong i have done for the configuration or missed something?
Thanks in advance for the help.
This is the web.xml
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/root-context.xml
    </param-value>
</context-param>

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.gif</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>