text:
Q: Exit my while loop after 10 seconds while I'm waiting a response from a TcpClient I'm trying to implement a ping in my basic client-server chat. My problem is on the server side. I send the ping and then I want to wait up to 10 seconds for the client to ping me back. If the client doesn't ping back after 10 seconds I want my while loop to break. Here is what I've done:
public void ping()
{
    send("#PIN#");
    bool ponged = false;
    while (true)
    {
        string rec = receive(); // it blocks here !!!!!!!!!!
        if (rec == "#PON#")
            ponged = true;
    }
}

There is no problem with my send() and receive() methods. They work fine everywhere else.
I tried using both a Stopwatch and a Timer to make the loop break after 10 seconds. The problem comes from the fact that the receive function blocks until a message has been received. Here is the part of the receive function that blocks:
bytesRead = clientStream.Read(byteMsg, 0, 4096);

As far as I know this is the proper way for receiving messages from my client. But of course if the client is disconnected, I will never get pinged back, which means my receive() method will never end. If my receive method never ends then my while loop never gets the opportunity to check stopWatch.Elapsed() or call an ElepsedEventHandler from a Timer.
So the question is, how can I force this while loop to break after 10 seconds knowing that one of the methods in that while loop is likely to not end?
Thank you for your time.

A: If you're using a NetworkStream to read your data, there is a ReadTimeout property you can use.

If the read operation does not complete within the time specified by
  this property, the read operation throws an IOException.


text:
Q: Spinnaker with Redhat, Amazon AMI or CentOS? Was wondering if anyone has installed spinnaker on a machine that isn't running Ubuntu or Mac. According to the spinnaker github they only have instructions for those two but seems possible for others. Assume I can not use either of those. Can it work on RHEL, amazon, etc? Any help would be greatly appreciated, thanks.

A: Diana Tkachenko from Stitch Fix recently gave a talk on the steps she had to take for Amazon Linux. You might find it useful - https://youtu.be/ywzPblFpIE0 . ( starts around 30 minutes in )

A: It can work on RPM based distro's with a bit of extra work (I know of folks running on Amazon Linux) - the project is only publishing deb files currently, so you have to build from source to get RPM packages for each of the components.
for each of the service git repos executing ./gradlew buildRpm will produce an installable RPM.

A: You can  Install spinnaker on Redhat by using Docker , Install docker on Redhat , then install Spinnaker on the docker , as docker can be installed anywhere and anything can be installed on docker files ..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt compile error: endl will always evaluate to true I have the following code snippet that compiles
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);

for (QStringList::Iterator it = commandList.begin(); it != commandList.end(); ++it) {
    out << "Command: " << *it << endl;
}

but always gives me this warning:
test.cpp:87: warning: the address of 'QTextStream& endl(QTextStream&)' will always evaluate as 'true' [-Waddress]
What does it mean and how do I fix it?  Since a newline character is printing I assume this is not a namespace issue...

A: When you are using a binary data stream, it is not a good practice to start inserting new lines. That is one of the main points over a simple QTextStream.
This code works fine for me without any warning with gcc version 4.8.1 20130725 (prerelease) (GCC)
main.cpp
#include <QByteArray>
#include <QDataStream>
#include <QIODevice>
#include <QStringList>

int main()
{
    QStringList commandList = QStringList() << "foo" << "bar" << "baz";
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);

    for (QStringList::Iterator it = commandList.begin(); it != commandList.end(); ++it)
        out << "Command: " << *it;
}

Building
g++ -std=c++11 -Wpedantic -Wall -I/usr/include/qt -I/usr/include/qt/QtCore -lQt5Core -fPIC main.cpp


text:
Q: CSS3 transition only applying to active link, and not all links On my site ( 1 ) Im trying to add this transition to all of my nav links, but i can only get it to work for the visited link. ( 2 ) Im trying to add this transition to the drop down menus.
body .main-nav .active-link >a, body .main-nav .active-link >a:visited {
border-top: solid 0px #3b5998;
color: #3b5998;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out }

A: You have incorrect selector if you need all of the links to have transition.
It should be:
body .main-nav li >a, body .main-nav li >a:visited

You have .active-link in your selector which exists only to the link of the page you are on.


text:
Q: How to fix DLL Load failed in visual studio code? when I try to import pygame , I facing an error.
The error shown by visual studio code as following:
from pygame.base import * # pylint: disable=wildcard-import; lgtm[py/polluting-import]
Import error: DLL load failed while importing base: The specified procedure could not be found

Additional Information:
I have already installed pywin32 and pypiwin32
python version-3.9
visual studio code version-1.51

A: Please check that the Python you are currently using is the same bit as the installed pygame (both are 64-bit or 32-bit).
It is recommended that you reinstall the module "pygame" in the python3.9 environment: pip3 install pygame==2.0.0 python==3.9
I am using python3.9(64), pygame2.0.0:


text:
Q: Trampolining scalaz' Monad.whileM_ to prevent stack overflow I'm using scalaz' Monad.whileM_ to implement a while loop in a functional way as follows:
object Main {

  import scalaz._
  import Scalaz._

  import scala.language.higherKinds

  case class IState(s: Int)

  type IStateT[A] = StateT[Id, IState, A]
  type MTransT[S[_], A] = EitherT[S, String, A]
  type MTrans[A] = MTransT[IStateT, A]

  def eval(k: Int): MTrans[Int] = {
    for {
      state <- get[IState].liftM[MTransT]
      _ <- put(state.copy(s = (state.s + 1) % k)).liftM[MTransT]
    } yield (k + 1)
  }

  def evalCond(): MTrans[Boolean] = {
    for {
      state <- get[IState].liftM[MTransT]
    } yield (state.s != 0)
  }

  def run() = {
    val k = 10
    eval(k).whileM_(evalCond()).run(IState(1))
  }
}

While this works for small k, it results in a StackOverflow error for large k (e.g. 1000000). Is there a way to trampoline whileM_ or is there a better way to be stack safe?

A: Use scalaz.Free.Trampoline instead of scalaz.Id.Id.
type IStateT[A] = StateT[Trampoline, IState, A]

The state operations used here return State[S, A] which is just an alias for StateT[Id, S, A]. You need to use the lift[M[_]] function defined on StateT to lift StateT[Id, S, A] to StateT[Trampoline, S, A].
def eval(k: Int): MTrans[Int] = {
  for {
    state <- get[IState].lift[Trampoline].liftM[MTransT]
    _ <- put(state.copy(s = (state.s + 1) % k)).lift[Trampoline].liftM[MTransT]
  } yield (k + 1)
}

def evalCond(): MTrans[Boolean] = {
  for {
    state <- get[IState].lift[Trampoline].liftM[MTransT]
  } yield (state.s != 0)
}

Finally, calling .run(IState(1)) now results in Trampoline[(IState, String \/ Unit)]. You must additionally run this as well.
eval(k).whileM_(evalCond()).run(IState(1)).run


text:
Q: Mongo/Java Map-Reduce function - MongoCommandException I get the following error: com.mongodb.MongoCommandException: Command failed with error 139: 'SyntaxError: missing ; before statement @:1:60
' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "SyntaxError: missing ; before statement @:1:60\n", "code" : 139
It seems I am missing a ; but cannot seem to see where.  The method is self-explanatory, I tend to create an map/reduce via mongo. Any help is appreciated.
public void mapFunction()
           {
               Mongo mongo = null;
               try{
               mongo = new Mongo("localhost", 27017);
               DB db = mongo.getDB("amarokforumdb");

               DBCollection comments = db.getCollection("comments");
               String map = "function() { "+
                     "var category; " +
                         "var numOfDocuments = "+db+".comments.count();" +

                         "for(i = 0; i < numOfDocuments; i++){ " +
                     "if (numOfDocuments <= 100) {"+
                     "category = 'New Comments'; }" +
                     "else if(numOfDocuments > 100){" +
                     "category = 'Old Comments'; }}"+
                     "emit(category,1);};";

               String reduce = "function(key, values) { " +
                                    "var sum = 0; " +
                                    "values.forEach(function(doc) { " +
                                    "sum += 1; "+
                                    "}); " +
                                    "return {comments: sum};} ";

                MapReduceCommand cmd = new MapReduceCommand(comments, map, reduce,
            null, MapReduceCommand.OutputType.INLINE, null);

            MapReduceOutput out = comments.mapReduce(cmd);

               for (DBObject o : out.results()) {
            System.out.println(o.toString());
               }}catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }

           }

A: Replace the "+db+".comments.count(); with an integer for testing, I think you got something wrong with that +db+ part


text:
Q: how do we combine matrices in R? I have done the following command to generate 20 matrices with the same number of column and row.
alive <- vector(mode="list",length= 20)
mu <- 0.1
n <- 10
alive[[1]] <- 100
for(i in 2:20)
    alive[[i]] <- rbinom(10, alive[[i-1]], exp(-mu))

alive

[[1]]
[1] 100

[[2]]
 [1] 92 92 84 90 86 91 91 89 93 90

[[3]]
 [1] 85 78 75 81 79 79 83 82 87 84

[[4]]
 [1] 77 72 70 72 76 70 76 75 76 72

[[5]]
 [1] 71 61 62 64 73 64 69 68 68 62

[[6]]
 [1] 64 56 56 61 68 59 65 59 64 54

[[7]]
 [1] 58 50 53 55 63 52 60 49 53 48

[[8]]
 [1] 54 47 48 51 57 45 56 45 48 41

[[9]]
 [1] 46 40 43 43 52 40 52 42 47 37

[[10]]
 [1] 39 40 42 41 46 35 43 38 45 33

[[11]]
 [1] 34 38 39 39 45 32 42 36 44 29

[[12]]
 [1] 32 37 38 33 39 27 34 35 42 25

[[13]]
 [1] 28 37 33 29 35 25 32 35 38 23

[[14]]
 [1] 26 34 29 28 32 21 27 33 35 19

[[15]]
 [1] 22 32 28 25 31 21 18 33 33 15

[[16]]
 [1] 20 30 24 21 29 19 16 29 29 11

[[17]]
 [1] 19 29 22 20 26 18 12 27 27 10

[[18]]
 [1] 19 23 20 19 23 13 11 25 25  8

[[19]]
 [1] 19 22 16 18 21 11 11 25 23  7

[[20]]
 [1] 18 21 13 17 19  8  9 24 22  5

And now, how do i combine all of the matrices to a single matrix?
I tried to use this command :-
A = matrix (cbind(alive[[i]]), nrow=10, ncol=20, byrow = TRUE)
A

However, it turns out to combine only the last matrix.

Can anyone help me with this?
Many thanks!


text:
Q: I get InterruptedException while sending data to kafka from multiple producers I am trying to run kafka producer using the kafka-clients api. I have multiple producers running with separate threads and each trying to write data to kafka. The problem is I get an interrupted exception from kafka when I increase the number of threads running in parallel. For example, if I run 20 threads in parallel, it doesn't throw any exception but when I run it with 100 threads in parallel, I get the below exception:

Exception in thread "pool-910-thread-1" org.apache.kafka.common.errors.InterruptException: java.lang.InterruptedException
      at org.apache.kafka.clients.producer.KafkaProducer.close(KafkaProducer.java:1154)
      at org.apache.kafka.clients.producer.KafkaProducer.close(KafkaProducer.java:1128)
      at org.apache.kafka.clients.producer.KafkaProducer.close(KafkaProducer.java:1107)
      at com.t4e.kafka.producer.IEC104KafkaReadMessageProcessor.runProducer(IEC104KafkaReadMessageProcessor.java:45)
      at com.t4e.iec104.connection.Iec60870ReadListener.writeToJsonFile(Iec60870ReadListener.java:707)
      at com.t4e.iec104.connection.Iec60870ReadListener.newASdu(Iec60870ReadListener.java:75)
      at org.openmuc.j60870.Connection$ConnectionReader$1.run(Connection.java:143)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
      at java.lang.Thread.run(Thread.java:748)
  Caused by: java.lang.InterruptedException
      at java.lang.Object.wait(Native Method)
      at java.lang.Thread.join(Thread.java:1260)
      at org.apache.kafka.clients.producer.KafkaProducer.close(KafkaProducer.java:1152)

Here's my producer code:
private static final Logger logger = LoggerFactory.getLogger(IEC104KafkaReadMessageProcessor.class);
    static KafkaProducerConfigReader kafkaConfig = new KafkaProducerConfigReader();
    static String newLine = System.getProperty("line.separator");

    /**
     * @param message
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static synchronized RecordMetadata runProducer(String message) throws InterruptedException, ExecutionException {
        Producer<Long, String> producer = ProducerCreator.createProducer();
        ProducerRecord<Long, String> record = new ProducerRecord<Long, String>(kafkaConfig.getTopicName(), message);
        try {
            RecordMetadata metadata = producer.send(record).get();
            logger.info(("Record sent with key " + " to partition " + metadata.partition() + " with offset "
                    + metadata.offset()));
            return metadata;
        } catch (ExecutionException e) {
            logger.error("ExecutionException : Error in sending record to kafka");
            throw new ExecutionException(e);
        } catch (InterruptedException e) {
            logger.error("InterruptedException : Error in sending record" + newLine);
            throw new InterruptedException();
        } finally {
            logger.info(" Closing Kafka producer ");
            producer.close();
        }
    }

A: The problem may not be in this piece of code where you are creating a producer. Looking at the log you shared,

Exception in thread "pool-910-thread-1" org.apache.kafka.common.errors.InterruptException: java.lang.InterruptedException

I can see that there are 910 thread pools active. Creating that many number of pools instead of creating threads keeping a single pool would probably be a better idea.
You might want to look at the place where you are creating the thread pools and control it.
I suspect a thread leak in your code would be causing this interrupt exception.


text:
Q: Using multiple screens with very different DPI simultaneously in Windows 8.1? I'm running Windows 8.1 inside VMWare Fusion 6. I have two screens:

*

*Macbook Pro Retina aka MBPr (15", 220 ppi)

*External HDMI monitor (24", 96 ppi)

VMWare Fusion IS indeed allowing me to use the native resolution of the Macbook Pro panel (i.e. 2880x1800) but in that mode my Desktop UI is all messed up. It's either too tiny for the Macbook Pro screen or too large for the external display.
I was under the impression that Windows 8.1 allows for per-monitor DPI? How can I set it up so that I have

*

*My Macbook Pro running at it's sharpest setting without making it too small
AND

*My external display showing it's contents without blowing it up too big?

I know it's discussed in older OS's but since they are exactly that - older OS's, please don't consider this is as duplicate in any way.

A: Upgrading to VMware Fusion 7 fix's the problem. It came out a few days ago.

A: Right-click the Windows desktop background and select Screen resolution. Click the "Make text and other items larger or smaller" link in the Screen resolution window and you'll be able to set a custom scaling level for your display.
If you choose the text box for "Let me choose scaling level for all my displays" you can manually adjust the scaling to fit your settings.
REF: http://www.howtogeek.com/175664/how-to-make-the-windows-desktop-work-well-on-high-dpi-displays-and-fix-blurry-fonts/


text:
Q: Why is the return value of Request.Form.ToString() different from the result of NameValueCollection.ToString() It seems like the ToString () in HttpContext.Request.Form is decorated so the result is different
from the one returned from ToString() whencalled directly on a NameValueCollection:
NameValueCollection nameValue = Request.Form;
string requestFormString = nameValue.ToString();

NameValueCollection mycollection = new NameValueCollection{{"say","hallo"},{"from", "me"}};
string nameValueString = mycollection.ToString();

return "RequestForm: " + requestFormString + "

NameValue: " + nameValueString;

The result is as the following:
RequestForm: say=hallo&from=me
NameValue: System.Collections.Specialized.NameValueCollection
How can I get "string NameValueString = mycollection.ToString();" to return "say=hallo&from=me"?

A: The reason you don't see the nicely formatted output is because Request.Form is actually of type System.Web.HttpValueCollection. This class overrides ToString() so that it returns the text you want. The standard NameValueCollection does not override ToString(), and so you get the output of the object version.
Without access to the specialized version of the class, you'll need to iterate the collection yourself and build up the string:
StringBuilder sb = new StringBuilder();

for (int i = 0; i < mycollection.Count; i++)
{
   string curItemStr = string.Format("{0}={1}", mycollection.Keys[i],
                                                 mycollection[mycollection.Keys[i]]);
   if (i != 0)
       sb.Append("&");
   sb.Append(curItemStr);
}

string prettyOutput = sb.ToString();

A: You need to iterate over mycollection and build a string up yourself, formatted the way that you want it. Here's one way to do it:
StringBuilder sb = new StringBuilder();

foreach (string key in mycollection.Keys)
{
   sb.Append(string.Format("{0}{1}={2}",
      sb.Length == 0 ? string.Empty : "&",
      key,
      mycollection[key]));
}

string nameValueString = sb.ToString();

The reason that simply calling ToString() on your NameValueCollection does not work is that the Object.ToString() method is what's actually being called, which (unless overridden) returns the object's fully qualified type name. In this case, the fully qualified type name is "System.Collections.Specialized.NameValueCollection".

A: Another method that works well:
var poststring = new System.IO.StreamReader(Request.InputStream).ReadToEnd();


text:
Q: Legend in ggplotly doesnt display all the values I have created the following dataframe
  ##### TOY SET
  DF1<-data.frame("Sl_NO"= c(1:70))

 DF1$ID<-paste0("A_1234_2345_3456_4567_7777", as.character(DF1$Sl_NO))

  DF1$Value<-DF1$Sl_NO

Next I Create 2 more dataframes with the following changes
  DF2<-DF1
  DF2$Value<-DF1$Sl_NO*1.5
  DF3<-DF1
  DF3$Value<-DF3$Sl_NO*1.25

Next we rbind the dataframes
    DFmain<-rbind(DF1, DF2, DF3)
    library(ggplot2)

Create a plot with ggplot
     p<-ggplot(data = DFmain)+geom_line(aes(x = Sl_NO, y = Value, color=ID))
     p
     library(plotly)
     ggplotly(p, dynamicTicks = T)

When I run the plot, p runs and all the legend entries are visible. When I run the part with ggplotly, the legend appears as a scroll down but the number of legend items is less than the number of plotted lines.
Is there a way to ensure all the legend entries are visible. Request someone to help

A: I get length(unique(DFmain$ID)) = 70 and I can see 70 items in the legend. I visualize the plot in Chrome. Probably you get an issue because you visualize in RStudio. It's better to use a browser like Chrome.


text:
Q: Convert Row with duplicate values to Column - MySQL I have a table 'A' that looks something like:
_______________________________________________________________
|query_id |   query      |  response   |user_response_count    |
|---------------------------------------------------------------
|   1     |   acne       |   BothBad   |       2               |
|   1     |   acne       |  BothGood   |       1               |
|   2     |   asthma     |   BothBad   |       1               |
|   2     |   asthma     |   product 1 |       1               |
|   2     |   asthma     |   BothGood  |       1               |
|   3     |   bell palsy |   product 2 |       2               |
|   3     |   bell palsy |   BothGood  |       1               |
 ---------------------------------------------------------------

I want to write a query to get something that looks like:
__________________________________________________________________________________
| query_id |   query   |   BothGood   |   BothBad   |   Product 1 |   Product 2   |
-----------------------------------------------------------------------------------
|    1     |    acne   |         1    |    2        |       0     |         0     |
|    2     |   asthma  |         1    |    1        |       1     |         0     |
|    3     | bell palsy|         1    |    0        |       0     |         2     |
-----------------------------------------------------------------------------------

That "user_response_count" column actually says, 2 users selected "BothBad" option for "acne" query.
I know, by using max, I can change my rows to the column, but here it would be difficult to the max. Any Thoughts?

A: Conditional aggregation:
select query_id, query,
       sum(case when response = 'BothGood' then cnt else 0 end) as BothGood,
       sum(case when response = 'BothBad' then cnt else 0 end) as BothBad,
       sum(case when response = 'product 1' then cnt else 0 end) as product1,
       sum(case when response = 'product 2' then cnt else 0 end) as product2
from a
group by query_id, query;

A: You can use a conditional aggregation as
select query_id, query,
   max( coalesce(case when response = 'BothGood'  then user_response_count end,0) )
     as BothGood,
   max( coalesce(case when response = 'BothBad'   then user_response_count end,0) )
     as BothBad,
   max( coalesce(case when response = 'product 1' then user_response_count end,0) )
     as Product_1,
   max( coalesce(case when response = 'product 2' then user_response_count end,0) )
    as Product_2
  from tableA
 group by query_id, query

Demo


text:
Q: Conditional group membership with Ansible I'm trying to assign the group "webadmins" to a directory if the group already exists or set it to group "root" if it doesn't exist.
- getent:
    database=group
    key=webadmins
    fail_key=no

- debug:
    var=getent_group.webadmins

- file:
    path=/var/www
    state=directory
    owner=root
    group="{{ (getent_group.webadmins == '') | ternary('root', 'webadmins') }}"
    mode=0775

The debug task returns this when the group doesn't exist:
ok: [host] => {
    "getent_group.webadmins": ""
}

But the value assigned to the group propriety is always "webadmins", even if the group doesn't exist, so it make my playbook to fail.
The group may exists in AD domain, so I cannot parse /etc/group.

A: The following condition should work for you:
group="{{ (getent_group.webadmins is defined) | ternary('webadmins', 'root') }}"

If you displayed the value of getent_group in your debug task, you'd notice the value of webgroup key is actually set to null, not an empty string.
"getent_group": {
    "webgroup": null
}

A: Try this without using the ternary filter:
{{ 'webadmins' if getent_group.webadmins != '' else 'root' }}


text:
Q: Copy on Write for References Perl currently supports Copy on Write (CoW) for scalar variables however it doesn't appear to have anything for hashrefs and arrayrefs.
Perl does, however, have subroutines to modify variable internals like weaken so I'm guessing that there might exist a solution.
I have a situation where I have a large structure I'm returning from a package which keeps an internal state of this large structure. I want to ensure that if either the returned references or the internal reference (which are both currently the same reference) is modified that I end up with a Copy-on-write situation where the data the references are pointing to is copied, modified and the reference used to modified the data is updated to point to the new data.
package SomePackage;
use Moose;

has some_large_internal_variable_ref => (
    'is'  => 'rw',
    'isa' => 'HashRef',
);

sub some_operation {
    my ($self) = @_;
    $self->some_large_internal_variable_ref({
        # create some large result that is different every time
    });
}

sub get_result {
    my ($self) = @_;
    return $self->some_large_internal_variable_ref;
}

1;

use strict;
use warnings;
use SomePackage;
use Test::More;

# Situtation 1 where the internally stored reference is modified
# This will pass!

my $package = SomePackage->new();
$package->some_operation();
my $result1 = $package->get_result();

$package->some_operation();
my $result2 = $package->get_result();

isnt($result1, $result2, "These two references should no longer be the same");

# Situtation 2 where the externally stored references is modified
# This will fail

$package = SomePackage->new();
$package->some_operation();
$result1 = $package->get_result();
$result1->{foo} = "bar";

$result2 = $package->get_result();

isnt($result1, $result2, "These two references should no longer be the same");

done_testing;

I'm trying to avoid a situation where I have to clone the values on the get_result return as this would result in a situation where memory usage is doubled.
I'm hoping there is some form of weaken I can call on the variable to indicate that, should a modification be made to behave with Copy on Write behaviour.


text:
Q: protractor (selenium?) setSize width less than 400 It seems when I try to set my browser window to a width of less than 400, the browser does not go below that width.  I would like to test at mobile browsing sizes, but it seems I cannot do that.
Is there a workaround or is that by design?
I set the window-size using chromeOptions:
export let config: Config = {
    ...
    multiCapabilities: [
    {
        'browserName': 'chrome',
        ...
        'chromeOptions': {
            args: ['window-size:320,667']
        }
    }
}

But with a browser.explore() command in my test, I enter browser.manage().window().getSize() and get back
{ width: 400,
  hCode: 51200,
  class: 'org.openqa.selenium.Dimension',
  height: 667 }

Attempting to do: browser.manage().window().setSize(350,667) does not shrink the browser size. I can set it higher than 400 and it will set.
I'm on a iMac.

A: Of course, shortly after posting this question, I did find a work around from chrome browsers.
{
    browserName: 'chrome',
    'chromeOptions': {
        'mobileEmulation': {
            'deviceName': 'iPhone 5' // Use any device from the emulated device list
        }
    }
}


text:
Q: Mongolab and Mongoose Not connecting So on Sep 30 2015 MongoLab has updated their MongoDB to version 3.0.6.

They have been sending out emails about this for some time. stating "
You must ensure that your free Sandbox databases running 2.6 meet the upgrade requirements for 3.0 which includes a list of MongoDB 3.0-compatible drivers. If you do not upgrade your app to a 3.0-compatible driver before this upgrade, you may be unable to connect to your deployment
We are running the latest version of mongoose but still getting an error
MongoError: auth failed

or this error trying to connect
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }

I have updated to the latest NPM of mongodb, mongoose, I don't understand what drivers need to be updated
FYI I have run
sudo npm install mongoose
sudo npm install mongo

still no luck
Also I did a new brew install of mongodb and it works from bash connecting to mongolab
when i run mongoose in bash
 var mongoose = require('mongoose');
mongoose.connect("mongodb://XXX:XXX@XXX.mongolab.com:XXX/XXX");  //X'ed out user name and password and db

I get this Response:
MongoError: auth failed
    at Object.toError (/app/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js:114:11)
    at /app/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1156:31
    at bound (domain.js:250:14)
    at runBound (domain.js:263:12)
    at /app/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1890:9
    at bound (domain.js:250:14)
    at runBound (domain.js:263:12)
    at Server.Base._callHandler (/app/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:448:41)
    at /app/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:481:18
    at MongoReply.parseBody (/app/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)

Any Help Would be much appreciated


text:
Q: Why I can't print out environment variables in gdb? #include <unistd.h>
#include <stdio.h>

extern char **environ;
int main(int argc, char *argv[]) {
  int i = 0;
  while(environ[i]) {
    printf("%s\n", environ[i++]);
  }
  return 0;
}

Here's my ops:
(gdb) n
8       printf("%s\n", environ[i++]);
(gdb) p environ[i]
Cannot access memory at address 0x0
(gdb) n
LOGNAME=root
7     while(environ[i]) {

As you can see,printf can print out environ[i],but p environ[i] gives me Cannot access memory at address 0x0,why?

A: gdb resolves the wrong environ symbol. I don't know why though. See below as to why.
But you can test it. Change the program to:
#include <unistd.h>
#include <stdio.h>

extern char **environ;
int main(int argc, char *argv[]) {
  int i = 0;
  printf("%p\n", &environ);
  while(environ[i]) {
    printf("%s\n", environ[i++]);
  }
  return 0;
}

Now let's run this in the debugger.

(gdb) n
7         printf("%p\n", &environ);
(gdb) n
0x8049760
8         while(environ[i]) {
(gdb) p &environ
$1 = (char ***) 0x46328da0
(gdb)

So. The actual program has, during its linking, resolved environ to the address 0x8049760.
When gdb wants to access the environ symbol, it resolves to 0x46328da0, which is different.
Edit.
It seems your environ symbol is actually linked to the environ@@GLIBC_2.0 symbol.
In gdb write this:

(gdb) p environ

And hit the tab key (twice), it'll autocomplete the symbols. Which yields:

(gdb) p environ
environ             environ@@GLIBC_2.0

environ@@GLIBC_2.0 is the one actually linked to the extern char **environ
Printing this yields the same address as the program sees, 0x8049760:

(gdb) p &'environ@@GLIBC_2.0'
$9 = ( *) 0x8049760
(gdb) p ((char**)'environ@@GLIBC_2.0')[i]
$10 = 0xbffff6ad "XDG_SESSION_ID=1"

So, at one point glibc deprecated the environ symbol, and added a newer version

A: Environment variables are accessed in C/C++ using the function getenv() defined in stdlib.h. However, using the envp parameter of the main function you can use the following example to iterate over environment variables.
#include <stdio.h>

int main(int argc, char *argv[], char *envp[])
{
  char **next = envp;

  while (*next)
  {
    printf("%s\n", *next);
    next++;
  }
  return 0;

}

Tested on a Mac

A: Like grundprinzip said, use getenv(sz) and remember to null-check the return value
Alternatively,
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[], char*[] environ) {
  int i = 0;
  while(environ[i]) {
    printf("%s\n", environ[i++]);
  }
  return 0;
}

A: Probably the process under debugging is started with
execve(binary, NULL, NULL);

and the extern char **environ gets that 2nd NULL even though there's an environment available.
With a little change, your program works both standalone and under gdb.
/* #include <unistd.h> */           /* no more environ */
#include <stdio.h>

/* extern char **environ; */        /* no more environ */
int main(int argc, char *argv[]) {
  int i = 0;
  char **ptr = argv + argc + 1;     /* points to environment, in Un*x */
  while(ptr[i]) {
    printf("%s\n", ptr[i++]);
  }
  return 0;
}

Why, and how, that NULL gets converted to the proper value inside gdb I have no idea.

A: There's nothing wrong with your code.  I tried it on my machine and it printed the environment as expected.  You should not need to use getenv().
Are you running this application from the terminal?  If not, you should be.  Other means of executing an application might be calling your binary without passing it the environment.
From the terminal what is your output when you run "env"?  It should output the same list as your program.  It does on my machine.


text:
Q: Oracle Spatial: I can't get sdo_inside to work I'm trying to build a map tile server for Oracle Spatial Database. I need to filter the query with bounding boxes so that I can get individual tile data.
I convert the bounding box data into WKT and I'm trying to use SDO_UTILS.FROM_WKTGEOMETRY with SDO_INSIDE so that I can get tile data. Here is my resulting query:
select SDO_UTIL.TO_WKTGEOMETRY(SDO_UTIL.SIMPLIFY(sdo_cs.transform(SHAPE, sdo_cs.map_epsg_srid_to_oracle(4326)), 6, 0.000001)) as GEOM,
column_1,
column_2,
column_3
from tablename
where SDO_INSIDE(SHAPE, SDO_UTIL.FROM_WKTGEOMETRY(TO_CHAR('POLYGON ((28.125 40.979898069620155, 30.9375 40.979898069620155, 30.9375 43.068887774169625, 28.125 43.068887774169625, 28.125 40.979898069620155))'))) = 'TRUE'

This query says:
ORA-29902: Runtime error on ODCIIndexStart()
ORA-13208: [window SRID does not match layer SRID]
ORA-06512: location "MDSYS.SDO_INDEX_METHOD_10I", line 333

Then I tried sdo_cs.transform on both the column SHAPE and sdo_util.from_wktgeometry geometries in the same way as the first line of the query and it receives another error.
EDIT: I checked out the question that might contain the answer, I applied the transform and what I got is:
ORA-13226: interface not supported without a spatial index
ORA-06512: location "MDSYS.MD",  line 1723
ORA-06512: location "MDSYS.MDERR",  line 8
ORA-06512: location "MDSYS.SDO_3GL",  line 88

A: There are several issues with your example.
The first error ("window SRID does not match layer SRID") happens because the geometries in your table are properly encoded with a coordinate system identifier (SRID) but your query window does not have one. This means that the query system has no way to correlate the coordinates you pass with those of the data you query. Note that the SRID of the query window does not have to be the same as that of the table being queried.
Then you do not need to explicitly transform from WKT: the SDO_GEOMETRY constructor does that automatically. Just pass it the WKT string along with the SRID of the query window, like this:
SDO_GEOMETRY('POLYGON ((28.125 40.979898069620155, 30.9375 40.979898069620155, 30.9375 43.068887774169625, 28.125 43.068887774169625, 28.125 40.979898069620155))',4326)

The second error ("interface not supported without a spatial index") is because the first argument to SDO_INSIDE is not spatially indexed. A spatial index is required if you want to perform any kind of spatial query.
You transform the shapes returned by the query to WGS84 using this:
sdo_cs.transform(SHAPE, sdo_cs.map_epsg_srid_to_oracle(4326))

That is only needed iff the data in your SHAPE column is in another coordinate system than WGS84. And why do you need the map_epsg_srid_to_oracle(4326) call ?
Finally, you said that this works:
SDO_INSIDE(SDO_UTIL.FROM_WKTGEOMETRY(SDO_UTIL.TO_WKTGEOMETRY(SHAPE)), SDO_UTIL.FROM_WKTGEOMETRY('INSERT LARGE WKT TEXT HERE'))

That is just impossible - unless you defined a spatial index on the first expression SDO_UTIL.FROM_WKTGEOMETRY(SDO_UTIL.TO_WKTGEOMETRY(SHAPE)). Is this what you did ? I don't see the point. All you need is a spatial index on the SHAPE column.
Considering the above, the following will work (don't forget to define an index on TABLENAME.SHAPE. If that table is already in WGS84, then the transformation is not needed either.
select SDO_UTIL.TO_WKTGEOMETRY(SDO_UTIL.SIMPLIFY(sdo_cs.transform(SHAPE,4326)),6, 0.000001)) as GEOM,
column_1,
column_2,
column_3
from tablename
where SDO_INSIDE(SHAPE, SDO_GEOMETRY('POLYGON ((28.125 40.979898069620155, 30.9375 40.979898069620155, 30.9375 43.068887774169625, 28.125 43.068887774169625, 28.125 40.979898069620155))',4326)) = 'TRUE';

A: I did:
SDO_INSIDE(SDO_UTIL.FROM_WKTGEOMETRY(SDO_UTIL.TO_WKTGEOMETRY(SHAPE)), SDO_UTIL.FROM_WKTGEOMETRY('INSERT LARGE WKT TEXT HERE'))

And everything started working.


text:
Q: How to configure or set cookie as json before making a post request in locust load test tool for FastHTTPUser Locust is having option to use HTTPUser and FastHTTPUser
HTTPUSer internally using python requests which accepts cookies as an argument with json content
e.g. self.client.get(url, header=myheader, cookies=mycookies) here I can configure mycookies as json. Same is not working if I change the code to FastHTTPUser instead of HTTPUser. Need details how to configure hardcoded cookies as key value before making the request in FastHTTPUser approach.

A: I don't see why you have received downvotes for your question. I found it valid and I think you should create an issue in the locust github page:
https://github.com/locustio/locust/issues/
I think you could solve it like this:
from requests.cookies import cookiejar_from_dict

@task
def task_cookie(self):
    cookiejar_from_dict(mycookies, self.client.cookiejar)
    self.client.get(url, header=myheader)

I will try to make a PR to make this automatic


text:
Q: How do i make a circular view collide with the paddle Whenever the circular view collides with the paddle on storyboard, it actually collides with the rectangular frame of the view. How do I resolve this issue. I have also tried UIBezierPath, CAShapeLayer and it doesn't seem to be working.
The red arrow is the colliding point, As it does not seem to be colliding with ball instead it collides with the frame of the view. once, the frame is touched with the paddle it bounces back and so on.

A: If you're using UIDynamicAnimator, you can define the collisionBoundsType and the collisionBoundingPath for the items that will be colliding, for example:
@IBDesignable public class BallView : UIView {

    @IBInspectable public var fillColor: UIColor = UIColor.blackColor() {
        didSet { setNeedsLayout() }
    }

    override public var collisionBoundsType: UIDynamicItemCollisionBoundsType {
        return .Path
    }

    override public var collisionBoundingPath: UIBezierPath {
        let radius = min(bounds.size.width, bounds.size.height) / 2.0

        return UIBezierPath(arcCenter: CGPointZero, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
    }

    private var shapeLayer: CAShapeLayer!

    public override func layoutSubviews() {
        if shapeLayer == nil {
            shapeLayer = CAShapeLayer()
            shapeLayer.strokeColor = UIColor.clearColor().CGColor
            layer.addSublayer(shapeLayer)
        }

        let radius = min(bounds.size.width, bounds.size.height) / 2.0

        shapeLayer.fillColor = fillColor.CGColor
        shapeLayer.path = UIBezierPath(arcCenter: CGPoint(x: bounds.size.width / 2.0, y: bounds.size.height / 2.0), radius: radius, startAngle: 0, endAngle: CGFloat(M_PI * 2.0), clockwise: true).CGPath
    }
}

@IBDesignable public class PaddleView : UIView {

    @IBInspectable public var cornerRadius: CGFloat = 5 {
        didSet { setNeedsLayout() }
    }

    @IBInspectable public var fillColor: UIColor = UIColor.blackColor() {
        didSet { setNeedsLayout() }
    }

    override public var collisionBoundsType: UIDynamicItemCollisionBoundsType {
        return .Path
    }

    override public var collisionBoundingPath: UIBezierPath {
        return UIBezierPath(roundedRect: CGRect(x: -bounds.size.width / 2.0, y: -bounds.size.height / 2.0, width: bounds.width, height: bounds.height), cornerRadius: cornerRadius)
    }

    private var shapeLayer: CAShapeLayer!

    public override func layoutSubviews() {
        if shapeLayer == nil {
            shapeLayer = CAShapeLayer()
            shapeLayer.strokeColor = UIColor.clearColor().CGColor
            layer.addSublayer(shapeLayer)
        }

        shapeLayer.fillColor = fillColor.CGColor
        shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height), cornerRadius: cornerRadius).CGPath
    }
}

If you do this, and then add these items to your UICollisionBehavior, it will respect the collision boundaries you defined for the items. For example:

The above illustrates a glancing blow, like in your original image. If you want it to bounce up even if it hits the edge of the paddle, you can specify the collisionDelegate for the UICollisionBehavior and give it a new direction:
let collision = UICollisionBehavior(items: [paddleView, ballView])
collision.translatesReferenceBoundsIntoBoundary = true
collision.collisionDelegate = self
self.animator.addBehavior(collision)

And conform to UICollisionBehaviorDelegate and then implement collisionBehavior(beganContactForItem:withItem:atPoint:):
func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item1: UIDynamicItem, withItem item2: UIDynamicItem, atPoint p: CGPoint) {
    let postCollisionDirection = UIDynamicItemBehavior(items: [ballView])
    postCollisionDirection.addLinearVelocity(CGPoint(x: ballView.center.x - paddleView.center.x, y: -200), forItem: ballView)
    animator.addBehavior(postCollisionDirection)
}

That yields something like:

Clearly, you'll have to play around with this quite a bit to get the desired effect, but it illustrates the basic idea of detecting a collision and adding a linear velocity to the ball, accordingly.

A: An even simpler answer than the accepted answer would be to set the bounds to be elliptical instead of a defined path:
 override public var collisionBoundsType: UIDynamicItemCollisionBoundsType {
        return .Elliptical
 }


text:
Q: Grid layout, need 3 divs to occupy 2 columns and a row I have the following markup:

One

Two

Three

I want the layout to accomplish a layout in which the first two child divs are arranged next to each other as two columns while the 3rd sits on a row of its occupying full width.
The first child column will be a fixed width (30px), while the second should occupy the remaining space.
I have tried this, but it doesn't accomplish what I need:
.wrapper {
    display: grid;
    grid-template-columns: 20px auto 100%;
    border:1px solid white;
}

A: Maybe something like this

.wrapper {
  display: grid;
  grid-template-columns: 30px 1fr;
  grid-gap: 1rem;
}

.child {
  padding: 1rem;
  border: 1px solid red;
  display: flex;
  align-items: center;
  justify-content: center;
}

.three {
  grid-column: 1 / -1; /*  It makes this element take all available columns (the whole row)
}

One

Two

Three

A: That's the method I prefer.
First, you fraction in four with grid-template: 1fr 1fr / 1fr 1fr. This is column sizes / row sizes
After that, imagine you have two squares together in the first row (first 1fr 1fr)
Now imagine the three lines (The first line of the left square draws one vertical line, the two squares touching draw a second line, and the 2nd square draws the third one).
|▢|▢|
So, you say to #red, start in line 1 and finish in line 2 grid-column: 1 / 2, to the #green, start in the two and finish in the 3, and so on.
The result looks like this:

.grid
{
   display: grid;
   grid-auto-flow: row dense;
   /* This is column column / row row */
   grid-template: 1fr 1fr / 1fr 1fr;
   height: 300px;
}

#red {
   background-color: red;
   grid-column: 1 / 2;
   grid-row: 1 / 2;
}
#green {
   background-color: green;
   grid-column: 2 / 3;
   grid-row: 1 / 2;
}

#blue {
   background-color: blue;
   grid-column: 1 / 3;
   grid-row: 2 / 3;
}

/* To make the first row 30px you can use this instead */
.grid
{
   grid-template: 1fr 1fr / 30px 1fr;
}

Blue

Red

Green


text:
Q: Question about many to many relationship: complete iteration I have a many-to-many relationship between two tables.
I would like to show the elements of a table with the corresponding elements of the other table.
For example:
user1->group2
       group5
user2->group1
       group3
       group4
...

In an easy and smart way, of course. I'm using php, symfony and propel 1.4.
Any advice or tutorial?
EDIT:
I used a join and I get the objects from the exchange table, so if I iterate it I get:
user1->group2
user1->group5
user2->group1
user2->group3
user2->group4

But I'm wondering how could i get the group objects from the user objects.
Regards
Javi

A: Well.. would a simple join suffice?

A: If you have defined the relationshop between your user and your group table in the propel schema, the User objects will have a getGroups() method. Call this from one User and you get a list of all groups this user is joined with. You can do this without doing the join yourself but it will be less efficient, as it will do one extra database query per user. If you do the join when you query for the users, the groups will be cached too.


text:
Q: How to change the value of a cell in a gridview at runtime? Details
I have a datagridview that manipulate data from a DataBase. I have a column that has numeric value and each number is representation of a string value, for example,
0 => "group 1",
1 => "group 2"
and so on...

User must see this data as an readable format, meaning 0 => "group 1". something like this:
id          priceGroupID
----------- ------------
1234        -1 => "group -1"
36968       0  => "group  0"
1           2  => "group  2"
2           2  => "group  2"
3           2  => "group  2"
1003        2  => "group  2"

in this link: (stackoverflow.com/questions/10314996/…) represent an idea, but I want something else. something more powerful. don't be shy, if there is no other way please tell me that there is not.
Summary and questions
so in brief:

*

*I want to display this data in the Gridview without any change in my db.

*I want the proposed format. Is there a simple way to make that format, meaning n => "group m".

*cellformatting is not what I'm wanting here. CellFormatting just formats the cell in terms of the data format. (msdn)

and one more thing: my programming language is c# in the windows app.
I hope to say what I mean.
thanks in advance.

A: Let see what you got.

I want to display this data in the gridview without change in my db.

Great, this is how it should be. Data must be separated from the data representation.

cellformatting is not what I'm wanting here. cellformatting just formats the cell in terms of the data format.

Wrong!
Formatting is exactly what you need. One and the same data can be represented in many ways. For instance, one and the number or date value can be shown (formatted) using thousands ways (formats). This is exactly what string.Format (and other Format) methods do. Another example is Checkbox showing bool value. Yet another example is ComboBox displaying ValueMember as DisplayMember. Etc.
In fact your requirement is a variation of the Format function and can be achieved with a Custom Numeric Format String. All you need is to set DataGridViewColumn.DefaultCellStyle property Format to "Group 0".
If the format wasn't enough, contrary to what some people say, the CellFormatting event is exactly what you need.

By default, the DataGridView control will attempt to convert a cell's value into a format suitable for display. For example, it will convert a numerical value into a string for display in a text box cell. You can indicate the formatting convention to use by setting the Format property of the DataGridViewCellStyle returned by properties such as the DefaultCellStyle property.
If the standard formatting is insufficient, you can customize the formatting by handling the CellFormattingevent. This event lets you indicate the exact display value as well as the cell styles, such as background and foreground color, to use for the cell display. This means you can handle this event for any kind of cell formatting, regardless of whether the cell value itself needs formatting.

The effect on the performance is negligible most of the time because the value is converted to string only when needed to be displayed on the screen, and the screen can a limited number of rows compared to the total number of rows (in case you have a huge data).
One of the advantages of the value/display text separation is that the grid sorting works correctly (by numeric rather than by text).
To conclude, don't be fooled to convert your data storage values for display. Every control has formatting capabilities, just use them. Since you asked for a simple way, Format property is the simplest yet effective solution in your case.
Here is an example with 100,000 rows using both formatting approaches (comment the one and uncomment the other to play with). You can see that there is absolutely no performance issues, and GroupId column sorting works correctly.
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace Samples
{
    static class Program
    {
        static void UseFormat(DataGridView dg)
        {
            dg.ColumnAdded += (sender, e) =>
            {
                if (e.Column.DataPropertyName == "GroupId")
                {
                    e.Column.DefaultCellStyle.Format = "Group 0";
                }
            };
        }

        static void UseCellFormatting(DataGridView dg)
        {
            dg.CellFormatting += (sender, e) =>
            {
                if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
                {
                    var column = dg.Columns[e.ColumnIndex];
                    if (column.DataPropertyName == "GroupId" && e.Value != null)
                    {
                        e.Value = "Group " + e.Value.ToString();
                        e.FormattingApplied = true;
                    }
                }
            };
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form();
            var dg = new DataGridView { Dock = DockStyle.Fill, Parent = form, ReadOnly = true, AllowUserToAddRows = false };
            UseFormat(dg);
            //UseCellFormatting(dg);
            var data = new DataTable();
            data.Columns.Add("Id", typeof(int));
            data.Columns.Add("GroupId", typeof(int));
            var groupIds = Enumerable.Range(0, 15).ToArray();
            for (int i = 0; i < 100000; i++)
                data.Rows.Add(i, groupIds[i % groupIds.Length]);
            dg.DataSource = data;
            Application.Run(form);
        }
    }
}

A: sure, its simple.
you need to access the row index followed by the name of the column and set its value. For example:
this.dataGridView.Rows[0].Cells["FirstName"].Value = "billy";

this example accesses the first row and the cell "FirstName" and changes its value to "billy".
changes wont affect the DB but may affect the datasource binding thus causing the change on the datasource. instead you may want to not reference the datasource so the changes are not finally committed back to the DB when you operate with that datasource such as updating it.

A: Try this, you have to create a foreach loop to iterate through all items in the datagridview, this example shows you to change it for just the first record:
int groupIdentifier = this.dataGridView.Rows[0].Cells["Group"].Value;

this.dataGridView.Rows[0].Cells["Group"].Value = GetGroupName(groupIdentifier);

List<Groups> ListGroups = new List<Groups>();

private string GetGroupName(int groupIdentifier)
{
    var group = ListGroups.FirstOrDefault(g=>g.Id == groupIdentifier);
    return group.Name;
}

Use this when you are populating the grid.
Hope this helps


text:
Q: How do I make a search filter that you can only search for a specifc element within a set of divs? Currently, I am able to search for a hall by typing anything that is within a hall container (including name, location, capacity), however, I only want to be able to filter results for searches for a hall name.

      Search for Community Halls
      <input type="text" id="searchFilterText" placeholder="Search for the name of a community hall">

`

${data.Halls[halls[i]].Location[0].Address}, ${data.Halls[halls[i]].Location[1].Suburb}
Capacity: ${data.Halls[halls[i]].Room[0]["Standing Capacity"]}

${data.Halls[halls[i]]["Hall Name"]}

`;

$(document).ready(function(){
  $("#searchFilterText").on("keyup", function() {
    let value = $(this).val().toLowerCase();
    $(".hall").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

A: Instead of using toggle use show and hide.
(Use one, two, or three to test this reduced example).

$(function() {
  $("#searchFilterText").on('keyup', function() {

    // Grab the value
    const value = $(this).val().toLowerCase();

    // If it's not empty
    if (value) {

      // `filter` all the hall elements if
      // the text of the hallName element doesn't start with
      // the value and hide them
      $('.hall').filter(function() {
        const text = $(this).find('.hallName').text().toLowerCase();
        return !text.startsWith(value);
      }).hide();

    // Otherwise show them
    } else {
      $('.hall').show();
    }
  });
});

<input type="text" id="searchFilterText" />

One

Two

Three

A: $(document).ready(function(){
  $("#searchFilterText").on("keyup", function() {
    let value = $(this).val().toLowerCase();
    $(".hall *").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

Is this what you want? If not, let me know.


text:
Q: How to Subtract a value from the oldest expiration date and move to the next once it hits zero? I work for an organization and I am working on a way to better organize our part numbers that have expiration dates. I've started off by making an Excel sheet that has the part number multiple times based on the expiration date and then had the matching quantities of that expiration date. What im trying to do is what you always do in life, if something is going to go bad use up the one that will expire first. But now trying to do this in an excel table automatically. This is my Ex: my master log where they will put in the Part#, expiration date, and quantity, this is where most info will be pulled from.
I am now on to taking away our companies forecasted usage of these parts away from these quantities to show an overall usage over the months and pairing the intersecting expiration dates. I've got the Usage by using a pivot table to total these part numbers quantities. And I've made a chart mapping the overall usage to part quantity forecast with it being flagged if the expiration date interferes with the actual date. This is the forcasting for what we plan to use of each part #
This is me subtracting the usage number from the inventory of those part numbers and it being flagged when it expires.
=IF((IF((VLOOKUP($F60,Expires!$1:$1048576, 10, FALSE))<Sheet1!G$58, "Bad", "Good"))="good", T33, "Expired")
I used this function, my vlookup pulling from my first sheet and pulling the part numbers expiration date and if it is <the date up top (9/1,10/1 etc.) then it will be flagged as expired and wont even show the usage. T33 is simply pulling the fromual from another table which is just quantity- usage. Please lmk if this looks right my vlookup turns out pulls the latest expiration date from the multiple part #s.
But that is with total quantities, not separated based on the part number expiration dates. What I am wondering is how can I make a table like this but subtracts the usage from quantity of the part number that will expire first? Then after that quantity hits zero it takes away the usage from the next one due to expire? But also I want the Numbers to be able to auto populate from the sheet where the user enters the data (master log).
So this is what it will be doing and will look like the table above multiple of the same part number. Whats happening now
But needs to look like this Final table and add the part number to the list and quantity as they are entered in the master log. I was trying to do a Vlookup(MIN and take the part number from the other table based on the lowest expiration date first but I don't think excel is capable of that, I'm not sure here.
Please help, thank you!


text:
Q: Can I run two lines of python code at the same time? (Threading doesn't work) I want a input from the user , input() function will prompt in the terminal but I want to 'text to speech' that prompt at the same time (simultaneously).
if threading works please answer that in the comments for these code:
import pyttsx3
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty('rate', 180)  # Initialising
# Pyttsx3 Engine

def speak(audio):
   engine.say(audio)
   engine.runAndWait()

q1 = input(f"You're in the dorm. {question()}
     (stairs up/stairs down) ")

speak(q1)

'q1' should be at executed simultaneously with 'speak(q1)' where the f-string should be spoke. (inside input())

A: You can use threads like that.
import pyttsx3
import threading
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty('rate', 180)  # Initialising
# Pyttsx3 Engine

def speak(audio):
   engine.say(audio)
   engine.runAndWait()
while True:
    q1 = input(f"You're in the dorm. {question()}
         (stairs up/stairs down) ")

    t_handle = threading.Thread(speak, args=(q1,))
    t_handle.start()

A: pyttsx3 exports a function that runs event loop. You can start that function in a different thread.
thread = threading.Thread(target=engine.startLoop)
# This will start event loop
thread.start()

# from now on running speak will output voice immediately
# without calling .runAndWait()

engine.speak("test")


text:
Q: XML to ARRAY to JSON to ng-repeat I am getting data from an API that returns in XML.
I am converting this to a PHP array and running it through a foreach.
This then goes into a new array, which gets changed into json.
I'm then sending this to angularjs to be put into a ng-repeat for a form select.
My problem is when I try to put it in the ng-repeat I get a duplication error.
$http method calling the php script
$http({
        method: 'GET',
        url: 'assets/scripts/domains.php',
    }).then(function successCallback(response) {
        console.log(response);
        domains.tlds = response.data;
    }, function errorCallback(response) {
        console.log('Error!');
    });

php script calling the API
<?php

   require 'vendor/autoload.php';

   Requests::register_autoloader();

   $response = Requests::get('api_url_hidden_for_security');

   $xml = simplexml_load_string($response->body);
   $json = json_encode($xml);
   $array = json_decode($json,TRUE);

   $result = $array['tlds'];

   $array = array();

   foreach ($result as $extension) {
      $name = $extension['tld'];
      $active = $extension['active'];
      $array[] = array('title' => $name, 'active' => $extension['active']);
   }

   $content = json_encode($array);

   var_dump($content);

ng-repeat for final product
<select ng-model="domains.tld" class="form-control">
    <option value="" selected disabled>--Choose TLD--</option>
    <option ng-repeat="option in domains.tlds" ng-if="option.active == 1" value="{{option.title}}">{{option.title}}</option>
</select>

initial untouched response from api (partial) ($xml in php script)
object(SimpleXMLElement)#4 (7) { ["command"]=> string(1) "0" ["error_code"]=> string(1) "0" ["ttl"]=> string(5) "56000" ["tlds"]=> object(SimpleXMLElement)#719 (69) { ["com"]=> object(SimpleXMLElement)#720 (16) { ["tld"]=> string(3) "com" ["years"]=> object(SimpleXMLElement)#789 (10) { ["n0"]=> string(1) "1" ["n1"]=> string(1) "2" ["n2"]=> string(1) "3" ["n3"]=> string(1) "4" ["n4"]=> string(1) "5" ["n5"]=> string(1) "6" ["n6"]=> string(1) "7" ["n7"]=> string(1) "8" ["n8"]=> string(1) "9" ["n9"]=> string(2) "10" } ["renewal"]=> string(1) "1" ["transfer"]=> string(1) "1" ["registrar_lock"]=> string(1) "1" ["id_protect"]=> string(1) "1" ["epp"]=> string(1) "1" ["whois"]=> string(1) "1" ["description"]=> object(SimpleXMLElement)#790 (0) { } ["refund_price"]=> string(2) "12" ["specialdnsreg"]=> string(1) "0" ["rgp"]=> string(1) "1" ["check_registrar"]=> string(8) "verisign" ["registrar"]=> string(8) "verisign" ["extra_attributes"]=> object(SimpleXMLElement)#791 (0) { } ["active"]=> string(1) "1" } ["net"]=> object(SimpleXMLElement)#721 (16) { ["tld"]=> string(3) "net" ["years"]=> object(SimpleXMLElement)#791 (10) { ["n0"]=> string(1) "1" ["n1"]=> string(1) "2" ["n2"]=> string(1) "3" ["n3"]=> string(1) "4" ["n4"]=> string(1) "5" ["n5"]=> string(1) "6" ["n6"]=> string(1) "7" ["n7"]=> string(1) "8" ["n8"]=> string(1) "9" ["n9"]=> string(2) "10" } ["renewal"]=> string(1) "1" ["transfer"]=> string(1) "1" ["registrar_lock"]=> string(1) "1"

final response from php script (complete) ($content in php script)
string(2058) "[{"title":"com","active":"1"},{"title":"net","active":"1"},{"title":"org","active":"1"},{"title":"info","active":"1"},{"title":"biz","active":"1"},{"title":"us","active":"1"},{"title":"uk","active":"1"},{"title":"co.uk","active":"1"},{"title":"ca","active":"1"},{"title":"eu","active":"1"},{"title":"com.au","active":"1"},{"title":"website","active":"1"},{"title":"we.bs","active":"1"},{"title":"space","active":"1"},{"title":"co","active":"1"},{"title":"ae","active":"1"},{"title":"qa","active":"1"},{"title":"co.za","active":"1"},{"title":"ru","active":"1"},{"title":"es","active":"1"},{"title":"me","active":"1"},{"title":"tv","active":"1"},{"title":"xyz","active":"1"},{"title":"top","active":"1"},{"title":"pro","active":"1"},{"title":"company","active":"1"},{"title":"solutions","active":"1"},{"title":"services","active":"1"},{"title":"deals","active":"1"},{"title":"in","active":"1"},{"title":"de","active":"1"},{"title":"it","active":"1"},{"title":"nl","active":"1"},{"title":"fr","active":"1"},{"title":"co.il","active":"1"},{"title":"ch","active":"1"},{"title":"se","active":"1"},{"title":"co.nz","active":"1"},{"title":"pl","active":"1"},{"title":"ph","active":"1"},{"title":"jp","active":"1"},{"title":"club","active":"1"},{"title":"news","active":"1"},{"title":"name","active":"1"},{"title":"mobi","active":"1"},{"title":"cc","active":"1"},{"title":"ws","active":"1"},{"title":"be","active":"1"},{"title":"mx","active":"1"},{"title":"com.mx","active":"1"},{"title":"org.uk","active":"1"},{"title":"me.uk","active":"1"},{"title":"net.au","active":"1"},{"title":"org.au","active":"1"},{"title":"at","active":"1"},{"title":"nu","active":"1"},{"title":"asia","active":"1"},{"title":"net.nz","active":"1"},{"title":"org.nz","active":"1"},{"title":"cn","active":"1"},{"title":"com.cn","active":"1"},{"title":"net.cn","active":"1"},{"title":"org.cn","active":"1"},{"title":"tw","active":"1"},{"title":"com.tw","active":"1"},{"title":"org.tw","active":"1"},{"title":"idv.tw","active":"1"},{"title":"host","active":"0"},{"title":"hosting","active":"0"}]"

Error code provided from angularjs
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: option in domains.tlds, Duplicate key: string:r, Duplicate value: r

Basically I want my workflow to work like so:

*

*AngularJS Calls php Script.

*Php script calls api.

*PHP script transform api response from xml to json and sends back to angularjs

*AngularJS uses response to generate a form select using ng-repeat.


text:
Q: Why are block level elements forcing a vertical scrollbar and blank space at the top? The
 in the following code is forcing a vertical scrollbar, which is, in turn, causing a blank space (it's red; i.e. the body) at the top of the page.
Why?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" >
    <title>Test</title>

LOLOL

hi
hi
hi
hi
hi
hi
hi

Note: This result cannot be replicated on jsfiddle, making me even more confused.

A: So today you learn something new about HTML. Margins combine/collapse/merge. So the margin on the H3 element is combining with the margin on the body element, and giving the body element the margin.
See http://www.w3.org/TR/CSS21/box.html#collapsing-margins
You can add intervening elements (padding, border) to prevent this, or remove the margin from the H3 element.
This was done (I believe) because that's how the original P tag worked. Above and below the P tag was some space - but if you had two P tags one after the other, you did not get twice the space, but rather just once. In order to replicate this behavior when HTML switched to CSS they created 'margin', and made it combine.


text:
Q: Advantages and disadvantages of usercontrol in asp.net Can some one please tell me if I should use user controls in my project as much as I can? Ff so why and if not why not?

A: It's an interesting question; but think of it this way.
You've just written a table, listing all of your users. You show this on the List Users page of your website.
On the "Find User" page, you might want to be able to show a list of users. Do you rewrite the same HTML, code, javascript, CSS as before? Or do you reuse the control, this time adding the ability to filter by a user name or other attributes?
Essentially, user controls are there to package up reusable bits of your website. Rather than repeating the same code everywhere, you can package it up in a user control, and simply add it to any page you want just by adding the appropriate tag.
Also, you have just made ONE control in your project responsible for dealing with some functionality - all of the logic for it is in one place and separated from other code. This is an important concept too, as it stops all of your code being jumbled together. In the users example, you can interact with a list of users through an interface, rather than mixing it with other code that might do different things. This is called SRP and can be a good thing.
As a practical example, we have a control that shows a list of our products. We can reuse the same control on the Find screen, the Admin screen, the "Products Like this" screen, and on the "Products you have chosen" screen. This code contains a lot of logic that is all in one place so it can be maintained easily, and it can be reused very simply too.
User Controls can be a very good thing. So you should use them when you feel like you can package up a group of existing controls, HTML etc. It makes them reusable, and much easier to maintain.
There is also the concept of custom controls - these are usually reimplementations of existing controls - you might have an ExtendedTextBox, for example, that validates the text as someone types it.
You can read more about both kinds of controls here

A: User controls are good for the same reasons that subroutines/functions/methods are good: code (and markup) re-use.
Like subroutines, controls can be a problem if they do things like modify global state, make lots of DB or other off-box calls that aren't always needed, introduce unavoidable synchronous blocking, etc. They can also add an unnecessary layer of complexity if they are never re-used.

A: I would use the controls that the VS IDE Toolbox provides as much as possible.  I would only roll my own control if something that the environment supplied, didn't quite do what I wanted it to do.


text:
Q: Ajax sending variables I have trouble finding the issue, sending Id's from my database with ajax. I have this $testjobids[$count]., and it will contain the id received from my database. But how do I send it by image click to my other .php file?
<?php
        if ($FlagStatus[$count] == ('YES')) {

            echo'';
        } elseif($FlagStatus[$count] == ('NO')){
            echo'';
        }

echo'

    ';
?>

echo.php
<?php
$receiver = $_POST['FlagID'];
echo $receiver;
?>


text:
Q: JQuery: slide not working as expected This will hopefully be a simple one:
I have a div I want to slide into the screen when the page loads.
I'm trying to find out why this works:
$(function() {
    $('.mydiv').slideDown(500);
});//END ONLOAD

But not this:
$(function() {
    $('.mydiv').show('slide', { direction: 'down' }, 500);
});//END ONLOAD

Can anyone give me some advice? Thanks!
(ps: CSS is .mydiv {display:none;}

A: jQuery core does not include effects for show() method, however jQueryUI extends show() with effects. Code you have displayed would require you to include jQueryUI library ( or components)  along with jQuery .
show( effect, [options], [speed], [callback] )

jQuery UI show() docs

A: The Jquery API docs for the show method state that the show method defintions are as follows:
.show()
.show( duration [, callback] )
.show( [duration] [, easing] [, callback] )

where:
duration - A string or number determining how long the  animation will run.
easing - A string indicating which easing function to use for the transition.
callback - A function to call once the animation is complete.

the correct implementation using show would be
.show(500);


text:
Q: Do I have to repeat a verb before and after "and"? I am writing an essay and I am stuck with this sentence

The citizens cast their votes choosing Mark as president and choosing me as vice-president.

is this correct or should it be

The citizens cast their votes choosing Mark as president and me as vice-president.

A: Both are correct, and it sounds better not to repeat the verb.
Repeating the verb uses a compound clause:

The citizens cast their votes (choosing Mark as president) and (choosing me as vice-president).

Otherwise it is a compound object:

The citizens cast their votes choosing (Mark as president) and (me as vice-president).

Neither is more correct than the other, but the unnecessary repetition sounds wordy.

A: Those are both grammatically correct sentences but they have two different meanings.  It might be easier if I changed them slightly.

The citizens cast their votes choosing Obama as president and Biden as vice-president.

and

The citizens cast their votes choosing Jerry Brown as governor and choosing Gavin Newsom as vice-governor.

In the US system, the president and vice-president run together.  You choose them together.
In California, though, the governor and vice-governor are elected independently.
Does that help?


text:
Q: Sparse matrix, left matrix divide in C++ I have two sparse matrices A and B and I want to compute X as X = A\B also the same solution to the equation A*X = B
Is there a library in C++ that has this functionality?, I tried Eigen with SparseLU solver but it's taking too much time, when dealing with very large sparse matrices ((6*6)millions), much longer than Matlab.
any ideas?
Edit:
Here's the solving snippet in Eigen and OpenCV, the matrix is originally an image, the output is also an image, also it's better if B or EIN in the snippet to be dense but I can't do so in Eigen

Eigen::SparseLU<Eigen::SparseMatrix<float>> Solver;
EA.makeCompressed();
Solver.compute(EA);
if (Solver.info() != Eigen::Success) std::cout << Solver.lastErrorMessage() << std::endl;
else std::cout << "Success !" << std::endl;
cv::SparseMat IN(MatTraverse(Image));
Eigen::SparseMatrix<float> EIN = SparseCV2Eigen(IN);
Eigen::SparseMatrix<float> OUT = Solver.solve(EIN);
Eigen::MatrixXf OUTM(OUT);
OUTM.resize(Image.cols,Image.rows);
cv::Mat CVOUT(OUTM.rows(), OUTM.cols(), CV_32F, OUTM.data());

Another, the same equation can be solved in Matlab using X = A\B in a much faster time

A: Try this one:
http://arma.sourceforge.net/docs.html#operators
It has lots operators for matrix:
operators:  +  −  *  /  %  ==  !=  <=  >=  <  >
Overloaded operators for Mat, Col, Row and Cube classes
Meanings:

*

*Addition of two objects
−
Subtraction of one object from another or negation of an object

/
Element-wise division of an object by another object or a scalar
*
Matrix multiplication of two objects; not applicable to the Cube class unless multiplying a cube by a scalar
%
Schur product: element-wise multiplication of two objects
==
Element-wise equality evaluation of two objects; generates a matrix of type umat with entries that indicate whether at a given position the two elements from the two objects are equal (1) or not equal (0)
!=
Element-wise non-equality evaluation of two objects

=
  As for ==, but the check is for "greater than or equal to"
  <=
  As for ==, but the check is for "less than or equal to"
As for ==, but the check is for "greater than"
  <
  As for ==, but the check is for "less than"


text:
Q: MySQL Query to replace string with value I have requirement like as below.
Need a MYSQL query to replace value with maching the below condition.
i have a table containg the Product ID
Product_ID
1
2
3
4
5
15
25

I want to replace the 5 with value of 1.111. My requiremnet is this that it should only replace the 5 value not the 15 value.
example 5 should be 1.111 but it sould not replace the 15 value.

A: You can use IF() or CASE to select a different value when the value meets a condition.
SELECT IF(product_id = '5', '1.111', product_id)
FROM yourTable

or
SELECT CASE product_id
        WHEN '5' THEN '1.111'
        ELSE product_id
       END
FROM yourTable

CASE generalizes more easily to other values that you want to replace, since you can have multiple WHEN clauses.


text:
Q: Is the dx is a derivative a multiplier? I apologize for the dumb question but is the dx (or dy or similar) used in calculus a multiplier? I don't have a good grasp on what it really means or why it's there.
I'm getting to the point in integration where we are converting dx to du and it's weird for me to manipulate it like this.
An ELIF answer would be nice if that's even possible!

A: Yes it is.
When you have a relation such as
$$y=f(x)$$
you write
$$dy=f'(x)\,dx.$$
In this relation, $dx$ is an arbitrary nonzero quantity, and $dy$ is the linear part of the variation of $y$ corresponding to $dx$; it is also an ordinary number.
Hence you can rewrite the previous equation as
$$\frac{dy}{dx}=f'(x)$$ or $$\frac{dx}{dy}=\frac1{f'(x)}$$
or
$$dx=\frac{dy}{f'(x)}.$$

In integrals,
$$dx=\frac{dx}{du}du=x'(u)\,du.$$


text:
Q: I want to find the polygon of n overlapping rectangles Having n Rectangles (x1,y1,x2,y2) in each group, I need to find the polygon that contains all of them for each group.
Also, I need to detect if a group of rectangles has one or more rectangles that do not touch any other rectangle.
group 1
103 59  321 162
241 178 308 183
259 103 523 359
281 169 577 198

group 2
98  7   386 129
143 281 399 406
196 97  392 355
254 181 519 382

I don't know the best approach to solve it programmatically. I fell comfortable using C#.
The number of groups does not matter, because the solution to solve one group will be applied n times.


text:
Q: What is the purpose of the Church's doctrine? The Elementalist Church in Vampire Academy was founded quite recently (under 500 years in a setting where the Moroi can live for more than 200 without trouble), having apparently been created with little pre-existing religious basis for unclear but shady reasons (specifically, not from genuine conviction). It is thus of note that their doctrine is quite bad, seeming to have the primary goal of putting the Moroi in danger, to say nothing of the Dhampir:

*

*They teach that using elemental powers as a weapon is a sin, thus depriving Moroi of quite a powerful weapon against the Strigoi.

*They force everyone to specialize in an element, thus eliminating any versatility (however weak) they might have.

*They deny the existence of Spirit users and suppress any evidence of their existence. Spirit is the only element that can heal and is the basis of the wards that are quite literally the only thing protecting them from annihilation.
Now, one might say that at least the last point helps the Church retain power, but since they already claim that the Royals are descended from the Saints in any case, and by elimination the other Saints must have had only ordinary elemental powers, it's not clear how useful this is.
As such, why does the Church have the particular doctrine that it does? Is there any hidden goal behind their actions besides being doctrinaire?


text:
Q: C# Is value type assignment atomic? Is the assignement of a value type considered to be atomic in .Net?
For example, consider the following program:
struct Vector3
{
    public float X { get; private set; }
    public float Y { get; private set; }
    public float Z { get; private set; }

    public Vector3(float x, float y, float z)
    {
        this.X = x;
        this.Y = y;
        this.Z = z;
    }

    public Vector3 Clone()
    {
        return new Vector3(X, Y, Z);
    }

    public override String ToString()
    {
        return "(" + X + "," + Y + "," + Z + ")";
    }
}

class Program
{
    private static Vector3 pos = new Vector3(0,0,0);

    private static void ReaderThread()
    {
        for (int i = 0; i < int.MaxValue; i++)
        {
            Vector3 v = pos;
            Console.WriteLine(v.ToString());
            Thread.Sleep(200);
        }

    }

    private static void WriterThread()
    {
        for (int i = 1; i < int.MaxValue; i++)
        {
            pos = new Vector3(i, i, i);
            Thread.Sleep(200);
        }
    }

    static void Main(string[] args)
    {
        Thread w = new Thread(WriterThread);
        Thread r = new Thread(ReaderThread);

        w.Start();
        r.Start();
    }
}

Can a program like this suffer from a High-Level data race? Or even a Data Race?
What I want to know here is: is there any possibility that v will either contain:

*

*Garbage values due to a possible data race

*Mixed components X, Y or Z that refer to both pos before assignement and pos after assignment. For example, if pos = (1,1,1) and then pos is assigned the new value of (2,2,2) can v = (1,2,2)?

A: Structs are value types. If you assign a struct to a variable/field/method parameter, the whole struct content will be copied from the source storage location to the storage location of the variable/field/method parameter (the storage location in each case being the size of the struct itself).
Copying a struct is not guaranteed to be an atomic operation. As written in the C# language specification:

Atomicity of variable references
Reads and writes of the following data types are atomic: bool, char,
  byte, sbyte, short, ushort, uint, int, float, and reference types. In
  addition, reads and writes of enum types with an underlying type in
  the previous list are also atomic. Reads and writes of other types,
  including long, ulong, double, and decimal, as well as user-defined
  types, are not guaranteed to be atomic. Aside from the library
  functions designed for that purpose, there is no guarantee of atomic
  read-modify-write, such as in the case of increment or decrement.

So yes, it can happen that while one thread is in the process of copying the data from a struct storage location, another thread comes along and starts copying new data from another struct to that storage location. The thread copying from the storage location thus can end up copying a mix of old and new data.

As a side note, your code can also suffer from other concurrency problems due to how one of your threads is writing to a variable and how the variable is used by another thread. (An answer by user acelent to another question explains this rather well in technical detail, so i will just refer to it: https://stackoverflow.com/a/46695456/2819245) You can avoid such problems by encapsulating any access of such "thread-crossing" variables in a lock block. As an alternative to lock, and with regard to basic data types, you could also use methods provided by the Interlocked class to access thread-crossing variables/fields in a thread-safe manner (Alternating between both lock and Interlocked methods for the same thread-crossing variable is not a good idea, though).


text:
Q: How to play dojo with sprockets in rails edge? Rails 3.1 edge use sprockets to handle .js and .scss files.
Sprockets use comments to deal with dependencies.
I put the three folders (dojo dijit dojox) in vendor/assets/javascripts.
Then add a line in app/assets/javascripts/application.js
    //= require dojo/dojo
    console.log(dojo);
Now dojo has been merged into application.js.
But dojo has dependency system itself. When I require more dojo modules. It cannot find the right path.
    dojo.require("dojox.grid.DataGrid");
    // Error in webkit console: Error: Could not load 'dojox.grid.DataGrid'; last tried '../dojox/grid/DataGrid.js'
    // Error in rails server log: Started GET "/undefined../dojox/grid/DataGrid.js" for 127.0.0.1 at Sat Apr 16 01:26:05 +0800 2011
These are two different dependency systems. How can I put them together?

A: dojo.js doesn't take too naturally to being renamed.  This is because part of Dojo's initialization process involves searching through the DOM for the script tag responsible for loading itself.  It does this for two reasons:

*

*Determine its baseUrl if not already specified

*Pick up any djConfig (or data-dojo-config in 1.6+) properties specified in the script tag itself

When it searches for this script tag, it looks for one with src set to dojo.js or dojo.xd.js; it's not finding it in your case, thus the failures.
It should be possible to work around both of these issues, by specifying djConfig (or dojoConfig in 1.6+) fully programmatically in another script tag before the one that loads Dojo, and by specifying baseUrl manually in these config properties.
For example, if your application.js were in vendor/assets/javascripts as referred to in your original post, you could try doing this:
<script type="text/javascript">
    //if you're using 1.5 or earlier, use djConfig instead of dojoConfig
    var dojoConfig = {
        //note that baseUrl points to the folder containing dojo.js, therefore the dojo folder
        baseUrl: 'vendor/assets/javascripts/dojo/'
    };
</script>
<script type="text/javascript" src="vendor/assets/javascripts/application.js"></script>

For more information on dojo config settings: http://dojotoolkit.org/reference-guide/djConfig.html  (in fact, that page actually has a note under baseUrl specifically about renamed dojo.js.)

A: Try adding the dojo files into a dojo/scripts directory under /vendor/assets/javascripts. In the dojo directory, create a dojo.js file in the dojo directory and put //= provide "scripts" in that file.
Then in your application.js file put //= require <dojo>. Check out the Sprockets site http://getsprockets.org/ for info but that should work.
The docs aren't out for Rails 3.1 and the asset pipeline yet so a lot of this stuff is kind of trying to figure out on your own.

A: Umm... why are you placing your javascripts in vendor and app rather than public/javascripts? you have include anything in public/javascripts with =javascript_include_tag('path_to_javascript') where path_to_javascript would be "dojo/DataGrid" for public/javascripts/dojo/DataGrid.js
http://guides.rubyonrails.org/getting_started.html

A: I know it's maybe a bit late but I could help someone else.
I finally made it work and posted the explanations here.


text:
Q: Cannot install .bin package on Ubuntu I try to install clip2net application on Ubuntu 9.10 and get the error.
lyuba@lyuba-laptop:~/Desktop$ chmod a+x linux_clip2net01b_installer.bin
lyuba@lyuba-laptop:~/Desktop$ sudo linux_clip2net01b_installer.bin
[sudo] password for lyuba:
sudo: linux_clip2net01b_installer.bin: command not found

What may cause the problem?

A: It's unlikely that ~/Desktop is in your path.
Did you try:
sudo ./linux_clip2net01b_installer.bin
(After the other steps mentioned)?


text:
Q: python selenium ide generated unittest, exporting using nose (xunit) with multiple cases using same browser So the code below is a webdriver python code generated from selenium ide on firefox. I have some other code that is generated but its very long and i wanted to keep this simple and short.
So my problem is that i want to generate a test case for each line in the test_ function but i need it to go in order, i don't want to create multiple test functions. So i have tried doing using the yield functionality ( explained here http://nose.readthedocs.org/en/latest/writing_tests.html) but it doesn't get passed loading the web browser up. It's kinda hard to explain since i don't have my actual code below.
I will be exporting the results using nosetests --with-xunit and then letting Jenkins deal with the xml. When i run the code now and look at the xml, it only contains one large block of text from the output and thats all in one tag, its not separated.
So is there a way to generate separate test cases but still go through the instructions sequentially. One solution i have is that i could send in the first instruction (driver.get(self.base_url + "/")), then do that first one and the second one, then first, second, third. But I don't think that is the best way.
Also i know about assertions and most of the stuff about unittest, i just need a way to have each web browser action be a test case but not close the browser when it finishes each case, i need it to keep one browser open and go through each action like it would if you played it through selenium's ide on firefox.
Maybe i am looking at my problem wrong, or coding it wrong.
Here is the generated code:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class Test(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.google.ca/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_(self):
        driver = self.driver
        driver.get(self.base_url + "/")
        driver.find_element_by_id("lst-ib").clear()
        driver.find_element_by_id("lst-ib").send_keys("nba")
        driver.find_element_by_link_text("NBA.com").click()
        driver.find_element_by_link_text("Tickets").click()
        driver.find_element_by_link_text("Stats").click()

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException, e: return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

here is what i want it to do (with pseudo code):
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class Test(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.google.ca/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_(self):
        driver = self.driver

        #run the instruction below and add it to the list of tests
        driver.get(self.base_url + "/")

        #if the previous instruction was successful, run the one below and add it to the list
        driver.find_element_by_id("lst-ib").clear()

        #do the same
        driver.find_element_by_id("lst-ib").send_keys("nba")

        #etc, you get the idea...hopefully :)
        driver.find_element_by_link_text("NBA.com").click()
        driver.find_element_by_link_text("Tickets").click()
        driver.find_element_by_link_text("Stats").click()

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException, e: return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

the output would look like this if it runs the way i want it to run:
Website loaded google.ca ... ok
element found lst-ib and cleared ... ok
element found lst-ib and sent keys nba ... ok
element found nba.com and clicked ... ok
element found tickets and clicked ... ok
element found stats and clicked ... ok

----------------------------------------------------------------------
Ran 6 tests in 5.0s

currently looks like this:
loaded google, searched and clicked nba.com, clicked tickets and then starts... ok

----------------------------------------------------------------------
Ran 1 tests in 5.0s

in the xml is just one large block and it doesn't look good, nor does it give good feedback on the tests
thanks for any help :)
--------update--------------
seems like i didn't explain the problem well enough
so what i want the code to do is this:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class Test(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.google.ca/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_one(self):
        driver = self.driver
        driver.get(self.base_url + "/")

    def test_two(self):
        driver = self.driver
        driver.find_element_by_id("lst-ib").clear()

    def test_three(self):
        driver = self.driver
        driver.find_element_by_id("lst-ib").send_keys("nba")

    def test_four(self):
        driver = self.driver
        driver.find_element_by_link_text("NBA.com").click()

    def test_five(self):
        driver = self.driver
        driver.find_element_by_link_text("Tickets").click()

    def test_six(self):
        driver = self.driver
        driver.find_element_by_link_text("Stats").click()

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException, e: return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

in the situation above the xml file that would be created would have 6 different entries, but it doesn't do what i need it to do since it creates a new browser every time it starts the test. I need it to create the 6 cases but not close the browser. thinking about it now i could probably some how remove the setup from the test functions


text:
Q: Reversing Linked List Confusion in Java I'm having difficulty understanding a particular line of code when reversing a linked list in Java. Here is the method:
public static ListNode reverseList(ListNode head)
{
    ListNode prev = null;

    while(head != null)
    {
        ListNode nextNode = head.next;
        head.next = prev;

        prev = head;
        head = nextNode;
    }

    return prev;
}

What I am having trouble with is the line head.next = prev;. When this happens, I assumed that nextNode's value would also change because it also points to head.next. However, it remained the same. I know this has something to do with object references but I am not exactly sure.
This confuses me because if I create 2 ListNode objects by pointing one to another likeso:
    ListNode test = new ListNode(5);

    ListNode test2 = test;

and modify the 'test' object's val and print it out from 'test2', I get the same exact value likeso:
    test.val = 8;

    System.out.println(test2.val); // this also prints out 8

A: Some Pictorial images for better illustrations
Here head, node1 and nextNode is an object

As seen, headNext and nextNode is pointing to node1. headNext is not an object but just referencing to node1.
Next headNext is pointed to prev. Notice nextNode is still pointing to node1

For second example, after creating listNode test with value 5, test2 is assigned and pointed to test object. Hence any changes to test value will reflect to test2 too

Hope it helps to comprehend!