Does a HTTP tunnel solution exist that doesn't use CONNECT, HTTPS or chunked encoding?

Question: I am looking for a way to get a fast OpenVPN connection out through a restrictive firewall (this is not a workplace and I am not breaking any code of conduct).
Currently I'm using port 443 direct to the openvpn server, as the firewall allows arbitrary TCP on this port. No ports besides 80 and 443 are open (TCP only) and DNS is internal. However, port 443 has a speed limit of 15mbit/s applied, and is extremely unreliable (openvpn link will fail completely every few minutes).
I've thoroughly tested and come to the conclusion that port 80 will only allow traditional HTTP requests - anything involving CONNECT or Transfer-Encoding: Chunked will be silently dropped.
The ping is low enough (5-10ms) and speed high enough (70mbit down, 15mbit up) that I'm genuinely ready to consider a HTTP polling tunnel (or some wizardry that sets a massive content-length and fires down loads of dummy data), but the problem is that I can't find one. Does any solution for this exist already?
I've tried the generally recommended http://sourceforge.net/projects/http-tunnel/, but no joy as it requires chunked encoding.
Edit: Found a semi-solution - http://www.targeted.org/htthost/. Works but unfortunately too slow in terms of latency to really do much with. Interestingly before I put it behind nginx, by opening its internal URLs I was able to see the default page of the transparent proxy I'm behind (wampserver apache apparently).
Comment: ssh may forward http traffic and act as a SOCKS proxy (see `-D` option). Is that feasible?
Answer: Are you having the problem mentioned in this article from Olaf Titz?
http://sites.inka.de/bigred/devel/tcp-tcp.html
Citing (since I could not say it any clearer). Note that the upper and the lower layer TCP have different timers. When an upper layer connection starts fast, its timers are fast too. Now it can happen that the lower connection has slower timers, perhaps as a leftover from a period with a slow or unreliable base connection.
Imagine what happens when, in this situation, the base connection starts losing packets. The lower layer TCP queues up a re-transmission and increases its timeouts. Since the connection is blocked for this amount of time, the upper layer (i.e. payload) TCP won't get a timely ACK, and will also queue a re-transmission. Because the timeout is still less than the lower layer timeout, the upper layer will queue up more re-transmissions faster than the lower layer can process them. This makes the upper layer connection stall very quickly and every re-transmission just adds to the problem - an internal meltdown effect.
TCPs reliability provisions backfire here. The upper layer re-transmissions are completely unnecessary, since the carrier guarantees delivery - but the upper layer TCP can't know this, because TCP always assumes an unreliable carrier."
Maybe this the discussion in this thread (http://news.ycombinator.com/item?id=2409090) will get you some pointers that will help.


Return a key of an object based on value of an array

Question: I want to ask if I have an object like this
const dataArray = {
    key1: ["a", "b"],
    key2: ["c", "d"],
    key3: ["e", "f"],
};

I tried
    const obj = Object.keys(dataArray).map((data, index) => {
        return dataArray[data];
        if (dataArray[data].indexOf("water") > -1) {
            return Object.keys(dataArray);
        }
    });

I want to return a key (key1, key2, key3) that has values of the string "c".
How do I do that? please help
Comment: you can do it one liner `console.log(Object.keys(dataArray).find(k => dataArray[k].includes("c")));`
Comment: Pretty close to [this question](https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value), just needs to be adapted to search array values
Answer: You should know a difference about .map, .find, .filter

const dataArray = {
    key1: ["a", "b"],
    key2: ["c", "d"],
    key3: ["e", "f"],
};
const result1 = Object.keys(dataArray).map((data, index) => {
        return dataArray[data];
        // The line below do not affect !!!
        if (dataArray[data].indexOf("water") > -1) {
            return Object.keys(dataArray);
        }
    });
console.log(result1.join(',')); // All records from `dataArray`

/*******Find one item => using find*/
console.log(Object.keys(dataArray).find(k => dataArray[k].includes("c")));

/*******Find multiple items => using filter*/
console.log(Object.keys(dataArray).filter(k => dataArray[k].includes("c") || dataArray[k].includes("e")));

The map() method creates a new array populated with the results of
calling a provided function on every element in the calling array.

The find() method returns the value of the first element in the
provided array that satisfies the provided testing function. If no
values satisfy the testing function, undefined is returned.

The filter() method creates a new array with all elements that pass
the test implemented by the provided function.
Comment: @Goacgras Does this answer your question? Let me know if you need any help https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: You can get the entries of the object (key / value pairs) and iterates to get your desired key (if value includes 'c')

const dataArray = {
    key1: ["a", "b"],
    key2: ["c", "d"],
    key3: ["e", "f"],
};

const entries = Object.entries(dataArray);

for(let entry of entries){
    if(entry[1].includes('c')){
        console.log(entry[0])
    }
}


Scope of a temporary mysql table or specifying that a table is temporary

Question: In a set of prepared statements I want to pass the keys found in one prepared statement into a later prepared statement.
I can do this using:
PREPARE get_Class_Session FROM
    "CREATE TABLE time_Table_Keys
             (SELECT time_Table_Key,
                           date,
                           DATE_FORMAT(date, '%W') AS day,
                           slot,
                           class_Session
                FROM `Time_Table`
             WHERE (((date >=? && date <= ?) && DAYOFWEEK(date)=? && (slot >=? && slot <=?)) && class_Session ='0')
            )";

Followed by:
PREPARE update_Time_Table FROM
    "UPDATE Time_Table SET class_Session='8888'
      WHERE time_Table_Key IN ( SELECT time_Table_Key FROM time_Table_Keys)";

And lastly:
PREPARE drop_Tmp_Table FROM
    "DROP TABLE time_Table_Keys";

However:
I really want to use CREATE TEMPORARY TABLE and DROP TEMPORARY TABLE but when I attempt to do that the IN clause cannot find the temporary table because of course it doesn't exist when the prepare is parsed.
Is there some way of specifying the scope of a temporary file and or is there someway of telling the prepare that the table in the IN clause is temporary.
Answer: Maybe I'm missing something, but do you even need the temp tables for this particular case?  Would something like this work?
UPDATE Time_Table
SET class_Session='8888'
WHERE
(
  (
     (date >=? && date <= ?) &&
     DAYOFWEEK(date)=? &&
     (slot >=? && slot <=?)
  )
  && class_Session ='0'
)

Here is the SQL Fiddle.
Comment: ok yes totally accept what you are saying there. But this is just one instance and I would still like to understand how a temporary table might be utilised within prepared statements.
Comment: @wickedrunr - please do not simply edit out "Good luck"; these are minor edits and clog the review queue with needless reviews.  Please only edit if you *substantially* improve a question or answer.
Comment: @LittleBobbyTables then there should be a way to flag an edit as "minor" (as in Wikipedia), since it makes no sense not to be able to improve a bad post. You can't even fix small grammar errors since edits <10 chars are rejected!
Comment: @Lohoris - there is a "Minor" reject option, and it *was* rejected as minor. See: http://meta.stackexchange.com/a/140011/148949.  Anyways, this is clogging up an answer, so we can continue in chat if you want.


React - cannot read property 'myFunction' of undefined

Question: I am trying to define a function in my component that will redirect the window to a new URL
class MyComponent extends Component {

 setWindowLocation = function(e)
 {
    window.location = e;
 }

 handleClick = function(eventKey){
    setWindowLocation("https://google.com")
 }

 render() {
    ...
 }
}

This compiles fine and doesn't throw an error, yet when i click the button that calls 'handleClick' my console window shows:

Uncaught TypeError: Cannot read property 'setWindowLocation' of undefined

Any idea?
Answer: You should reference it with this.setWindowLocation(...).
The function is an instance property.
Answer: Functions in a React Component in ES6 will be defined like setWindowLocation()
and called like this.setWindowLocation
class MyComponent extends Component {

 setWindowLocation(location)
 {
    window.location = location;
 }

 handleClick(eventKey){
    this.setWindowLocation("https://google.com")
 }

 render() {
    ...
 }
}

Comment: They *can* be, but if you're using the class property transformation, it'll work fine as written once it's correctly referenced.


Converting from Date-Time to GPS time

Question: I want to convert an array of date-time strings (YYYY-MM-DD hh:mm:ss) to GPS seconds (seconds after 2000-01-01 12:00:00) in the python environment.
In order to get the GPS seconds for a single date in Linux BASH, I simply input date2sec datetimestring and it returns a number.
I could do this within a for-loop within python. But, how would I incorporate this within the python script, as it is an external script?
Or, is there another way to convert an array of date-time strings (or single date-time strings  incorporated into a for-loop) to GPS time without using date2sec?
Answer: Updated Answer: uses Astropy library:
from astropy.time import Time

t = Time('2019-12-03 23:55:32', format='iso', scale='utc')
print(t.gps)

Here you are setting the date in UTC and t.gps converts the datetime to GPS seconds.
Further research showed that directly using datetime objects doesn't take leap seconds into account.
other helpful links here:
How to get current date and time from GPS unsegment time in python
Comment: I'm not sure it is the correct answer. The question was about GPS time, and `total_seconds()` docs say nothing. But `timestamp` doc gives us hints (using `total_seconds()`: it uses the POSIX convention and not the GPS convention. I never saw `date2sec` command, so I'm not sure which time are really meant.
Comment: I did further research based on your feedback and found out using Astropy library might be the least complicated approach to the problem. Thanks for your input :)
Answer: Here is the solution that I used for an entire array of date-times in a for-loop:
import numpy as _np
J2000 = _np.datetime64('2000-01-01 12:00:00')                    # Time origin
dateTime = [...]                                                 # an array of date-times in 'YYYY-MM-DD hh:mm:ss' format
GPSarray_secs = []                                               # Create new empty array
for i in range(0,len(dateTime)) :                                # For-loop conversion
     GPSseconds = (_np.datetime64(dateTime) - J2000).astype(int) # Calculate GPS seconds
     GPSarray_secs = _np.append(GPSarray_secs , GPSseconds)      # Append array

The simple conversion for one date-time entry is:
import numpy as _np
J2000 = _np.datetime64('2000-01-01 12:00:00')                    # Time origin
GPSseconds = (_np.datetime64(dateTime) - J2000).astype(int)      # Conversion where dateTime is in 'YYYY-MM-DD hh:mm:ss' format

Importing datetime should not be required.
Comment: Also your answer is not correct: you may miss some seconds. It uses unix time, so leap seconds will be ignored in the count of seconds. GPS time includes the leap second in the total seconds.

Converting from Date-Time to GPS time


Sequences defined as solutions to equations : $u_{n}=v_{n}^n$

Question: For $n$ a positive integer at least equal to $2$, define the two following functions as follows :
$$
\begin{align*}
  f_{n}(x) & = \pi/4 + \arctan(\sqrt[n]{x})-\arctan(1/x) \text{ for all nonzero }x, \\
  g_{n}(x) & = x^{n+1} +x^n+x-1 \text{ for all real }x.
\end{align*}
$$
We can find, using differentiation for instance, that these two functions have each one unique real root and, using the intermediate value theorem, that it lies in the interval $(0,1)$. If we define the sequence $u_{n}$ as the real root of $f_{n}$ and $v_{n}$ as the real root of $g_{n}$, my question is to prove that the equality $u_{n}=v_{n}^n$ holds for all $n\geq 2$.
EDITED : I corrected the statement from $g_{n}(x)  = x^{n+1} +x^4+x-1$ to $g_{n}(x) = x^{n+1} +x^n+x-1$.
Comment: Careful.  There is definitely a real root of $g_n$ in $(0,1)$.  But if $n$ is odd, then the degree of $g_n$ is even.  Since complex roots come in pairs, there will have to be more than one real root in these cases.
Comment: For example, if $n=3$ then $g_n(x) = 2x^4 +x -1$ has two real roots, at $-1$ and $0.6477988...$ (according to magma).
Answer: Since $\arctan(1/x)=\pi/2-\arctan(x)$ for every positive $x$, $\arctan(\sqrt[n]{u})+\arctan(u)=\pi/4$. Since $\tan(a+b)=(\tan(a)+\tan(b))/(1-\tan(a)\tan(b))$ for every suitable $a$ and $b$, one gets $1=\tan(\pi/4)=(u+\sqrt[n]{u})/(1-u\sqrt[n]{u})$, that is, $u+\sqrt[n]{u}+u\sqrt[n]{u}=1$. Using $v=\sqrt[n]{u}$, one gets $v^{n+1}+v^n+v=1$.
This proves that $u=v^n$, provided $v$ solves $v^{n+1}+v^n+v=1$.
Comment: And, in the question, $x^4$ should read $x^n$.
Comment: Thank you, Mr. Piau. I found this problem manuscript so maybe I misread $x^n$. The statement is now edited.


How to validate a trigger in SQL Server

Question: My problem is this: sometimes changes to database schema invalidate the SQL statements in a trigger. For instance I may drop a column in a table that a trigger references. When I do that, I do not receive any indication of that problem until the next time the trigger fires, which might be months out in production in certain situations.
What is the best way to validate objects, such as triggers or user defined functions, in a SQL server database?
Answer: Have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).
In your case: search for e.g. columns that you've dropped, and let SQL Search find all stored procs, triggers etc. that referenced that column -> gives you an easy list of those things that you need to fix.

It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??
Comment: Just wanted to say Thanks, have been working with SQL Search for a few months now and have to say it is a great tool. Very fast, and great for the problem I described above.
Answer: I'm not totally sure if this case is covered, but you should try the 'Find Invalid Objects' feature in Red Gate's SQL Prompt 5. Let me know if this doesn't work.

How to validate a trigger in SQL Server


Why accuracy gradually increase then suddenly drop with dropout

Question: I am building an image classification network in tensorflow(several convolutional layers and fully connected layers, then softmax cross entropy, optimize using Adam with a learning rate of 1e-4).
Without dropout, I can get a pretty good performance. Though the loss is still very high, even the in-sample error approaches zero.
With dropout (dropout rate less than 0.25), the accuracy will gradually increase and loss will gradually decrease first. Then, accuracy will suddenly drop to 1/(# of class), and loss will also stay close to a small constant.
Does anyone know why that might happen? how I can solve this issue? Thank you
Answer: When you increase dropout beyond a certain threshold, it results in the model not being able to fit properly. Intuitively, a higher dropout rate would result in a higher variance to some of the layers, which also degrades training. Dropout is like all other forms of regularization in that it reduces model capacity. If you reduce the capacity too much, it is sure that you will get bad results.
The solution is to not use such high dropout. If you must, lowering the learning rate and using higher momentum may help.
Furthermore, be careful where you use dropout. It is usually ineffective in the convolutional layers, and very harmful to use right before the softmax layer.
Comment: Thanks for your reply. I didn't apply it to convolutional layers or output layer. I only applied it to hidden fully connected layer. And this happened even with really small dropout rate (~5%). Since the model can overfit the training data hard without dropout, I don't think it's any thing related to model capacity.
Answer: I think I met the same problem with this dramatic-drop-in-accuracy issue. I think the problem with this issue might be related to the softmax function and the cross-entropy that you defined(loss function). Mine issue comes exactly from this cross-entropy function, and I used one-hot-format labels BTW. Taken that classic way of cross-entropy would cause nan or 0 gradient if "predict_y" is all zero or nan, so when the training iteration is big enough, all weights could suddenly become 0. This is exactly the reason why we can witness a sudden and dramatic drop in training accuracy. I solved this problem by using "tf.nn.softmax_cross_entropy_with_logits" instead, which can handle the extreme case safely.
The alternative loss function is defined as follow:
<code>tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=ture_y,logits=predict_y))
</code>
You can give it a shot.


No Burflags in registry

Question: I have a problem where my Windows 2012 Domain Controller SYSVOL and NETLOGON shares did not get created on my secondary domain controller. When I run dcdiag /q it tells me that it failed the advertising test, and cannot access the netlogon share.
Everything I have read about this issue tells me to do a non-authoritative restore by changing the registry value in:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\NtFrs\Parameters\Backup/Restore\Process at Startup
However, I do not have this registry key in the registry. Is this the cause of my issue? Or do I have to create this key?
Answer: "burflags" was for FRS.  Windows Server 2012 doesn't have FRS, so the comparable procedure is described in this lengthy article:
How to force an authoritative/non-authoritative synchronization for DFSR-replicated SYSVOL (like "D4/D2" for FRS)
http://support.microsoft.com/kb/2218556
Note that there are two separate procedures, one for authoritative, the other for non-authoritative.
"You want to force the non-authoritative synchronization of SYSVOL on a domain controller. In the File Replication Service (FRS), this was controlled through the D2 and D4 data values for the Burflags registry values, but these values do not exist for the Distributed File System Replication (DFSR) service. You cannot use the DFS Management snap-in (Dfsmgmt.msc) or the Dfsradmin.exe command-line tool to achieve this. Unlike custom DFSR replicated folders, SYSVOL is intentionally protected from any editing through its management interfaces to prevent accidents."
[...]  the two procedures, like D2 (non-auth) or D4 (auth) ...
"If setting the authoritative flag on one DC, you must non-authoritatively synchronize all other DCs in the domain. Otherwise you will see conflicts on DCs, originating from any DCs where you did not set auth/non-auth and restarted the DFSR service. For example, if all logon scripts were accidentally deleted and a manual copy of them was placed back on the PDC Emulator role holder, making that server authoritative and all other servers non-authoritative would guarantee success and prevent conflicts.
If making any DC authoritative, the PDC Emulator as authoritative is preferable, since its SYSVOL contents are usually most up to date.
The use of the authoritative flag is only necessary if you need to force synchronization of all DCs. If only repairing one DC, simply make it non-authoritative and do not touch other servers.
This article is designed with a 2-DC environment in mind, for simplicity of description. If you had more than one affected DC, expand the steps to include ALL of those as well. It also assumes you have the ability to restore data that was deleted, overwritten, damaged, etc. previously if this is a disaster recovery scenario on all DCs in the domain."

No Burflags in registry


How to mantain a position from a local variable?

Question: So, im getting this error "Variable doesn't exist in current context?" line(30, 12), which doesn't matter too much, i just want to know how can i mantain the position that my "for" have and put in a variable. I need this because i'm trying to do and "Id" check as you can see in the code (Just look for the idImagem part). Is there a way to do that?
By the way, here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class RandomizarCartas : MonoBehaviour {

public Sprite[] _meusOutrosSprites;
private Image[] _images;
private int idImagem;
private int numeroSpriteInt;

public void Start()
{
 _images = gameObject.GetComponentsInChildren<Image>();
 StartCoroutine(Count());
}

IEnumerator Count()
{
     for(int i = 0; i < _images.Length; i++)
     {
           var numeroSprite = Random.Range(0, _meusOutrosSprites.Length - 1);
          _images[i].sprite = _meusOutrosSprites[numeroSprite];
     }

     yield return new WaitForSeconds(0);
}
public void PegarID(){
  switch (numeroSprite){
      case 0:
        idImagem=1;
        break;
      case 1:
        idImagem=2;
        break;
      case 2:
        idImagem=3;
        break;
      case 3:
        idImagem=4;
        break;
      case 4:
        idImagem=5;
        break;
      default:
      break;

  }
public void LetraA(){
  if(idImagem==1){
      SceneManager.LoadScene("Sucesso");
  }else{
      SceneManager.LoadScene("Fases");
  }
}

public void LetraB(){
  if(idImagem==2){
      SceneManager.LoadScene("Sucesso");
  }else{
      SceneManager.LoadScene("Fases");
  }
}

public void LetraC(){
  if(idImagem==3){
      SceneManager.LoadScene("Sucesso");
  }else{
      SceneManager.LoadScene("Fases");
  }
}

public void LetraD(){
  if(idImagem==4){
      SceneManager.LoadScene("Sucesso");
  }else{
      SceneManager.LoadScene("Fases");
  }
}

public void LetraE(){
  if(idImagem==5){
      SceneManager.LoadScene("Sucesso");
  }else{
      SceneManager.LoadScene("Fases");
  }
}

public void LetraF(){
  if(idImagem==6){
      SceneManager.LoadScene("Sucesso");
  }else{
      SceneManager.LoadScene("Fases");
  }
 }
}

Comment: **1.** `private int numeroSpriteInt;` should be `private int numeroSprite` since that's what you're using in your `switch (numeroSprite)` code. Not sure why you have "Int" at the end of it. **2.** You assign value to variables with **one** `=` not two. So, replace your `idImagem == 1;  `with `idImagem = 1;`. Do that for the rest of the `case` code. **3**. I suggest you start with some [C# tutorial for beginners](https://unity3d.com/learn/tutorials/s/scripting).
Comment: `im getting this error,` What exact error, on what exact line?
Comment: What are you trying to achieve by `idImagem==1;`?
Comment: Possible duplicate of [Variable doesn't exist in the current context](https://stackoverflow.com/questions/44140583/variable-doesnt-exist-in-the-current-context)
Comment: Your `PegarID` doesn't do anything, (nor is it being called) but maybe you should be passing `numeroSprite` as a parameter?
Comment: First answer is for "mjwills"
1.When i say "this error", i mean by the title
2.I came from Javascript to C#, in that language is like that, it is just me being a noob basically, sorry...
3.Nooooope, is not, i read this article before and it didn't helped me
Thanks for the help!
Comment: Second answer goes to "Programmer"
1. The Variable `private int numeroSpriteInt` was made for that, my original plan was making numeroSprite=numeroSpriteInt, but it didn't worked aaaand i want to keep the positions that are inside the var (created in the `IEnumerator Count()` for, in a variable, but i couldn't manage to do this yet.
2.Ops, sorry, i came from JavaScript and there is like that, gonna correct this right away.
3. Truth hurts ;-;
Thanks for the help!
Comment: Third answer goes to "Draco18s"
Would it mantain the position that it got from the for?
Answer: numeroSprite is declared as local variable inside of IEnumerator Count(). It doesn't exist outside of that method. If you want to be able to access it in another method make it a private variable:
private int numeroSprite;

private IEnumerator Count()
{
     for(int i = 0; i < _images.Length; i++)
     {
           var numeroSprite = Random.Range(0, _meusOutrosSprites.Length - 1);
          _images[i].sprite = _meusOutrosSprites[numeroSprite];
     }

     yield return new WaitForSeconds(0);
}

public void PegarID(){
  switch (numeroSprite){

  // ...

or use the numeroSpriteInt you already declared but never used just the same way.
private int numeroSpriteInt;

private IEnumerator Count()
{
    for (int i = 0; i < _images.Length; i++)
    {
        numeroSpriteInt = Random.Range(0, _meusOutrosSprites.Length - 1);
        _images[i].sprite = _meusOutrosSprites[numeroSprite];
    }

    yield return new WaitForSeconds(0);
}

public void PegarID(){
  switch (numeroSpriteInt){

  // ...

As Programmer already sayd in your cases you rather want to do
idImage = XY;

Instead of your whole switch thing to me it looks way more reasonable to just use something like
if(numeroSprite >=0 && numeroSprite <=10)
{
    idImage = numeroSprite + 1;
}

Comment: Wuuuuut, it was that easy? i feel like and idiot now...
And by the way, that `idImagem` solution is nice, really, buuuut in my case it's not working cause the idImagem number doesn't seem to be correct, thanks for all the help!


Card with scroll in vuetify

Question: It's possible to create a v-list in vuetify with fixed height and when my user add some content he show a scrollbar in the v-list
tks
Answer: What your asking is not entirely clear, but with CSS you can add a scroll bar to a card if its not automatic.
Here is the codepen:
https://codepen.io/AleaQ/pen/WJZqWb

  <v-app id="inspire">
    <v-container fluid>
      <v-layout>
        <v-flex xs6>
      <v-card class="scroll" height="100">
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
      </v-card>
          </v-flex>
        </v-layout>
    </v-container>
  </v-app>

//CSS MARKUP
    .scroll {
      overflow-y: auto;
    }

Comment: The CodePen link is broken.

Card with scroll in vuetify


Why am I getting 'IOError Exception Value: [Errno 2] No such file or directory' When saving file with PIL

Question: I am building a site using Django/Python and there is one page where the user can upload a photo which is then re-sized and saved using the following function:
<code>from PIL import Image, ImageFile

def resize(file_to_resize, string_id,):
    parser = ImageFile.Parser()
    while True:
        s = file_to_resize.read(1024)
        if not s:
            break
        parser.feed(s)
    image = parser.close()
    ms = image.copy()
    size = 320,240
    ms.thumbnail(size, Image.ANTIALIAS)
    ms.save('http://www.mysite.com/site_media/images/profile/' + string_id, "JPEG") `
</code>
This worked fine while running locally, but once I uploaded the site to my host and ran it under Apache, I got the following error:
Request Method:     POST
Request URL:     http://www.mysite.com/saveimage/8/
Django Version:     1.2.1
Exception Type:     IOError
Exception Value:
[Errno 2] No such file or directory: u'http://www.mysite.com/site_media/images/profile/8'
Exception Location:     /usr/local/lib/python2.6/site-packages/PIL/Image.py in save, line 1299
Python Executable:     /usr/languages/python/2.6/bin/python
Python Version:     2.6.6
Also, I am new to web development and Django/Python, this is actually a project I am working on the learn and plan on sharing it with friends and family, so I'm not sure if this is even the best approach when it comes to security and allowing a file to be written directly to the site.  Any advice is appreciated.
Answer: You have no directory called "http:" in the current directory.
If you're actually trying to save a file over HTTP, this is not how.
Comment: Thank you so much, you are right, I changed the line to: ms.save('site_media/images/profile/' + string_id, "JPEG")
and it worked.


Create BigInteger Array from int Array

Question: I have an int array with me. Is there a way to convert this int array directly to BigInteger Array without iterating through the elements?
Comment: You will need iteration. No escape from that AFAIK
Comment: Wait, do you mean convert it to an array of BigIntegers where each `int` is converted to 1 `BigInteger` ?
Comment: Are you just looking for a one-liner or do you feel that you have to save the cost for the iteration?
Comment: I would like to convert in such a way that each int value is converted to BigInteger value.And yes ,I'm trying to do this to save the cost for iteration.
Comment: The cost of the iteration will be incurred, no matter what. If not your code then some other (library) code  will have to iterate over the array of ints and create the BigInteger instances.
Answer: This should do the job if you're using java-8
int[] ints = new int[]{1,2,3};

System.out.println(Arrays.toString(ints)); // [1, 2, 3]

BigInteger[] bigs = Arrays.stream(ints)
                          .mapToObj(BigInteger::valueOf)
                          .toArray(BigInteger[]::new);

System.out.println(Arrays.toString(bigs)); // [1, 2, 3]

Comment: @Jean-FrançoisSavard Yes, changing it :)
Comment: @YassinHajaj the line `toArray(BigInteger[]::new)` that you had previously did work and was in my opinion cleaner. Still, it works, +1.
Answer: There is no way to accomplish this without iteration under Java-8 (and why does that matter, does the performance hinder your runtime by so much? Is this the bottleneck of your application? You must know that the iteration "cost" will take its toll from your application no matter if you use it directly or not).
Anyway, for the sake of completeness and to make this answer more useful, this is how you might do that:
for (int i = 0; i < arr.length ; i++)
    bigIntegerArray[i] = BigInteger.valueOf(arr[i]);

And if you decide you want to convert your int array to a single BigInteger, there is the constructor public BigInteger(byte[] val) that:

Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.

(And as you probably know int can be represented as 4 bytes)

Create BigInteger Array from int Array


Odds-Ratio in Comprehensive Meta-Analysis

Question: I am conducting a meta analysis and using the program Comprehensive Meta-Analysis.
I have a problem with one of the Odds-Ratios I inserted.
The program.
It is now colored in red and it is written that the lower and upper limits are not symmetric.
These are the original numbers from the study I'm using, what can I do with it? If left unchanged, these numbers won't be calculated in the meta analysis, so I have to change it somehow.
thanks!
Comment: This has happened to me before. It's rare, but could be a rounding or reporting error.
Answer: You have a number of choices.
See how far each (log) limit is from the central (log) estimate. If the difference is small and could possibly be accounted for by rounding error then adjust one of them to make it symmetric and report that fact in your report.
Write to the authors of the primary study and ask them.
Assume the one furthest from the central one is right, back-calculate the standard error and re-compute the erroneous limit. This rests on a lot of assumptions and I would be very cautious about doing it myslef.


rotate imagebutton around itself without moving it

Question: Hello I am working with ImageButton for android application
the button in xml looks like that :
[LEFT][LEFT]
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignTop="@+id/imageButton1"
android:layout_toRightOf="@+id/imageButton1"

I am trying to rotate it with this code
RotateAnimation ra =new RotateAnimation(1000, 90);
ra.setFillAfter(true);
ra.setDuration(0);
prevBut.startAnimation(ra);

The ImageButton does rotate - but it moves a bit to the left after rotation.

I am interested of rotating the ImageButton only without moving it to
  the side is that possible ?
Comment: try `RotateAnimation anim = new RotateAnimation(0.0f, 360.0f, Dimension.RelativeToSelf, 0.5f, Dimension.RelativeToSelf, 0.5f);
`
Comment: hey did you try the answer i posted ?
Comment: Yes i did but Eclipse doesnt recognize Dimension, he is asking me to create local varible, how could i fix that ?
Comment: Yes it Does only that i need to write  Animation.RELATIVE_TO_SELF
instead of Dimention.RELATIVE_TO_SELF
Thanks a lot
Answer: Try this:
RotateAnimation rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

ImageView image = findViewById(my image);
image.setAnimation(rotate);
rotate.setDuration(1000)
rotate.start();

Comment: thanks a lot  that solved my problem.
using Animation.RELATIVE_TO_SELF


403 Error on AJAX Request in add new item (collection field)

Question: I have normal content type which has 12 collection fields
each field has unlimited value
when i try to click add new item on any field it gives me ajax error
An AJAX HTTP error occurred.
HTTP Result Code: 403
Debugging information follows.
Path: /?q=system/ajax
StatusText: Forbidden
ResponseText:

I have another content type and also has collection field with unlimited value .. but it works without any problem
so please help me why some content type has error and the other doesn't have
by the way: i use D7 and i upgraded it to 7.35 but this problem was before the upgrading
i have checked all the answers in the Drupal Answers but unfortunately did it help
edit:
ResponseText:
@import url("http://example.org/modules/system/system.base.css?nlmla7");
@import url("http://example.org/modules/system/system.base-rtl.css?nlmla7");
@import url("http://example.org/modules/system/system.menus.css?nlmla7");
@import url("http://example.org/modules/system/system.menus-rtl.css?nlmla7");
@import url("http://example.org/modules/system/system.messages.css?nlmla7");
@import url("http://example.org/modules/system/system.messages-rtl.css?nlmla7");
@import url("http://example.org/modules/system/system.theme.css?nlmla7");
@import url("http://example.org/modules/system/system.theme-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/date/date_api/date.css?nlmla7");
@import url("http://example.org/sites/all/modules/date/date_api/date-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/date/date_popup/themes/datepicker.1.7.css?nlmla7");
@import url("http://example.org/sites/all/modules/date/date_repeat_field/date_repeat_field.css?nlmla7");
@import url("http://example.org/modules/field/theme/field.css?nlmla7");
@import url("http://example.org/modules/field/theme/field-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/field_hidden/field_hidden.css?nlmla7");
@import url("http://example.org/modules/node/node.css?nlmla7");
@import url("http://example.org/sites/all/modules/recieve_orders/css/orders_styles.css?nlmla7");
@import url("http://example.org/modules/search/search.css?nlmla7");
@import url("http://example.org/modules/search/search-rtl.css?nlmla7");
@import url("http://example.org/modules/user/user.css?nlmla7");
@import url("http://example.org/modules/user/user-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/views/css/views.css?nlmla7");
@import url("http://example.org/sites/all/modules/views/css/views-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/admin_menu/admin_menu.css?nlmla7");
@import url("http://example.org/sites/all/modules/admin_menu/admin_menu-rtl.css?nlmla7");
@import url("http://example.org/sites/all/modules/admin_menu/admin_menu.uid1.css?nlmla7");
@import url("http://example.org/sites/all/modules/ctools/css/ctools.css?nlmla7");
@import url("http://example.org/sites/all/modules/adminimal_admin_menu/adminimal_admin_menu.css?nlmla7");
@import url("http://example.org/modules/shortcut/shortcut.css?nlmla7");
@import url("http://example.org/modules/shortcut/shortcut-rtl.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/reset.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/style.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/style-rtl.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/mobile.css?nlmla7");
@import url("http://example.org/sites/all/themes/adminimal_theme/css/tablet.css?nlmla7");ySite.org/sites/all/themes/adminimal_theme/css/tablet.css?nlmla7");

and there are too many custom modules in my site
but the thing which make me more conflicted is why it doesn't give error in the other content type
Comment: Memory limit errors can be seen in the PHP error log (although I don't think this error comes from that). Ask your hosting provider to know how you can check the error log. If you haven't check the error log you should.
Comment: Is there any custom modules your installation? What's the response text content?
Comment: @tunic I added the response text but i have very much costume modules
Comment: Hard to know, the error is pretty strange. I suggest to disable your custom modules or use a XDebug to debug the error.
Comment: do you thing it can be related to the **memory limit** in the php.ini because i have too much collection fields with unlimited value in the same form ,, if can be i will call my hosting company to increase it because it is not possible from my side
Comment: and if some module has problem ,, this problem must affect on the any other content type ... i am just thinking logically ;)
Answer: for what it's worth we just wrestled with this for a while on our own sites. The solution actually ended up being disabling cloudflare on 'system/ajax' URLs. If you're running CF and have this problem - try it!


Pointer points to another pointer in structure

Question: I have structure named temp with member n:
struct temp
{
    int n;
}

I wish to declare a pointer p to access member n.
struct temp *p

How to access member n by another pointer p1 which points to pointer p.
Comment: `const int my_fav_num = 7; temp val; temp* p = &val temp** p1 = &p (*p1)->n = my_fav_num;`
Comment: `temp a; temp *p = &a temp **p1 = &p (*p1)->n = 2;`
Comment: `temp *ptr = new temp; ptr->n = 7; delete ptr`
Comment: @Thomas Sablik. Please explain
Answer: You can access member n through a pointer to p with
temp a;
temp *p = &a;
temp **p1 = &p;
(*p1)->n = 2;

p1 is a pointer to p. Dereferencing it gives a reference to p. (*p1) and p are equivalent.


How do I Activate the Guest Account in Windows Server 2012 Essentials R2

Question: I'm trying to activate the Guest account in Windows Server 2012 Essentials R2.  Everything I've read states that I should do it from the Users tab within Windows Server Essentials Dashboard.  The problem is, the Guest account is not listed under either Administrator (thank God) or Standard user.
My objective is to grant the Guest account full control over a share, so that anyone on my network can access that share anonymously.
This server is located in a home, by the way.
Answer: Have you taken a look at your GPOs to make sure that the guest account is enabled?
Guest account GPOs
In other words, launch Group Policy Management, select a GPO or create a new one, and you'll find the option to enable guest account under
Computer Configuration\Policies\Windows Settings\Security Settings\Local Policies\Security Options
Comment: So in Group Policy Object I picked the existing Default Domain Controllers Policy at random.  The other was Default Domain Policy.  Those are the only two listed.  Then I drilled down to Accounts: Guest account status and changed it from Not Defined to Enabled.  Then I picked Default Domain Policy and drilled down through that to Accounts: Guest account status, expecting that it would now be Enabled, but it was set to Not Defined.  So these settings seem to affect only the selected GPO.  So your suggestion that I select one (presumably at random) or create one confuses me, as the ...
Comment: ... Accounts: Guest account status setting would seem to affect only the selected (or newly created) GPO.  Does Accounts: Guest account status need to be Enabled for a specific GPO?  If so, which one?
Comment: I wouldn't modify the default policies.  Instead, create a new policy object:  Start "Group Policy Management", expand your forest (on the left), right-click on "Group Policy Objects" and select New.  Give the new policy a name, then press OK.
Comment: The two policies are different, modifying one will not affect the other. To visualize this, click on each policy and look at "Links" in the right pane, you'll notice the 2 are different.  Links are targets where GPOs are applied, so you changed on GPO but not the other.
Comment: And to clarify the comment that was cut short: after you add the new policy, right-click to edit and make any changes there. When finished drag the policy from "Group Policy Objects" to your  forest (e.g., mydomain.local) to "enable" for machines in your forest.  Now machines in your forest will apply the policies as long as the security filtering shown for the policy allows it.  Wait 15mins and reboot the target machine for the GPO to take effect.  As a general word of caution, GPOs can be tricky and sometimes refuse to propagate and troubleshooting can be very long.


Automorphism in complex analysis

Question: Just a quick question about naming: in complex analysis, it appears to me that an "Automorphism" of $\Omega\subseteq \mathbb C$ means a conformal mapping from a subset $\Omega$ to itself. So, an automorphism doesn't necessarily preserve the group structure of $\mathbb C$  However, in group theory, "automorphisms" should be isomorphisms.
Why the same word mean such two different things?
NOTE Someone appears to say that this is a duplicate question, so let me make it more clear: My question is, does the word "automorphisms" mean means completely different things in group theory and complex analysis? Or actually they mean similar things?
That question does not mention groups at all.
Comment: Possible duplicate of [Is Conformal selfmap same as automorphism?](https://math.stackexchange.com/questions/296312/is-conformal-selfmap-same-as-automorphism)
Comment: Where did you see this definition of conformal automorphisms? The standard definition requires an automorphism to be defined in the entire $\Omega$.
Answer: This is because the notion of isomorphism depends on the category in which you are working.  If  we are working in the category of groups, then the right  maps are those which preserve the structure  of the group: that is, maps of groups $f:G\to H$ so that $f(xy)=f(x)f(y)$ for $x,y\in  G$. This is the notion of a group homomorphism. Then, an isomorphism of groups should be a bijective homomorphism with homomorphic inverse.
The real idea behind the scenes is that an isomorphism (of groups) is equivalent to a pair of maps $\phi:G\to H$ and $\psi:H\to G$ which are structure preserving in the sense above with $\phi\circ \psi=\mathbb{1}_H$ and $\psi\circ \phi =\mathbb{1}_G$. So, an automorphism is a group homomorphism $\phi:G\to G$ which is a bijection with a homomorphism for inverse.
If we change to the complex case, then the thing that changes is the notion of "structure preserving." If $\Omega\subseteq \mathbb{C}$ is open, it is in particular a $1-$dimensional complex manifold, and is equipped with a complex structure $\mathcal{O}$. So, maps between such spaces should be  "structure preserving" also. The appropriate notion of such maps is a holomorphic map. So, an isomorphism of subdomains of the complex plane is a pair of such maps as above, $f:\Omega_1\to \Omega_2$ and $g:\Omega_2\to \Omega_1$ holomorphic with $f\circ g=\mathbb{1}_{\Omega_2}$ and $g\circ f=\mathbb{1}_{\Omega_1}$.
An automorphism is then a map $f:\Omega\to \Omega$ which is a holomorphism with holomorphic inverse.
So, these notions of automorphism/isomorphism are examples of the same more general idea.
As for why an isomorphism of complex subdomains need not preserve group structure: well, firstly notice that a subdomain of the complex plane is almost never equipped with a natural group structure. However, a complex structure need not be anything to do with a group structure. More precisely, the complex structure $\mathcal{O}_\mathbb{C}$ of $\mathbb{C}$  makes no mention of the group structure of $\mathbb{C}$, so we should not expect that an isomorphism of complex spaces would pay any heed to the group structure.

Automorphism in complex analysis


Event signature pattern in .net

Question: What's the point in the standard pattern for event delegates in .net?  I.e. the EventHandler predefined delegate?  Why not just choose the most appropriate signature for the requirement?
Edit: And furthermore, is it necessary to slavishly follow Microsoft's example in all cases?
Answer: In C# 1.0 the convention didn't make a lot of sense. In C# 2.0, where there is a certain amount of delegate variance, it makes more sense.
If you have an event handling method which doesn't really care about the parameters, e.g.
public void SaveDocument(object sender, EventArgs args)
{
    // Save the document here
}

you can now use that method to subscribe to any event which follows the convention, even if the actual sender or args are more strictly typed. This means you can use the same handler for a keyboard event, a button click etc.
Answer: It's mainly for consistency and versioning—with the sender paramater as always System.Object and the args parameter as always a System.EventArgs, or a dervied class thereof, you can change the sender argument passed to it as well as change the EventArgs type afterwards without breaking any existing code.
The whole .NET eventing idiom was designed to support component-based development, where the calling code is not under control of the developer of the component with the events.
Answer: This is a good question. Heretical, but good. I read a blog post recently (I can't find the link--does anyone have that link) that debunked the myth that you need to always override System.EventArgs to provide good event handling.
I'm all for convention and following the rules, but this is one that I think can be argued to be bendable--if not avoidable. Needing to constantly override System.EventArgs for every event adds to the coupling of the routine--now there is yet another thing to keep track of.
Having an "e" that provides members isn't any more helpful or intuitive than a well-named set of arguments. I don't think the argument can be won to dispatch the recommended System.EventArg pattern, but I'd put in with you to make that argument.
rp
Answer: It decouples the caller from the callee.

Event signature pattern in .net


I want to display no scrollbar in fullcalendar

Question: I am trying to display the calendar with NO scrollbar on the right. I tried setting contentHeight but it is not working as intended.  There is no scrollbar and the calendar is all displayed, but it streches the rows so that they are all the same height as the row with the most events.
Example, row 3 of the month has 10 events, so the row will strech to display all 10 events, however ALL other rows will have the same height even empty rows.
I tried with this value. contentHeight: 2800
The EventLimit is set to False.  As I want every events to be displayed.
Thanks for any help.
Answer: Have you tried to set the height to auto? Check to official doc.
I hope it helps. ;)
Comment: Sorry for the long delay to answer :-S.  I'm not on this project anymore so I cannot check back but the solution was something like this.  Thanks :-)


Adding the NOT_NULL constraint to an SQL column

Question: I'm trying to add the NOT_NULL constraint to a column in an SQL h2 database, using
ALTER TABLE CHARACTERS ADD CONSTRAINT nn_PID NOT_NULL (PLAYER_ID);

This follows the pattern I found here:
ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

Except I change the constraint, table and column names. But I get this error:

Syntax error in SQL statement "ALTER TABLE CHARACTERS ADD CONSTRAINT NN_PID NOT_NULL[*] (PLAYER_ID) "; expected "., COMMENT, PRIMARY, INDEX, KEY, CHECK, UNIQUE, FOREIGN"; SQL statement:
  ALTER TABLE CHARACTERS ADD CONSTRAINT nn_PID NOT_NULL (PLAYER_ID) [42001-168] 42001/42001 (Help)

How can I add the NOT_NULL constraint?
Answer: From H2 SQL Grammar:
ALTER TABLE TEST ALTER COLUMN NAME SET NOT NULL;

So we can use:
ALTER TABLE CHARACTERS ALTER PLAYER_ID SET NOT NULL;

Comment: Just a question: According with H2 grammar...

        ALTER TABLE TEST ALTER COLUMN NAME NULL;

is also valid. it does not have any effect. Do you know why?


Generate random number with normal distribution?

Question: I encountered this question, where given it is a normal distribution, how do we go about it to generate a series of random numbers beside Monte Carlo?
The clue given was using exponential function.
Comment: If you're generating  a series of random numbers, ... how is that not in some fashion "Monte Carlo"? Can you more clearly explain what it's intended that the phrase rule out?
Comment: @snookvc Seems like a homework?
Comment: I was 'shown' a little that using exponential function to generate the numbers instead.
Comment: Not homework. More of conversation form
Answer: Assuming you want to generate random numbers following the given normal distribution, a basic way would be to do Inverse Transform Sampling; the basic idea of which is to feed standard uniform random numbers to the inverse Cumulative Distribution Function (CDF), which in the case of a (for example standard) normal distribution is:
$ \Phi(x) = \frac{1}{\sqrt{2\pi}} \int_{- \infty}^{x} e ^ { \frac{-t^2}{2} } dt$
Now the CDF of the normal distribution does include an exponential function as your hint suggests. However, it is in the form of an intractable integral; meaning that it cannot be expressed by elementary functions and you should compute it with approximation methods. Besides, you would still have to compute the inverse of the above function. Take a look at Quantile function in the same Wikipedia page.
So if the discussion is more high-level and theory-driven, you can stop at the artificial closed form of the normal CDF and say "we feed standard uniform random numbers to the inverse of this function". But practically, you would have to tackle the integral with approximation methods\.


Is is possible to evaluate $\int \frac{1-\text{sech}(\pi x)}{x} \, dx$ to some reasonable form?

Question: Is it possible to evaluate this integral to some reasonable formula?
$$\int \frac{1-\text{sech}(\pi  x)}{x} \, dx$$
I used integration by parts and got this result:
$$\int \frac{1-\text{sech}(\pi  x)}{x} \, dx=-\frac{2}{\pi} \int \frac{\tan ^{-1}\left(\tanh \left(\frac{\pi  x}{2}\right)\right)}{x^2} \, dx+\log (x)-\frac{2 \tan ^{-1}\left(\tanh \left(\frac{\pi  x}{2}\right)\right)}{\pi  x}$$
Hoping for simplifying somehow $\tan ^{-1}\left(\tanh \left(\frac{\pi  x}{2}\right)\right)$ but without any success.
Comment: As Einstein could have said, the cocept of *some reasonable formula* is very relative. Nice problem. Cheers :-)
Comment: Seriously updated !
Comment: @TymaGaidash. I changed a lot of things using the hypergeometric function and deriving the reccurences. I think it is cleaner now. What do you think about my anwer ? Your is nice.
Comment: @ClaudeLeibovici I have posted a bit of feedback in your question.
Answer: One method is to use the series expansion for $\text{sech}(x)$ in the form
$$ \text{sech}(x) = \sum_{n=0}^{\infty} \frac{E_{2n} \, x^{2n}}{(2n)!} \hspace{10mm} |x| < \frac{\pi}{2}.$$
This leads to
\begin{align}
I &= \int \frac{1 - \text{sech}(\pi x)}{x} \, dx \\
&= - \sum_{n=1}^{\infty} \frac{E_{2n} \, \pi^{2n}}{(2n)!} \, \int x^{2n-1} \, dx \\
&= - \sum_{n=1}^{\infty} \frac{E_{2n} \, (\pi \, x)^{2n}}{(2n) \, (2n)!} + c_{0}
\end{align}
for $|x| < \frac{1}{2}$.
Comment: How about for complex x or at least |x|$\ge\frac12$? Also is $E_y$ the yth Euler Number or something else?
Comment: Nice, although very limited convergence. I need it also for larger real `x`.
Answer: Here is a solution with justified steps at the end:
$$\mathrm{\int\frac{1-sech(\pi x)}{x}dx=ln(x)-\int \frac{sech(\pi x)}{x}dx=ln(x)-2\int \frac{1}{1-\left(-e^{2\pi x}\right)}\frac{e^{\pi x}}{x}dx=ln(x)-2\int \frac{e^{\pi x}}{x} \sum_{n=0}^\infty \left(-e^{2\pi x}\right)^n=\sum_{n=0}^\infty(-1)^n\int\frac{e^{(2n+1)\pi x}}{x}dx= \boxed{\mathrm{ C+ln(x)-2\sum_{n=0}^\infty(-1)^n Ei((2 n+1) π x)}}, \left| -e^{2\pi x}\right|<1\implies \boxed{\mathrm{Re(x)<0}}}$$

Integrate the reciprocal function.
Use the main definition of the hyperbolic secant function and use partial fractions.
Use the Best Friend Geometric Series expansion
Rearrange and factor using algebra and integrating term by term.
Use the definition of the Exponential Integral function
Simplify and add constant of integration.
First please see What is the integral of $\frac1x$?. Note the ln(x) is not a typo. The absolute value bars would cause
the complex numbers to be calculated wrongly. This means the negative signs must cancel for x$< 0$ in integration , for example:
$\mathrm{a,b\ge0:ln(-b)-ln(-a)=ln\left(\frac
{-b}{-a}\right)=ln(b)-ln(a)=ln|-b|-ln|-a|}$

For an example see this computation and this other computation for a sum representation of:
$$\mathrm{\int_{-1}^{-1-3i} \frac{1-sech(\pi x)}{x}dx= \frac{ln(5)+ln(2)}{2}+tan^{-1}(3)i-2i\pi -2\sum_{n=0}^\infty \left[(-1)^n\big(Ei((-1-3i)(2n+1)\pi )-Ei(-(2n+1)\pi )\big)\right]=1.12618…+1.25671…i}$$
Notice that the function is odd, so you do not necessarily need $\mathrm{Re(x)>0}$. Please correct me and give me feedback!
Comment: The convergence here is for all $Re(x)<0$. This is also the simplest answer in terms of character usage.
Comment: $Ei(x)$ is exponential integral... so you just replaced one integral with sum of infinite integrals.
Comment: @azerbajdzan Yes it works. Please click the [Computation](https://www.wolframalpha.com/input/?i=ln%28-1-3sqrt%28-1%29%29-ln%28-1%29+-2sum+%28%28-1%29%5En%28Ei%28%28-1-3sqrt%28-1%29%29%282n%2B1%29pi+%29-Ei%28-1%282n%2B1%29pi+%29%29%29+from+n%3D0+to+200) [links](https://www.wolframalpha.com/input/?i=integral+%281-sech%28pix%29%29%2Fx+from++-1+to+-1-3+sqrt%28-1%29+). If Claude Leibovici used the hypergeometric function, then I do not see why I cannot use the [Ei function](http://specialfunctionswiki.org/index.php/Exponential_integral_Ei). I can write the Ei function as a sum if you want.
Comment: I am not saying that it does not work. Your formula works in its convergence range but I think that there might be formulas avoiding integrals and with much wider range of convergence.
Answer: Using the sequence of substitutions
$$\pi x=y \qquad y=2 \tanh ^{-1}(z) \qquad z=\sqrt w\implies \color{blue} {x=\frac{2 }{\pi }\tanh ^{-1}\left(\sqrt{w}\right)}$$
$$I= \int \frac{1 - \text{sech}(\pi x)}{x} \, dx= \int \frac{\sqrt{w}}{\left(1-w^2\right) \tanh ^{-1}\left(\sqrt{w}\right)}\,dw$$
$$\frac{\sqrt{w}}{\tanh ^{-1}\left(\sqrt{w}\right)}=1-\sum_{n=1}^\infty a_n \,w^n$$
Looking at sequence $A216272$ in $OEIS$
$$a_n=\frac 1 {2n-1}\sum _{m=0}^{2 n-1} \frac{2^{m+1} }{m+1} \binom{2 n-1}{m}\sum _{k=0}^{m+1} \frac{k!\,
   S_{k+m}^{(m)}\, \mathcal{S}_{m+1}^{(k)}}{(k+m)!}$$ where appear Stirling numbers of the first and second kinds.
The first coefficients $a_n$ are
$$\left\{\frac{1}{3},\frac{4}{45},\frac{44}{945},\frac{428}{14175},\frac{10196}{46777
   5},\frac{10719068}{638512875},\frac{25865068}{1915538625},\frac{5472607916}{4884
   62349375},\cdots\right\}$$
$$I=\frac{1}{2} \log \left(\frac{1+w}{1-w}\right)-\sum_{n=1}^\infty a_n \int \frac {w^n}{1-w^2}\,dw$$ with
$$J_n=\int \frac {w^n}{1-w^2}\,dw=\frac{w^{n+1} }{n+1}\,\, _2F_1\left(1,\frac{n+1}{2};\frac{n+1}{2}+1;w^2\right)$$ and the reccurences are simply
$$J_{2n+1}=J_{2n-1}-\frac{w^{2n}}{2n}\qquad \text{with} \qquad J_1=-\frac{1}{2} \log \left(1-w^2\right)$$
$$J_{2n+2}=J_{2n}-\frac{w^{2n-1}}{2n-1}\qquad \text{with} \qquad J_0=\tanh ^{-1}(w)$$
Now, integrating from $w=0$ to   $w=\frac 9{10}$ that is to say from $x=0$ to $x=\frac{2 }{\pi }\tanh ^{-1}\left(\frac{3}{\sqrt{10}}\right)$, numerical integration gives as a result $1.09693$.
Computing
$$K_p=\frac{1}{2} \log \left(\frac{1+w}{1-w}\right)-\sum_{n=1}^\infty a_n\, J_n$$ the results are
$$\left(
\begin{array}{cc}
p & K_p \\
 10 & 1.09969 \\
 20 & 1.09725 \\
 30 & 1.09698 \\
 40 & 1.09694 \\
 50 & 1.09693
\end{array}
\right)$$
Comment: I guess you forgot those `arctanh` and `arctan` functions in the last line. The convergence is only in `|z|<1`.
Comment: @Claude Just to verify, is the convergence only for |z|<1; it seems like the hypergeometric function should impact the rate? You should also post the entire answer without any substitutions. It is a resourceful answer.
Answer: This is exact formula with (if I am not mistaken) globally convergent series:
$$\frac{1-\text{sech}(\pi  x)}{x}=\frac{1}{x}-\frac{4}{\pi  x} \sum _{n=0}^{\infty } \frac{(-1)^n (2 n+1)}{(2 n+1)^2+4 x^2}$$
So we have:
$$\int \frac{1-\text{sech}(\pi  x)}{x} \, dx=\frac{2}{\pi } \sum _{n=0}^{\infty } \frac{(-1)^n (2 n+1) \log \left((2 n+1)^2+4 x^2\right)}{(2 n+1)^2}$$
If someone is interested how I found these results - I used some of formulas from this wolfram site page and from Partial fraction expansion section of Wikipedia page on Trigonometric functions.
Comment: Lots and lots of manipulation, I have no time to write it all here. I am trying to derive another variant of formula now.
Comment: @Tyma Gaidash: Even simpler formula added...
Comment: What is the inspiration for the problem? Thanks.


How to get new data from database (php) using ajax

Question: I am trying to get new content from database with php, here is the code:
<?php
if($row['permalink'] == $_GET['contents']){
?>

<?php echo $row['title']; ?>

<img style="" src="portfolio/<?php echo $row['first_img']; ?>.jpg">

<?php
}
}
?>

So that works fine. So if I click on  then that would change the above content. However, I am try to figure hour how to get the result with jquery so that I do not have to reload the page.
I have managed to come this far:
$("#thums").click(function(){
$.ajax({ url: 'index.php',
data: {permalink: 'listaker'},
type: 'get',
success: function(output) {
$('#workproject').html(output);
}
});
});

But this loads the entire page from the start. is there a way that I can only reload the workproject id only. Or any other way to get this to work
Thanks
Comment: Is the `#thumbs` element a link? If that is the case you should `return false;` from the click handler. You should replace the `#workproject` element like this `$('#workproject').replaceWith(output);`
Comment: but the output is the fulll page, how can I remove bits from it
Answer: Try this
$('#workproject').load('index.php?permalink=listaker #workproject');

instead of your $.ajax() code


Definition of multiplication of complex numbers

Question: I know that given two complex numbers $z_1 = a + bi$ and $z_2 = c + di$, the multiplication of these two numbers is defined as
$$
z_1*z_2 = (ac - bd) + i(ad + cb)
$$
I also know that I can easily derive this formula by applying the distributive property of multiplication and considering $i^2 = -1$.
But $i^2 = -1$ is a consequence of the definition of multiplication.
So, the question is: How mathematicians defined the multiplication of complex numbers whether they didn't know the value of $i^2$?
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Answer: Indeed, $i^2=-1$ is coherent with the definition of multiplication, but things appeared in the reverse order.
While working on the resolution of algebraic equations (roots of polynomials), the need arose to consider square roots of negative numbers. Hence the "imaginary" symbol $i=\sqrt{-1}$, which is enough to represent the square root of any negative number $\sqrt{-a}$ as $\sqrt ai$.
From there, the algebra of complex numbers easily follows, treating $i$ as a variable and using the rule $i^2=-1$:
$$(a+bi)+(c+di)=a+bi+c+di=(a+b)+(c+d)i,$$
$$(a+bi)(c+di)=ac+adi+bci+bdi^2=ac+adi+bci-bd=(ac-bd)+(ad+bc)i.$$

Division is not much more difficult to invent, using a trick to turn the denominator to a real number,
$$\frac{a+bi}{c+di}=\frac{(a+bi)(c-di)}{(c+di)(c-di)}=\frac{(a+bi)(c-di)}{c^2+d^2}.$$

Now, what about the square root $\sqrt{a+bi}$ ?
Well, let us try and solve $a+bi=(c+di)^2=c^2-d^2+2cdi$, or $$a=c^2-d^2\\b=2cd.$$
Then,
$$a^2+b^2=c^4-2c^2d^2+d^4+4c^2d^2=c^4+2c^2d^2+d^4=(c^2+d^2)^2,$$
so that
$$c^2=\frac{\sqrt{a^2+b^2}+a}2,\\d^2=\frac{\sqrt{a^2+b^2}-a}2.$$
As you can see, $c$ and $d$ are always real numbers, so that no new symbol needs to be introduced to take square roots. From the last formulas, we have $$\sqrt i=\frac{1+i}{\sqrt2}.$$
Answer: Being fairly new to the site I'm not sure if I can reference a book but there is an excellent text called Visual Complex Analysis by Tristan Needham which explains the origin of complex numbers as a leap of faith required to make a general solution to the cubic equation work. Early mathematicians found that if only they could suppose the existence of this imaginary square root of -1 then they could happily cancel some terms and give the correct solution. It is not as many people suppose to give the equation
$$
x^2 + 1 = 0
$$
a solution because mathematicians could see that it didn't need one. Yves' answer is more to the point but I heartily recommend you check out this book for understanding and fun.
Comment: Whatever the roundabout historical path to complex numbers might have been, after they emerged, theoretical mathematicians didn't wait for a motivating application to go looking for other neat number systems in the same spirit, leading to quaternions and octonions before that trick stopped working.
Answer: I think the best answer to your question is to distinguish between the historical order in which information developed and the logical order in which that information is now presented.
In the case of complex numbers, the historical order is that people imagined a square root of $-1$, gave it a name $i$, and proceeded to do arithmetic and algebra (and even calculus) with it, using the same computational rules that they already knew for real numbers.  In particular, those rules led to the general formula for multiplication that you quoted in the question.
In a rigorous modern presentation of the complex number system, one sets out, right at the beginning, the definitions of the arithmetical operations, including the general formula for multiplication.  Then the fact that $i^2=-1$ emerges as just a simple special case of the general definition.
The distinction between the order of discovery and the order of presentation is not a special situation for the complex numbers.  For example, in plane geometry, many facts were known before Euclid systematized the subject and deduced vast numbers of facts from just a few axioms. The axioms precede the theorems in a logical development, but that does not mean that the axioms were discovered (and explicitly stated) before the theorems were.
Answer: To solve equations, we came up with equations like $x - 1 = 0$, what is $x$?, and the naturals solved them easily. Now, what about $x + 1 = 0$? So we need negative numbers. Wait, what about $2x = 1$? So we need rational numbers. Finally, what about $x^2 = 2$? So we need irrational numbers.
Finally, what about $x^2 = -1$? So we need to invent the "imaginary" numbers to solve it.
Pairs of numbers. Now, we define a new number system, only now there are always pairs of numbers. Then go through explaining how addition and multiplication work.
Then we show that in this system, we have  $(0,1)\times (0,1) = (-1,0)$, i.e., we have defined a new system, under which it makes sense to say that $\sqrt{-1} = i$, when $i=(0,1)$. And that's really all there is to imaginary numbers: a definition of a new number system, which makes sense to use in most places. And under that system, there is an answer to $\sqrt{-1}$.
So we have the following definitions: $$(a, b) + (c, d) = (a+c, b+d)$$ $$(a, b)\times (c, d) = (ac-bd, ad+cb)$$

For instance, the programming language Python implements the complex numbers and their algebraic operations. Maybe you can see a good reference in its source code.
Answer: By definition $i^2 = -1$. Your concern is about how can one even speak of "$i*i$" at all without having defined the operator "$*$". The answer is: We don't care for now what "$*$" is, as long as there will be a "$*$" product that satisfies $i*i = -1$ and generalizes the notion of product in $\mathbb R$, i.e., $a*c = a \cdot c$, where $a,c \in \mathbb R$ and "$\cdot$" is the real product.
Now you define what is a complex number, and that you can represent them as $z = a + i b$. On top of that some brilliant person defined once the product of two of these numbers to follow also the commutative, associative and distributive laws: $z_1*z_2 = a*c + i(a*d + c*b) + (i*b)*(i*d) = a \cdot c + i(a \cdot d + c \cdot b) + (i*i)*(b \cdot d)$.
Since we defined $i^2 = i*i = -1$, we obtain your result: $z_1*z_2 = (ac - bd) + i(ad + cb)$, as you already know. So, to answer your question, $i^2 = -1$ does not follow from the product rule, but it precedes the notion of the product in $\mathbb C$, we established a definition of "$*$" that is consistent with it.
Everybody agreed on this definition because of the "nice"$^{1}$ properties, e.g. $\mathbb C$ is a ring that generalizes $\mathbb R$, you can represent complex numbers geometrically by vectors in $\mathbb R^2$ and, the nicest property for me, you can divide these vectors by each other!
$^{1}$: Let me elaborate on what is meant by "nice". Let me first give you an example of an "ugly" complex product: Define an operator $**$ such that $z_1 ** z_2 = ac-bd$ and call it "complex quasi-product", it also fulfills $i ** i = -1$ and, moreover, it is consistent with the product of two real numbers!: $z_1 * z_2 = a c$. No one can stop you from using it as a complex multiplication as well, but it lacks of many "nice" (geometrical or algebraic) properties, as, for example, the quasi-product of a real times a complex number won't be to "stretch" the complex vector (in the $\mathbb R ^2$ representation).
Comment: I'm not doing the common mistake of assuming some proposition A that implies some result B, and then you use B to "show" A. I told I know how to obtain z1∗z2=(ac−bd)+i(ad+cb) if I already know that i² = -1. But what I want to know is: how was defined the multiplication of complex numbers without that information.
Comment: I wasn't willing to be mean to you. I think now I got your point, so I expanded the answer.
Answer: I came up with my own derivation of multiplication in the complex field. Maybe it will gain us insight into how earlier mathematicians viewed this subject.
We start with the following question: Find $x$ such that $x^2 +1=0$. Now there does not exist such $x\in\mathbb{R}$ since $x^2 >0,\forall x\in\mathbb{R}$ is an immediate consequence of the Field axioms. Perhaps considering different fields might shine some light on this problem. Let's consider $\mathbb{R}^2$. We try and define addition and multiplication to satisfy the Field Axioms.
Choose $(a,b)\in\mathbb{R}^2$ and $(c,d)\in\mathbb{R}^2$. Then $(a,b)+(c,d)=(a+c,b+d)$ satisfies all the addition axioms. Also, we have that the additive identity element is $\left(0,0\right)$ as a consequence of that definition.
Now, we try and define multiplication. First, we start with defining it as $(a,b)(c,d)=(ac,bd)$. However, $(3,0)\ne(0,0)$ does not have a multiplicative inverse. Therefore, that particular definition breaks the multiplicative inverse Field axiom. It is now clear that any sort of definition of multiplication must involve addition and integrate both elements otherwise elements of $\mathbb{R}^2$ such as $(3,0)$ will always not have an inverse.
We now try the following definition. Define $(a,b)(c,d)=(ac+bd,ad+bc)$. Immediately, we find that the multiplicative identity is $(1,0)$ as a result of that definition. So far good, let's try and find a general equation for the multiplicative inverse of $(a,b)$. We must have that $ac+bd=1$ and $ad+bc=0$. We then end up with $c=\dfrac{a}{a^2-b^2}$ and $d=\dfrac{-b}{a^2-b^2}$. However, this can still break because we are not guaranteed that $a^2 -b^2\ne0$.
We finally end up with the following definition. Define $(a,b)(c,d)=(ac-bd,ad+bc)$. This satisfies all the multiplication Field axioms.
This Field we defined has a solution for $x^2 +1=0$. We have that $(0,1)^2+(1,0)=(-1,0)+(1,0)=(0,0)$. We call this new Field $\mathbb{C}=\mathbb{R}^2$.


Create a circular bitmap in Android 2.3

Question: I need to create a completely round image in Android. I've got the following code which works in newer version of Android, but in older versions (2.3), it is just a black circle:
<code>    Bitmap avatar = null;
    if (avatarUrl == null || avatarUrl.equals("")) {
        avatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_no_avatar);
    } else {
        avatar = HttpClientHelper.downloadImage(avatarUrl);
    }

    if (avatar == null) {
        // No avatar? Load the default one and use it instead
        avatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_no_avatar);
    }

    float width = 50; // avatar.getWidth();
    float height = 50; // avatar.getHeight();
    float ratio = (float)avatar.getWidth() / (float)avatar.getHeight();

    // Scale the avatar to the area that it needs to fit into
    avatar = Bitmap.createScaledBitmap(avatar, (int)(width * ratio), (int)height, true);

    // Turn the avatar into a round image
    Bitmap circleBitmap = Bitmap.createBitmap((int)width, (int)height, Bitmap.Config.ARGB_8888);

    BitmapShader shader = new BitmapShader(avatar, TileMode.CLAMP, TileMode.CLAMP);
    Paint paint = new Paint();
    paint.setShader(shader);

    RectF rect = new RectF(0.0f, 0.0f, width, height);
    Canvas c = new Canvas(circleBitmap);
    c.drawCircle(width / 2, height / 2, (width / 2) - 1, paint);
</code>
Is there something different I should do with 2.3 to make this work?
Answer: Use this
<code>              float width = 50; // avatar.getWidth();
                  float height = 50; // avatar.getHeight();
                  float radius = 45;
                Bitmap bmpBG = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);

            Canvas c = new Canvas(bmpBG);

//YOU CAN ADD SHADER FOR EFFECTS

            Paint p = new Paint();
            p.setAntiAlias(true);
            p.setDither(true);

            p.setColor(Color.RED);//SET YOUR COLOR HERE

            c.drawCircle(width/ 2, height/ 2,
                    radius , p);

    //NOW USE bmpBG
</code>
Answer: This must be a bug in 2.3. I was previously setting the round bitmap as the ImageView background which caused the black circle. When I set it as the foreground, the problem went away.
Again, this only happens with 2.3. After 3.0 this problem no longer exists.

Create a circular bitmap in Android 2.3


Suggestion about writing a Java class which executes Test classes in the other modules of project

Question: I am using intellij idea 11 to develop a java project.
I have various modules under the project e.g. com.a.b.c which have src and test folders. The test folders are test route folders of the project. There are various test cases under that folders.
Now i need to write a new module which has a java class that invokes the test cases in various modules. I am not finding a way.
I have created a module e.g. com.a.b.testsuite and have added dependencies on those other modules where respective test cases are present.
Please suggest me a way further? Can i use JUnitCore class? i am not sure how to use that.
Comment: why reinvent the wheel? use maven to build your project and it'll run the tests in each module as part of the build
Comment: You can rate your code coverage using a cobertura plugin and maven.

http://mojo.codehaus.org/cobertura-maven-plugin/
Comment: Agreed; what's the ultimate goal?
Comment: i want to calculate the code coverage using intellij code coverage tool. So, i thought having a program to run all the test cases can help me have one program which runs test cases for all modules and gets the code coverage.
Answer: As everyone else has suggested - I would suggest converting your project to a Maven project.
Then create a profile in your POM and use the cobertura plugin something like this:
<code><profile>
        <id>testcheck</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>cobertura-maven-plugin</artifactId>
                    <version>2.5.1</version>
                    <configuration>
                        <check>
                            <branchRate>0</branchRate>
                            <lineRate>0</lineRate>
                            <haltOnFailure>true</haltOnFailure>
                            <totalBranchRate>90</totalBranchRate>
                            <totalLineRate>90</totalLineRate>
                            <packageLineRate>0</packageLineRate>
                            <packageBranchRate>0</packageBranchRate>
                        </check>
                    </configuration>
                    <executions>
                        <execution>
                            <phase>verify</phase>
                            <goals>
                                <goal>clean</goal>
                                <goal>check</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</code>
this really is the best way to go. Especially since each module you include in your project can also have it's own POM, with it's own coverage rates and checks.


Trocar vogais por "*"

Question: Estou fazendo um programa para substituir as vogais de um frase digitada por * e mostrar para o usuário:
#include<stdio.h>
#include<string.h>
#define TAM 50

int main(){
    char f[TAM];
    int t_f,n;
    printf("Digite a frase:\n");
    fgets(f,TAM,stdin);
    t_f=strlen(f);
    for(n=0;n<=t_f;n++){
        if((f[n]=='A') ||(f[n]=='a')|| (f[n]=='E')|| (f[n]=='e') || (f[n]=='I') || (f[n]=='i') || (f[n]=='O') || (f[n]=='o') || (f[n]=='U') || (f[n]=='u')){
            f[n] ='*';
        }
    }
    for(n=0;n<=t_f;n++){
        printf("Frase criptografada:%s",f[n]);
    }
    return(0);
}

Não estou entendendo porque o programa não roda e a mensagem "segmentation fault (core dumped)" está aparecendo.
Comment: Por que você faz um `for` percorrendo `n` para exibir a frase final?
Comment: Aqui no SO br tem dezenas de respostas para esse problema, dê uma olhada aqui www.shorturl.at/flPU3
Comment: Isso aqui te ajuda: https://pt.stackoverflow.com/questions/52555/erro-segmentation-fault-core-dumped
Comment: Note que em C um array (que pode ser uma string: um array de caracteres seguido do caractere terminador '\0') os índices variam de 0 até o tamanho-1. Seu comando `for` considera uma posição a mais. Este é um erro mas não a causa do problema relatado que está no último printf.
Answer: Esse trecho de código não faz sentido:
for(n=0;n<=t_f;n++){
    printf("Frase criptografada:%s",f[n]);
}

Você está percorrendo a frase inteira para exibir caractere a caractere, mas coloca como printf o texto "frase", indicando que quer exibir a frase inteira, adiciona %s para exibir uma cadeira de caracteres, mas passa como parâmetro do printf o valor f[n] que é um caractere. Em metade do código você dá indícios que quer exibir caractere por caractere e em outra metade você dá indícios que quer exibir a frase inteira. No fim, misturou tudo.
Para exibir o resultado, basta fazer:
printf("Frase criptografada: %s", f);

Pois f já é uma sequência de caracteres.
Comment: Entendi. Muito Obrigada :)

Trocar vogais por "*"


Get value of enum by reflection

Question: I have an enum declared like this:
public enum Mode{
  RUNNING("SytemRunning"),
  STOPPED("SystemStopped"),
  IDLE("tmpIdle");

  public static String key;

  private Mode(String key){
    this.key = key;
  }
}

Now, I want to get out the keys(SystemRunning, SystemStopped, tmpIdle) for this enum by reflection:
Class<?> c = Class.forName("Mode");
Object[] objects = c.getEnumConstants();
// now this is not what I want, but almost
for(Object obj : objects){
  System.out.println("value : " + obj);
}

the output is:
RUNNING
STOPPED
IDLE
However, I'd like to have the Strings SystemRunning, tmpIdle etc..
Thank you very much in advance.
Comment: Why is `key` `static`?
Comment: http://stackoverflow.com/questions/5316311/java-enum-reverse-look-up-best-practice does such a thing (without need for reflection). A small error in your code: remove `static` for field `key`. Knowing `Mode.values()`?
Answer: Firstly, you need to make your key a non-static variable.
private String key; // I made it private on purpose

Then you need to add a getter method in your enum which will return the key
public String getKey() {
    return key;
}

and then change your for loop to something like this.
for (Object obj : objects) {
    Class<?> clzz = obj.getClass();
    Method method = clzz.getDeclaredMethod("getKey");
    String val = (String) method.invoke(obj);
    System.out.println("value : " + val); // prints SytemRunning, SystemStopped and tmpIdle
}

Answer: Add a method toString() that returns your key, then it will work.
Your 'key' property shouldn't be static.
If you know that all your enums have a key property, you can ask for it directly by reflection too.
public enum Mode{
  RUNNING("SytemRunning"),
  STOPPED("SystemStopped"),
  IDLE("tmpIdle");

  public String key;

  private Mode(String key) {
    this.key = key;
  }
  public String toString() {
    return this.key;
  }
}

Get 'key' with reflection:
Class<?> c = Class.forName("Mode");
Object[] objects = c.getEnumConstants();
// now this is not what I want, but almost
for(Object obj : objects) {
  try {
    Field keyField = obj.getClass.getDeclaredField("key");
    keyField.setAccessible(true); // if it is private for example.
    System.out.printn("value : " + keyField.get(obj);
  } catch (NoSuchFieldException e) {
    // fallback to toString()
    System.out.println("value : " + obj);
  }
}

Comment: this should be the correct answer as it didn't introduce additional getter
Answer: There is no point using reflection for this:
public interface EnumWithValue<T> {
    T getValue();
}

public enum Mode implements EnumWithValue<String> {
    RUNNING("SytemRunning"),
    STOPPED("SystemStopped"),
    IDLE("tmpIdle");

    private final String value;

    private Mode(String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return value;
    }
}

public void test() {
    try {
        Class<? extends EnumWithValue<String>> clazz = (Class<? extends EnumWithValue<String>>) Class.forName("Mode");
        EnumWithValue<String>[] values = clazz.getEnumConstants();

        for (EnumWithValue<String> enumWithValue : values) {
            System.out.print(enumWithValue + " = " + enumWithValue.getValue());
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ConverterEnum.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Get value of enum by reflection


Python metaclass use with object instantiation

Question: With following code, I expect the output to be:
# meta.__new__
# meta.__new__
# meta.__init__
# Before instantiation of Entity
# meta.__call__
# __new__
# __init__
# __call__
#

Instead I got following output:
# meta.__new__
# meta.__new__
# meta.__init__
# Before instantiation of Entity
# meta.__call__
# __new__
# __init__
# Traceback (most recent call last):
#    File "test.py", line 39, in <module>
#       e(3,4)
# TypeError: 'NoneType' object is not callable

class MyMetaClass(type):
    def __new__(cls, name, bases, dct):
        print 'meta.__new__'
        return super(MyMetaClass, cls).__new__(cls, name, bases, dct)

    def __init__(cls, name, bases, dct):
        print 'meta.__init__'
        super(MyMetaClass, cls).__init__(name, bases, dct)

    def __call__(self, *more):
        print 'meta.__call__'
        super(MyMetaClass, self).__call__(*more)

class Entity(object):
    __metaclass__ = MyMetaClass

    def __new__(cls, *args, **kwargs):
        print '__new__'
        return super(Entity, cls).__new__(cls, *args, **kwargs)

    def __init__(self, x, y):
        print '__init__'
        self.x, self.y = x, y

    def __call__(self, x, y):
        print '__call__'
        self.x, self.y = x, y

if __name__ == '__main__':
    print 'Before instantiation of Entity'
    e = Entity(1,2)
    e(3,4)

Comment: What do you actually want the metaclass to *do*? Why implement `__new__` and `__init__` and `__call__`?
Answer: Note that MyMetaClass.__call__, which is being invoked on creation and instantiation of e, doesn't actually return anything, hence e is None afterwards. The minimal fix is therefore to:
class MyMetaClass(type):

    ...

    def __call__(self, *more):
        print 'meta.__call__'
        return super(MyMetaClass, self).__call__(*more)
      # ^ add return

But without an explanation of why you've implemented __new__ and __init__ and __call__ on the metaclass, including a less abstract example, it's hard to provide advice on what the most appropriate fix might be.


How can I generate all odd numbers less than N which are divisible by 5?

Question: Given a number $N$, how can I write down a summation of all odd numbers divisible by 5 which are also less than $N$?
For instance, if $N = 27$ then I am looking for a series to generate $5+15+25$.
Its pretty clear the series looks like
$$\sum_{k=0}^{???} 5(2k+1)$$
but I am having trouble with that upper index.  It must involve flooring to the nearest integer divisible by 5 (maybe write this as $\lfloor N \rfloor_5$ perhaps there is better notation).
Answer: You want $5(2k+1) \le N < 5(2(k+1)+1)$, which means $k \le \frac{N/5-1}{2} < k+1$; now take floors.
Answer: You want $5(2k+1) \leq N$. Thus
$$k \leq \frac{N}{10}-\frac{1}{2}.$$
Thus $k=\left\lfloor \frac{N}{10}-\frac{1}{2}\right\rfloor$.
Answer: We have to find the sum of all odd numbers less than N and divisible by 5
where N is given. For a given N you can find the number of odd numbers divisible
by 5 is $$\left[\frac{N}{5}\right]-\left[\frac{N}{10}\right]$$ So the reqired sum is equal to $$\sum_{i=1}^{\left[\frac{N}{5}\right]-\left[\frac{N}{10}\right]}\left(5+10(i-1)\right)$$.


Proving sequence $x_n= \sum_{k=1}^{n} \frac{1}{k}$ diverges

Question: Proving sequence $x_n= \sum_{k=1}^{n} \frac{1}{k}$. For $n \geq 2 , \frac{1}{2} \geq \frac{1}{n}$.
so i write $x_n > 1 + \frac{1}{2} + \frac{1}{2} + \frac{1}{2} + ... + \frac{1}{2}$.
$x_n > 1 + \frac{n-1}{2}$. Now,  $b_n = \frac{n-1}{2} $,  $b_n$ diverges $\rightarrow \infty$
Comment: $x_n > 1 + \frac{1}{2} + \frac{1}{2} + \frac{1}{2} + ... + \frac{1}{2}$ is wrong.
Comment: What you get is $x_n <1 + \frac{1}{2} + \frac{1}{2} + \frac{1}{2} + ... + \frac{1}{2}$ which doesn't help.
Comment: @geetha290krm $n \geq 2, \frac{1}{2} \geq \frac{1}{n}$
Comment: Look for divergence of harmonic series, this series (i.e sequence of partial sums) is bound to show up.
Comment: $\displaystyle \int_1^n \frac{1}{x} ~dx = \log(n).~$ Contrast this with the union of tall rectangles, that completely cover the corresponding region under the curve, where, for $~k \in \{1,2,\cdots,n-1\},~$ the rectangle from $~k~$ to $~k+1~$ is of height $~\dfrac{1}{k}.$
Comment: @coffeemath but x_n is bigger than a sequence which diverges to infinity..
Comment: @SophieClad You showed $\frac{1}{2} \ge \frac{1}{k}$ for any $k\ge 2$. Sum both sides from $k=2$ to $n$ to see that $$
\underbrace {\frac{1}{2} + \frac{1}{2} +  \ldots  + \frac{1}{2}}_{(n - 1)\text{ times}} \ge x_n  - 1
$$ So you just showed that $x_n$ is at most a sequence that tends to infinity, but that could be true even if $x_n$ was convergent. You need a diverging lower bound, not an upper bound for $x_n$.
Comment: @Garyi think inequality sign is on incorrect
Comment: Yes, it is incorrect in your post. If $1/k$ is smaller than $1/2$ for any $k\ge 2$ then the sum of the $1/k$s is also smaller than the sum of the $1/2$s. Think about it. Why would the direction of the inequality suddenly be reversed?
Comment: Try it for a concrete $n$, say $n=4$. $1/2 \ge 1/2$, $1/2 \ge 1/3$ and $1/2 \ge 1/4$. Then $1/2+1/2+1/2 \ge 1/2+1/3+1/4$.
Comment: This is the correct way to do it with $1/2$s: https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#Comparison_test
Comment: @Gary thanks.... i quite see
Answer: The strategy to show this typically involves this comparison of the sum:
$$\sum_{k=1}^{2^n}\frac{1}{n}=1+\frac{1}{2}+\left(\frac{1}{3}+\frac{1}{4}\right)+\left(\frac{1}{5}+\frac{1}{6}+\frac{1}{7}+\frac{1}{8}\right)+\cdots\geq 1+\frac{1}{2}+\left(\frac{1}{4}+\frac{1}{4}\right)+4\cdot\frac{1}{8}+\cdots$$
$$=1+\frac{1}{2}+\frac{1}{2}+\frac{1}{2}\cdots$$
This strategy was first used by Nicole Oresme around 1350.
Alternatively, on a similar process on every even term after $x_2$, you can show the sum is greater than or equal to $\frac{1}{2}+x_n$, so the sum diverges.


SkipPolicy do Spring Batch, para que serve?

Question: Gostaria de saber para que serve o SkipPolicy que é setado no StepBuilderFactory.
Se possível gostaria de alguma documentação explicando.
Comment: Poderia dar algum exemplo do contexto em que você está usando?
Answer: De acordo com a documentação, uma classe que implementa a interface SkipPolicy deve determinar um critério para quando um processamento (Step) deve ser executado, ou não. A interface possui o método boolean shouldSkip(java.lang.Throwable t, int skipCount) throws SkipLimitExceededException que deve retornar true caso o Step deve continuar normalmente se a Throwable t for lançada durante a execução do passo, ou false caso contrário. Já o parâmetro skipCount corresponde ao número de vezes que o passo foi pulado dada a execução atual.


Click and mouse cursor events are inverted when using VNC in my QT application

Question: I am programming a QT application which is deployed to a linux embedded system. It uses the TSLIB for touch screen, and a framebuffer VNC server. When I use the touch screen, it works just fine. However, when I use VNC, the mouse cursor on the VNC window presents a inverted x, and y axis. When I do the ts_test, I can clearly see that the touch screen generates events with the right axis coordinates, but the cursor on the VNC viewer generates mirrored coordinate events (I tried to use different VNC clients but I did not have success). Thus, this inverted axis problem happens only when using VNC. Seems like I can solve this problem in three different ways, that is:
1 - Through QT env variables, on which I could invert the axis coming from input events (as in the documentation https://doc.qt.io/qt-6/inputs-linux-device.html).
2 - Through linux kernel, on which I could invert the output of my specific dev input event coming from the VNC (which seems to be /dev/input/Event1, could I get the exact device through a tslib command line?).
3 - Check if it is a framebuffer VNC server configuration problem (did some research but I could not find ways to do such configuration on my framebuffer VNC server).
Nonetheless, I've tried approach 1, by following the documentation mentioned, and by running the following commands (that did not work):
export QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS=/dev/input/Event1:invertx:inverty
export QT_QPA_EGLFS_DISABLE_INPUT=1
export TSLIB_TSDEVICE=/dev/touch0
export QT_QPA_EGLFS_HIDECURSOR=0
export QT_QPA_EGLFS_FORCE888=1
export QT_QPA_PLATFORM=eglfs
export QT_QPA_EGLFS_NO_LIBINPUT=1
$MY_APPLICATION_PATH -platform eglfs -plugin tslib

For approach two, I've googled how to invert x, and y coordinates coming from /dev/input devices, but still could not get it.
Could anybody help me solve this?
Answer: QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS is for the evdev plugin according to the docs. You should probably use QT_QPA_EGLFS_NO_LIBINPUT for that to be taken into consideration. However, the original problem is unclear to me, sorry.
Comment: Hey @Luca Carlon, I just set the env variable QT_QPA_EGLFS_NO_LIBINPUT to 1, and I still have the same axis inverted behavior. I've just updated my question with all QT env variables that I am setting, in case you can help.
Comment: Also, I've also tried to run my application with the evdevtouch plugin, by running ```$MY_APPLICATION_PATH -platform eglfs -plugin evdevtouch``` and it still did not work.
Comment: Are you sure the path is correct? /dev/input/Event1 with a capital letter?
Comment: It is with lower capital, but still did not work
Comment: QT_DEBUG_PLUGINS may be useful for you to confirm the evdev plugin is being used.


xenserver 5.6 without raid

Question: The domU in my environment is a xenserver 5.6 fp1 installed on a regular desktop with intel board and i3 processor.  I have 8GB or RAM installed and 1 500GB SATA HDD.
Obviously, i don't have RAID and i was wondering whether it would have an effect on the VM disk read/write speed if i increase the number of drives as local SR.
Is it just more storage i'd be gaining and zero effect on the VM disk speed?
Thanks!
Answer: It depends on what RAID level you use and your usage characteristics.
If you converted your single slow consumer drive setup into a RAID 0 array it's be faster yes but would introduce a very significant risk of complete array failure.
If you converted it to RAID 1 then you may see some performance increase dependent on load type but would make your system more resilient to failure.
If you converted it to RAID 5 that would be stupid.
If you converted it to RAID 6 that would be ok but you're see writes taking longer.
If you convert it to RAID 10 you'd see performance and resilience benefits all round.
This site's for professional sysadmins, did you not think to search previously asked questions? if you'd searched for 'raid' you'd have been linked to THIS previous question which might have been more help to you and less of a duplication of effort for us.
Comment: Chopper3, I dont have raid and i cant create any sort of array with the 2 drives combined, the idea was just whether it would improve the vm disk speed with 2 drives (no array whatsoever) as an SR instead of one if i add another drive and attach it as second SR
Comment: Not a great question - ultimately we can only respond with "...it depends...", there's not enough information here.
Comment: seems like you're not getting the point. This is NOT raid related for me to have poorly researched in the first place, i have many raid scenarios that i've helped discuss in here even.   it's the opposite and it's never mentioned before. all im asking is whether or not the number of drives IN A NON RAID ENVIRONMENT would improve vm disk performance in xenserver.
Comment: And the answer is "it depends".
Comment: depends on what exactly?
Comment: How you intend to utilise a second disk.
Comment: i said that. just attach it as a local SR like the first one. xenserver 5.6 combines them into a shared one.
Comment: It depends, on the same bus then probably not.

xenserver 5.6 without raid


Cannot deserialize value of type `java.lang.Long` from Object value (token `JsonToken.START_OBJECT`) in JAX-RS PUT Endpoint

Question: I'm getting an error that no matter what I try doesn't seem to get fixed. In my eyes everything looks correct. This is my service for the endpoint
@PUT
    @Path("/{bookId}")
    public Response editBook(@PathParam("bookId") Long bookId, Book newBook) {

        if (!JWTTokenAuth.validateJwtToken(JWTTokenAuth.extractTokenFromHeaders(headers))) {
            return Response.status(Response.Status.UNAUTHORIZED).build();
        }

        Book book = bookDao.getBookById(bookId);
        if (book == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        book.setTitle(newBook.getTitle());

        bookDao.updateBook(book);

        return Response.ok().build();
    }

And this is my entity
@Entity
@Getter
@Setter
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;

    @OneToMany(mappedBy = "book")
    private List<Review> reviews;

}

When I try to hit the endpoint through postman (for example) http://localhost:8080/api/books/2
with the authorization setup correctly and my JSON payload set as this
{
    "title": "defgefgege"
}

I get this error and I think it has to do with the PathParam?
Cannot deserialize value of type java.lang.Long from Object value (token JsonToken.START_OBJECT)
at [Source: (io.undertow.servlet.spec.ServletInputStreamImpl); line: 1, column: 1
]
Comment: I don't think it's the PathParam. I think it's looking for `Long id` in `Book`.
Comment: @DavidConrad I had the parameter as query param before and it worked fine with the same payload. So I'm pretty sure it's the PathParam's fault
Answer: I suspect the problem is not in your Java code but in PostMan. Have you mist-typed the parameter in the URL or forgot to set it?
My guess is that PostMan is not sending this URL:
http://localhost:8080/api/books/2
but
http://localhost:8080/api/books/{bookID}
That would explain the error message you are seeing.
Answer: I've fixed the issue, which was that I was receiving an empty path parameter.
I had imported PathParam from jakarta.websocket.server.PathParam;
While it should have been from jakarta.ws.rs.PathParam;


Link tags in template file auto closing.

Question: I'm having an issue wrapping a link around some output in a template file.   I have the right template file; and I can put text like 'start here' and 'end here'  and it prints out where I want the 'a href' tag to start and end.
However when I put in the starting 'a href' it auto closes.   I can put in a 'div' and that doesn't auto close.   I've tried

  and although that html output looks right it doesn't work either.
I've also used at 'function l' but can't pass the $content in.
Any ideas how I can either stop the auto close, get the javascript to work or a function I can use to output the link but will except the content being passed in.
Here's my code
print '';
     print $field->content;
     print '';

Comment: Does the content that you are wrapping have an anchor tag inside it? This could be a hidden anchor that you will only see when inspecting source. I'm asking because you cant nest anchors.
Comment: If you wants whole  clickable. Instated of putting a "div" as wrapper you can write a css for your  tag. It will works as . just put a class and set the css property as display:block.
Comment: Can you mention the exact requirement because you can not write "href" attribute in  its for .
Comment: I'm trying to make a whole div clickable .
Comment: the 'a tag' auto closes, I don't know why it does this.  .  Otherwise the code would work fine.   so output is

my content
Comment: You will need to sanitize the $link variable if it's coming from a source you can't trust. A user can be a victim of XSS (cross site scripting). Check out [D7 handling text in a secure fashion](https://www.drupal.org/docs/7/security/writing-secure-code/handle-text-in-a-secure-fashion#s-in-practice]
Answer: The problem here was that there where links in the content being outputted.  Once I changed that the links stopped auto closing.
Answer: Use filter_xss on $field->content. You can filter out the anchor tags this way.


Good practice -- Should helper methods for strings extend the string class?

Question: I have some functions that work on strings for some business logic.
Should I put them as normal functions in helper files and access them as:
custom_function(my_var)
Or is it better to extend the string class and access them as:
my_var.custom_function
Comment: In general, avoid adding methods to core classes.  Use your helper methods instead. In a perfect world, ruby would support scoping mixins to specific scopes (e.g. class level/method level), but that will never happen.
Answer: I find extending built-in objects like that confusing. You move from project to project and wonder why you cannot do my_var.foo only to realize that foo was a function that your colleague wrote.
Just imagine you added extension methods indiscriminately. Now you have to copy a block of code from one project to another and spend time scratching your head about the extension methods.
Comment: Moreover, when two gems both try to define the same method on the same class (likely with subtly differing behaviours), bad things happen.  I've run into this on a couple of occasions (DataMapper and Garb both adding methods to Symbol being one that springs to mind).


Impressão usando Crystal Reports em WPF

Question: Eu estou com dificuldade em imprimir usando Crystal Reports no WPF, eu uso o mesmo sistema de impressão para um outro sistema e funciona normal, mas nesse sistema está aparecendo o seguinte erro...

Eu acredito que o erro esteja na fonte de dados que eu estou passando, pois se eu não envio os dados ele imprime normal...

DataSet

Crystal Reports
Comment: O erro era referente ao VS2015, ele estava conflitando com a versão do Crystal Reports que eu estou usando... Como era um projeto pequeno, eu refiz ele no VS2012...
Answer: O erro era referente ao VS2015, ele estava conflitando com a versão do Crystal Reports que eu estou usando... Como era um projeto pequeno, eu refiz ele no VS2012...

Impressão usando Crystal Reports em WPF