Run a void after an async void has been completed

Question: I am encrypting a file asynchronously,and after that I want to run a void to do some logic on the encrypted file. I want the compiler wait until the file has been encrypted completely.
So how can I wait for it to be completed? Have I to use "Task"?
Thanks.
public static async void AES_Encrypt(string path, string Password,Label lbl,ProgressBar prgBar)
    {
        byte[] encryptedBytes = null;
        FileStream fsIn = new FileStream (path, FileMode.Open);
        byte[] passwordBytes = Encoding.UTF8.GetBytes (Password);
        byte[] saltBytes = new byte[] { 8, 2, 5, 4, 1, 7, 7, 1 };
        MemoryStream ms = new MemoryStream ();
        RijndaelManaged AES = new RijndaelManaged ();

                AES.KeySize = 256;
                AES.BlockSize = 128;

                var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = key.GetBytes(AES.BlockSize / 8);

                AES.Mode = CipherMode.CBC;
        CryptoStream cs = new CryptoStream (ms, AES.CreateEncryptor (), CryptoStreamMode.Write);

        byte[] buffer = new byte[1048576];
        int read;
        long totalBytes = 0;

        while ((read = fsIn.Read (buffer, 0, buffer.Length)) > 0) {

            totalBytes += read;
            double p = Math.Round((double)totalBytes * 100.0 / fsIn.Length,2,MidpointRounding.ToEven);
            lbl.Text = p.ToString ();
            prgBar.Value = (int)p;
            Application.DoEvents ();
            await cs.WriteAsync(buffer,0,read);

        }
            cs.Close();
        fsIn.Close ();

                encryptedBytes = ms.ToArray();
        ms.Close();
        AES.Clear ();
        string retFile = path + ".cte";
        File.WriteAllBytes (retFile, encryptedBytes);
        Console.WriteLine ("ok");

    }

Comment: Thanks. I just use them for testing and debugging,I will remove them. I am new to using Streams. @HenkHolterman
Answer: You have no way of knowing when an async void method has completed.  That's exactly why you should virtually never be using an async void method.  The method should return a Task so that that Task can be used by the caller to determine when the method has finished, what the result(s) are (if applicable) and whether it was successful, cancelled, or faulted.


Javascript inheritance : How prototype chain works between native prototypes

Question: As we know everything in Javascript inherits from Object:

So if I create an object using constructor function like below:

function Rabbit() {
  this.color = 'White'
}

let obj = new Rabbit();

alert(Rabbit.__proto__ === Function.prototype)       //true
alert(obj.__proto__ === Rabbit.prototype)            //true
alert(obj.__proto__.__proto__ === Object.prototype)  //true

alert(Function.__proto__ === Object.prototype)  //false
alert(Object.getPrototypeOf(Function) === Object.getPrototypeOf(Object))  //true

The first 3 results make sense because obj inherits from Rabbit function which itself inherits from Function. But if Function inherits from Object then why is the 4th result False. Also why do both Object and Function have same prototype (last result)?
Can someone explain this behavior. Am i missing something here?
Comment: All (most of) the objects in your diagram inherit (indirectly) from `Object.prototype`, not from `Object`.
Comment: `Object` and `Function` are just like the `function f(args) { … }` in your diagram.
Answer: Problems like this are better explained with images (like the one in your question):

Legend:

   blue color = objects
   {} = simple object (+constructor name)
   Ⓟ = prototype object (+constructor name)

   magenta color = functions (ƒ + function name)

Basically, the __proto__ chain for functions is:
concrete function (e.g. Rabbit, Object or Function itself)
-> abstract function (aka Function.prototype)
-> Object.prototype
-> null

Comment: `f` and magenta color are functions, blue color are objects, `(P)` are objects that are prototypes,  `{}` is a simple object. `null` is null ;)
Comment: Wow thanks. That's a lot of valuable info in one picture. Can you comment on the parts a bit more. For example what is `f Object` vs `P Object` and similarly for Rabbit `{} Rabbit`, `f Rabbit` and `P Rabbit`. Also, what is the `f` here?
Comment: @VSX: the part after the `ƒ` is the function name. Just `ƒ` is a function without a name (anonymous). Your expression corresponds to two arrows from `ƒ Object __proto__` and `ƒ Function __proto__` to the anon function
Comment: The ultimate resource for questions like this is the standard: http://www.ecma-international.org/ecma-262/8.0 . It's not particularly user-friendly, but it does contain all the answers.
Comment: Don't wanna sound nit picky but i find that website really confusing. Can't even search for a particular keyword (the search on the top left doesn't do anything).
Answer: alert(Object.getPrototypeOf(Function) === Object.getPrototypeOf(Object)) // true

Both Function and Object are functions, their prototype is Function.prototype. Can be verified with
Object.getPrototypeOf(Function) === Function.prototype // true
Object.getPrototypeOf(Object) === Function.prototype // true

This very object was used to create the prototype of Function function, thus
Function.__proto__ === Function.prototype // true

rather than
Function.__proto__ === Object.prototype // false

alert(Object.getPrototypeOf(Function) === Function.prototype)
alert(Object.getPrototypeOf(Object) === Function.prototype)
alert(Function.__proto__ === Function.prototype)
Answer: You're confusing Function.__proto__ (and equivalently Object.getPrototypeOf(Function)), the prototype of the function constructor, with Function.prototype.__proto__, the prototype of functions.

function Rabbit() {
  this.color = 'White'
}

let obj = new Rabbit();

console.log(Rabbit.__proto__ === Function.prototype)       //true
console.log(obj.__proto__ === Rabbit.prototype)            //true
console.log(obj.__proto__.__proto__ === Object.prototype)  //true

console.log(Function.prototype.__proto__ === Object.prototype)  //true
console.log(Object.getPrototypeOf(Function.prototype) === Object.getPrototypeOf(Object.prototype))  //false


how to make the borders of a window wider in gnome 3.26?

Question: I am running gnome 3.26 under Fedora 27, but this question has actually bugged me for a while.
How do I make the borders on a window wider?  I try to resize the windows by dragging the borders right and left, up and down, and that works.  But it is hard to get my mouse at precisely the right place.  If the border was even 5 pixels wide (10 would be better for me), then that would be much easier.
I tried finding the setting using gconftool-2 but I couldn't find anything in there at all, let alone anything useful.
I realize that this is a small thing.  Considering how often I resize a window, it becomes a bigger deal.  I've done a lot of google searches and have not found anything useful.  I cannot believe that I am the first person to mention gnome window border width , am I?
Thank you
Comment: Borders are important for SEEING the window .. borders.I'm having issues with stacked windows with the same background colour.
Comment: Are you aware that you can resize windows to fullscreen/half-screen by pressing Super (usually Windows) key + up/left/right/down? You can also resize to any size by pressing Alt+F8 and moving the mouse.
Comment: I did not know that, thank you.  That helps.n  But I'd still like to know how to make the borders wider.  Everything else in gnome seems to be customizable.
Answer: Type the following in your Terminal:
<code>gsettings set org.gnome.mutter draggable-border-width 15
</code>
10 is the default value, but I guess you'll be happy with a more sloppy mouse dragging border.  Adjust to your personal taste.
Have a ball!


solana - /node_modules/@toruslabs/eccrypto/index.js: 'return' outside of function

Question: I am using vue for solana development.
The library I use is @solana/wallet-adapter
error shows:
/node_modules/@toruslabs/eccrypto/index.js: 'return' outside of function

Since the example is only for React, it's hard for me to find the root cause of the error.
App.vue
<template>

    <WalletConnectButton/>

</template>

Codesandbox
https://codesandbox.io/s/strange-oskar-j1byt?file=/src/App.vue:0-906
Answer: Im not sure if this helps or not, but maybe the module is missing.
npm i @toruslabs/eccrypto
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Why is Windows injecting my directory listing into argv when I use **?

Question: Here's the following main method:
int main(int argc,char** argv)
{
    std::string expression=argv[1];
    for(int i=2;i<argc;i++)
    {
        expression+=' ';
        expression+=argv[i];
    }
    std::cout << expression << std::endl << std::endl;
    Expression* expr = Expression::build(expression.c_str());
    std::cout << expr->evaluate() << std::endl;
    delete expr;
    return 0;
}

Which, for some reason works great most of the time, but see this input / output examples:
D:\Tyler\Desktop>a 2**3
2**3

8

D:\Tyler\Desktop>a 2 ** 3
2 10284556_10203827451228798_9031461414658797199_o.jpg 15686-vanille.p3t 18
865-MiraiNikki.p3t 20777-MIRRORSEDGE2AnimatedTheme.p3t [APE] gras.gpl [Irfa
nView] [APE] gras.pal a.exe arboles_FM.png calc.c calc.cpp couch.png deskto
p.ini gras.pal hackzorz log.txt montanas_FM.png p3textractor p3textractor.z
ip PALLET TOWN.bmp PALLET TOWN.png Pokemon FireRed.bak Pokemon FireRed.gba
Pokemon FireRed.ini Pokemon FireRed.zip ROM Hackers GBA Tool Pack roms send
eros_cope.png senderos_FM.png Thumbs.db Tileset0.bmp Tileset0.pal untitled.
bmp untitled.PNG wdps 3

I have a feeling that this is some kind of windows thing, or am I missing something critical here?
Comment: possible duplicate of [Problem of \* in Command line argument](http://stackoverflow.com/questions/2718873/problem-of-in-command-line-argument)
Comment: You can fix your code by using `GetCommandLine()` instead of `argv`, though note that this will also include the executable.  (That is, it will return `a 2 ** 3` rather than `2 ** 3`.)
Comment: I had a feeling there would be a complicated way to get this to work. I guess a few ifdef's aren't so horrible, but I hate using windows.h ;_;
Thank you for pointing that out, I wasn't aware that was an actual function, as it seems a little bit unnecessary beyond weirdly specific use-cases.
Answer: ** is a classic "wildcard" in many shells, windows included.. It will be replaced with a list of all files in the current directory.
Therefore, you can do del * to delete all files.  Using multiple *'s is the same as single *'s.
Comment: This is incorrect; the Windows shell does *not* do any such replacement.  The executable itself is responsible for doing so if appropriate.  Typically this is handled by the runtime library.
Comment: Huh, I'd known about a single asterisk, but never heard of the double asterisk being a wildcard. Thanks! (:
Comment: Are you saying that GCC's CRT is responsible for replacing ** with the directory listing? If that were the case, wouldn't it make more sense for it to adopt the linux wildcard [ a single asterisk? ] I feel pretty confident that my code isn't doing that, and I tried running `del **.exe` and it worked well enough. Can you explain a little bit more what you mean when you say it's handled by the runtime library?


Open balls appearance

Question: We know that with the euclidean metric the open balls in $\mathbb{R}^2$ are circles without the frontier, of course.
My question is if there exist a known metric in $\mathbb{R}^2$ such that the open balls have the appearance as triangles or hexagons?
Thank you for the support.
Comment: Why don't you try $d \left( \left( x_1, y_1 \right), \left( x_2, y_2 \right) \right) = \left| x_1 - x_2 \right| + \left| y_1 - y_2 \right|$ or $d \left( \left( x_1, y_1 \right), \left( x_2, y_2 \right) \right) = \max \left\lbrace \left| x_1 - x_2 \right|, \left| y_1 - y_2 \right| \right\rbrace$? Try making open balls of radius $1$ centered at origin with these metrics. You will find your answer.
Comment: Open balls in the taxicab metric are squares, see for example [this link](https://math.stackexchange.com/questions/131746/describe-and-illustrate-the-ball-b-10-0).
Comment: You may refer https://people.uwec.edu/mbirika/M316_Notes/Metric_Spaces_Open_Balls_and_Limit_Points.pdf for more information
Answer: I guess that you want a metric which induces the standard topology on $\mathbb{R}^2$.
If you want that the metric is induced by a norm, then you can find an answer here: Norm induced by convex, open, symmetric, bounded set in $\Bbb R^n$. . Note that any open norm-ball centered at $0$ must be  bounded, open, convex and centre symmetric (for bounded recall that all norms on $\mathbb{R}^n$ are equivalent). This excludes triangles, but allows hexagons.
Edited:
Let $H$ be an open hexagon with centre $0$ and vertices lying on the unit circle. It is  bounded, open, convex and centre symmetric. As in the above link define
$$\|x\|_{hex} = \inf \{k>0 : x/k \in H  \} .$$
This is a norm such that $H = \{ x \in \mathbb{R}^2 \mid \|x\|_{hex} < 1 \}$. Note that
$$\{ x \in \mathbb{R}^2 \mid \|x\|_{hex} < r \} = r H ,$$
the latter being defined as $r H  = \{r h \mid h \in H \}$. This is again an open hexagon stretched by the factor $r$. Our norm induces the metric
$$d_{hex}(x,y) =  \|x - y\|_{hex} .$$
Then
$$B_{hex}(x;r) = \{ y \in \mathbb{R}^2 \mid d_{hex}(x,y) < r \} = x  + B_{hex}(0;r) = x +r H$$
which is an open hexagon with centre $x$.
The same construction can be performed for any bounded, open, convex and centre symmetric set $A$. Then all open balls with respect to the metric $d_A$ are copies of some $rA$ (which is obtained by stretching $A$).
Comment: Well, and my question is there exist (or how you can construct) a metric such that the open balls be hexagons?
Comment: I edited my answer.

Open balls appearance


Div's moving with scroll

Question: I'm looking for a solution, which let me make a Div's moving with scroll. I would like to make it like on picture below:

So Box 1 and Box 2 are Div's which moving with scroll within a Div1/Div2 area. The Footer is a limiter. If we have a very high footer - Box 1 and Box 2 stay at the end of Div1/Div2 area.
I would also like to on mobile devices these items are not moving but are static.
Thanks in advance,
Best Regards,
D.
Answer: position:sticky will do this

one link among others http://www.sitepoint.com/css-position-sticky-introduction-polyfills/
mobile ? https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

div {
 display:flex;
}
aside, main, footer, div div {
  border:solid;
  flex:1;
  margin:5px;
}
main {
  min-width:60%;
  min-height:90vh
}
footer {
  height:40vh;
}
aside div {
  position:sticky;
  top:0;
  height:60vh
}
.bgr {
  height:70vh;
  }

 sticky

 main

 sticky

  footer

Div's moving with scroll


Bass guitar amp power socket issues

Question: I have a rather unusual question. I have a Fender Affinity Jazz Bass starter kit and it comes with a 15W amp - "Rumble 15 Bass Combo Amp".
I also have a cat in the house, and every time I don't cover my amp with a plastic bag, my amp becomes an instant scratching post. However, to cover the amp between each practice session, I have to unplug/plug my power cord into the amp every time I use it.
The problem is, the plug socket is unusually tight, really tight. I'm not a big guy, but I'm not weak by any means either. Yet it takes me quite a lot of effort just to plug and unplug it. I'm not sure how to quantize the level of effort so you guys understand, but lets just say if I try to unplug I have to use two hands, I have to always start by wiggling the plug out, and my body even moves back a bit after I finally pull it out.
I don't think this is usual, and I think the wiggling has been damaging the bass amp. I believe the amp just happened to be manufactured with a not-too-good socket. So my questions are:

Is there anything I can do to make the socket less tight or make it easier to plug/unplug?
or... how would you keep your cat away from the amp?

UPDATE: Turns out it's a cable problem as Chocos suggested... the material for the cable plug is very stiff and probably not exactly the right size and I'm pretty sure the cable's made in china. I've also cut a little slot in the bag to slide over the cable. Thanks for your help guys!
Comment: How about using a different cat? :-)   No, actually, mod the cover so it fits over/around the cord.
Comment: have you tried using a different cable?
Comment: @Chochos that's a good point, don't know why I didn't think of trying that
Answer: Cats and scratching... yeah, I can relate.
A great way to get the cat to stop it is to drape duct-tape, sticky side out, all over the sides where the cat likes to scratch. The second the cat gets sticky tape on its paws it'll change its mind about how fun it is to scratch that particular "post" and will leave it alone.
This doesn't hurt the cat at all; They hate anything stuck to their feet, so it will drive it nuts.
This same trick works for cats jumping on furniture.
Answer: I'm guessing the cat enjoys clawing the speaker mesh. Try leaving the amp. facing down on the floor. Is the socket a kettle plug sort ?
Comment: Cat or amp. Amp or cat...
Comment: Cat conditioning - every time it scratches it, play a loud discordant set of notes :-) (note this is actually a joke. I wouldn't really condone torture of animals through music. Well, there is opera, I suppose...)
Comment: Yep, it's the kettle plug. The cat enjoys the fuzzy wood panels of it unfortunately. =/
Comment: kettle plugs are available in right-angled form, both to the side and downwards. You may be able to slip the cover over then. Alternatively, I can recommend a lovely cats' home...
Answer: We've had some success - not on music gear (that stays behind closed doors) - but on walls by taping tin foil (aluminum foil) to the walls.  The cats hate the sound of it, and I think they don't like how it feels.
Plus it looks excellent.

Bass guitar amp power socket issues


Comparing two slopes

Question: I have a dataset structured as follows:
<code>Variable1  Variable2  Variable3  Variable4  Variable5  Variable6  Variable7  Variable8
  60         70         75          73        57         69         85         90
  55         66         47          79        63         76         82         97
</code>
etc.
Each variable represents the detection performance for a certain position and condition. Variables 1 to 4 are meant to represent condition 1, Variables 5 to 8 are meant to represent condition 2. Detection performance for the same locations (but different conditions) are represented by variables 1 & 5, variables 2 & 6, variables 3 & 7, variables 4 & 8.
I now have plotted the detection performance for both conditions as a line chart.
What I want to do, is to compare the slope of both curves using SPSS. What would be the best way to accomplish this? I would like to test if one slope is steeper than the other.
Both curves are representing the detection performance of a target at different locations. I have the directional hypothesis, that the slope of the one curve would be flatter than the other.
I am aware that there are different slopes within the curve, so what I am looking for is the "overall slope" for each curve. I suppose this could be accomplished by calculating a regression line. However I am not aware about how to do this with my dataset. Usually predictor and predicted variable are positioned in two fields of your SPSS file. But now they are in the same field: the location of the target should predict the detection performance. And variable 1 to x represents the detection performance on location x.
Do I have to split those two pieces of information detection performance and location, or can this problem be solved with the existing structure of my dataset?
This is how the plot looks like:

And I want to test if the curve of one condition is steeper / flatter than the curve of the other condition.
Detection performance for condition 1 (4 possible target locations) is represented by variables 1 to 4. Detection performance for condition 2 (4 possible target locations) is represented by variables 5 to 8.
The explanatory variables would be the position of the target, the response variable would be the detection performance. Both pieces of information are represented by the same field: Variable1 stands for detection performance on position a, Variable2 stands for detection performance on position b, and so on.
My study design is a within subjects design, each participant was tested on both conditions. In the sample data I provided, each row stands for one participant. Each number stands for the average detection performance of the respective participant for the respective condition (condition 1: variable 1 - 4; condition 2: variable 5 - 8) and the respective location (the same location is represented in Variable 1 & 5, Variable 2 & 6, Variable 3 & 7, Variable 4 & 8).
Comment: I have edited the question. Please see the last paragraph. An no, this is no homework nor assignment.
Comment: When you say 'curve' and 'slope', note that curves tend to have more than one slope. Can you be more specific about your model and what you want to test, please?
Comment: So what are you plotting exactly and what are you trying to achieve? For example, what are your explanatory and response variables? Are you trying to understand some treatment effect and if so have treatments been allocated randomly or is this some form of observational study? As it is currently presented, I think it's going to be difficult for others to respond to your questions with useful guidance. Also, apologies, this should have been a comment rather than an answer.
Comment: Thanks for your comment. I have added some more information. I hope I could clarify things with the addition.
Comment: Your question is still ambiguous on what is explanatory. See your wording: "result in" conditions 1, 2. It sounds as conditions 1, 2 are pre-existing conditions and so which condition you have is explanatory. If that's true, you need to restructure your data so that you have fields for explanatory variables, but I don't use SPSS and have no idea how you would do that.
Comment: What do you mean by "split those two pieces of information detection performance and location"? Did you set the position of the target and measure the performance for each trial?
Comment: Yes, that's right. Possible target positions were fixed and the same for each subject. Each subject had to detect a target on each position for several time. In my dataset the percental detection performance for each position and subject is given.
Answer: It isn't clear to me whether my last post was converted into a comment as such I am re-posting as another answer and will follow up when I am back on line. Answer follows:
Am I correct in responding by saying you are interested in determining whether position and condition affects detection performance? If so, I think that considering the slopes is not the correct approach, although I do think it is possible that a linear model may be suitable. While I am still struggling to understand exactly what you are trying to do, I think a MANOVA (multivariate ANOVA) approach may be applicable.
To give you a bit more context, a MANOVA approach would be useful if you were interested in determining if party affiliation (Democrat, Republic etc) and gender have any effect on voters views on issues such as taxes, gun control etc.
Comment: Thanks for your advise.
This is what I already have done. I have computed an ANOVA with condition and position as within-subjects factors. This worked quite well, and answered my question if condition and target position influence detection performance. So this did confirm my first hypothesis.
But the cause why I am asking here for help, is the verification of my second hypothesis. The second hypothesis assumes that the overall slope of condition 2 would be flatter than the slope of condition 1.
Comment: Is the position of the target a continuous variable or a categorical variable? I am thinking you could regress detection performance on position, condition (as an indicator/dummy variable) and an interaction term. If the interaction term is significant then the slopes are different.
Comment: The position of the target is continuous.
Thanks for the advice. I will have a look at it! :-)

Comparing two slopes


How can I prove that an iterated transformation describes all odd integers?

Question: This is a question where I want to find "a best" way (or even different ways) to prove my assumption - just to widen my understanding of similar problems and how to approach them. It's a question of proof-strategy. (This is also related to my studies of the Collatz-problem)
Remark: this problem was less difficult than I thought it were, see my own answer. Regarding my question for a proof-strategy it is a nice example for how a tabular representation can obfuscate the problem and mislead the mind away from a relatively simple solution.

Consider the transformation on odd positive numbers
$$ x_{k+1} = \left\{ \begin{array} {}
 { 3x_k-1 \over 2} &\qquad \text{ if } x_k \equiv 1 \pmod 4 \\
 { 3x_k+1 \over 2} &\qquad \text{ if } x_k \equiv -1 \pmod 4  \end{array}
\right. $$ such that for instance the trajectory beginning at $5$ continues like $  5 \to 7 \to 11 \to 17 \to \ldots $
Because the numbers of the form $ x \equiv 3 \pmod 6$ have no preimage I take them as "roots" and order all trajectories in the following two-way infinite array of odd natural numbers $ \ge 3$ :
$$ \small \begin{array} {r|rrrr}
 3 & 5 & 7 & 11 & 17 & 25 & 37 & 55 & \cdots \\
 9 & 13 & 19 & 29 & 43 & 65 & 97 & 145  & \cdots \\
 15 & 23 & 35 & 53 & 79 & 119 & 179 & 269  & \cdots  \\
 21 & 31 & 47 & 71 & 107 & 161 & 241 & 361  & \cdots \\
 27 & 41 & 61 & 91 & 137 & 205 & 307 & 461  & \cdots \\
 33 & 49 & 73 & 109 & 163 & 245 & 367 & 551  & \cdots \\
 39 & 59 & 89 & 133 & 199 & 299 & 449 & 673  & \cdots \\
 45 & 67 & 101 & 151 & 227 & 341 & 511 & 767 & \cdots \\
 \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \ddots
\end{array} $$
The number $1$ forms a cycle $ 1 \to 1 $ and is not in this table.
It looks quite obvious, that I've got all positive odd numbers in this table, but now my question:
Q: How can I begin and proceed with a proof, that this table contains /that this transformation rule describes all positive odd integers $ \ge 3$ ?
Remark: perhaps my question is not optimally formulated, I'd even like getting help for this

I tried, whether it is useful to reformulate the transformation in such a way:
$$T: x_k = 4j + r \to x_{k+1}=6j +r \qquad \qquad \text{ for } j \ge 1 , r \in \{-1,1\} $$
then look at the inverse and ask, whether any number of the form $ x=6j \pm 1$ under the inverse transform has a trajectory, which ends at a number of the form $3+6i $.
But I have no idea how to arrive at a so-to-say "completeness"-statement.

[update] after the comment of André Nicholas - ansatz transferred into a new answer
Comment: Your inverse transformation idea should do it.
Comment: @André : I've got it now. It came out that for me it has been a problem of unnecessary complication, also known as "obfuscation" ...
Comment: Yes, you go backwards until you can't do it any more. Must happen, since terms are decreasing (fast) and remain positive.
Answer: You can show by induction that every odd number greater than $1$ is in your table :
If $n = 6k+3$ then $n$ is a root.
If $n = 6k+5$ then $n = T(4k+3)$, and $1 < 4k+3 < 6k+5$.
If $n = 6k+7$ then $n = T(4k+5)$, and $1 < 4k+5 < 6k+7$.
Comment: Hmm, I don't see the induction... Perhaps I'm completely dense at the moment and should take a break first...
Answer: Hint 1: What would be the smallest odd integer missing from the list?
Hint 2: You already made the observation that an odd integer $\not\equiv 3\pmod6$ has a preimage (that is smaller).
Hint 3: The empty set is the only set of positive odd integers that does not have a smallest element. Fermat's infinite descent was one of the first proofs by induction.
Comment: Hmmm... it's immediate, that if a number $x_k$ has the form $x_k = 6j_k+r_k \qquad r_k \in \{-1,1\},j_k \gt 0$ then there exists a smaller number $ x_{k+1} = 4j_k+r_k $. But for the next step we must either have $ x_{k+1} = 6j_{k+1} + 3 $ which is then a root without further preimage or we must have $ x_{k+1} = 6j_{k+1} + r_{k+1} = 4j_k+r_k $ where $j_{k+1} \lt j_k$ . So now one more step ...
Comment: Hmm. At hint 1: such a number whose inverse trajectory does not arrive at a number of the form $3 + 6j$ ...?  - I've actually no idea ...
Comment: If it has a preimage smaller than itself, it cannot be the smallest missing number. So the smallest missing number cannot have a preimage at all, so...
Comment: So you can prove that there is no smallest counterexample. So the set of counterexamples has to be empty. That's the essence of induction!
Comment: Yes. I've got it now. I recognize now my main problem in that I was obfuscated/mislead by the two-dimensional structure of the table and that I could not intuitively exclude the idea, that in one row the proceeding from the right to the left could perhaps jump between two of the 3-divisible roots.  $ \\ $ Omitting the vizualisation by the table, considering simply the set of consecutive odd numbers with one lowest number makes the solution obvious. I'll add that insight in terms of an extra answer later. Thanks for your hints!
Comment: Just to "accept" one answer I accept this because it gave me the hints how to proceed. My solution is then in my own answer. Thanks Jyrki and also @André which was also helpful
Answer: We consider the odd numbers $ x \ge 3$ . Any of that numbers can be written as
$ x = 6j - 3$ or $x=6j-1$ or $x=6j+1 $ with $j \gt 0$ .
We define the inverse transformation in the following way:
we pick some $x_0$.

Case 1: if $x_0$ is of the form $x=6j -3$ we have that number in our
table as a "root" entry.
Case 2: if $x_0$ is of the form $x=6j +r$ where $ r \in \{-1,1\}$ we
transform that number according to

$  \qquad U: x_k = 6j_k + r_k \to x_{k+1} = 4 j_k+r_k $
Because $x_{k+1}$ is again odd, it is again  $ x_{k+1} = 4 j_k+r_k = 6j_{k+1} + r_{k+1} $ and of one of the two Cases and we can repeat:

Case 1: if it is of the form $x_{k+1} = 6j_{k+1} - 3 $ we have again, that it is in the table, and with it all numbers $x_0 \ldots x_k$ in between.
Case 2a: if $ j_k >1 $ we have $ x_{k+1} = 4j_k + r_k $ and the smallest of that numbers is with $j_k = 2$ the number $ x_{k+1} = 4 \cdot 2 -1 = 7 = 6 \cdot 1 +1 $ such that $j_{k+1}=1$
Case 2b: And if finally $ j_k =1 $ we have either
$ \qquad \qquad x_{k+1} = 4\cdot 1  -1 = 3$ and this is in the table and closes the trajectory or we have
$ \qquad \qquad x_{k+1} = 4 \cdot 1 +1 = 5$ and this transforms to $x_{k+2}=3$ which then closes again the trajectory.

Because all trajectories end on some number which is divisible by 3 and these numbers are in the table by definition together with all of their preimages, the given table contains all odd natural numbers $ x \ge 3$ .
(I think the way of arguing and the formalism should be improvable, please point out any error or weakness...)


Laravel OR operator in filter PHP

Question: I'm following this tutorial to make filters on my site.
I'm trying to add an OR statement within the filter in the HTML.
For example,
 request('type'),
    'sort' => request('sort'),
    'region' => 'Lisbon'|'Lisboa',
    ]) }}">Lisbon

However, if I do this, only results for "Lisbon" appear, but those for "Lisboa" do not.
I have also tried
'region' => ('Lisbon|Lisboa'),
'region' => ('Lisbon||Lisboa'),
'region' => array('Lisbon','Lisboa'),
['region' => 'Lisbon', 'region' => 'Lisboa',],

all with no luck.
It seems like when there is a comma between "Lisbon" and "Lisboa" that the operator only looks at the first option, "Lisbon" in this case.
(If you're wondering, Google Maps API gives me either Lisbon or Lisboa for the admin district, even though I have restricted it to English.)
Then, for my controller, here is how I am doing the filters:
  public function index()
    {
        $rooms = new Room;
        if (request()->has('type')) {
            $rooms = $rooms->where('type', request('type'));
        }
        if (request()->has('region')) {
            $rooms = $rooms->where('region', request('region'));
        }
        if (request()->has('sort')) {
            $rooms = $rooms->orderBy('created_at', request('sort'));
        }
        $rooms = $rooms->paginate(20)->appends([
          'type' => request('type'),
          'region' => request('region'),
          'sort' => request('sort'),
        ]);
        return view('rooms.index')->with('rooms', $rooms);

Any idea what could be a possible solution here?
Thanks!
Comment: The code you presented are just defining route parameters, not anything to do with the actual filtering of data.
Comment: True. Thanks @Devon I will add the content from my controllers.
Comment: Also, not sure what syntax you are trying to use with `('Lisbon')|('Lisboa')`.  This evaluates to a string of `Lisboo`.
Comment: To be honest, @Devon , I was trying several different ways and made a few up along the way... Sorry if that was a dumb attempt.
Answer: Laravel collections include a whereIn() method to filter against arrays.  where() only accepts one value.
https://laravel.com/docs/5.5/collections#method-wherein
Therefore, if you are passing in an array of data as the region, you could do:
$rooms = $rooms->whereIn('region', request('region'));

Furthermore
A string of 'Lisbon|Lisboa' is a string, not an expression.  You should not expect any code to understand that as two separate values.  Wrapping it in parentheses doesn't change anything, parentheses are used to provide an order to the operations, like in math.
'Lisbon'|'Lisboa' is a bitwise operation as | is a bitwise operator and not what you are looking for. || is an OR operator, but you can't just pass an expression as a parameter, you'll just be passing what that expression evaluates to which would be true or false if you use ||.
When dealing with a list of values, you almost always want to utilize PHP arrays and array functions.  in_array is the underlying function that
 powers this filter.  Be sure to understand arrays and review the available functions here.
Comment: Sounds  like you aren't passing an array
Comment: Thanks @Devon, but for some reason, I keep getting an error: (1/1) ErrorException
Invalid argument supplied for foreach()
Comment: You're absolutely right! Sorry about that. So, I did it like this and it worked: 'region' => ['Lisbon','Lisboa'],

Laravel OR operator in filter PHP


Sympy error: The function cannot be automatically detected for -k*x

Question: I am trying to make a script to calculate the eigen states/energy levels of a simple harmonic oscillator using sympy.
This is a system that exhibits periodic motion, such as a mass on a spring. In general, the equation of motion for a simple harmonic oscillator can be written as:
F = -kx
where:

F is the force on the oscillator.
k is the spring constant.
x is the displacement from the equilibrium position.

The eigenvalues of a simple harmonic oscillator are the possible energy levels of the system. For a simple harmonic oscillator, the eigenvalues are given by:
E_n = (n + 1/2) \* h \* nu
where:

n is an integer representing the energy level
h is the Planck constant
nu is the frequency of the oscillator.

These eigenvalues are equally spaced and form a discrete spectrum, which is a characteristic property of quantum systems.
import sympy as sym

# Define the variables and the equation of motion
x, k, m, h, nu,t = sym.symbols('x k m h nu t')
eq = sym.Eq(-k * x, m * sym.diff(x,t, 2))

# Solve the equation of motion for the displacement x(t)
sol = sym.dsolve(eq)

# Compute the eigenvalues of the oscillator
E = sym.solve(sym.det(sol.lhs - nu * sym.eye(2)), nu)

# Print the eigenvalues
print(E)

where the code defines the displacement (x), spring constant (k), mass (m), Planck constant (h), and frequency (nu) as symbolic variables, and then uses these variables to define the equation of motion for a simple harmonic oscillator.
I am however getting this error and cannot find a way to debug it.
ValueError                                Traceback (most recent call last)
Input In [18], in <cell line: 8>()
      5 eq = sym.Eq(-k * x, m * sym.diff(x,t, 2))
      7 # Solve the equation of motion for the displacement x(t)
----> 8 sol = sym.dsolve(eq)
     10 # Compute the eigenvalues of the oscillator
     11 E = sym.solve(sym.det(sol.lhs - nu * sym.eye(2)), nu)

File /opt/python/3.9/envs/pulsar/lib/python3.10/site-packages/sympy/solvers/ode/ode.py:605, in dsolve(eq, func, hint, simplify, ics, xi, eta, x0, n, **kwargs)
    602 given_hint = hint  # hint given by the user
    604 # See the docstring of _desolve for more details.
--> 605 hints = _desolve(eq, func=func,
    606     hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics,
    607     x0=x0, n=n, **kwargs)
    608 eq = hints.pop('eq', eq)
    609 all_ = hints.pop('all', False)

File /opt/python/3.9/envs/pulsar/lib/python3.10/site-packages/sympy/solvers/deutils.py:180, in _desolve(eq, func, hint, ics, simplify, prep, **kwargs)
    178 # preprocess the equation and find func if not given
    179 if prep or func is None:
--> 180     eq, func = _preprocess(eq, func)
    181     prep = False
    183 # type is an argument passed by the solve functions in ode and pde.py
    184 # that identifies whether the function caller is an ordinary
    185 # or partial differential equation. Accordingly corresponding
    186 # changes are made in the function.

File /opt/python/3.9/envs/pulsar/lib/python3.10/site-packages/sympy/solvers/deutils.py:82, in _preprocess(expr, func, hint)
     80     funcs = set().union(*[d.atoms(AppliedUndef) for d in derivs])
     81     if len(funcs) != 1:
---> 82         raise ValueError('The function cannot be '
     83             'automatically detected for %s.' % expr)
     84     func = funcs.pop()
     85 fvars = set(func.args)

ValueError: The function cannot be automatically detected for -k*x

Would appreciate any help.
Answer: Print out the different quantities in your expression to debug what is happening. Your equation is
In [5]: eq
Out[5]: -k⋅x = 0

I'm guessing that's not what you intended it to be. The reason is this:
In [6]: diff(x, t, 2)
Out[6]: 0

That's because x as a symbol does not depend on t so as far as differentiating wrt to t it is a constant and its derivative is zero. You should make x be a function of t:
In [7]: x = Function('x')

In [10]: eq = Eq(-k*x(t), m*diff(x(t), t, 2))

In [11]: eq
Out[11]:
              2
             d
-k⋅x(t) = m⋅───(x(t))
              2
            dt

In [12]: dsolve(eq)
Out[12]:
                  _____             _____
                 ╱ -k              ╱ -k
           -t⋅  ╱  ───        t⋅  ╱  ───
              ╲╱    m           ╲╱    m
x(t) = C₁⋅ℯ             + C₂⋅ℯ

If you were hoping to see sin and cos there then the issue is that you haven't said anything about the symbols k and m:
In [13]: k, m = symbols('k, m', positive=True)

In [14]: eq = Eq(-k*x(t), m*diff(x(t), t, 2))

In [15]: dsolve(eq)
Out[15]:
             ⎛√k⋅t⎞         ⎛√k⋅t⎞
x(t) = C₁⋅sin⎜────⎟ + C₂⋅cos⎜────⎟
             ⎝ √m ⎠         ⎝ √m ⎠


Binding datacontext to a user control using MVVM

Question: I have a model
    public class PersonModel : INotifyPropertyChanged
    {
        private string _firstname;
        public string FirstName
        {
            get {return _firstname; }
            set { _firstname = value; RaisePropertyChanged("FirstName"); }
        }

        private string _lastname;
        public string LastName
        {
            get { return _lastname; }
            set { _lastname = value; RaisePropertyChanged("LastName"); }
        }

        public string FullName
        {
            get { return string.Format("{0} {1}", FirstName, LastName); }
        }

        protected void RaisePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

I have a viewmodel:
 public class PersonViewModel
    {
        public ObservableCollection<PersonModel> Person { get; set; }
        public PersonViewModel()
        {
            Person = CookPersonData();
        }

        internal static ObservableCollection<PersonModel> CookPersonData()
        {
            ObservableCollection<PersonModel> persons = new ObservableCollection<PersonModel>();
            persons.Add(new PersonModel{ FirstName="Raj", LastName="kumar" });
            return persons;
        }
    }

The Usercontrol is
<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfApplication1"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.DataContext>
        <local:PersonViewModel></local:PersonViewModel>
    </UserControl.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="FirstName"></TextBlock>
        <TextBox Text="{Binding FirstName,Mode=TwoWay}" Name="txtFirstName" Margin="115,0,0,106" DataContext="{Binding Path=Person}" Background="#FFF0F0F0" />
        <TextBlock Grid.Row="1" Text="FirstName"></TextBlock>
        <TextBox Grid.Row="1" Text="{Binding LastName,Mode=TwoWay}" Name="txtLastName" Margin="115,0,0,110" DataContext="{Binding Path=Person}" Background="#FFF0F0F0" />
    </Grid>
</UserControl>

I need to rebind the datacontext which is not happening
can you suggest what is the problem?

Answer: The ViewModel does not implement INotifyPropertyChanged so when you set the collection the view isn't notified of this change.
In general I advise against this setup: you are mixing Model and ViewModel this will create a dependency in the View on the Model. Although it might work now in future releases it might become a problem plus it is against the MVVM pattern.
Answer: Change that code on this one:
public class PersonViewModel : INotifyPropertyChanged
   {
       public ObservableCollection<PersonModel> _person = new ObservableCollection<PersonModel>();

       public ObservableCollection<PersonModel> Person
       {
           get { return _person; }
           set { _person = value; RaisePropertyChanged("Person"); }
       }

       public PersonViewModel()
       {
           UpdateView = new DelegateCommand(this.OnUpdateView, this.CanUpdateView);

           var tmp = CookPersonData();
           Person.Clear();

           foreach (var item in tmp)
           {
               Person.Add(item);
           }
       }

       internal static ObservableCollection<PersonModel> CookPersonData()
       {
           ObservableCollection<PersonModel> persons = new ObservableCollection<PersonModel>();
           persons.Add(new PersonModel { FirstName = "Raj", LastName = "kumar" });
           return persons;
       }

       internal static ObservableCollection<PersonModel> CookPersonData2()
       {
           ObservableCollection<PersonModel> persons = new ObservableCollection<PersonModel>();
           persons.Add(new PersonModel { FirstName = "Raj2", LastName = "kumar2" });
           return persons;
       }

       public ICommand UpdateView { get; private set; }
       private void OnUpdateView()
       {
           var tmp = CookPersonData2();
           Person.Clear();

           foreach (var item in tmp)
           {
               Person.Add(item);
           }
       }
       private bool CanUpdateView()
       {
           return true;
       }

       protected void RaisePropertyChanged(string propertyName)
       {
           var handler = PropertyChanged;
           if (handler != null)
           {
               handler(this, new PropertyChangedEventArgs(propertyName));
           }
       }

       public event PropertyChangedEventHandler PropertyChanged;
   }

And XAML file:
   <Window.DataContext>
        <local:PersonViewModel />
    </Window.DataContext>
    <StackPanel>
        <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="FirstName"></TextBlock>
        <TextBox Text="{Binding Person[0].FirstName,Mode=TwoWay}" Name="txtFirstName" Margin="115,0,0,106"  Background="#FFF0F0F0" />
        <TextBlock Grid.Row="1" Text="FirstName"></TextBlock>
        <TextBox Grid.Row="1" Text="{Binding Person[0].LastName,Mode=TwoWay}" Name="txtLastName" Margin="115,0,0,110" Background="#FFF0F0F0" />

    </Grid>
        <Button Content="Update" Command="{Binding UpdateView}" />
    </StackPanel>

Comment: Thanks, It worked now i have better understanding thanks a lot.


Check to see if a directory exists remotely (shell script)

Question: Is there a way to see if a directory exists on a remote server?
Perhaps there's a better way, but I'm writing an application deployment script, and I want to create a directory on a remote server if the directory doesn't exist to place the files.
Thanks in advance!
Answer: You can use ssh to call a programme on the remote host, test tests for certain conditions.
if [[ `ssh firstname.lastname@example.com test -d /path/to/my/directory && echo exists` ]] ; then
    # put code in here
fi

Comment: This didn't work for me (probably your backquotes got mangled). I used `if [[ \`ssh email@example.com test -d /path/to/my/directory && echo exists\` ]]` and that worked.
Answer: mkdir -p

But if that isn't quite what you're after you can check the existence of a directory with
ssh user@host test -d /home && echo exists

Answer: Just use
ssh remoteHost 'mkdir -p /whatever/your/dir/is'

It will create the dir if it doesn't already exist.
Comment: if you add a `-p` to your mkdir command it will not report an error if the directory already exists and it will make the entire path.
Comment: I added it, but it depends on what exactly he wants. Now he can't use the command in an if statement anymore.
Answer: I'd recommend looking at using the RPM mechanism to install your application, rather than writing something home grown, since the problems you'll come across with your own script will almost certainly have already been solved with RPM.  Here's an excellent tutorial on RPM.
Answer: How do you intend to talk to this remote server? SSH, SMB, NFS, something else? there's usually a way of finding this stuff out but you'll need to know what protocols and authentication option you have open to you before knowing exactly how to to this.
Comment: It can be accessed through SSH, however I wasn't sure if there is another tool that will allow me to create the directory.
Comment: If you have SSH simply script an mkdir, if it exists it'll just fail with an error.
Comment: Yeah, after doing some research, this is the way I'll be doing it.  I'm kind of a linux noob, so I didn't realize you could execute a script and have it continue to execute commands remotely.
Answer: #its simple

if [[ "`ssh -q hostname ls /dir/filename.abc 2>dev/null`" == "/dir/filename.abc" ]]
then
echo "file exists"
else
echo "file not exists"
fi

Answer: if ssh $REMOTE_HOST ls $BACKUP_DIR_REMOTE/$REMOTE_DAILY;
then
    ssh $REMOTE_HOST btrfs subvolume delete $BACKUP_DIR_REMOTE/$REMOTE_DAILY
else
    echo "Older snapshot does not exist."
fi


Percentages work differently than pixels (after using percentages, elements overlap)

Question: I try to use percentages on my page but then the "a" elements overlap. I would like not to change "box-sizing: border-box;". I tried to find a solution on the internet but without success. Sorry for my English.
I've the following code:
<!DOCTYPE html>

A

B

C

D

Any suggestions?
Comment: Dont use % on the links, use it on the `li`.
Comment: Also, consider using `calc()` to avoid overlapping: I mean, if an element is set to be `20%` wide, but it has margins or paddings, choose `calc(20% - foo)`; this is enough to avoid `border-box` and that's what I do in these cases. If a browser doesn't support it, just add Autoprefixer.
Comment: @Paulie_D After using % for `li`, the text inside the `a` elements overlaps
Answer: ul li {
  display: inline-block;
width:20%;
  }

Comment: Works, but now the text inside the "a" elements overlaps. (If this text is long enough)


Smooth path in javaFX

Question: I'm drawing a Path in JavaFX and I would like to draw path (lineTo and arcTo) of this type:

Is there any simple way how to connect arcs with lines(and other arcs) to get a smooth path like this?
I don't know the perimeter of an arc, I know only the beginning point and ending point. In the picture are only half circles, I need to draw another types of arcTo as well.
The only idea, I've had so far was getting the direction of the end of the path and then counting and joining another arcTo / lineTo in this direction. However, I didn't found any method to do this as well.
Comment: For a given length, how often should the arcs be? Also, please clarify on these "other types of `arcTo`"
Comment: I'm looking for general solution of connecting arcs smoothly to lines, not only for one case of this (the image was only for illustration of the problem), therefore I can't specify, how often should the arcs be. Under other type of arcTo I mean arcs with central angle different  from 180°
Comment: So you have a given array/list of arcs that you want to connect?
Comment: No, I always have a line and a point somewhere in the `Pane`. I want to draw an `arcTo` beginning at a specified end of the line and ending in the given point.
Answer: A Cubic Bezier Curve is defined by four points, start, end, and two "control points" control1 and control2. It has the property that

it starts and ends at start and end
initially (i.e. at start) it is tangential to the line segment between start and control1
at end it is tangential to the line segment between control2 and end

The shape of the curve is also determined by the sizes of the line segments from start to control1 and control2 to end: roughly speaking these control the "speed" with which the line approaches the control points before turning towards the end points.
So to join two line segments with a smooth curve, you can use a cubic curve whose start is the end of the first line segment and whose end is the start of the second line segment. Compute the control points just by extending each line beyond its end (first line) or start (second line). Using the same length for the extensions will give a balanced look.
Here is an example. Run this code: drag the mouse across the pane to draw one line, then again to draw a second line, and the two lines will be connected by a cubic curve.
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.CubicCurve;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

public class JoinLineSegmentsWithCubic extends Application {

    private Line unconnectedLine = null ;
    private Line currentDraggingLine = null ;

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();
        pane.setOnDragDetected(e -> {
            currentDraggingLine = new Line(e.getX(), e.getY(), e.getX(), e.getY());
            pane.getChildren().add(currentDraggingLine);
        });
        pane.setOnMouseDragged(e -> {
            if (currentDraggingLine != null) {
                currentDraggingLine.setEndX(e.getX());
                currentDraggingLine.setEndY(e.getY());
            }
        });
        pane.setOnMouseReleased(e -> {
            if (currentDraggingLine != null) {
                currentDraggingLine.setEndX(e.getX());
                currentDraggingLine.setEndY(e.getY());

                if (unconnectedLine != null) {
                    connect(unconnectedLine, currentDraggingLine, pane);
                }
                unconnectedLine = currentDraggingLine ;
                currentDraggingLine = null ;
            }
        });

        Scene scene = new Scene(pane, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void connect(Line line1, Line line2, Pane parent) {
        Point2D line1Start = new Point2D(line1.getStartX(), line1.getStartY());
        Point2D line1End = new Point2D(line1.getEndX(), line1.getEndY());
        Point2D line2Start = new Point2D(line2.getStartX(), line2.getStartY());
        Point2D line2End = new Point2D(line2.getEndX(), line2.getEndY());

        double line1Length = line1End.subtract(line1Start).magnitude();
        double line2Length = line2End.subtract(line2Start).magnitude();

        // average length:
        double aveLength = (line1Length + line2Length) / 2 ;

        // extend line1 in direction of line1 for aveLength:
        Point2D control1 = line1End.add(line1End.subtract(line1Start).normalize().multiply(aveLength));

        // extend line2 in (reverse) direction of line2 for aveLength:
        Point2D control2 = line2Start.add(line2Start.subtract(line2End).normalize().multiply(aveLength));

        CubicCurve cc = new CubicCurve(
                line1End.getX(), line1End.getY(),
                control1.getX(), control1.getY(),
                control2.getX(), control2.getY(),
                line2Start.getX(), line2Start.getY());

        cc.setStroke(Color.BLACK);
        cc.setFill(null);

        parent.getChildren().add(cc);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

You can also incorporate a cubic Bezier curve into a path, using the path element CubicCurveTo. Here is an example using a Path, with vertical line segments connected by cubic bezier curves (the method generating the path will work for arbitrary line segments):
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.CubicCurveTo;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;

public class SmoothPathWithCubicBezier extends Application {

    @Override
    public void start(Stage primaryStage) {
        double[] points = new double[24];
        for (int i = 0; i < 24 ; i+=8) {
            double x = (1 + i/8) * 200 ;
            points[i] = x ;
            points[i+1] = 200 ;
            points[i+2] = x ;
            points[i+3] = 400 ;
            points[i+4] = x + 100 ;
            points[i+5] = 400 ;
            points[i+6] = x+ 100 ;
            points[i+7] = 200 ;
        }
        Pane pane = new Pane();
        pane.getChildren().add(createPath(points));

        Scene scene = new Scene(pane, 800, 800);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // points should be an array of length a multiple of four,
    // defining a set of lines {startX1, startY1, endX1, endY1, startX2, ...}
    // The path will consist of the straight line segments, joined by
    // cubic beziers
    private Path createPath(double[] points) {
        Path path = new Path();
        for (int i = 0 ; i < points.length; i+=4) {
            double startX = points[i];
            double startY = points[i+1];
            double endX = points[i+2];
            double endY = points[i+3];

            if (i==0) {
                MoveTo moveTo = new MoveTo(startX, startY);
                moveTo.setAbsolute(true);
                path.getElements().add(moveTo);
            } else {

                double lastStartX = points[i-4];
                double lastStartY = points[i-3];
                double lastEndX = points[i-2];
                double lastEndY = points[i-1];

                double lastLength = Math.sqrt((lastEndX-lastStartX)*(lastEndX-lastStartX)
                        + (lastEndY-lastStartY)*(lastEndY-lastStartY));
                double length = Math.sqrt((endX-startX)*(endX-startX)
                        + (endY-startY)*(endY-startY));
                double aveLength = (lastLength+length)/2;

                double control1X = lastEndX + (lastEndX-lastStartX)*aveLength/lastLength ;
                double control1Y = lastEndY + (lastEndY-lastStartY)*aveLength/lastLength ;

                double control2X = startX - (endX-startX)*aveLength/length ;
                double control2Y = startY - (endY-startY)*aveLength/length ;

                CubicCurveTo cct = new CubicCurveTo(control1X, control1Y, control2X, control2Y, startX, startY);
                cct.setAbsolute(true);
                path.getElements().add(cct);

            }
            LineTo lineTo = new LineTo(endX, endY);
            lineTo.setAbsolute(true);
            path.getElements().add(lineTo);

        }

        return path ;
    }

    public static void main(String[] args) {
        launch(args);
    }
}

This gives

Smooth path in javaFX


time.time() and datetime.datetime.now() does not get current time when used in a descriptor

Question: When coding in Python, the common way to get the current time is time.time() or datetime.datetime.now(). But I never doubted their result until this code:
import time

class A(object):
    def __get__(self, instance, owner):
        print '__get__ is run'
        return time.time()
    def __set__(self, instance, value):
        print('let me set, but i will not', value)

class C(object):
    a = A()

c1 = C()
c2 = C()
print(c1.a)
c1.a = time.time()
print(c1.a)
print('-' * 20)
print(c2.a)

The result of this code is:
__get__ is run
1512115138.19
('let me set, but i will not', 1512115138.188)
__get__ is run
1512115138.19
--------------------
__get__ is run
1512115138.19
[Finished in 0.2s]

What happened on earth? Why do these three time.time() calls get the same result?
The same result is for datetime.datetime.now(). And the same result in python 2 and python 3.
I can't find some python technique to explain it.
Comment: This should help you
https://stackoverflow.com/questions/415511/how-to-get-current-time-in-python
Answer: Actually, it is a problem about precision, check this link. You can see a more precise output:
__get__ is run
1512115904.6300762
let me set, but i will not 1512115904.631677
__get__ is run
1512115904.6346197
--------------------
__get__ is run
1512115904.6372328

Comment: So it is:) Thank you!


Inequality involving Jensen (Rudin's exercise)

Question:
Exercise (Rudin, R&CA, no. 3.25). Suppose $\mu$ is a positive measure on the space $X$ and let $f \colon X \to (0,+\infty)$ be such that $\int_X f \, d\mu=1$.
Then for every $E \subset X$ with $0<\mu(E)<\infty$ we have
  $$
\int_E \log f \, d\mu \le \mu(E) \log \frac{1}{\mu(E)}.
$$

This is not homework, it is self-studying. I think I should use Jensen's inequality, but I cannot get it.
I thought considering the positive probability measure $\nu$ given by $\nu:=f\mu$ but I do not see which are the right functions to play Jensen's inequality with. Since $\log$ is concave, I would have
$$
\int_E f \log f \, d\mu \le \log \int_E f^2 \, d\mu
$$
but this is not helpful. Than I can try $\log \frac{1}{x}$ which is convex and I would have
$$
\int_E f \log\left( \frac{1}{f}\right) \, d\mu \ge \log \int_E 1\, d\mu = \log \mu(E)
$$
which looks nicer since it gives
$$
\int_E f \log f \, d\mu \le \log\left(\frac{1}{\mu(E)}\right)
$$
but now I do not know how to handle the LHS.
Any hint, please? Thanks in advance.
Answer: Write the inequality as
$$\frac{1}{\mu(E)} \int_E \log f\,d\mu \leqslant \log \frac{1}{\mu(E)}.$$
Jensen's inequality gives you
$$\exp \left(\frac{1}{\mu(E)}\int_E \log f\,d\mu\right) \leqslant \frac{1}{\mu(E)}\int_E f\,d\mu.$$
The remaining part should be clear.
Comment: Now we have to take $\log$ of both sides and from $\int_E f d\mu \le 1$ we conclude, right? Thank you very much for your help.
Comment: Yes, exactly so.


Why can't I INSERT INTO?

Question: So this might be dumb, but I can't get anything to insert into a MySQL on a certain account, and I've been staring at this for two hours. I'm a newbie to PHP, so I could very well be doing something dumb. I attached a screen shot of the DB I am trying to INSERT INTO.
Here is what I'm talking about:
 (imgur seems to be down for me)
Here's the code I have, and PhpMyAdmin told me  GRANT ALL PRIVILEGES ON . TO  ...
$fbFirstName = $me['first_name'];
$fbLastName = $me['last_name'];
$fbEmail = $me['email'];
mysql_real_escape_string($fbFirstName,$fbLastName,$fbEmail);

$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID=$uid");
$userrowsreturned=mysql_num_rows($getuserresult);
if ($userrowsreturned=0)
  {
        echo '
user already exists, will update something here eventually
';
  }
else {
        $sql = mysql_query("INSERT INTO newusers (fbUID,callsAttempted,callsMade,fbEmail,fbFirstName,fbLastName) VALUES ($uid,'1','0',$fbEmail,$fbFirstName,$fbLastName)");
        if(!$sql) {
            die("Nope");
        } else {
            echo "1 record added";
        }
        echo '
created user
';
}

Comment: Can you `die(mysql_error())`, instead?
Answer: Two things go wrong here. Escaping goes like:
$fbFirstName = mysql_real_escape_string($fbFirstName);
// for all variables

// or, just in one go:
$fbFirstName = mysql_real_escape_string($me['first_name']);

// and for integers, make sure they are actually integers (and prevent mayhem)
$some_id = (int)$me['some_id'];
$uid = (int)$uid;

And when inserting you must quote non-integer values:
$sql = mysql_query("INSERT INTO `newusers`
     (`fbUID`,`callsAttempted`,`callsMade`,`fbEmail`,`fbFirstName`,`fbLastName`)
     VALUES
     ('$uid',1,0,'$fbEmail','$fbFirstName',$fbLastName')");

(but you may quote integers as well - you never know if some external id is, or may become, alphanumeric.)
Comment: It is amazing that feeding `mysql_real_escape_string` incorrect parameter data types as well as one more parameter than it's documented as accepting isn't fatal.
Comment: Brilliant! Thanks for the help. Gradually learning. I will mark this as correct when it allows me to in 3 minutes! THANKS!
Comment: great. I gave some more background you should know about, such as casting of integer values (forcing them to be numbers only) and quoting field/table names in mysql. (for if you have a field named `order`, or `table` you will not run into hard to find bugs)
Comment: this function simplifies things: http://programanddesign.com/php/sql-injection-safe-queries-redux/
Answer: You have an error
if ($userrowsreturned=0)

should be (use double equals to test equivalence, single equals for assignment)
if ($userrowsreturned==0)

I also think you actually mean the following since you're checking if a user already exists
if ($userrowsreturned==1)

Answer: first of all you must change
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID=$uid");

to
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID='$uid'");

after that change your insert to:
$sql = mysql_query("INSERT INTO newusers (fbUID,callsAttempted,callsMade,fbEmail,fbFirstName,fbLastName) VALUES
     ('$uid','1','0','$fbEmail','$fbFirstName',$fbLastName')");

Why can't I INSERT INTO?


sending json stored as string property of an object as JSON object to client

Question: I am using cassandra as DB and storing user address as JSON in "address" field of User object.
class User {
  private long id;
  private String name;
  private String address;
}

Then the User row in DB columns as follows
id   |  name  |   address
================================
12345|  jhon  | {"hno":"12-10-46/3","street":"lavella road","city":"begaluru"}

But when I query User object from DB and returned as result of a REST api I see Jackson converting User object to JSON. But I observed that "address" field as string type instead of another JSON object. But I want that "address" should be interpreted as JSON object on client side.
How I could say jackson to convert internal string property to JSON as well?
Answer: I think you should use the annotation @JsonRawValue in your address field.

@JsonRawValue: per-property marker that can be used to specify that
  the value of property is to be included in serialization ''exactly''
  as is, with no escaping or decoration -- useful for embedding
  pre-serialized JSON (or whatever data format is being used) in output

https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations
Comment: This also works for JSON included JSOn stored as String?
Answer: It's being treated as a string because it is a string.  You'll need to convert it to an object.  Not being fluent in Java I managed to find this snippet that uses the javascript engine to eval the string into an object, the same as a browser would do:
 ScriptEngineManager manager = new ScriptEngineManager();
 ScriptEngine engine = manager.getEngineByName("js");
 Object result = engine.eval([Your Address String Variable Here]);

And then result should be an object derived from the string.
Hope this helps.


Can deep learning determine if two samples of handwriting are by the same person?

Question: I have dabbled using Tesseract CNN OCR on handwriting records before and was surprised by the accuracy. I am wondering, is it possible to use it, or something else, to determine if a sample of handwriting is written by the same person?
I have searched for solutions but it is difficult to get results for anything but OCR recognition with handwriting. Has anyone attempted this before or can point me in the right direction? Thank you.
Answer: This paper seems to do exactly what you want: recognize authorship of handwriting samples, even when the texts don't match.
"DeepWriter: A Multi-Stream Deep CNN for
Text-independent Writer Identification"
Linjie Xing, Yu Qiao. 2016.

Text-independent writer identification is challenging due to the huge variation of written contents and the ambiguous written styles of different writers. This paper proposes DeepWriter, a deep multi-stream CNN to learn deep powerful representation for recognizing writers. DeepWriter takes local handwritten patches as input and is trained with softmax classification loss. The main contributions are: 1) we design and optimize multi-stream structure for writer identification task; 2) we introduce data augmentation learning to enhance the performance of DeepWriter; 3) we introduce a patch scanning strategy to handle text image with different lengths. In addition, we find that different languages such as English and Chinese may share common features for writer identification, and joint training can yield better performance. Experimental results on IAM and HWDB datasets show that our models achieve high identification accuracy: 99.01% on 301 writers and 97.03% on 657 writers with one English sentence input, 93.85% on 300 writers with one Chinese character input, which outperform previous methods with a large margin. Moreover, our models obtain accuracy of 98.01% on 301 writers with only 4 English alphabets as input.

Siamese networks are used to compare things like signatures; it seems reasonable to try and extend this method to handwriting analysis. One challenge would be that whereas signatures are kind of like "stamps" in the sense that the writer will want to reproduce the same symbol over and over, two handwriting samples might not be writing the same words and phrases. So the success or failure of the project hinges on whether the neural network can recognize the writing style as distinct from the words.
Jane Bromley, Isabelle Guyon, Yann LeCun, Eduard Sickinger and Roopak Shah. "Signature Verification using a 'Siamese' Time Delay Neural Network." AT&T Bell Labs. 1994

This paper describes an algorithm for verification of signatures written on a pen-input tablet. The algorithm is based on a novel, artificial neural network, called a "Siamese" neural network. This network consists of two identical sub-networks joined at their outputs. During training the two sub-networks extract features from two signatures, while the joining neuron measures the distance between the two feature vectors. Verification consists of comparing an extracted feature vector with a stored feature vector for the signer. Signatures closer to this stored representation than a chosen threshold are accepted, all other signatures are rejected as forgeries.

Another approach is to use the triplet-loss and embedding strategies such as that used in FaceNet. Then you compare the embeddings by some means to decide if two images have the same or a different author. The success on faces taken from different angles and different lightning conditions is promising, and perhaps a better fit for matching handwriting samples.
Florian Schroff, Dmitry Kalenichenko, James Philbin. "FaceNet: A Unified Embedding for Face Recognition and Clustering"

Despite significant recent advances in the field of face recognition, implementing face verification and recognition efficiently at scale presents serious challenges to current approaches. In this paper we present a system, called FaceNet, that directly learns a mapping from face images to a compact Euclidean space where distances directly correspond to a measure of face similarity. Once this space has been produced, tasks such as face recognition, verification and clustering can be easily implemented using standard techniques with FaceNet embeddings as feature vectors.
Our method uses a deep convolutional network trained to directly optimize the embedding itself, rather than an intermediate bottleneck layer as in previous deep learning approaches. To train, we use triplets of roughly aligned matching / non-matching face patches generated using a novel online triplet mining method. The benefit of our approach is much greater representational efficiency: we achieve state-of-the-art face recognition performance using only 128-bytes per face.
On the widely used Labeled Faces in the Wild (LFW) dataset, our system achieves a new record accuracy of 99.63%. On YouTube Faces DB it achieves 95.12%. Our system cuts the error rate in comparison to the best published result by 30% on both datasets.
We also introduce the concept of harmonic embeddings, and a harmonic triplet loss, which describe different versions of face embeddings (produced by different networks) that are compatible to each other and allow for direct comparison between each other.
Comment: Thank you! This is so helpful. Just what I needed.


Calculate claim amount?

Question: Let X be the random variable representing the claim amount for flooding damage from house insurance policies of bungalow type houses. Past claims show evidence that X is a normally distributed random variable with an average claim amount of μ = 21000 euro and a standard deviation of σ = 4000 euro.
e) An insurance company notes that for 2.5% of claims the claim amount is above K euro, calculate K.
I am lost is 2.5% is the z-score? How can you solve this?
Comment: This looks like a homework problem, you need to add the self-study tag.  It would help for you to explain your understanding of z-scores and describe why you think it is useful in this problem.
Comment: The z score would require a value for X  It would be (K -21000)/4000. The 2.5 % represents the percentile of the standard normal distribution.  From that you get Z and can then determine K..
Comment: Sigh.  Insurance claims are so not normally distributed.
Comment: I have the self-study tag, please help me thanks
Answer: The information given in the problem tells you that
$$ \text{Claim Amount} \sim N(21000, 4000) $$
The second piece of information tells us that the number $K$ is unknown, but satisfies
$$ P(\text{Claim Amount} \geq K) = 0.025 $$
Or, in terms of the left tail
$$ P(\text{Claim Amount} < K) = 1 - 0.025 $$
The cumulative distribution function of the normal distribution with mean $21000$ and standard deviation $4000$ describes these probabilities.  I'll use the notation $\Phi_{21000, 4000}$, for this cumulative distribution function
$$ \Phi_{21000, 4000}(K) = 1 - 0.025 $$
To isolate $K$, we need to use the inverse function
$$ K = \Phi_{21000, 4000}^{-1}(1 - 0.025) $$
Now it's just using whatever software you are comfortable with to compute this quantity.  I'll use python
normal = norm(loc=21000, scale=4000)
normal.ppf(1 - 0.025)

This gives me the result $K \approx 28839$.
As a check
normal.cdf(28839)

Returns $\approx 0.975$.
Comment: It gave me as a wrong answer
Comment: What is the greek symbol never seen it. Can you solve it by hand?
Comment: That's a capital phi, which is usually used for a cumulative distribution function of the normal distribution.  I don't think there is a way to do this without a computer, or a calculator, or some tables containing values of the CDF of the normal distribution (which would be a very antiquated way to do things).
Comment: How do you do it on a calculator? As I have got new numbers and python is not working for me, I am not good at coding. Thank you for your reply
Comment: I suppose that depends on the calculator you are using.  There are probably calculators that have the functionality to do it exactly this way.

Calculate claim amount?


Indefinite Integration issue

Question: $\int\frac{x\sqrt{\ln(x²+1)}}{x²+1} = \frac{1}{2}\sqrt{\ln(x²+1)}$
how should I get $1/2$ ?
I thought I could assume $\ln(x²+1)$ as u, but now I am lost
I thought it must be $1/u$ form to get the answer. If I used the method, I cant get $1/2$
Answer: HINT:
Let $\sqrt{\ln(1+x^2)}=u\implies du=\dfrac1{2\sqrt{\ln(1+x^2)}}\cdot\dfrac{2x}{1+x^2}dx$
$\iff\dfrac{x\sqrt{\ln(1+x^2)}}{1+x^2}dx=u^2du$

Indefinite Integration issue


Problems with Box Layout

Question: I'm trying to use scala.swing package for my gui's. Before that, I was using plain GroupLayout (was writing it by hand :), but scala way seems better. I ran into some problems though - I like BoxLayout, but when I try to add several panes into it, and try to specify different horisontal alignments, I get something strange.
Here is the code:
new Frame {
  contents = new BoxPanel(Orientation.Vertical) {
    contents += new Button("A") {
      xLayoutAlignment = 1.0f
    }
    contents += new Button("B")
    size = (200, 200)
  }
  size = (200, 200)
  visible = true
  peer.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
}

At the very least, I expected to see button B to the left of the button A. Here is what I saw:

Java version of this code does exactly the same, so it is not scala.swing bug.
What am I doing wrong?
Answer:
and try to specify different horisontal alignments, I get something strange.

It's the way BoxLayout was designed to work.
See Fixing Alignment Problems for a better explanation and a simple demo that allows you to play with alignments to better understand how they work.
Comment: I don't think that tutorial explains how BoxLayout was designed to work, and I challenge anyone to look at the source code and tell me what it is trying to do. The tutorial identifies the one case where the behavior is predictable, which is when every component has the same alignment.

Problems with Box Layout


How to append a number to a txt file after specific index

Question: I am beginner in Python and I have question if anybody can help please.
I have txt file. It has structure like is
-0.368242,-0.256205,-0.893732,2.27449e-17, -0.346157,-0.349505,-0.870645,1.21266e-17, -0.239658,0.461163,-0.854338,7.31435e-19,-0.21521,-0.21521,-0.213487, -0.213487,-0.952947,-4.74783e-19
all data type in the file is string.
I need to append to it some data which is coming from function.
This data type is numpynd array. The data is like this
[ 1 2 3 4 5 671 122 1 39 ...]

I would like to append this array after every 4th element in the file.
Example:
-0.368242,-0.256205,-0.893732,2.27449e-17,[ 1 2 3 4 5 671 122 1 39 ...],
-0.346157,-0.349505,-0.870645,1.21266e-17,[ 1344 26 73 84 5 671
122 1 39 ...]

The new array data is changing with time, it is a data coming for like 1 minute, so the first data comes and to be added after 4th element, and the second data will come and will be appended after the next series of elements
example
data 1= [1 2 3 4]
data 2 = [5 6 7 88]

output should be in the file like :
-0.368242,-0.256205,-0.893732,2.27449e-17,[1 2 3 4],
-0.346157,-0.349505,-0.870645,1.21266e-17,[5 6 7 88]

I tried this but never had good results.
with open("test.txt", "a") as f:
   tmp = line.strip().split(",")
   values = [float(v) for v in tmp]  # CONVERTING THE VALUES TO FLOAT
   insertation = np.insert(f, slice(0, None, 4), my_new_data)
   f.write(','.join(str(v) for v in insertation.flat) + '\n')

any help will be appreciated. Thanks:)
Update: the input file was created from this function
    f = open("test_desc2.txt", "w")  # Erases the file content.
    f.close()

>  `HERE TRINGULATE FUNCTION EXISTS.`

    f = open("test.txt", "a")
    f.write(','.join(str(v) for v in self.tringulate.T.flat) + '\n')
    f.close()

Comment: Does this answer your question? [How to append an output to a txt file after every 4th element in this file](https://stackoverflow.com/questions/62821021/how-to-append-an-output-to-a-txt-file-after-every-4th-element-in-this-file)
Comment: @Ehsan No, It doesn't  Thanks for your recommendation
Comment: @Ehsan I see you wrote comments in the other thread. I tried it but not very useful for my case. Any advice please?
Comment: So your input txt file has line breaks in the middle of the data items?
Comment: @alaniwi If I understand you correctly, It should have yes. I will update the post now to show how the input file was made.
Comment: @Timon I am referring to a number like `2.27449e-17` being split across two lines. Either you are having to cope with a very ill-formed input file, or it is just a formatting error in the question. UPDATE - having now seen how your input file is generated, there is no reason why it would do that (i.e. it is just a formatting error in the question) - please can you fix that? See near the start of the question.
Comment: @alaniwi I am not sure if I understand you much:) What is exactly wrong near the start of the question?
Comment: @alaniwi Update: Done, Do you have any advice for my problem?
Comment: @Timon I am not understanding exactly what you are trying, but the first argument to `np.insert` is meant to be an array, and you are giving it a file object.
Comment: @alaniwi Ok, let's say I want to append [1 2 3 4] to the input txt file after every 4th element in the file (Index[3]) as python starts from 0. How would the algorithm/function/code look like? Thanks
Comment: I mean after every 4th element , like after every 4th and then 8th and then 12th ,etc.
Comment: Seems to me that `values` is just a list, and maybe you want to insert directly into that list rather than using numpy - lists have an `insert` method.
Comment: @alaniwi great, but how to insert in every 4th element. That's the tricky part for me. Sorry I am still beginner:)
Answer: I'm afraid, you can not use Numpy to perform your task.
The reason is that Numpy arrays have each element of just the same type,
whereas your list, at least after the insertion, contains a mixture of
floats and (nested) lists.
So I came up with a solution how to insert your sequence of
lists into a plain pythonic list.
I left out reading your list from a text file (at the start) and
writing it back into this file (at the end).
Assume that your source variables are as follows:

Source list (to insert into):
 a = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5]

The sequences to insert:
 seqToIns = [[51.0, 52.0], [71.0, 72.0]]

The step between consecutive insertion points:
 step = 4

To circumvent the problem of "moving indices" (after each insert),
the idea is to insert your sequences in a reversed order.
To iterate over them you can use seqToIns[::-1].
To generate (also reversed) list of target indices, you can use
range(len(seqToIns) * step, 0, -step).
So the task boils down calling insert in a loop, based on "zipped"
results of both above expressions:
for ind, seq in zip(range(len(seqToIns) * step, 0, -step), seqToIns[::-1]):
    a.insert(ind, seq)

When you print your list again, you will get:
[0.1, 0.2, 0.3, 0.4, [51.0, 52.0], 0.5, 0.6, 0.7, 0.8, [71.0, 72.0], 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5]

Comment: Thank you very much for your help. I tried that but it is appending the list data 1= [1 2 3 4] ( Which needs to be appended) to the input txt file not in the correct order. It is appending it like that = [89.96 23.6 0.74 0.923 1 0.2 0.5 0.8 0.4 2 0.23 0.524 0.2155 0.225 4 etc] It is basically appending EACH element of the data1 to the list separately . I want to append all data 1 after the 4th element and then data 2 after the 8th element, etc.
Comment: Maybe there is something wrong with your data. Run my code on **my** data and check that the result is correct. At respective points there are inserted **lists**, without flattetning them.


How to switch all 1's and 0's in a string at once

Question: I have a string of numbers made up of 1's and 0's and I'd like to switch all the 1's to 0's and 0's to 1's at the same time.
My main issue is I can only figure out how to do it one at a time so the result is always either 0000 or 1111.
Comment: `inverted = ''.join('0' if ch == '1' else '1' for ch in s)` - there's more clever ways, but this is a trivial and readable way to do it.
Answer: Assuming the string contains only 1s or 0s:
s = '100110'

out = ''.join('1' if c == '0' else '0' for c in s)

Output:
'011001'

You can also use a translation table (str.mktrans + str.translate), which would also work if you have characters other than 0/1 (they would remain unchanged):
s = '1002110'

t = str.maketrans('01', '10')

out = s.translate(t)

Output:
'0112001'

Answer: Another way to solve this Problem is to chain Pythons String.replace() function. To avoid a String with only 1 or 0 after two replacements, you have to replace one char with an completely diffrent char.
test = '10011110101'
test.replace('0', '_').replace('1', '0').replace('_', '1')

Output:
'01100001010'


Como mostrar mensagem no retorno de postagem de contato

Question: Tenho um formulário de contato onde envio as informações inseridas para o meu BD, gostaria de deixar uma mensagem ao usuário após a submissão do form e não estou tendo sucesso, o que fiz foi isso:
Tenho uma div posicionada acima do meu form, assim:

Ao submeter o form faço uma validação dos campos do mesmo e tendo emitir a mensagem, está assim:

$(document).ready(function(){

   // Scripts de submissão
  $('.contactForm').submit( function(){
        //statements to validate the form
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var email = document.getElementById('e-mail');

        if (document.cform.nome.value == "") {
            $('.nome-missing').css({'opacity': 1 });
        } else {$('.nome-missing').css({'opacity': 0 });}

        if (document.cform.telefone.value == "") {
            $('.telefone-missing').css({'opacity': 1 });
        } else {$('.telefone-missing').css({'opacity': 0 });}

        if (!filter.test(email.value)) {
            $('.email-missing').css({'opacity': 1 });
        } else {$('.email-missing').css({'opacity': 0 });}

        if (document.cform.cidade.value == "") {
            $('.cidade-missing').css({'opacity': 1 });
        } else {$('.cidade-missing').css({'opacity': 0 });}

        if (document.cform.uf.value == "") {
            $('.uf-missing').css({'opacity': 1 });
        } else {$('.uf-missing').css({'opacity': 0 });}

        if (document.cform.assunto.value == "") {
            $('.assunto-missing').css({'opacity': 1 });
        } else {$('.assunto-missing').css({'opacity': 0 });}

        if (document.cform.mensagem.value == "") {
            $('.mensagem-missing').css({'opacity': 1 });
        } else {$('.mensagem-missing').css({'opacity': 0 });}

        if ((document.cform.nome.value == "")       ||
            (document.cform.telefone.value == "")   ||
            (!filter.test(email.value))             ||
            (document.cform.cidade.value == "")     ||
            (document.cform.uf.value == "")         ||
            (document.cform.assunto.value == "")    ||
            (document.cform.mensagem.value == "")) {
            return false;
        }

        if ((document.cform.nome.value != "")       &&
            (document.cform.telefone.value != "")   &&
            (!filter.test(email.value))             &&
            (document.cform.cidade.value != "")     &&
            (document.cform.uf.value != "")         &&
            (document.cform.assunto.value != "")    &&
            (document.cform.mensagem.value != "")) {

            // Mostrar a barra de carregamento
            $('.loader').append();

            //send the ajax request
            $.post('processo.php',{
                                nome:$('#nome').val(),
                                telefone:$('#telefone').val(),
                                email:$('#e-mail').val(),
                                cidade:$('#cidade').val(),
                                uf:$('#uf').val(),
                                assunto:$('#assunto').val(),
                                mensagem:$('#mensagem').val()
                                },

            // Retornar os dados
            function(data){
              // Oculta
              $('.loader').append(data).slideDown(800);
            });

            // Espera 2000, em seguida, fecha o formulário e desaparece
            setTimeout('$(".resposta").slideUp(800)', 6000);

            // Permanecer na página
            return false;
        }
  });
});

O meu .php está assim:

$nome = $_POST['nome'];
$email = $_POST['email'];
$telefone = $_POST['telefone'];
$cidade = $_POST['cidade'];
$assunto = $_POST['assunto'];
$mensagem = nl2br($_POST['mensagem']);

$subject = $assunto;
$body = "From $nome, \n\n$mensagem";
$headers = 'From: '.$email.'' . "\r\n" .
    'Reply-To: '.$email.'' . "\r\n" .
    'Content-type: text/html; charset=utf-8' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail("firstname.lastname@example.com", $subject, $body, $headers);

Obrigado <?php echo $nome ?>!

Em breve entraremos em contato com você.

O css da div resposta está assim:

    .resposta {
    border-bottom: 1px solid #eee;
    padding-bottom: 15px;
    margin-bottom: 15px;
}
Comment: Eu acredito que há maneiras melhores e mais simples de fazer esse envio utilizando o método  `$.ajax({ ... })`. Quanto a validação, é mais fácil e seguro fazer isso direto no PHP e retornar a mensagem via ajax. Vou tentar elaborar uma resposta, só que vai ficar longa.
Answer: Para começar pense em fazer a validação no PHP, chamando uma página via ajax, instanciando a classe conforme abaixo:
class SendEmail
{
   private $nome;
   private $email;
   private $telefone;
   private $cidade;
   private $assunto;
   private $mensagem;
   private $receive_mail;

   public function __construct($data)
   {

    $this->receive_mail = "email@example.com";
      try
      {
        if (count($data) < 6) {
           throw new Exception("Todos os dados devem ser preenchidos.");
        }

        if ($data['nome'] == "") {
           throw new Exception("Preencha seu nome completo corretamente.");
        }

        if ($data['email'] == "") {
             throw new Exception("Preencha seu e-mail corretamente.");
        }

        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL) === false) {
             throw new Exception("Preencha um e-mail válido.");
        }

        if ($data['telefone'] == "") {
             throw new Exception("Preencha seu telefone corretamente.");
        }

        if (!preg_match('/\([0-9]{2}\) [0-9]{4}\-[0-9]{4,5}/', $data['telefone'])) {
             throw new Exception("Preencha um número corretamente, exemplo: (11) 1234-1234.");
        }

        if ($data['cidade'] == "") {
             throw new Exception("Preencha a cidade corretamente.");
        }

        if ($data['assunto'] == "") {
             throw new Exception("Preencha o assunto corretamente.");
        }

        if ($data['mensagem'] == "") {
             throw new Exception("Preencha a mensagem corretamente.");
        }
        //envia a mensagem
         return $this->sendMail();

      } catch (Exception $e) {
            return json_encode(array('success'=>'0','errors'=>$e->getMessage()));
      }

     }

     public function sendMail()
     {
      $subject = $this->assunto;
      $body = "From {$this->nome}, \n\n{nl2br($this->mensagem)}";
      $headers = 'From: ' . $this->email . "\r\n" .
        'Reply-To: ' . $this->email . "\r\n" .
        'Content-type: text/html; charset=utf-8' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

       if (mail($this->receive_mail, $this->assunto, $body, $headers)) {
          return json_encode(array('success'=>'1','message'=>'Mensagem enviada com sucesso!'));
       } else {
          throw new Exception("Ocorreu um erro no envio da mensagem, por favor, tente mais tarde.");
       }
     }
}

if ($_POST) {
    //aqui ele retornará um JSON com os erros ou a mensagem de sucesso
    echo new SendEmail($_POST);
}

Agora no javaScript, execute o método em ajax:
function sedMail() {
   var data = {
       nome:$('#nome').val(),
       telefone:$('#telefone').val(),
       email:$('#e-mail').val(),
       cidade:$('#cidade').val(),
       uf:$('#uf').val(),
       assunto:$('#assunto').val(),
       mensagem:$('#mensagem').val()
  }
    $.ajax({
              url:'sendEmail.php',
              method:'post',
              dataType:'json',
              data: data,
              success: function(data) {
                    if (data.success) {
                         $('.success').text(data.message);
                    } else {
                        if (data.errors.length > 0) {

                            var errorsList = '
\

Corrija os erros abaixo:
\

';
                            for (var i in data.errors) {
                               errorsList+= "
- "+data.errors[i]+"
\n";
                            }
                            errorsList+= '
\

';
                         $('.errors').html(errorsList);
                        }
                    }

              }
     });

E na view, coloque apenas onde irá exibir as mensagens de erro e a mensagem de sucesso:

Comment: Tem uma diferença entre os dois tipos para versões inferiores  `array()` e `[]`.
Comment: Acredito que seja a versão do seu PHP, eu mudei o array, tente novamente.
Comment: Olá @Iva Ferrer, antes de mais nada muitíssimo obrigado pela grande ajuda, no código postado está acusando erro em duas linhas, a primeira é essa: return json_encode(['success'=>'0','errors'=>$e->getMessage()]);
e a outra é essa:  return json_encode(['success'=>'1','message'=>'Mensagem enviada com sucesso!']);
Comment: agradeço a paciência e a grande ajuda, ficou excelente.


Microsoft Office 32-bit over 64-bit leads to error

Question: On a Windows 2012 R2 server used as remote desktop, we installed Microsoft Office 2013 64-bit.
Several weeks later, an accounting software was installed. This required Microsoft Office 32-bit (we tested with 64-bit: failed).
So I uninstalled the 64-bit version, and installed the 32-bit version.
Word and Excel work well.
But Outlook display an annoying error message when launched (but works flawlessly).
The message is not displayed when Outlook is ran as an administrator (being admin is not sufficient, we have to right-click and ask to run as administrator).

when someone run Outlook, we first have the usual blue rectangle with "Outlook" written in the middle
then we immediatly have a small window titled "Microsoft Office 64-bit Components 2013" with a progress bar stating "Please wait while Windows configure Microsoft Office 64-bit Components 2013"
1 or 2 second later an error pop-up appear indicating "Error 2503: an internal error occured. Contact Microsoft support blahblah"
we click on "Ok"
we immediatly have the same pop-up but with error 2502
we click on "Ok"
Outlook now run correctly, until the next time we run it

Each time someone run Outlook we have this exact same scenario.
Steps 1 and 2 occur even when ran with administrator privileges.
I uninstalled/reinstalled the 32-bit version.
I did a repair install.
I deleted a vestigal C:\Program Files\Microsoft Office\.
It is recreated if we run Outlook with administrator privileges.
The error is the same with or without this folder. I even tested with full rights for everyone on this folder and its content.
Any idea to solve this problem?
Comment: Why so many VTCs? If it's used as a remote desktop host, it's a perfectly reasonable business pratice to install Office on a server system.
Comment: How about doing what the message says - contacting Microsoft support?
Answer: This is a know issue. Office 2013 32 bit on a 64 bit OS need the Windows Search service.
"Please wait while Windows Configures Microsoft Office 64-bit Components 2013" message when you start Outook 2013 | https://support.microsoft.com/en-ca/kb/2643974
Cause
This issue occurs when the following conditions are true:
- The 32-bit version of Office is installed on a 64-bit version of the operating system.
- The Windows Search Service is not installed.

Windows Server 2012
Start Server Manager.
Click Manage, and then click Add Roles and Features.
On the Before You Begin page, click Next.
On the Installation Type page, select Role-based or Feature-based Installation, and then click Next.
On the Server Selection page, select the server or virtual hard disk on which you want to install the Windows Search Service.
On the Features page, select Windows Search Service, and then click Next.
On the Confirmation page, verify that Windows Search Service is listed, and then click Install.

If you prefer not to use or install the Windows Search Service, you
  can disable indexing in Outlook. To do this, follow these steps:
Exit Outlook.
Start Registry Editor. To do this, use one of the following procedures, as appropriate for your version of Windows.
    Windows 8: Press Windows Key + R to open a Run dialog box. Type regedit.exe and then press OK.
    Windows 7, Windows Server 2008, or Windows Server 2012: Click Start, type regedit.exe in the search box, and then press Enter.
In Registry Editor, locate and then click the following registry subkey:

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Windows Search
Point to New on the Edit menu, and then click DWORD (32-bit) Value.
Type PreventIndexingOutlook, and then press Enter.
Right-click PreventIndexingOutlook, and then click Modify.
In the Value data box, type 1, and then click OK.
On the File menu, click Exit to exit Registry Editor.

The error stops immediatly after Windows Search Service is installed.
If you don't use the Windows Search Service, just disable it in the service console.
Comment: I didn't found this MS KB, nor anything on Google. Many thanks!


WWW version as website binding or a DNS record?

Question: In a windows server I am trying to setup a new domain and run a website. Which method should I use to access the website using www. prefix?

using IIS by adding a website binding with www. prefix to the website settings? It seems this method has nothing to do with DNS records.
or adding A record in dns manager with the name www?

(or both are needed?)
Thanks.
Answer: If you want to access the site via www.example.com then you need a DNS record for www, or a wildcard DNS record.
Adding the binding to IIS is optional. If this is the only website in IIS then all requests will go to this website, regardless of the name the user types in the browser.
www.example.com, mysite.example.com, blahblahblah.example.com, etc., etc.