text:
Q: Uncaught (in promise) TypeError: undefined is not a function (Vue.js, Electron) i am trying to animate some elements using anime.js with some promise functions, the problem is that the second function wont run once the previous one was successful.
<script>
import Splash from '../components/Splash.vue';
import Intro from '../components/Intro.vue';

export default {
  components: {
    Splash,
    Intro,
  },
  mounted() {
  //This is the line of the error `const animateSplash = async () => {`
    const animateSplash = async () => {
      const splashAnim = this.$anime({
        targets: '.logo',
        easing: 'cubicBezier(.5, .05, .1, .3)',
        keyframes: [
          { duration: 1000, opacity: 0 },
          { duration: 1000, opacity: 1 },
          { delay: 3000, duration: 500, opacity: 0 },
        ],
        complete(anim) {
          document.querySelector('.logo-wrapper').style.display = 'none';
        },
      }).finished;

      await Promise.all(splashAnim);
    };

    animateSplash().then(() => {
      const introAnim = this.$anime({
        targets: '.intro-wrapper',
        easing: 'cubicBezier(.5, .05, .1, .3)',
        keyframes: [
          { duration: 1000, opacity: 0 },
          { duration: 1000, opacity: 1 },
        ],
        begin(anim) {
          document.querySelector('.intro-wrapper').style.display = 'flex';
        },
      }).finished;
    });
  },
};
</script>

I am getting an error
Home.vue?76f2:17 Uncaught (in promise) TypeError: undefined is not a function which again points to const animateSplash = async () => {. But it runs the first animation which is splashAnim.

A: A few points:

*

*Promise.all() accepts Array. splashAnim appears not to be Array. (as already acknowledged)

*If splashAnim is Promise (or even just a thenable), then simply return splashAnim;.

*If you are dealing with Promises, you can (and arguable should) avoid those cumbersome begin and complete callbacks.

As far as I can tell (and assuming that this.$anime().finished does indeed return Promise), you are trying to do as follows:
export default {
    components: { Splash, Intro },
    mounted() {
        return this.$anime({
            'targets': '.logo',
            'easing': 'cubicBezier(.5, .05, .1, .3)',
            'keyframes': [
                { 'duration': 1000, 'opacity': 0 },
                { 'duration': 1000, 'opacity': 1 },
                { 'delay': 3000, 'duration': 500, 'opacity': 0 }
            ]
        }).finished
        .then(() => {
            document.querySelector('.logo-wrapper').style.display = 'none';
            document.querySelector('.intro-wrapper').style.display = 'flex';
            return this.$anime({
                'targets': '.intro-wrapper',
                'easing': 'cubicBezier(.5, .05, .1, .3)',
                'keyframes': [
                    { 'duration': 1000, 'opacity': 0 },
                    { 'duration': 1000, 'opacity': 1 },
                ]
            }).finished;
        });
    }
};

Note that the two return statements allow the caller of mounted() to be informed, by way of Promise, of completion of the whole animation process.

A: It turns out the problem was this one line which awaited for the promise
await Promise.all(splashAnim);
I changed it to
await splashAnim;
and it worked fine. This is a mistake because Promise.all should work with only with multiple promises and not one.


text:
Q: Public Key Error WCF Client I am working on a WCF service. It is hosted in IIS and secured by SSL. I am using custom biding with Soap11. I have a private key for this service and it is referenced in the web.config file. I have exported the public key from the private key and plan to give this public key to a vendor who will call this service.
When I try to test the service using a client. I am getting the below error. In my client I have referenced the public key. My client is sending the request to the service which is secured by the private key. I have checked the private key to make sure I have "you have a private key that correspond to this certificate. also, i have the IIS app pool running under my user name. I am the administrator in the computer.
However, when i try to send a request, I get the error "The private key is not present in the X.509 certificate." in the client. What could be causing this error?
Stack Trace:
System.NotSupportedException was caught
  HResult=-2146233067
  Message=The private key is not present in the X.509 certificate.
  Source=mscorlib
  StackTrace:
    Server stack trace:
       at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetSignatureFormatter(String algorithm)
       at System.IdentityModel.SignedXml.ComputeSignature(SecurityKey signingKey)
       at System.ServiceModel.Security.WSSecurityOneDotZeroSendSecurityHeader.CompletePrimarySignatureCore(SendSecurityHeaderElement[] signatureConfirmations, SecurityToken[] signedEndorsingTokens, SecurityToken[] signedTokens, SendSecurityHeaderElement[] basicTokens, Boolean isPrimarySignature)
       at System.ServiceModel.Security.SendSecurityHeader.CompleteSignature()
       at System.ServiceModel.Security.SendSecurityHeader.CompleteSecurityApplication()
       at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDictionaryWriter writer)
       at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)
       at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
       at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)
       at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
       at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at PaymentGatewayTestClient.Customer.ICustomerDetails.CustomerDetails(CustomerDetailRequest request)
       at PaymentGatewayTestClient.Customer.CustomerDetailsClient.CustomerDetails(CustomerDetailRequest request) in c:\temp\Test\PaymentGatewayTestClient\PaymentGatewayTestClient\Service References\Customer\Reference.cs:line 937
       at PaymentGatewayTestClient.Program.Main(String[] args) in c:\temp\Test\PaymentGatewayTestClient\PaymentGatewayTestClient\Program.cs:line 38
  InnerException:

A: It looks like the server can't access the private part of the key. You have to grant permission to the private key for the user that runs your app pool.
Also see this:
PrivateKey trust permissions for local machine "Trusted roots" certificates

redpajama_set_name: RedPajamaStackExchange


text:
Q: Asterisk Digium TE110P I have Trixbox(Asterisk) with TE110P E1 card installed.
There is a question:
- is the TE110P driver capable to register ISDN PRI(E1) timing and slips errors ?
Which way the number of such errors can be measured ?
Alexey


text:
Q: How to findByIdAndUpdate() without deleting existing data? Let's say I have a mongoose Person model that looks like this:
const PersonSchema = new mongoose.Schema({
    name: String,
    address: {
        street: String,
        number: number
    }
});

Then I have a method for updating people's info, like this:
const updatePerson = async (req, res) => {
    const updatedPerson = await Person.findByIdAndUpdate(req.params.id, req.body, { new: true });
    return updatedPerson;
}

So far, so good. Now let's say I have this record in my database:
{
    "_id": "5ed2918bc96be94f130e1354",
    "name": "Freddy",
    "address": {
         "street": "Elm Street",
         "number": 42
    }
}

And I want to update the name and the street, so I send this request:
{ "name": "Ryu", "address": { "street": "fighter" } }

My document will become like this:
{
    "_id": "5ed2918bc96be94f130e1354",
    "name": "Ryu",
    "address": { "street": "fighter" }
}

In other words, the "number" property was deleted from the record. Since I didn't provide a value for "number" in my request, the original one was overwritten by undefined. Is there any way I can preserve existing data with the .findByIdAndUpdate() method?
I know you can do this with .findById(), updating what you need "manually" and then calling .save(), but I guess it would be more elegant if you could pass some option to .findByIdAndUpdate() instead.

A: One solution to your problem is to update the object's property directly by setting its value and not setting the object to a new object.
Old:
{ "name": "Ryu", "address": { "street": "fighter" } }

New:
{ "name": "Ryu", "address.street": "fighter" }

A: try this
Person.findByIdAndUpdate(req.params.id,{$set:
{'fieldtoupdate1':newvalue1,'fieldtoupdate2':newvalue2}}).exec()


text:
Q: asio underlying behavior in async_receive I have worked with asio library for a few projects and have always managed to get it work, but I feel there are somethings of it that I have not entirely/clearly understood so far.
I am wondering how async_receive works.
I googled around a bit and had a look at the implementation but didn't understand it quite well. This is the way that I often use async communication:
socket.async_receive(receive_buffer, receiveHandler);

where receiveHandler is the function that will be called upon the arrival of data on the socket.
I know that the async_receive call return immediately. So here are my questions:

*

*Does async_receive create a new thread each time it is called?
If not, does it mean that there is a thread responsible to waiting for data and when it arrives, it calls the handler function? When does this thread get created?

*If I were to turn this call into a recursive call by using a lambda function like this:

void cyclicReceive() {
  // Imagine the whole thing is in a class, so "this" means something here and
  // "receiveHandler" is still a valid function that gets called.
  socket.async_receive(receive_buffer,
    [this](const asio::error_code& error_code, const std::size_t num_bytes)
    {
       receiveHandler(error_code, num_bytes);
       cyclicReceive();
    });
}

is there any danger of stack overflow? Why not?
I tried to show a minimal example by removing unnecessary details, so the exact syntax might be a bit wrong.

A: *

*Asio does not create implicitly any new threads. In general it is based on queue of commands. When you call io.run() the framework is taking the commands from the queue and executing them until queue is empty. All the async_ operations in ASIO push new commands to the internal queue.

*Therefore there is no risk of stack overflow. Worst possible but not really probable scenario is out_of_memory exception when there is no space left for commands in command queue (which is very unlikely).


text:
Q: How can light cross $c$ in the given hypothetical experiment? Where I am wrong? There is a concave mirror, which has somehow  maintained the speed $\frac{c}{2}$ toward west ( for instance) , and there is a light wave or you can say a ray of light is moving in N-E direction. So we can say the component of velocity vector of light parallel to principal axis of mirror is the vector involving in the calculation of  relative speed between the photon and mirror (frame of reference is mirror) and will be
$v_1$ (parallel) = $\frac{(\frac{c}{2} + \frac{c}{2^1/2})}{(1 + \frac{c^2}{2(2^{1/2})(c^2)})} = c \,\ (0.89180581)$
There will be no change in the velocity vector perpendicular to principal axis, since there is no motion of mirror in that direction, $v_2$( perpendicular) = $\frac{c}{2^{1/2}} = c \,\ (0.70710678)$,
then the total velocity of  light w.r.t mirror is
$(v_1^2 + v_2^2) = c\,\ (1.13812021) > c$;
How??
NOTE: i have used concave mirror because i was also curious about the angle on which the photon will be reflected. But this is more important.

A: In a given frame, there is no problem measuring a relative velocity > $c$.  If a mirror moves left at $0.5c$ (relative to the lab frame) and a photon moves right to strike it, we will measure that the two objects have a relative velocity of $c + 0.5c = 1.5c$.
But this is just a calculation.  It doesn't say that observers in the frame where the mirror is at rest see the same photon move at that speed.  Indeed, any such observer sees that photon move at exactly $c$ as well.
So you are allowed to measure relative speeds in excess of $c$.  But never a single object moving relative to your frame in excess $c$.


text:
Q: How to get Java USA to correctly read Excel files in Spanish I have written a Java program (in USA) that reads and writes Excel files. The package includes a set of example Excel files (USA).  Spanish language users get error when reading these Excel example files because of confusion about "." and "," in numerical files.  How can I program so that Java determines the users default language and accounts for this in using Excel.

A: Just create NumberFormat using specific locale for Spanish.
Here I create locale for Spanish from Spain (es-ES) and parse the number as String.
NumberFormat nf = NumberFormat.getInstance(new Locale("es", "ES"));
Number number = nf.parse(numberString);


text:
Q: generate custom uri (or url) from named routes with params on a Rails3 app, from a Rake task, i want to generate a uri path of a collection page (with a pagination set by the params[:page]), and i wish the outcome had:

*

*"/mycustomname"

*"/mycustomname/1"

*"/mycustomname/2"

*"/mycustomname/n"

then i have setup the custom rule on routes.rb, according to my needs:
get 'mycustomname/:page' => 'mycontroller#myaction', :constraints => { :page => /\d+/ }, :as => "myelement"
get 'mycustomname' => 'mycontroller#myaction', :as => "myelement"

then when i try it from console, for example:
app.myelement_path(:page=>3)

i retrieve the:

*

*"/mycustomname?page=3"

instead of

*

*"/mycustomname/3"

What is missing to get the result I want?

A: Try passing the page number literally: app.myelement_path(3)


text:
Q: Swift NaturalLanguage framework error "Token SequenceType length is 0" I'm currently using Apple's CreateML to generate a NLP model from a JSON file I have. Here is my code:
import Foundation
import CreateML
import NaturalLanguage

let trainingData = try MLDataTable(contentsOf: Bundle.main.url(forResource: "Fel", withExtension: "json")!)
let model = try MLWordTagger(trainingData: trainingData, tokenColumn: "tokens", labelColumn: "labels")
let metadata = MLModelMetadata(author: "Sai Kambampati", shortDescription: "The Felicity Named Entity Recognizer", license: "MIT", version: "1.0")
try model.write(to: URL(fileURLWithPath: "/Users/SaiKambampati/Desktop/Felicity.mlmodel"), metadata: metadata)

The JSON file has 116,096 lines and Xcode was able to parse it correctly. It generated a validation set from 5% of the data. However, when it began tokenizing the data and extracting features, I got an error saying:
▿ MLCreateError
  ▿ generic : 1 element
    - reason : "Token SequenceType length is 0"
I have no idea what this means and can't find anything online! Can anyone help please?

A: Your JSON file must be in this format to work with MLWordTagger's tokenColumn param. Tokens as a list of strings and labels as a list of string.
[
    {
      "tokens": [
        "Aprender",
        "a",
        "realizar",
        "Aquisição",
        "de",
        "usuários"
      ],
      "labels": [
        "GENERIC_ACTION",
        "NONE",
        "ACTION",
        "TOPIC",
        "NONE",
        "NONE"
      ]
    }, ...


text:
Q: NASA tiles with leaflet in R I would like to ask some help with regard to the leaflet package. When you draw an interactive map, you can do something like this.
library(leaflet)
library(magrittr)

m <- leaflet() %>%
     setView(lng = -71.0589, lat = 42.3601, zoom = 8) %>%
     addTiles()

m

If you want to add a third-party tile, you can do that too. The following link offers options for third-party tiles (http://leaflet-extras.github.io/leaflet-providers/preview/index.html) The following image is created with OpenWeatherMap.Precipitation.
### They work
m %>% addProviderTiles("MtbMap")
m %>% addProviderTiles("HikeBike.HikeBike")
m %>% addProviderTiles("OpenWeatherMap.Precipitation")

Some of the tile options in the link include tiles by NASA. I wanted to use one of them. So I tried the following codes. None of them unfortunately worked.
### The default map appears, then a black layer appears on top of the default layer.
m %>% addProviderTiles("NASAGIBS.ModisTerraTRUEColorCR")
m %>% addProviderTiles("NASAGIBS.ModisTerraBands367CR")

The only option which is working is the following.
m %>% addProviderTiles("NASAGIBS.ViirsEarthAtNight2012")

My next attempt was to use custom URL template with addTiles(). The URL is from the link above. But, this was not successful either; no error message appeared, but no change in tile.
m %>%addTiles(urlTemplate = "http://map1.vis.earthdata.nasa.gov/wmts-webmerc/MODIS_Terra_CorrectedReflectance_Bands367/default/{time}/{tilematrixset}{maxZoom}/{z}/{y}/{x}.{format}",
              tileOptions(minZoom = 1, maxZoom = 8))

My final attempt was the following. This showed the default map, but an additional tile did not appear either.
leaflet() %>%
addTiles() %>%
setView(lng = -71.0589, lat = 42.3601, zoom = 8) %>%
addTiles(urlTemplate = "http://map1.vis.earthdata.nasa.gov/wmts-webmerc/MODIS_Terra_CorrectedReflectance_Bands367/default/{time}/{tilematrixset}{maxZoom}/{z}/{y}/{x}.{format}",
         tileOptions(minZoom = 1, maxZoom = 8))

My question is whether this is a potential bug specifically with NASA tiles. Alternatively, what revision do I need in these scripts? Thank you for your help in advance.
UPDATE
I found a website which uses same NASA tiles. I specified NASAGIBS.ModisTerraTRUEColorCR and got the following image. The image is showing how a mail traveled from the US to Sweden. As you see, there is no image for both US and Europe. I think this could be the reason why I saw a black tile. I would like to know if anybody knows some details of NASA tiles. I chose the area which I can see the NASA image. But, I had no luck.
### I expected to see Japan area this time.
foo <- leaflet() %>%
       setView(lng = 137.37, lat = 35.93, zoom = 5) %>%
       addTiles()

foo %>% addProviderTiles("NASAGIBS.ModisTerraTRUEColorCR")

UPDATE 2
Today, I gave one more shot. At this moment, I managed to get the following image. I zoomed out a bit when I captured it. In UPDATE, I provided a map which you cannot see the US and Europe. In the new image, you see West coast of the States is in black. Given all observations, it seems to me that one may not get NASA images of a location all the time. Depending on when you ask NASA tiles, you may/may not have an image you want.
m <- leaflet() %>%
     setView(lng = -71.0589, lat = 42.3601, zoom = 8) %>%
     addTiles()

m %>% addProviderTiles("NASAGIBS.ModisTerraBands367CR")

A: Your final conclusion is correct: depending on what location you request imagery for and on the time of the request, the satellite may or may not yet have acquired the image. So you may get an actual image or just an empty one. (This is also stated in the GIBS API documentation.)
However, you can specify what day to request the image for via the 'time' option for addProviderTiles(). By specifying a date in the near past, you can get non-empty images for all locations if that is what you prefer.
This is the syntax:
> library(leaflet)
> library(magrittr)

> m <- leaflet() %>%
       setView(lng = 4.5, lat = 51, zoom = 1) %>%
       addTiles() %>%
       addProviderTiles("NASAGIBS.ModisTerraTrueColorCR",
                        options = providerTileOptions(time = "2015-08-31", opacity = 0.5))

> m

At the time of writing (2015-08-31) I get this result:

It's cloudy in England, who would have guessed?
Most data happens to be there already, but there is no imagery for Alaska yet. If on the other hand, I specify yesterday's date
options = providerTileOptions(time = "2015-08-30", opacity = 0.5)

we get the full image:

Finally, the reason why
m %>% addProviderTiles("NASAGIBS.ModisTerraTRUEColorCR")

didn't work was probably because of a typo. It should be
m %>% addProviderTiles("NASAGIBS.ModisTerraTrueColorCR")


text:
Q: Disable parent click but keep child click event active I want my button in code below to have click event but not parent div.

<!DOCTYPE html>

 <title></title>

    <video controls="" autoplay="" name="media">
        <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
    </video>
    <button id="myButton">Play Video</button>

I tried using css pointer events but if parent has it then child button is not working.

A: add onclick event handler like this:
<button id="myButton" onclick="function(e) {e.stopPropagation();}">Play Video</button>
event.stopPropagation stops the click event propagation to parent elements. Learn more here: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

A: I believe this is what you're looking for:

  <video name="media" id="video">
    <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
  </video>

<button id="myButton" onclick="document.getElementById('video').play()">Play Video</button>

A:

var myVideo = document.getElementById("myVideo");

function playPause()
{
    if (myVideo.paused)
        myVideo.play();
    else
        myVideo.pause();
}
<!DOCTYPE html>

 <title></title>

    <video ID="myVideo" controls="" autoplay="" name="media">
        <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
    </video>
    <button onclick="playPause()">Play/Pause</button>

This will help you
Happy Coding....

A: You've at least two options.
The first is to check whether the event was fired by the button or the div.
Or to prevents the event from bubbling up the DOM tree. In jQuery you can do that by calling the method "stopPropagation()".
Here the answer to a similar question.


text:
Q: Two generators of random points in a disk I have two ways to generate points in a disk:
The first is:
$
a, b \sim U[0, 1].
$ Point is generating the next way: $(a \cos(2\pi b), a \sin(2 \pi b))$.
The second is: $a, b \sim U[-1, 1]$ and point generating only if $a^2 + b^2 \le 1$.
Suppose I've given points already distributed. I want to derive by what method (first or second) it was produced.
By the way graph of this two method is:
It's easy to see, that for the first method points are more 'squeezed' to zero than for the second method.
My approach: is very clumsy. I'm finding probability that points are more concentrated to the center in first method, i.e. I'm finding $\mathbb{P}(-0.2 < x < 0.2)$ for each method. I'm doing it using Cumulative Distribution Function estimation:
$$ \tilde F(t)=\frac{1}{n + 1} \left(\frac{1}{2}  + \sum_{i: x_i < t} 1  \right) $$ For the first it is near the $0.4$, while for the second it is more near the $0.25.$
Any ideas how to solve it more mathematical way?

A: The test you suggest is reasonable; let's spice it up a bit.
The second sampling scheme you mention is called acceptance-rejection sampling and produces data that are uniformly distributed on the unit disk $B=B(0,1)$. So we can test the hypothesis that our data is produced from the distribution $X \sim U(B)$; i.e.
$$\begin{align*}
H_0&: X \sim U(B) \\
H_1&: X \not\sim U(B)
\end{align*}$$
A general statistical test for the hypothesis that data arises from a certain distribution is the $\chi^2$ test. To run it in this case, pick radii $0 = r_0 < r_1 < r_2 < \ldots < r_m = 1$. Now, we let $d_i$ be the number of points contained between the circles of radius $r_{i-1}$ and $r_i$. Under the null hypothesis, you expect $d_i$ to be close to $E_i = (r_i^2 - r_{i-1}^2) n$, where $n$ is the total number of data points in your sample.
We can then find the observed $\chi^2$ statistic for this test by computing: $$L^2 = \sum_{i=1}^m \frac{(d_i - E_i)^2}{E_i} $$
Under the null hypothesis $L^2$ is approximately $\chi^2$-distributed with $m-1$ degrees of freedom, so you may use the probability $P(\chi_{m-1}^2 > L^2)$ as a decision tool to accept or reject the null.


text:
Q: How to programattically update a form field value in antd I am using antd version 4.0.0-rc.3,
I have a form that contains the following values
{
   user: {
     address: {
        country: 'India',
        state: 'abc',
        zipcode: 123456
     }
   }
}

How can I update zipcode value into 98765?
setFieldsValue is updating fields in the root level only
i was trying with
setFieldsValue({
   ['user.address.zipcode']: 98765
})

result of this function is
{
   user: {
     address: {
        country: 'India',
        state: 'abc',
        zipcode: 123456
     }
   },
   user.address.zipcode:98765
}

Thanks in advance for your valuable answers

A: const newData = {user: {...address, zipcode:98765 }}

A: use setFields
setFields([{
   name: ['user', 'address', 'zipcode'],
   value: 98765,
}])

A: You can either use immutability-helper:
import update from 'immutability-helper';

setFields(update(fields, {
  user: {
    address: {
      zipcode: {$set: 98765}
    }
  }
}))

or the spread operator:
setFields({
  ...fields, // if there is only user inside the fields, that's not necessary
  user: {
    ...fields.user, // if there is only address inside the user, that's not necessary
    address: {
      ...fields.user.adress, // This will copy all the address attributes (country, state, zipcode)
      zipcode: 98765 // This will overwrite the zipcode
    }
  }
})

Either will set a copy of your previous state changing only the zipcode.


text:
Q: Python Division Of Complex Numbers Without Using Built In Types and Operators I have to implement a class called ComplexNumbers which is representing a complex number and I'm not allowed to use the built in types for that.
I already have overwritten the operators (__add__, __sub__, __mul__, __abs__, __str_ which allows to perform basic operations.
But now I'm stuck with overwriting the __div__ operator.
Allowed to use:
I'm using float to represent the imaginary part of the number and float to represent the rel part.
What I have already tried:

*

*I looked up how to perform a division of complex numbers (handwritten)

*I have done an example calculation

*Thought about how to implement it programatically without any good result

Explanation of how to divide complex numbers:
http://www.mathwarehouse.com/algebra/complex-number/divide/how-to-divide-complex-numbers.php
My implementation of multiply:
 def __mul__(self, other):
        real = (self.re * other.re - self.im * other.im)
        imag = (self.re * other.im + other.re * self.im)
        return ComplexNumber(real, imag)

A: I think this should suffice:
def conjugate(self):
    # return a - ib

def __truediv__(self, other):
    other_into_conjugate = other * other.conjugate()
    new_numerator = self * other.conjugate()
    # other_into_conjugate will be a real number
    # say, x. If a and b are the new real and imaginary
    # parts of the new_numerator, return (a/x) + i(b/x)

__floordiv__ = __truediv__

A: Thanks to the tips of @PatrickHaugh I was able to solve the problem. Here is my solution:
  def __div__(self, other):
        conjugation = ComplexNumber(other.re, -other.im)
        denominatorRes = other * conjugation
        # denominator has only real part
        denominator = denominatorRes.re
        nominator = self * conjugation
        return ComplexNumber(nominator.re/denominator, nominator.im/denominator)

Calculating the conjugation and than the denominator which has no imaginary part.


text:
Q: What is "Nor'n Iron" short for? I was reading a post on a website when I ran into this title.

How's about ye? is a very, very Nor'n Iron expression with which I am
  sure The Great Panjandrum is regularly greeted by his kith and kin.

Source: Wordreference
I don't know what it means and that is okay, but I only want to know what Nor'n is short for in Nor'n Iron?

A: "Nor'n Iron" refers to Northern  Ireland  speech.

*

*Contraction of Northern Ireland. Northern Ireland said in the Ulster dialect sounds like Norn Iron and therefore evolved into a Northern Irish saying.


text:
Q: Subtracting two Option[Double] I have two variables that are optional double and I want to consider them as 0 when they are None
var x: Option[Double] = Option(0)
var y: Option[Double] = Option(0)
println("Expected 0 : "+(x ++ y).reduceOption(_ - _)) // 0

x = Option(4)
y = Option(0)
println("Expected 4 : "+(x ++ y).reduceOption(_ - _)) // 4

x = Option(0)
y = Option(4)
println("Expected -4 : "+(x ++ y).reduceOption(_ - _)) // -4

x = Option(4)
y = None
println("Expected 4 : "+(x ++ y).reduceOption(_ - _)) // 4

x = None
y = Option(4.0)
println("Expected -4 : "+(x ++ y).reduceOption(_ - _)) // 4

The last one I am expecting -4 but I get 4.
If I use
(for (i <- x; j <- y) yield i - j)

then I get None.
Also If I try
x.getOrElse(0) - y.getOrElse(0) // value - is not a member of AnyVal

then I get error value - is not a member of AnyVal

A: The (x ++ y).reduceOption(_ - _) is a perfect example of how to confuse people in Scala IMHO. It's not immediate that ++ operates on Option because they are also Seq.
That being said, as already suggested in the comments, the straightforward way would be to use getOrElse:
x.getOrElse(0d) - y.getOrElse(0d)

You need to precise the d to have an Double otherwise, you get an AnyVal because AnyVal is the only common parent type of Int (from the getOrElse) and Double (value in the option).


text:
Q: program crashes when started via ssh I have this problem with a tool, that I launch from a terminal on a specific computer - as far as I can tell it's a binary executable. If I remotely connect via ssh (using the -Y option) to this computer and launch the tool it crashes immediately reporting a segmentation fault. When I launch it locally it works.
Since it is part of a toolkit (actually started by a TCL script, not by myself) I'm not even sure if it creates any UI elements. The TCL script generates a UI which works fine.
The computer where the tool runs, is running some older version of red hat, RHEL 5 I believe. My computer (the one I want to ssh-connect from) runs a very recent version of Ubuntu.
Of course what I would like is be able to run the tool remotely without segmentation fault. Perhaps it is caused by the discrepancy between versions of the systems (or of ssh)? What could cause a program to crash only when launched via ssh?

A: does the program work, if you run it on the remote machine locally?
try to run it with DISPLAY=:0 variable as prefix in your ssh session.

A: Expanding on Harry's suggestion: Did you run "xhost +" on your local machine before you you ran
env DISPLAY=:0 yourapp
on the remote machine? Overall, using ssh -Y is more likely to work than ssh -X, but it is till worth it to try a plain setup where the X11 connection runs on an unencrypted side channel directly to DISPLAY :0.


text:
Q: Laravel eager loading, select only those which have related models Projects and users are Many-to-many related, how can I select only projects that have related users? Do I have to use join?
Something like:
$projects = Project::with('users')->having('count(users)','>',0)->get();

A: Use has() method:
Project::with('users')->has('users')->get();


text:
Q: Capture screen remotely of iphone device.
Possible Duplicate:
Programatically capture video of screen

I am building an app in which i have to capture the screen of iPhone mobile (rooted phone) remotely...
Means i have to capture screen from one iPhone to another iPhone remotely...
please suggest me...
Thanks in advance.

A: To programmatically capture screen snapshots, you can:
#import <QuartzCore/QuartzCore.h>

- (void)saveScreenSnapshot:(UIView *)view
{
    UIGraphicsBeginImageContext(view.frame.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // do what you want with this image; I frequently just drop it in the device's photo album
    //
    // UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}

Alternatively, can get a PNG representation of that image via:
NSData *data = UIImagePNGRepresentation(image);

You obviously have to add the QuartzCore.framework to your target app's libraries.


text:
Q: SQL query to count number of checkins per month To put a long story short, I am working on a database using PostgreSQL that is managing yelp checkins. The checkintable has the attributes business_id(string), date(string in form yyyy-mm-dd), and time(string in form 00:00:00).
What I simply need to do is, given a business_id, I need to return a list of the total number of checkins based on just the mm (month) value.
So for instance, I need to retrieve the total checkins that were in Jan, Feb, March, April, etc, not based upon the year.
Any help is greatly appreciated. I've already considered group by clauses but I didn't know how to factor in '%mm%'.

A: Why would you store the date as a string?  That is a broken data model.  You should fix the data.
That said, I recommend converting a date and truncating to the first day of the month:
select date_trunc('day', datestr::date) as yyyymm, count(*)
from t
group by yyyymm
order by yyyymm;

If you don't want these based on the year, then use extract():
select extract(month from datestr::date) as mm, count(*)
from t
group by mm
order by mm;

A: Reiterating Gordon, class or not, storing dates and times as strings makes things harder, slower, and more likely to break. It's harder to take advantage of Postgres's powerful date math functions. Storing dates and times separately makes things even harder; you have to concatenate them together to get the full timestamp which means it will not be indexed. Determining the time between two events becomes unnecessarily difficult.
It should be a single timestamp column. Hopefully your class will introduce that shortly.

What I simply need to do is, given a business_id, I need to return a list of the total number of checkins based on just the mm (month) value.

This is deceptively straightforward. Cast your strings to dates, fortunately they're in ISO 8601 format so no reformatting is required. Then use extract to extract just the month part.
select
  extract('month' from checkin_date::date) as month,
  count(*)
from yelp_checkins
where business_id = ?
group by month
order by month

But there's a catch. What if there are no checkins for a business on a given month? We'll get no entry for that month. This is a pretty common problem.
If we want a row for every month, we need to generate a table with our desired months with generate_series, then left join with our checkin table. A left join ensures all the months (the "left" table) will be there even if there is no corresponding month in the join table (the "right" table).
select
  months.month,
  count(business_id)
from generate_series(1,12) as months(month)
left join yelp_checkins
  on months.month = extract('month' from checkin_date::date)
 and business_id = ?
group by months.month
order by months.month

Now that we have a table of months, we can group by that. We can't use a where business_id = ? clause or that will filter out empty months after the left join has happened. Instead we must put that as part of the left join.
Try it.


text:
Q: How to add ttest results to esttab I am constructing a table of means and p-values from ttest. How can I get all of this in the same esttab table? Here is a MWE:
Get the sample, save it as a temporary file, create a local with the variables we will consider, create a local that is the length of the first local:
sysuse auto2, clear
*create two groups: 0 and 1
gen group = _n<37
tempfile a
save `a'

local vars "price headroom trunk weight"
local vars_n: word count `vars'

ssc install estout
eststo clear

Calculate the means of group 0 (column 1) and group 2 (column 2):
*group 0 means
use `a', clear
keep if group==0
eststo: estpost sum `vars'

*group 1 means
use `a', clear
keep if group==1
eststo: estpost sum `vars'

Conduct t-tests for each variable (is there an easier way to do this?):
*t-test
*create blank matrix
matrix pval = J(`vars_n',1,.)
use `a', clear
forvalues i=1/`vars_n' {
    local var `: word `i' of `vars''
    ttest `var', by(group)
    *add the two-sided p-value to matrix
    matrix pval[`i',1]=r(p)
}

This previous block of code saves the p-values (column 3) into a matrix.
Use esttab to output the results:
esttab, cells(mean(fmt(2))) collabels(none) nodepvars nonumber replace label

esttab matrix(pval, fmt(2 0))

My issue is that I need to have the p-values in the same esttab as the means, but I currently have them in a matrix. How can I use something like eststo: estpost to get them so that I can use esttab (as opposed to esttab matrix)? Or is there a better way to do all of this? My goal is to run esttab, cells(mean(fmt(2))) collabels(none) nodepvars nonumber replace label and have it create a table with the first two columns being the means and the third column being the p-values.

A: All the information you need is in estpost ttest, so an easy solution would be this:
sysuse auto2, clear
gen group = _n<37
local vars price headroom trunk weight
estpost ttest `vars', by(group)
esttab ., cells("mu_1 mu_2 p") nonumber label

-----------------------------------------------------------

                             mu_1         mu_2            p
-----------------------------------------------------------
Price                    5847.526     6500.639     .3445597
Headroom (in.)           2.828947     3.166667     .0861206
Trunk space (.. ft.)     12.39474     15.19444     .0041618
Weight (lbs.)            2654.474     3404.722     .0000115
-----------------------------------------------------------
Observations                   74
-----------------------------------------------------------


text:
Q: Having issues with gamesharing on PS4 I've been game sharing Destiny 2 and PS Plus with a friend of mine and recently he decided to buy the Forsaken DLC on his account (Destiny 2 and PS Plus were purchased on my account).
So I logged into his account and set my PS4 as primary so I could obtain the DLC but for some reason he lost all access to my PS Plus subscription but still has access to the games hes downloaded off my account. He only had access to my PS Plus subscription if I login to his account and deactivate my PS4, but then I lose the ability to play the Forsaken DLC.
Is there a way for me to have access to the Forsaken DLC and for him to have access to my games and PS Plus at the same time or does he have to buy PS Plus as well?


text:
Q: Question regarding cardinality of differences Give an example of a set $A = \{ 1,2,...k \}$ for a smallest $k \in \mathbb{N} $ containing subsets $A_1, A_2, A_3$ such that $ |A_i - A_j| = |A_j - A_i | = |i-j|$ for every two integers $i$ and $j$ with $ 1 \leq i < j \leq 3 $.
Is it correct if you say $k=4$ with $A_1 = \{1,2\}, A_2 = \{2,3\}, A_3 = \{3,4\}$?

A: Yes, your example is good ($k = 4$ is minimal).
To see this:

*

*The condition  $|A_i - A_j| = |A_j - A_i|$ implies that $|A_i| = |A_j|$. Also, all the $A_i$ must be proper non-empty subsets (otherwise some of your conditions are not satisfied).

*For $k = 1,2,3$, it's easy to see that the remarks in the previous  point imply that some other condition is not satisfied.


text:
Q: How to clear all current/pending AJAX requests when users click certain links on my app it makes ajax requests... What I want to do is on every main click, abort all existing ajax requests either current or pending. Is this possible?
The reason why is requests are getting out of sync. Meaning if a user clicks on a project, which should load tasks. If they then click on another project, the first click's tasks are being populated.
Thanks

A: Simply keep a global variable which stores the most recent ajax request and then abort it before making the next request.

A: When we abort an variable-cum-ajaxRequest using variable.abort(); it is permanently disabled and cannot be used to create another request in the future.
So to avoid this we can use dynamic variables window["var"+i] and increase the value of i everytime  an new request is made.
Then at the time a request is to be cancelled use window["var"+(i-1)].abort();


text:
Q: Is it possible to return a user-input declared double within an if statement for use in the main? I am wishing to prompt the user again if a double outside of the accepted range (0-100) is input, until the input is valid. When the input is considered valid, I am wanting to return correct input value, yet, returned instead is the first incorrect value. How can I return the correct input, as accepted by the if statement?? Many thanks!
public class examscore {
    public static void main (String[] args) {
        Scanner console = new Scanner(System.in);
        double sumfin = finalscore(console);
        System.out.println(sumfin); // if user input is initially invalid, but then corrected, the first, incorrect, value is printed
    }

    public static double finalscore (Scanner console) {
        System.out.println();
        System.out.println("Input final exam score: ");

        while(!console.hasNextDouble()) { //prompts the user, if invalid input, to input again, until a valid value is input
            System.out.println("Please input a mark between 0 and 100. ");
            console.next();
        }
        double examscore = console.nextDouble();

        if (examscore >=0 && examscore<= 100) {
            System.out.println();
            System.out.println("Exam Score = "+examscore);
        } else {
            System.out.println("Error:");
            finalscore (console);
        }
        return examscore; //an attempt to return the VALID exam score: fails
    }
}

A: A do-while loop would be a perfect fit. Example:
Scanner console = new Scanner(System.in);
double userInput = 0;
do {
    System.out.println("Please input a mark between 0 and 100. ");
    try {
        userInput = console.nextDouble();
    } catch (InputMismatchException e) {
        System.out.println("Your input could not be interpreted as a floating-point number.");
    }
} while (userInput <= 0D || userInput >= 100D);

A: You missed to assign result of finalscore(console) to examscore inside the else block.
        if (examscore >= 0 && examscore <= 100) {
            System.out.println();
            System.out.println("Exam Score = " + examscore);
        } else {
            System.out.println("Error:");
            examscore = finalscore(console);
        }

A: You can either use a loop or a recursive call to accomplish this. I prefer a recursive call:
private static double getValidScore(Scanner console) {
    System.out.println();
    System.out.println("Input final exam score: ");
    try {
        double score = Double.parseDouble(console.nextLine());
        if (score >= 0 && score <= 100) {
            return score;
        }
    } catch (NumberFormatException nfe) {}
    System.out.println("Please input a mark between 0 and 100.");
    return getValidScore(console);
}


text:
Q: Convert A NSString into NSDate to add days to the dynamic date I am getting a NSString(in which i have a date)from database, I need to add days like suppose 10//12/15/45/60 days to the date, How can I do it.
when I am trying with this piece of code :
NSString *expiryDateStr = [NSString stringWithFormat:@"%@",[[assets valueForKeyPath:@"assetrewards.expirydate"] objectAtIndex:0]];
        NSLog(@" date %@",expiryDateStr);

        //DATE FORMATTER
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"dd/MM/yyyy"];
        NSDate *_date = [dateFormat dateFromString:expiryDateStr];
        [dateFormat setDateFormat:[NSString stringWithFormat:@"dd MMM yyyy HH:mm"]];
        [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:3600*5]];
        NSLog(@"date format %@",dateFormat);
        NSLog(@"Date: %@", _date);

I am getting output like this :
date 07/10/2013
date format <NSDateFormatter: 0x9f9d4a0>
Date: 2013-10-06 18:30:00 +0000

the date is getting changed, I am not knowing where i am going wrong, if that is the correct date how to add the days to the date.

A: NSString *expiryDateStr = @"07/10/2013";
NSLog(@" date %@",expiryDateStr);
expiryDateStr=[expiryDateStr stringByAppendingString:@" 00:00:00 +000"];
//DATE FORMATTER
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy HH:mm:ss Z"];
NSDate *_date = [dateFormat dateFromString:expiryDateStr];
[dateFormat setDateFormat:[NSString stringWithFormat:@"dd MMM yyyy HH:mm"]];
[dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit fromDate:_date];
NSInteger day = [components day]+1; // U can add as per your requirement

[components setDay:day];
NSDate *NextDate = [[NSCalendar currentCalendar] dateFromComponents:components];

NSLog(@"Next Date: %@", NextDate);

A: you can and days into date like below...
set timezone like below...
  [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSDate *dateAftertwenty = [NSDate dateWithTimeInterval:10*24*60*60 sinceDate:date]; //TimeInterval is of 10 days....you can set any number of days.24 is hours, 60 is minutes and 60 is seconds at last..

Let me know it is working or not!!!
Happy Coding!!!!

A: UPDATE:
First  setTimeZone to localTimeZone like bellow..
[formatter setLocale:[NSLocale currentLocale]];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

Convert that String Date to NSDate with my bellow method..
-(NSDate *)convertStringToDate:(NSString *) date dateFormat:(NSString*)dateFormat{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDate *nowDate = [formatter setDateFormat:dateFormat];// set format here which format in string date
    date = [date stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
    nowDate = [formatter dateFromString:date];
    // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate);
    return nowDate;
}

and Use it like bellow..
NSDate *startDate = [self convertStringToDate:@"07/10/2013" dateFormate:@"dd/MM/yyyy"];

above set date formate which format is define in string

A: NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSDate *_date = [dateFormat dateFromString:expiryDateStr];

is perfectly fine -- no problem.  The "problem" is that
NSLog(@"Date: %@", _date);

will display the date as UTC/GMT, and hence (in India) a value five and a half hours earlier than the "real" date.  This is not a problem -- when you format the date into a different string format (with the second incarnation of the date formatter) then it will come out correctly (so long as you DO NOT set the timezone for that version, if you didn't set it for the first).
To increment the date it's usually best to use NSDateComponents (more or less as shown by Paras) vs simply adding increments of 24 hours, in case there is any sort of "daylight savings time" transition in the date range.

A: I have modified your code and I believe this is what you want:
NSString *expiryDateStr = @"07/10/2013";
NSLog(@" date %@",expiryDateStr);

//DATE FORMATTER
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];

[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *_date = [dateFormat dateFromString:expiryDateStr];
NSLog(@"date format %@",dateFormat);
NSLog(@"Date: %@", _date);

Output:
 date 07/10/2013
date format
Date: 2013-10-07 00:00:00 +0000
Now changed the time zone in the code:
NSString *expiryDateStr = @"07/10/2013";
NSLog(@" date %@",expiryDateStr);

//DATE FORMATTER
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];

[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+5:30"]];
NSDate *_date = [dateFormat dateFromString:expiryDateStr];
NSLog(@"date format %@",dateFormat);
NSLog(@"Date: %@", _date);

And the output is:
date 07/10/2013
date format
Date: 2013-10-06 18:30:00 +0000
This is the output you were getting. This is because your time zone from your computer is being used.
EDIT(Number of days to add is denoted by days integer ):
NSString *expiryDateStr = @"07/10/2013";
NSLog(@" date %@",expiryDateStr);

//DATE FORMATTER
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];

[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *_date = [dateFormat dateFromString:expiryDateStr];
NSInteger days = 30;
_date = [_date dateByAddingTimeInterval:(60*60*24*days)];

NSLog(@"date format %@",dateFormat);
NSLog(@"Date: %@", _date);

Output of EDITed code:
date 07/10/2013
date format
Date: 2013-11-06 00:00:00 +0000


text:
Q: Sci-fi book about Earth's first colony Not sure if one book or a series. Earth's first colony loses touch with Earth. Without supplies they'd counted on from Earth (food, building materials, vehicles, weapons), the colonists struggle, mostly because the planet's wildlife (plants and dinosaur-ish animals) are all deadly 24/7. The main female character is a cop, who, at the beginning, has to rescue a female friend in the badlands from a large dinosaur-ish thing.
Half-way through the book, the female cop crash lands in the middle of the deadly wilderness. The main male character, who she doesn't like, goes to rescue her. After a week or so and lots of peril and at least one broken leg (hers), they end up getting back safely by making a canoe out of the shell of a huge animal (and in love).
The colony has major political and leadership issues, some gun-fueled, and then Earth shows up and wants to take over everything. There's also a creepy guy who starts a brothel and a gambling establishment and schemes to be get elected the boss. Somebody starts a stampede of the dinosaur-ish wildlife down the town's main-street in the middle of the night, and also traps the main male character in his house with a big dinosuar-ish animal by blocking the door with a programmable excavating machine.

A: This is one of the Donovan series by W Michael Gear, I read it a few years ago.
However I no longer have any of the novels so I can't identify the particular book, hopefully this'll be enough to see which one it was.
Update:-
I've now downloaded book one of the series and this is the one I was thinking of, it's titled Outpost and the female cop is called Talina Perez


text:
Q: Finding the degree of $\Bbb Q(\zeta_9)$ I know that the degree is $6$. But now I need to prove it without using Galois theory or the theorem about the function $\phi(n)$. May I ask a proof with an explicit minimal polynomial of $\zeta_9$ over $\Bbb Q$ with justification? Thanks!

A: The minimal polynomial is $$x^6 + x^3 +1.$$ That the polynomial is irreducible over $\mathbb{Q}$, follows from the fact that it is irreducible mod 2.
Following Kaj Hansens's comment: To show that the polynomial is irreducible, you have to check that it has no roots (mod 2) and it cannot be factored by an irreducible polynomial of degree 2 or 3 (mod 2). There are not so many of those. A complete list is the following:
$$x^2+x+1, \quad x^3+x^2 +1,\quad x^3+x +1.$$


text:
Q: What kind of damping is this $F = -ax|x'|$? From Applied Mathematics by Logan:

A mass hanging on a spring is <...> governed by
  $$mx'' = -ax|x'| - kx$$
  where $-ax|x'|$ is a nonlinear damping force.

I looked up "nonlinear damping" and found $F=-a|x'|^px'$ which is clear enough.
As far as I know one thinks of $F= -ax'$ damping as of viscous drag.
What is the interpretation of $F = -ax|x'|$ damping?
It confuses me that it has $x$ in it. Why would the damping force care whether the mass is above or below the origin? Shouldn't the damping force depend solely on the velocity of the mass?

A: I would look at this in a slightly different way. Rearranging it:
$$ m \ddot{x} = -(a|\dot{x}|+k) x = -k_{eff} x$$
If you look at it that way, it is really a variable, non-linear stiffness $k_{eff}$ that depends on the velocity, rather than a damping that depends on the position. In this respect (assuming $a > 0$), the stiffness coefficient has a lower bound of $k$ and the maximum depends on the maximum velocity. Given a periodic-type motion, at least initially, the stiffness would be $k$ at $\pm x_{max}$ and the stiffness would be a maximum when it was near $x = 0$, where velocity is a maximum.
Given all of that, I cannot think of exactly what kind of physical scenario this would represent off the top of my head. But one could imagine it is a mass oscillating somehow in a non-Newtonian fluid. I suppose it would be a shear-thickening fluid where viscosity is zero when the body is not moving and viscosity is a maximum when the body is moving fastest.
Displacement-dependent dampers seem to have applications in automotive and aircraft suspensions -- see this paper and references at the end of the introduction. It would appear that hydraulic systems pushing/pulling fluid through an orifice may be modeled this way, as well as tapered pistons and a few other things.


text:
Q: Color transformation with paper.js in a range I have a problem and need a solution after thinking about it the whole day. I want to generate a canvas which changes his color by using a range. Sound simple.
The colors are in (HSB). There are 6 colors.

*

*blue (230, S,B)

*green (130, S,B)

*yellow (55, S,B)

*orange (40, S,B)

*red (0(or 360), S,B)

*violette (315, S,B)

The saturation and brightness are insignificant (can be the same all the time).
the color has to change in this range

*

*blue 0 - 2.9 green

*green 3 - 5.9 yellow

*yellow 6 - 8.9 orange

*orange 9 - 11.9 red

*red 12 - 14.9 violette

so if i've get some data like this
var sample Data = new Array(0.1,0.2,0.3,0.4,3.4,5.9,9.3,9.4,9.5,9.6,...);

the canvas has to change the hue between slow from blue to green and then there should be a "color-cut" because of the "big jump" from 0.4 to 3.4 (something between green and yellow).
I'm looking for the "logic" behind this problem. I have already the HTML with canvas. For canvas and colors I'm using Paper.js
hope someone understand my problem!
thanks

A: I don't know Paper.js, so I can't help getting the colors on the canvas, but I can help to convert the data into a color. Since your five hue ranges havn't same size we have to do a separate calculation for each.
var sampleColors = [],
    l = sampleData.length,
    s = '50%',
    b = '50%';
function getColor(d) {
    var c, m = d % 3;
    if (d < 3) c = 230 - m * 33.333;
    else if (d < 6) c = 130 - m * 25;
    else if (d < 9) c = 55 - m * 5;
    else if (d < 12) c = 40 - m * 13.333;
    else c = 360 - m * 15;
    return 'hsb(' + Math.round(c) + 'deg,' + s + ',' + b + ')';
}

for(var i = 0; i < l; i++) {
    sampleColors.push(getColor(sampleData[i]));
}

Now sampleColors contains the hsb color strings that belong to the items in sampleData.
sampleData[0] == 0.1;    sampleColor[0] == 'hsb(227deg,50%,50%)';
sampleData[4] == 3.4;    sampleColor[4] == 'hsb(120deg,50%,50%)';

If the color notation doesn't fit your needs, please post critique.


text:
Q: Connection issues with Mongo replica sets Having a strange issue whereby I've set the mongodb uri to be.
mongodb://User:Password@machine1.uk.com:27017,machine2.uk.com:27017,machine3.ukx.com:27017/test_db_name

However when I use the following spring configuration
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:mongo="http://www.springframework.org/schema/data/mongo"
   xmlns:task="http://www.springframework.org/schema/task"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

<mongo:mongo />

<mongo:db-factory uri="${datamanager.host}" />

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongoDbFactory" />
</bean>

<mongo:repositories base-package="com.datasource.service" />

<task:annotation-driven />

I get the following exception. Note the fact that machine1 has had its extension "uk.com" removed.
Caused by: com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting for a server that matches {serverSelectors=[ReadPreferenceServerSelector{readPreference=primary}, LatencyMinimizingServerSelector{acceptableLatencyDifference=15 ms}]}. Caused by: com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting for a server that matches {serverSelectors=[ReadPreferenceServerSelector{readPreference=primary}, LatencyMinimizingServerSelector{acceptableLatencyDifference=15 ms}]}. Client view of cluster state is {type=ReplicaSet, servers=[{address=machine1:27017, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.UnknownHostException: machine1}}, {address=machine2.uk.com:27017, type=ReplicaSetSecondary, averageLatency=11.7 ms, state=Connected}, {address=machine3.uk.com:27017, type=ReplicaSetSecondary, averageLatency=11.8 ms, state=Connected}]

For now I've updated my host file to change it to the IP Address which works but it seems strange.


text:
Q: Digital clock made using React not working I'm learning React from Udemy. When I use the older React version my code is working but with the new 18.1 version, it's not working. I'm trying to build a simple digital clock but sadly not working. Anyone plz help

import React, { useState } from "react";
import logo from './logo.svg';
import './App.css';
function App() {
  setInterval(Time, 1000);
  const date = new Date();
  const time = date.toLocaleTimeString();
  const [uptime, funcTime] = useState(time)
  // event.preventDefault()

  function Time() {

    return (
      funcTime(time)
   )
  };
  return (
    <>

TIME

      {uptime}
      {/* <button onClick={Time} type="submit">submit</button> */}
    </>

  )
}
export default App;

A: I have moved the time interval to useEffect try this
import React, { useState,useEffect } from "react";
import logo from './logo.svg';
import './App.css';

function App() {
  const date = new Date();
  const time = date.toLocaleTimeString();
  const [uptime, funcTime] = useState(time);

  useEffect(() => {
    const interval = setInterval(() => {
      const newTime = new Date().toLocaleTimeString();
      funcTime(newTime);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, [time]);
  // event.preventDefault()

  return (
    <>

TIME

      {uptime}
      {/* <button onClick={Time} type="submit">submit</button> */}
    </>
  );
}


text:
Q: My first multi-file C++ Program Keeps Giving Me Error Messages Add.cpp
int add(int x, int y)
{
    return x + y;
}

Main.cpp
#include <iostream>

int main()
{
    using namespace std;
    cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
    return 0;
}

When I try to compile this program I get an error message for line 6 of main.cpp that states: "error: 'add' was not declared in this scope".

A: Create a header file
Contents:
    int add(int x, y);

Include that file main.cpp
i.e. #include "headerfile.h"
Then the rest is up to the compiler environment. Basically need to compile each .cpp to object code and then link them. You need to read up about this as this differs between environment. Also read up on header guards and also stuff like graadle, SCONS, Makefiles. Also good to learn about version control systes e.g. mercurial.
Guess you going to have a busy day

A: You need Add.h file and include it in your Main.cpp
Add.h
int add(int x, int y);

Main.cpp
#include <iostream>
#include "Add.h"

...

A: In c++ the scope is all visible functions/methods and variables. In order for it to be seen in the scope in this instance you would have to create a header file that contains your method "add". One way to do this would be to instead of having it in a .cpp file have it in a .h file, then include that .h file in your main.cpp file like this
#include "Add.h"


text:
Q: bash: IF condition with keyworld within FOR loop I am dealing with simple for loop, which loop the filles and execute on it some commands. I need to set up the filter with IF statement to consider only file started with the keyword "AllBoxes":
  for pdb in "${storage}"/"${experiment}"/*.pdb ; do
    pdb_name=$(basename "$pdb" .pdb)
    # if file starts with pharase AllBoxes do something on the file
    if [[ ${pdb_name} =='AllBoxes*' ]] ; then
    echo Vizualisation of ${pdb_name} is being processed!
    fi
    done

This gives me an error in the IF statement.
Also would it be enought to skipp all of the rest filles (that does not start with "AllBoxes" keyworld? Need I introduce something like Else or Elif Break to exit the loop ?

A: The error is probably because you need a space after the == however you won't be able to use wildcards like that in an expanded test.  You could use =~ to do regex matching (something like AllBoxes.*) however if you quote it, it will be treated literally.  If you only care about AllBoxes files however you could just modify your loop to:
for pdb in "${storage}/${experiment}"/AllBoxes*.pdb ; do


text:
Q: Prove that if $\lim _{n\rightarrow \infty }a_{n}=1$ then $\lim _{n\rightarrow \infty }a_{1}+a_{2}+\ldots +a_{n}=\infty $ Would appreciate some help with proving the following statement:
Let $a_{n}$ be a sequence, and $\lim _{n\rightarrow \infty }a_{n}=1 $.
Prove that $\lim _{n\rightarrow \infty }a_{1}+a_{2}+\ldots +a_{n}=\infty $.
It's easy to see that if $a_{n}$ is monotonically decreasing, then we can choose the sequence $b_{n}=\sum ^{n}a_{n}k=1$, then $\lim _{n\rightarrow \infty }b_{n}=\infty$ and since $\forall n\in \mathbb{N} \left( a_{n+1}\leq a_{n}\right)$, we can assume that $\lim _{n\rightarrow \infty }a_{1}+a_{2}+\ldots +a_{n}=\infty $, but what happens when $a_{n}$ is monotonically increasing?

A: There exists $m$ such that $a_n >\frac 1  2$ for $n \geq m$. So, for $n >m$ we have  $$a_1+a_2+\cdots+a_{m-1}+a_m+a_{m+1}+\cdots+a_n$$ $$ > a_1+a_2+...+a_{m-1}+\frac {n-m+1} 2 \to \infty$$ as $n \to \infty$.

A: If $a_n \to 1$ then there is $N \in \mathbb N$ such that $a_n \ge 1/2$ for all $n \ge N$. Therefore, for $n \ge N$,
$$b_n = \sum_{k = 1}^n a_k \ge (n - N) \frac{1}{2} + \sum_{k = 1}^N a_k$$
and $(n - N)1/2$ goes to $\infty$ for $n \to \infty.$

A: There is some $n\in\Bbb N$ suche that $n\geqslant N\implies a_n\geqslant\frac12$. So, if $n\geqslant N$,$$a_1+a_2+\cdots+a_n\geqslant a_1+\cdots+a_{N-1}+\frac{n-N-1}2.$$Can you take it from here?


text:
Q: Disable Windows 10 fast boot via CMD/Powershell I dual boot Windows 10 alongside Ubuntu. Every so often I get an error that looks like this when I try to access my NTFS (Windows) drive from Ubuntu.
Error mounting /dev/sda5 at /media/mani/0AC217250AC21725:
Command-line `mount -t "ntfs" -o "uhelper=udisks2,nodev,nosuid,uid=1000,gid=1000" "/dev/sda5" "/media/mani/0AC217250AC21725"' exited with non-zero exit status 14:
The disk contains an unclean file system (0, 0).
Metadata kept in Windows cache, refused to mount.
Failed to mount '/dev/sda5': Operation not permitted
The NTFS partition is in an unsafe state. Please resume and shutdown Windows fully (no hibernation or fast restarting), or mount the volume read-only with the 'ro' mount option

Now I realise every time I start using Windows 10 it normally has updates, these cause fast boot to be enabled. So I go to the Control Panel and check if fast boot has been enabled if so I disable it and reboot to Windows 10 (to ensure the setting has been enabled), then shutdown Windows 10 and boot Ubuntu see if the error has gone away.
If it hasn't solved it I then go back to Windows and run cmd as Admin and enterpowercfg /h off and then its usually fixed.
But I figure if it keeps happening it seems a lot of reboots are required and its quite a tiresome process.

My idea:
First I need a way to disable fast boot every time I shut down Windows 10? Just incase it gets enabled by some update. To do this I would have a script that turns off fast boot every time I shut down? (I'm yet to find a way to turn of fast boot via CMD so this is the current issue)
Then also put in that script run powercfg /h off

If my idea is sound (I'm open to other suggestions) how do you disable fast boot via CMD/PowerShell?
Currently I have to go to the Control Panel -> Power Options -> Choose what the power buttons do -> (Untick) fast boot.
My purpose is to stop Windows 10 enabling Fast Boot option after every update (I want it off!).

A: Links to other sites aren't that helpful because the content can change. The information you need to include in the batch file is:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Power

HiberbootEnabled DWORD

0 = Turn off fast startup
1 = Turn on fast startup


text:
Q: QTMovie not playing in new window I have a MAC OSX application in which I would like to press a button in the main window and open a new window in which a movie is played. This is my IBAction code;
- (IBAction) playButtonClicked: (id) sender
{
   MoviePlayerController *moviePlayerWindow = [[MoviePlayerController alloc] initWithWindowNibName:@"MoviePlayer"];
  [moviePlayerWindow showWindow:self];

  NSError *error;
  NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"sample_iTunes" ofType:@"mov"];
  QTMovie *movie = [QTMovie movieWithFile:moviePath error:&error];
  if (error) {
      NSLog(@"%@", [error localizedDescription]);
  } else {
      [movie gotoBeginning];
      [moviePlayerWindow.movieViewer setMovie:movie];
      [moviePlayerWindow.movieViewer play:nil];
  }

}

movieViewer is a QTMovieViewer outlet inside the new window.
The window opens but no movie is played; can someone understand what I am doing wrong ? I can send the complete project (it is a test one, very small) if needed.

A: Try changing NSError *error; to NSError *error = nil;


text:
Q: Quiero insertarle texto a una etiqueta H1 en Js pero cuando lo hago se borran las demás etiquetas hijo

El problema es que cuando lo inserto me borra las etiquetas que ya habían dentro de este h1 y ni con innertext ni con innerhtml se quedan las etiquetas

A: Conseguí solucionarlo así:
En la variable "tempo" le doy todo el contenido html(Etiquetas Hijo) que puede tener el h1.
ej:
Mi h1 con el valor:

 let tempo = h1s[index].innerHTML

y luego inserto dentro de ese h1 el texto "Esto es un h1" concatenando además todas las etiquetas que este tenía antes.
´´´
h1s[index].innerHTML = "Esto es un h1"+tempo;
´´´
Si solo pusiéramos el "Esto es un h1" se sobrescribiría todo lo que hubiese dentro del h1.
Ej:

Esto es un h1

y de esta manera lo aplico a todos las etiquetas del documento

 let h1s = document.getElementsByTagName("h1");
        //Bucle para rellenar todos los h1 del documento
    for (let index = 0; index < h1s.length; index++) {
        let tempo = h1s[index].innerHTML
        h1s[index].innerHTML = "Esto es un h1"+tempo;

    }

A: Como tu pregunta carece de explicación sobre cómo exactamente querés, te comparto dos forma de realizar.
Primero, seleccionamos todos los p con la clase parrafito con querySelectorAll, y ahí le escribimos lo que sea: si es texto: innerText; o si será algo más como etiquetas: innerHTML

let h1s = document.querySelectorAll(".parrafito");

for (let index = 0; index < h1s.length; index++) {

    h1s[index].innerHTML = "Esto es un h1";

}

enlace

La segunda opción es seleccionar todos los h1 con clase o ID miH1 en insertamos una plantilla predefinida en javascript:

let h1s = document.querySelectorAll("#miH1");

// Esta plantilla se inserta en el H1
const template = `

Primer parrafo con enlace

Segundo parrafo

`;

for (let index = 0; index < h1s.length; index++) {

    h1s[index].innerHTML = template;

}

enlace


text:
Q: storing gziped strings in mysql I'm referencing this Store GZIP:ed text in mysql?.
I want to store serialized sessions in the database (they are actually stored in a memcached pool but i have this as a failsafe). I am gziping/uncompressing from php.
I want to ask the following:
1) Is this a good move? I am doing this to avoid using mediumtext as the data may be bigger than text. I think/hope i will have a lot of sessions stored there. Is it, in this case, worth to gzip? Table is MyISAM.
2) Do i need to set the encoding of the table field to binary? Or only do that if i have a complete gziped file?
3) Is serializing a bad move, should i use json_encode instead (because of the smaller size i guess)?
Thanks,

A: You should use a MEDIUMBLOB field instead of MEDIUMTEXT. BLOBs have no encoding, as they are raw byte streams.


text:
Q: for loop is skipping to the end? I am fairly new to Java, but my for loop is instantly skipping to the highest possible value in the following code:
System.out.println(i);
    for(i = 0; i <= (difficulty - 2); i++);{
        System.out.println(i);
        nextMineX = (int) (10*Math.random());
        nextMineY = (int) (10*Math.random());

        for(y = 0; y <= 14; y++){
            System.out.println(y);
            if(nextMineX == minesX[y] && nextMineY == minesY[y]){
                i = i-1;
            } else{
                minesX[i] = nextMineX;
                minesY[i] = nextMineY;
            }
        }
    }

The first for loop is screwing up, while the nested one is running fine. the variable i is initialized as 0, and difficulty is at 16. the output of this excerpt is as follows:
0
14
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14

If anyone can help me with his that would be extremely appreciated. Since I'm new, it is probably something small and basic that I'm overlooking.

A: The problem is the semicolon at the end of the second line. It's valid to have a for loop with no body. It's also valid to have standalone a block of code inside brackets (this defines a scope for variables--if you defined a variable inside the brackets, it wouldn't be available outside). So Java is interpreting the beginning of your code like this:
for(i = 0; i <= (difficulty - 2); i++); // for loop is done, so i = difficulty - 2

{
    System.out.println(i);
    ...

A: Your for loop statement ends with the semicolon you have
for(i = 0; i <= (difficulty - 2); i++); <- incorrect

for(i = 0; i <= (difficulty - 2); i++){ <- correct
     //body
}

A: For loop is terminating cause of semicolon ;
for(i = 0; i <= (difficulty - 2); i++); //semicolon terminating loop
{...}

so you should use for loop like this
for(i = 0; i <= (difficulty - 2); i++) //remove semicolon prevent to terminate
    {...}


text:
Q: Is it possible to get the value of NUnit custom attribute PropertyAttribute via reflection? I have something like the following
[TestFixture]
public class Test
{
    [Test]
    [Property("Test", "TEST-1234")]
    public void TestOne()
    {
        Assert.IsTrue(true);
    }

    [Test]
    [Property("Test", "TEST-5678")]
    public void TestTwo()
    {
        Assert.IsTrue(true);
    }
}

I need to get the value of the attribute Test i.e I need to get TEST-1234 via reflection. I know that  it's possible to get it at runtime with something like TestContext.CurrentContext.Test.Properties["Test"]) but that doesn't help me.
I've tried several methods like
test.GetCustomAttributes(typeof(NUnit.Framework.PropertyAttribute)).ToList()[0]

which gets me the attribute object itself but I cannot access the value itself, is this possible?

A: So, let's assume you have an array of property attributes, found on a given method. You got them by reflection specifying the type PropertyAttribute so you know that's what they are, even though the array is Attribute[].
So you need to find all attributes (or the first attribute if you just want one) with a Name property of "Test" as well as the value assigned to that property.
[BTW, "Test" seems a pretty bad name to me here, since NUnit has so many things called "Test" and your own test code probably does as well. But we will stay with that name for the example.]
You need to do something like this...
for each (PropertyAttribute attr in attrs) // attrs filled by you already
{
     if (attr.Name == "Test")
         testValue = attr.Value;

     // Process the value as you want. If there's just one and this is in
     // a function call, you can return it. If you are doing something else,
     // do it here and then `break` to exit the loop
}

You can do it with less code using System.Linq, but I think the loop will help you see more clearly what has to be done.


text:
Q: .Net windows application WebBrowser / Google Maps API v3 I'm developing an application in which the user will be able to enter a desired address and then press a button. This address will be found on the WebBrowser control in a .net windows application. I know that you can run javascripts on WebBrowser by using the WebBrowser1.DocumentText, and the calling the script by WebBrowser1.Document.InvokeScript ...
I'm having little issues with this and I was wondering if someone could show me the right way in order to do it.
CODE:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

  Dim AddressMap As String

  AddressMap = AddressM.Text

  WebBrowser1.DocumentText = "<meta name='viewport' content='initial-scale=1.0, user-scalable=no' />" & _
    "" & _
    "

"

   WebBrowser1.Document.InvokeScript("Initialize")

End Sub

below is another piece of code that i think should work but i still get an script error "An error has occured in the script on this page" Line 1 CHar 124 Error Expected ';' Code 0 URL about.blank
 WebBrowser1.DocumentText = " " +
                           " " +
                           " " +
                           "

  "

WebBrowser1.Document.InvokeScript("initialize", New String() {AddressM.Text})

i greatly appreciate the help
Leo P.
this is another piece of code slightly different that the previous two, it includes and if else statement pulled out from a html that actually runs the google maps script.
WebBrowser1.DocumentText = " " +
                       " " +
                       " " +
                       "

  "

        WebBrowser1.Document.InvokeScript("initialize")

html code below
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

A: Putting solution
HTML
Create page html in C:\page.html and using this code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

Windows Form - C#
private void Form1_Load(object sender, EventArgs e)
{
    // Put uri (http://www.example.com/page.html and c:\page.html is valid address)
    webBrowser1.Url = new Uri(@"C:\page.html");
}

private void button1_Click(object sender, EventArgs e)
{
    webBrowser1.Document.InvokeScript("initialize",
            new string[] { textBox1.Text });
}

and need form with this component with this names: textBox1, button1 and webBrowser1.


text:
Q: Нет звука в Ubuntu 16.04
Звук есть только в наушниках, через динамики звука нет. Все на максимуме, почему так? Кто шарит помогите

A: Я новичок в работе с Ubuntu, но столкнулся с похожей проблемой: у меня не было звука в наушниках.
Попробуйте выполнить следующее
sudo apt-get install pavucontrol
pavucontrol

Затем в открывшемся окне можно выбрать устройство вывода.


text:
Q: How do I get 'import' to work in a web page over file:// protocol Most browsers support 'import', so the following should work:
/**
* Adder.mjs
*/

class Adder {

    add(n1, n2) {
        return n1 + n2;
    }
}

export default Adder;

test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Import Test</title>
<script type="module">
    import Adder from "./Adder.mjs";
    var adder = new Adder();
    var result = adder.add(1, 1);
    console.log("Result: " + result.toString());
</script>
</head>
<body>
</body>
</html>

It however results in the following error (Chromium debug console):
Access to script at 'file:///home/gso/eclipse-workspace/Test/Adder.js' from origin 'null' has been blocked by CORS policy: The response is invalid.
test.html:7 GET file:///home/gso/eclipse-workspace/Test/Adder.js net::ERR_FAILED

A: As connexo pointed out:

"Modules don't work over the file:// protocol. You need a webserver."

It's also worth noting that Apache does not support the .mjs file extension, ES6 modules have to be suffixed .js.


text:
Q: ie9 webfonts not loading I've tried all the other solutions provided here and elsewhere and I'm still having issues with webfonts loading in ie9.
Implemented the fix to the .htaccess file:
<FilesMatch "\.(ttf|otf|eot|woff)$">
    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "*"
    </IfModule>
</FilesMatch>

Not receiving any css3 error messages in ie developer console.
Thing is when the initial page loads, the fonts don't load but when I navigate to any other page on the site, the fonts then load.  If I go back to the initial page the fonts will now load too.
Feel like I've tried everything I was able to find on the web.
Heres my css:
/** FONTS **/

@font-face {
    font-family: 'UniversUltraCondensedRegular';
    src: url('../fonts/univers-ultracondensed-webfont.eot'); /* IE9 Compat Modes */
    src: url('../fonts/univers-ultracondensed-webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('../fonts/univers-ultracondensed-webfont.woff') format('woff'), /* Modern Browsers */
         url('../fonts/univers-ultracondensed-webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('../fonts/univers-ultracondensed-webfont.svg#UniversUltraCondensedRegular') format('svg'); /* Legacy iOS */
         font-weight: normal;
         font-style: normal;
    }

@font-face {
    font-family: 'WebSymbolsRegular';
    src: url('../fonts/websymbols-regular-webfont.eot'); /* IE9 Compat Modes */
    src: url('../fonts/websymbols-regular-webfont.eot?#iefix') format('embedded-  opentype'), /* IE6-IE8 */
         url('../fonts/websymbols-regular-webfont.woff') format('woff'), /* Modern Browsers */
         url('../fonts/websymbols-regular-webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('../fonts/websymbols-regular-webfont.svg#WebSymbolsRegular') format('svg'); /* Legacy iOS */
         font-weight: normal;
         font-style: normal;
    }

Here's the link to the site!
Thanks

A: TRY USING AN ABSOLUTE URL
@font-face { font-family: 'UniversUltraCondensedRegular'; src: url('../fonts/univers-ultracondensed-webfont.eot');

becomes
@font-face { font-family: 'UniversUltraCondensedRegular'; src: url('http://www.yourdomain.com/fonts/univers-ultracondensed-webfont.eot');

A: In theory, the CSS you provided should work. Most likely, your problem is caused either by using the wrong paths or by having the wrong file permissions for your font files.
How to tackle this issue :
First, test whether everything works correctly if you use absolute paths (as zaba suggested).

*

*If that does work, it means your paths are incorrect. In that case, make sure the path is relative to the CSS file that contains the @font-face statement.

*If that doesn't work, then your issue is probably not related to the pathname. In that case, check whether the file permissions are OK for your font files and the folder it's in.


text:
Q: Finding the cheapest shop which has all the requested list items I am currently trying to use pure T-SQL with no additional work done using C# to find the cheapest store match to a list of products.
Finding the cheapest match works well, but my problem is that the found matches (the stores) do not necessarily have all the items in the list.
The tables necessary for this operation are:
Supermarkets - All available supermarkets.
ListItems - A table connecting item lists and products.
AvailProducts - A table that links between a product and a supermarket. If a row does not exist for a certain product ID and supermarket ID, then it means the supermarket does not have this product at all. This is the table which holds the Price for the product.
My current testing SQL statement is supposed to return up to 5 supermarkets which have the wanted products ordered from the cheapest to the most expensive sum, and it looks like this:
SELECT TOP 5 AvailProducts.[SuperID], SUM(AvailProducts.[Price]) AS "Price"
FROM AvailProducts, ListItems, Supermarkets
WHERE ListItems.[ListID]=3
AND AvailProducts.[ProductID]=ListItems.[ProductID]
AND AvailProducts.[SuperID]=Supermarkets.[ID]
AND (SELECT COUNT(*) FROM AvailProducts, ListItems WHERE AvailProducts.[ProductID]=ListItems.[ProductID] AND ListItems.[ListID]=3 AND AvailProducts.[SuperID]=)=(SELECT COUNT(*) FROM ListItems WHERE [ListID]=3)
GROUP BY AvailProducts.[SuperID]
ORDER BY SUM(AvailProducts.[Price])

The third line from the bottom is supposed to count the number of list items that are available in the supermarket and only return the supermarket's ID if the number of list items and the number of available items in this supermarket equal.
However, this does not work, because I cannot specify the current super market's ID in this statement.


text:
Q: Site rendering problem with the same browser! i'm having a pretty weird rendering problem with my site!
Using Safari on different computers, my site get rendered differently!
www.romasantandrea.sism.org
on the top left of the page there is a glowing logo. it happens that on these computer the glowing part is moved on the right instead of staying on the logo.
further more, the sidebar on the right is not in place as it should be!
I hope you can see this behaviour because, as i said is not browser specific but machine specific (or at least seem so)
My guess is that it is a user defaults problem


text:
Q: Why does the self.search() return None while being called by thesingleNonDuplicate() function? I am getting None as return value, the code doesn't work as expected, search() returns None in line 4. Why?
I am trying to call a search() function inside a function of a class. Theer seems to be a problem with the inner function returning to the outer one.
class Solution:
def singleNonDuplicate(self, nums):
    n = len(nums)
    ans = self.search(nums, 0, n-1)
    return ans

def search(self,l,low,high):

    if low == high:             # base case
        return (l[high])

    else:
        mid = low + (high-low)//2         # evaluate mid

        if mid%2 == 0:

            if l[mid] == l[mid + 1]:
                self.search(l,mid+2,high)

            else:
                self.search(l,low,mid)

        else:

            if l[mid] != l[mid+1]:
                self.search(l,mid+1,high)
            else:
                self.search(l,low,mid)

A: You are missing returns from the rest of your recursive function - every time you recurse (called self.search) you have to return the value - and eventually that result will make it up the chain.
class Solution:
   def singleNonDuplicate(self, nums):
     n = len(nums)
     ans = self.search(nums, 0, n-1)
     return ans

  def search(self,l,low,high):

     if low == high:             # base case
       return (l[high])
     else:
       mid = low + (high-low)//2         # evaluate mid

       if mid%2 == 0:
          if l[mid] == l[mid + 1]:
             return self.search(l,mid+2,high)
          else:
             return self.search(l,low,mid)
       else:
          if l[mid] != l[mid+1]:
              return self.search(l,mid+1,high)
          else:
              return self.search(l,low,mid)


text:
Q: JPG vs WebP performance on Android I´m trying to get performance stats about how Android load, decode and render WebP images against JPG, but my results are a little confuse.
Decoding WebP images to Bitmap are slow than JPG.
Some stats:

*

*WebP 66% less file size than JPG, 267% more time to decode.

*WebP 38% less file size than JPG, 258% more time to decode.

*WebP 89% less file size than JPG, 319% more time to decode.

Has someone know about any issue on performance, or why WebP decoding is harder than JPG.
This is my test:
public class BulkLoadFromDisk implements Runnable {

    private static final String TAG = "BulkLoadFromDisk";

    private static final int TIMES = 10;

    private final ResourceProvider resourceProvider;
    private final Activity context;
    private final int counter;
    private long averageLoadTimeNano;
    private long averageConvertTimeNano;
    private final ImagesFactory.FORMAT format;
    private final CompleteListener listener;

    public BulkLoadFromDisk(Activity context, ResourceProvider resourceProvider,
                            CompleteListener listener, ImagesFactory.FORMAT format) {
        this.resourceProvider = resourceProvider;
        this.context = context;
        this.counter = resourceProvider.length();
        this.format = format;
        this.listener = listener;
    }

    @Override
    public void run() {

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Log.e(TAG, e.getMessage(), e);
        }

        try {
            String file;
            long loadBegin, loadEnd;
            long convertBegin, convertEnd;
            Bitmap bitmap; Drawable d;
            String extension = "." + format.name().toLowerCase();
            InputStream inputStream;
            for(int j = 0; j < TIMES; j++) {

                for(int index = 0; index < counter; index++) {
                    file = resourceProvider.get(index).concat(extension);
                    inputStream = context.getAssets().open(file);

                    // Load bitmap from file
                    loadBegin = System.nanoTime();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    assert (bitmap != null);
                    loadEnd = System.nanoTime();

                    // Convert bitmap to drawable
                    convertBegin = System.nanoTime();
                    d = new BitmapDrawable(context.getResources(), bitmap);
                    assert (d != null);
                    convertEnd = System.nanoTime();

                    averageLoadTimeNano += (loadEnd - loadBegin);
                    averageConvertTimeNano += (convertEnd - convertBegin);
                }

            }
            averageLoadTimeNano = averageLoadTimeNano / (TIMES * counter);
            averageConvertTimeNano = averageConvertTimeNano / (TIMES * counter);

            if(listener != null && context != null) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listener.onComplete(BulkLoadFromDisk.this);
                    }
                });
            }

        }
        catch (final IOException e) {

            if(listener != null && context!= null) {

                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listener.onError(e);
                    }
                });

            }

        } finally {
            System.gc();
        }

    }

    public interface CompleteListener {
        void onComplete(BulkLoadFromDisk task);
        void onError(Exception e);
    }

    public long getAverageLoadTimeNano() {
        return averageLoadTimeNano;
    }

    public long getAverageConvertTimeNano() {
        return averageConvertTimeNano;
    }

    public ImagesFactory.FORMAT getFormat() {
        return format;
    }

    public String resultToString() {
        final StringBuffer sb = new StringBuffer("BulkLoadFromDisk{");
        sb.append("averageLoadTimeNano=").append(Utils.nanosToBest(averageLoadTimeNano).first
                + Utils.nanosToBest(averageLoadTimeNano).second);
        sb.append(", averageConvertTimeNano=").append(Utils.nanosToBest(averageConvertTimeNano).first
                + Utils.nanosToBest(averageConvertTimeNano).second);
        sb.append(", format=").append(format);
        sb.append('}');
        return sb.toString();
    }

A: I know this is an old question and i haven't studied the in-depths of WebP yet, but it's probably because it's a more complex algorith, hence why it has better compression ratios than JPEG. WebP is based on the VP8 codec, which is itself an royalty-free competitor to the widely-used, and heavy, h264 format.
JPEG is widely used, however, it's a really old format and is considerably simpler than the VP8 codec of WebP.


text:
Q: MVC one to zero inserting not updating I am using EntityFramework. I have an "Application" object (which has a field certificateReasonID) which can have one or zero CertificateReasons - so there is a ralationship to the "CertificateReason" table, and visiually on the edmx diagram we do not see the certificateReasonTypeID field.
When I update an Application - it INSERTS a new CertificateReason and UPDATES Application.certificateReasonTypeID to the new ID - instead of updatig Application.certificateReasonTypeID to the selected ID.
The CertificateReason object is in an added state(technically correct).
The aspx code is
<%foreach (var certReason in Model.CertificateReasons)
                  { %>

                        <%= Html.RadioButton("CertificateReason.id", certReason.id)%>

                          <input type="hidden" value="<%= certReason.meaning %>" name="CertificateReason.meaning"/>
                            <input type="hidden" value="<%= certReason.effectiveFrom %>" name="CertificateReason.effectiveFrom"/>
                            <input type="hidden" value="<%= certReason.createdWhen %>" name="CertificateReason.createdWhen"/>
                        <label for="certificateReasonTypeID<%=certReason.meaning%>"><%=certReason.meaning%>

                <%}%>

The update code is
 public ActionResult Edit(int id, FormCollection collection, ApplicationViewModel model)
 {
     var appToUpdate = OMF.Application.First(m => m.id == id);
     UpdateModel(movieToUpdate, collection.ToValueProvider());
     if (ModelState.IsValid)
     {

          OMF.ApplyPropertyChanges(movieToUpdate.EntityKey.EntitySetName, appToUpdate );
          OMF.SaveChanges();
      }
}

Thanks

A: answer was to pass the Application model into the Edit post - had to put a hidden field on form for the object to be filled correctly) and ensure I was getting the Application objetc not a var. Can't use the ModelState.IsValid as always false, but correctly updates not inserts. Other point was had to do an .Include("CertificateReasons") on the get.
public ActionResult Edit(Application app, FormCollection collection)
        {
        Application movieToEdit = OMF.GetApplication(app.id);
        if(app.CertificateReason != null)
            movieToEdit.CertificateReason = OMF.CertificateReason.First(d => d.id == app.CertificateReason.id);
        TryUpdateModel(movieToEdit);

        //if (ModelState.IsValid) --can't use this
       // {
            OMF.SaveChanges();
       // }
        return RedirectToAction("Edit", app.id);

    }


text:
Q: JAVA - Method/Function non detected I wrote a script in Java and everything is fine except a small detail. Java doesn't recoognize my function "ajouter" whereas it is well defined.
There are 2 Java files : Conteneur and Main (for the "public static void main").
Here the 2 source codes :
Conteneur :
 public static double[] ajouter(int Valeur, double Tableau[]){
    double x;
    for(int i =0; i<Tableau.length; i++)
    {
        x = Tableau[i];
        if (Double.isNaN(x) == true && i == 10){
            System.out.println("Tableau plein");
            return Tableau;}
        if( Double.isNaN(x) == true){
            Tableau[i]=Valeur;
        }

    }
    return Tableau;
}

Main :
public static void main(String[] args) {
    double Tableau[] = { 1, 2, 3, 4, 5 };
    System.out.println(ajouter(6, Tableau));
}

At the line where it is written : "System.out.println(ajouter(6,Tableau));", JAVA displays "method ajouter(int, double[]) is undefined for the type main".
Can you help me please ?
Thank you in advance !
Best regards !

A: Assuming you've imported the Conteneur class, in your main method you need to call it like this:
System.out.println(Conteneur.ajouter(6,Tableau));

A: You need to import static Conteneur.* in your Main class, in order to reference Conteneur's static methods without referencing and importing Conteneur itself.
So, either way:

*

*import static Conteneur.* // and no further change

*import Conteneur // reference "ajouter" with Conteneur.ajouter
You also want to:

*

*Use an IDE

*Use English in your code, unless your project is only ever going to be maintained by French-speaking people (and still, I'd use English anyway)

*Use proper variable naming, e.g. not CamelCase but camelBack

A: Should include class which defines static method.
Conteneur.ajouter(6, Tableau)

A: The following correctly prints the table Tableau.
public class Main {
public static void main(String[] args) {
        double Tableau[]={1,2,3,4,5};
       // System.out.println(Conteneur.ajouter(6,Tableau));
        Conteneur.ajouter(6,Tableau);
        for (int i=0; i<Tableau.length; i++){
            System.out.println(Tableau[i]);
        }
        }

}

However, Double.isNaN(x) will always be false (because x is a double) so the value Valeur will never be added.


text:
Q: Access-Control-Allow-Origin for http & https Following javascript XMLHttpRequest is working when accessing the site with https:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://site/api/status", true);
xhttp.withCredentials = true;
xhttp.send();

The web.config for the requested site is the following:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                    <add name="Access-Control-Allow-Origin" value="https://intranet.company.local" />
                    <add name="Access-Control-Allow-Credentials" value="true" />
                    <add name="Access-Control-Allow-Headers" value="Content-Type,Cache-Control,Pragma,Expires,Authorization" />
                    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

It should now also be possible to use the site with http also it is not secure. It is working if I change the XMLHttpRequest URL to "http://site/api/status" and the Access-Control-Allow-Origin to "http://intranet.company.local".
It is also not a problem to change the XMLHttpRequest URL based on the given protocol, but I cannot find a working web.config configuration to allow both protocols as the wildcard value for Access-Control-Allow-Origin is not working when using credentials.

A: Thansk to @Jaromanda X for the help. I used his reference from the iis cors module (Link)
to solve the problem:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <cors enabled="true" failUnlistedOrigins="true">
            <add origin="*" allowed="false"/>
            <add origin="https://intranet.company.local" allowCredentials="true">
                <allowHeaders allowAllRequestedHeaders="true" />
                <allowMethods>
                     <add method="GET" />
                </allowMethods>
            </add>
            <add origin="http://intranet.company.local" allowCredentials="true">
                <allowHeaders allowAllRequestedHeaders="true" />
                <allowMethods>
                     <add method="GET" />
                </allowMethods>
            </add>
        </cors>
    </system.webServer>
</configuration>