text:
Q: Apparent memory leak while using 2D vector in C++ I decided to use C++ 2D vectors for an applications. While testing some code I encountered a bad alloc error. I read that this may be caused by memory shortage so I investigated my program's memory use by calling the malloc_stats function at different steps in gdb.
While I am not sure I completely understand the output of the function, it seems to indicate memory leaks.
I tried to sum up the problem in the short code below:
#include <vector>
#include <iostream>

using namespace std;

vector<vector<double>> get_predictions(){
    vector<vector<double>> predictions;
    for(int i = 0; i < 10; i++){
        vector<double> new_state;
        new_state.push_back(600);
        new_state.push_back(450);
        new_state.push_back(100);
        new_state.push_back(200);
        predictions.push_back(new_state);
    }
    return predictions;
}

int main()
{
    cout << "start" << endl;

    // time loop
    for(int i = 0; i < 10; i++){
        auto predictions = get_predictions();
        // code that uses the latest predictions
    }

    cout << "end" << endl;
    return 0;
}

Now if I call malloc_stats() at the "start" line, the output is similar to this:
Arena 0:
system bytes     =     135168
in use bytes     =      74352
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      74352
max mmap regions =          0
max mmap bytes   =          0

At the "end" step, the function gives:
Arena 0:
system bytes     =     135168
in use bytes     =      75568
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      75568
max mmap regions =          0
max mmap bytes   =          0

The "In use bytes" field clearly increased.
Does it really mean that more allocated memory is held ?
If so, why ? Shouldn't the allocated content be freed once the different vectors go out of scope ?
Then, how to avoid such memory issues ?
Thanks a lot

A: Due to the suggestions in comments, I abandoned malloc_stats, which does not seem to behave as I expected, and tried out Valgrind on my code.
Valgrind confirms that there is no leak in the toy example above.
Concerning my main application, it is a program running on ARM. For reasons unknown to me, the base Valgrind implementation gotten via apt install valgrind did not output the lines concerned by memory leaks. I had to recompile it from sources available on Valgrind website. The problem must come from architecture-specific particularities ?
As a side-note, my application also uses CUDA code, which implies many false positives in Valgrind outputs.


text:
Q: If$f \in L_1 (R)$ so that $xf(x), x \hat{f}(x) \in L_1 (\mathbb R)$, show that $\sum|\hat{f}(n)| \le \infty$ and finally Poisson summation formula
PROBLEM (1)$f \in L_1 (\mathbb R)$ so that $xf(x), x \hat{f}(x) \in L_1 (\mathbb R)$, show that $\sum|\hat{f}(n)| \le \infty$.
(2)Also, show that $\sum_{n\in \mathbb Z} f(x-2\pi n)$ converges
  uniformly on $[-\pi, \pi]$
(3)Finally, prove the Poisson summation formula: for every $x \in
> \mathbb R$
  $$\sum_{-\infty}^{\infty} f(x+2 \pi n) = 1/2 \pi
> \sum_{-\infty}^{\infty}\hat f (n)e^{inx} $$

I even obstruct by (1) and cannot continue.
Using the condition, Fourier inversion and dominated convergence , $xf(x), x \hat{f}(x) \in L_1 (\mathbb R)$, I can show successively $\hat{f} \in L_1 (\mathbb R)$ , $f \in C_0 (\mathbb R)$ and $f \in C_0^1 (\mathbb R)$
Symmetrically, I also can show  $\hat f \in C_0^1 (\mathbb R)$.
Provided $f' \in L_1 (\mathbb R)$, we will have:
$$
 \hat f (n) =\int_{\mathbb R}\,f(x)e^{-i n x} dx
= \frac{f(x)e^{-i n x}}{-inx} \Big |^{\infty}_{-\infty}+(in)^{-1}\int_{\mathbb R}\,f'(x)e^{-i n x} dx
=(in)^{-1} \widehat{f'}(n)
$$
I try to imitate the proof of the corresponding question regarding $L_1 (\mathbb T)$, however, it doesn't work since we don't have  $f' \in L_1 (\mathbb R)$.
Please help!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to mark code lines licensed on MIT? When I am using some code licensed with the MIT license, but it's not in seperate files, is it OK mark it like this?
/* Here starts code licensed under the MIT License (../MIT.txt) */
// code
/* Here is the end of code licensed under the MIT License (../MIT.txt) */

Where in ../MIT.txt file, it would contain the MIT License text and the original author's copyright notices.
Also, when most of code is MIT licensed and I'm only changing some sections of the functions can I mark those parts with the same method as above but with my own license? Yes, it's going to be a lot of kilobytes of comments.

A: When you use MIT-licensed code in a non-MIT-licensed project, simply marking the MIT-licensed parts of the source code is not a good strategy. The license allows you to do just about anything with the code – including sublicensing the code –, under this one restriction:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Note that the MIT license should also be displayed to the end user of your software. Where you display your copyright to the user, you should also add something like

This program includes code from the FooBar library, used under the following license:
The "FooBar" library
Copyright (c) <year> <copyright holders>

<license body>

In addition, you might want to explicitly mark the sections in the code that were taken from an MIT-licensed source. From my understanding, this is not required, but it would be ethical.
When you modify an MIT-licensed source, you should not mark your contributions with a separate license, because this requires an user of the source to follow both the original license and your license. Instead, choose one of the following options:

*

*License your contributions under the same license as the rest of the code. You can edit the copyright notice to reflect that you contributed to the source, without marking what exactly you changed.

*Re-license the MIT-licensed source under your license, in a manner permitted by the MIT license. See above.

Notes:

*

*I'm a programmer, not a lawyer.

*The term "MIT license" is fairly ambiguous. This answer assumes the Expat License, but is also applicable to the X11 License.

A: That's insane. DON'T DO THAT.
If you are working in some one else's code that has an MIT license, then your changes should have the MIT license. If you can't for some reason use the same license as the rest of the project, then you shouldn't be fooling with it. If you have an ethical or whatever disagreement with the licensing of a project, then DON'T WORK ON THAT PROJECT.
It is TOTALLY unreasonable for you to place a veritable copyright compliance minefield throughout each source file. It's NOT reasonable for you to expect users of the code to review every line of every source file in order to determine what the licensing of the thing is.
If you simply MUST do things differently, then pull your code out to separate files, so that someone evaluating the code for their use would have a CHANCE of knowing what license the code was under.
Also: If it came down to a courtroom, I'm unclear how your shenanigans would fare. An unobservant person could legitimately claim to have not noticed your bits being licensed differently, and an unscrupulous one could potentially use the confusion to do things you didn't intend.

A: If you wanted to do this (and you didn't care about the possible backlash) you should at the very least:

*

*Add a license file, as you suggest.

*Point out in the readme file very clearly that the code is licensed as "foo" (whatever the original license is) except where bracketed by "some special start string" and "some special end string" which is MIT licensed. These strings must be unique and never misspelled, so that users could conceivably remove them using a simple script if they don't want your code.

To avoid excessive backlash, you should probably also do this:

*

*Provide the user with a link or script to get the code without your differently licensed changes.

*Make sure the code works (or, at least, all tests pass) if your code is removed.

*Put your code in separate files or wrap the original project (using for example a Git submodule) to guarantee that you're not modifying the original code.
The biggest issue with this is probably how your code would mesh with the rest of it. You can't modify even a single line of the original code and re-license it, so how are you going to do sane changes? For example, you can't statically link GPL code without changing your license to GPL. There are probably hosts of other issues with specific licenses, and you're very likely just creating problems for yourself and others. If you care about other users enough (assuming you're not selling the compiled project) to release your changes, why do you not care enough to use the original license?
A much simpler solution which has no guarantee of success is to calmly and reasonably explain to the original author(s) why you would like the software to use the MIT license, and whether they would be willing to dual license it.


text:
Q: Creating Global document in PDFSharp Not sure if this is specific to PDFSharp, but I have created a PDF document in the main form of a VB.Net project as shown below, and I want to make it global so that Subs in other modules can access it and create new pages and write to those pages. Thanks a lot for any assistance. I tried declaring "doc" as public, but that did not work.
This is the code I have:
[Main Form]
Public Class Form1

    Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim doc As PdfDocument = New PdfDocument
        doc.Info.Title = "Created with PDFsharp"

        Output.Addpage()

        Dim filename As String = "NewFile.pdf"
        doc.Save(filename)

        Process.Start(filename)

    End Sub
End Class

Output Module
Public Sub Addpage()

    page = doc.AddPage

    Using gfx As XGraphics = XGraphics.FromPdfPage(page)

        gfx.DrawRectangle(TablePen, dispLeftMarg - 4, dispTopMarg - 8, dispallowedL + 8, dispallowedH + 12)

    End Using
End Sub

A: I don't know how to make doc public in VB.NET.
In this case, I would not do it anyway.
It's cleaner to pass the doc as a parameter in the call to Public Sub Addpage().
Public Sub Addpage(ByVal doc As PdfDocument) should do the trick.


text:
Q: Why is my plot of the power of a negative number failing? I would like plot something like the power of a negative value. However the graph is empty. Why is that?
My code is like
Plot[{(-2)^n} {n, 1, 3}]

A: Try
ParametricPlot[{Re[(-2)^n], Im[(-2)^n]}, {n, 1, 3}]

A: Plot[Evaluate@Through[{Re, Im, Abs, Arg}[(-2)^n]], {n, 1, 3},
 PlotTheme -> "Detailed"]

Or
ListLogPlot@Table[(-2)^n, {n, -10, 10, 1}]

A: When a plot fails, it is often useful to look at a table of the values function being for a mesh over the domain of the plot. In your case,
Table[(-2)^n, {n, 1, 3, .1}] // Chop

reveals the problem by returning
 {-2., -1.85863 - 1.35038 I, -0.815501 - 2.50985 I, 0.936764 - 2.88306 I,
  2.81716 - 2.04679 I, 4., 3.71727 + 2.70075 I, 1.631 + 5.01971 I,
  -1.87353 + 5.76613 I, -5.63432 + 4.09357 I, -8.}

Plot can not plot the complex numbers in the list.
Perhaps what you really wanted was
ListPlot[Table[(-2)^n, {n, 3}]]


text:
Q: How to run rc.local as normal user? I have some commends that I wish to be called right after login, including 'startx', and I thought rc.local seems a nice place for them, but the problem is that rc.local is run as root and I don't want that, obviously I can do something like this:
su username -c somecommend-here

But I am looking for a way to run the whole 'rc.local' as normal user, or perhaps there is a better place to put my code ?
PS. I am using Ubuntu-mini-remix 1104i386
Thanks

A: The easiest way to launch a command when a user logs in is to create a .desktop file for the command and stick it in the ~/.config/autostart folder. What does the desktop file look like? Here is an example that retrieves the Ask Ubuntu home page with wget every time the user logs in:
[Desktop Entry]
Name=Launch wget
Comment=Fetches the Ask Ubuntu home page.
Exec=wget http://askubuntu.com/

A: I don't know the differences between /etc/rc.local and a crontab, but I generally make a service account and add the appropriate job. For example: sudo crontab -u p4padmin -e
@reboot ~/bin/p4p -d -r ~/var/p4p/cache/foo -p 2020 -t depot:2020 -L ~/var/p4p/log/foo.log

You don't have to login for the service to execute.

A: The linux way is to append your commands to ~/.bashrc instead of /etc/rc.local.
Every user has a .bashrc in it's home directory.
This scriptfile is run automatically just after a user logs in.
It is run with the credentials of the user so a su command is not needed.
It seems to me that this is exactly what you are looking for.


text:
Q: Have const variables in an object which is used in a vector container So I am trying to make snake clone.
I have made a BodyPiece class which has certain variables I would like to be const, as they should not change. This was not a problem when I simply created an instance of Bodypiece to test out. However I want to be able to add pieces as the snake grows so I made a vector body variable. As you can see from the code below:
In BodyPiece.h:
#pragma once
#include "D3DGraphics.h"
#include "Keyboard.h"
#include "Direction.h"

class BodyPiece
{
public:
    BodyPiece(int xPos, int yPos, Direction* dir);
    ~BodyPiece();
    void Draw(D3DGraphics& gfx);
    void UpdateDirection(KeyboardClient& kbd);
    void Move();
private:
    Direction* dir;
    int xPos;
    int yPos;
    int width = 5;
    int height = 5;
    int vx = 5;
    int vy = 5;
};

In Game.h file
BodyPiece vector body declared:
std::vector<BodyPiece> body;

In Game.cpp file
vector initialised in initialiser list.
body({ {400, 300, &d } })

If I make any variables in BodyPiece const, it will generate an error:
error C2582 'operator=' function is unavailable in class BodyPiece.
My questions here are:
What causes that? I have looked online and have a little bit of an idea but it really is only a little bit.
How can I have const variables, use a vector container(or another type of container if that will help, does not have to be vector) and keep the compiler happy? Or should I just completely change my approach?
Thank you in advance.

A: The problem is that if you don't have an assignment operator, then the compiler will generate one for you, that does simple shallow copying of the members. However, if you have actual const member variables (and not only default-initialized like yours) then those can't be copied and the compiler can't create an assignment operator.
The simple solution is to make the constants actual constants and also static so they are members of the class and not part of a single object:
class BodyPiece
{
    ...
    static int const width = 5;
    static int const height = 5;
};

The only drawback with this is that you need to actually define these member variables, in a single source file:
int const BodyPiece::width;
int const BodyPiece::height;

The other solution is to explicitly create an assignment operator that copies the data needed:
class BodyPiece
{
public:
    ...
    BodyPiece& operator=(BodyPiece const& other)
    {
        // Copy data from other to this
        xPos = other.xPos;
        ...
        return *this;
    }
    ...
};


text:
Q: access mongo db on digital ocean server from another machine I have a ubuntu 14.04 droplet set up on a digital ocean server. I have installed mongodb in that server. I have created a database which i can access using
pymongo.Mongoclient()

from a python shell in the server. But I want to create a remote connection to the database from my local machine ( or any other machine). How to do that?

A: Create a mongo connection string and then pass that to MongoClient.
For example:
mongo_url = 'mongodb://db1.example.net:2500/'
client = pymongo.MongoClient(mongo_url)
db = client.db_name
collection = db.collection_name


text:
Q: Assignments just bind names to objects? According to the Python tutorial, 9.2. Python Scopes and Namespaces:

Assignments do not copy data — they just bind names to objects.

So I'm surprised that the following code doesn't surprise me:
>>> a = 42
>>> b = a
>>> b = b / 2
>>> a
42
>>> b
21

If the assignment b = a just binds the name b to the int object 42, which is already bound to a, shouldn't a be 21 when after b = b / 2 is executed, since a and b refer to the same object?

A: Well, you do make another assignment to b:
b = b / 2

and since operations on int (immutable) types will always return a new object there's no changes made to the original value whatever the operation may be.
This differs for mutable types which can change in certain operations, namely augmented assignment operations were the changes are made in-place:
>>> a = [20]
>>> b = a
>>> b += [1]
>>> b
[20, 1]
>>> a
[20, 1]

Note, of course, that this doesn't happen with simple assignments were, as for ints the name refers to a new object:
>>> b = b + [1]
>>> b
[20, 1, 1]
>>> a
[20, 1]

A: after b =b/2, b is new object
>>> a = 42
>>> id(a)
8006428
>>> b = a
>>> id(b)
8006428
>>> b = b/2
>>> id(b)
8006680

A: Here is a trace of it:
>>> a = 42
a = 42
b is undefined
>>> b = a
a = 42
b = a
>>> b = b / 2
a = 42
b = 21
The operation b = b / 2 is creating a new object using b which at the time points to a.  It is not changing a, merely creating a new value by an operation involving a.  Now, b no longer refers to a, but a new value created using a.


text:
Q: Why does browser.wait cause protractor to wait indefinetely for an async task Im using the latest protractor version to run tests in an all angular2 app. I have one function, which navigates to the login page, does the login process and then calls browser.wait until an element, which appears after login is present. Then my actual test failes with 'Failed: Timed out waiting for asynchronous Angular tasks to finish after 11 seconds.'.
However if I do not wait for the login process to finish, the test passes. So apparently I am missing something with the browser.wait function. browser.sleep(x) causes the same behaviour.
My code lookes something like this:
this.login = () => {
  browser.get(${this.baseUrl}/login);
  let emailField = element(by.id('emailID-input'));
  let passwordField = element(by.id('passwordID-input'));
  let submitBtn = element(by.id('loginSubmitId'));
  emailField.sendKeys(credentials.email);
  passwordField.sendKeys(credentials.pass);
  submitBtn.click();
//browser.driver.sleep(3000);
  return browser.wait(() => {
    return element(by.xpath('//*[@id="header"]')).isPresent()
      .then((isPresent) => {
        console.log('Header is Present;', isPresent);
        return isPresent;
      });
  });
};

In the actual test-spec I want to login before running my tests:
beforeAll(async () => {
   helpers.login().then(() => {
   console.log('logged in');
   });
});

Edit 1:
I changed the wait condition to also include a timeout, but the problem persits.
let until = protractor.ExpectedConditions;
let header = element(by.xpath('//*[@id="header"]'));
return browser.wait(until.presenceOf(header), 5000);

A: You need to mention the wait time in browser.wait() method. Once the maximum wait time is reached protractor will throw Timeout exception based on your wait condition. And also try to use ExpectedConditions instead of direct isPresent() method.
var EC = protractor.ExpectedConditions;
var ele = element(by.xpath('//*[@id="header"]'));
return browser.wait(EC.presenceOf(ele),5000); //It will wait for 5 secs

A: In protractor there is default getPageTimeout: timeout_in_millis that is set to 10 secs. Your page is taking longer than 10 secs to load, and hence it is showing you timeout error message.
You can specify this in your conf.js file.


text:
Q: How to update all matches in array of objects? I want to update this array of objects
var a = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"}]

to
var a = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"found it"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"found it"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"found it"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"found it"}]

This only updates the first match in this array, but I need it to update all matches.
a.find(x => x.uuid == "93161c2b-6c56-4204-b6b5-c5c3cee0f38a").answer = "found it"

I know I can loop through the array to change each answer matching the uuid, but is there a better way to do this?

A: A short and simple way to loop through them all and change them would be with forEach:

var a = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"}];

a.forEach((elem, idx) => {
  if (elem.uuid == "93161c2b-6c56-4204-b6b5-c5c3cee0f38a") {
    elem.answer = "found it";
  }
});

console.log(a);

Alternatively, you can use map, another shorthand way to do effectively what you described. It returns a new array:

var a = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"}];

a = a.map(elem => elem.uuid == "93161c2b-6c56-4204-b6b5-c5c3cee0f38a" ? ({ ...elem, answer: "found it" }) : elem);

console.log(a);

Note that this still will loop through the array, but it's a neater way to do it (creating a new array based off of your original one). I used object spreading  { ...elem } syntax above so that it'll preserve other properties in your objects too if there are more. Another, more verbose way to do this would be:

var a = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"}];

a = a.map(elem => {
  if (elem.uuid == "93161c2b-6c56-4204-b6b5-c5c3cee0f38a") {
    elem.answer = "found it";
  }
  return elem;
});

console.log(a);

A: There are 2 ways to achieve the result:
1) Using forEach: (Preferred way)

var data = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"}]

const updateRecord = (data, id) => {
  data.forEach((record) => {
    if(record.uuid === id){
      record.answer = 'found it'
    }
    return record
  })

  return data
}

console.log(updateRecord(data, "93161c2b-6c56-4204-b6b5-c5c3cee0f38a"))

2) Using map:

var data = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"}]

const updatedData = data.map(record => record.uuid == "93161c2b-6c56-4204-b6b5-c5c3cee0f38a" ? ({ ...record, answer: "found it" }) : record);

console.log(updatedData);


text:
Q: Best lessons from well built web sites I am looking for examples of web sites that developers can learn from, inspiring sites that get everything right.
In particular, a site should excel in all these areas:

*

*Consistently fast load speed

*Semantic HTML

*Accessible

*RESTful

*Gracefully degrades

*Appropriate HTTP headers, including caching

*Secure

Please nominate a site and explain why it wins, and what we should learn from it.

A: Follow the YSlow and Google recommendations for making your web site as fast as possible.

A: I'd suggest http://html5boilerplate.com as a great example of didactic web development. It's entire raison d'être is to exemplify a the best practices it promotes.


text:
Q: How can I search variables from another template I am in my homepage template where I have only search box like google main search page looks like, Now I want to search variables from another template and display it but nothing happen. Below is my code
Homepage template
<form action="{% url 'loststuffapp:IndexView' %}" method="GET" value="{{request.GET.q}}" class="navbar-form" role="search" style="margin-left: 25em;">
        <input type="text"placeholder="Search....." name="q">
        <button type="submit" onclick="/Miscellaneous"></button>
</form>

Home page view
def IndexView(request):
    title="Homepage"
    return render(request, "loststuffapp/home.html", {"title":title})

Miscellaneous template

Jina la nyaraka:  {{Doc.docs_name}}

Aina ya nyaraka:  {{Doc.item_type}}

    {% if Doc.image %}

    {% endif %}

{{Doc.date}}

Miscellaneous view
def Miscellaneous(request):
    query = request.GET.get('q', '')
    qsets=(Q(docs_name__icontains=query)|Q(item_type__icontains=query))
    return render(request, "loststuffapp/Miscellaneous.html", context={"documents":Documents.objects.filter(qsets)})

A: If I understand you correctly you want to pass the q parameter from the form on your home page to the Miscellaneous view. Currently your code just calls your IndexView in submitting the form and returns to it.
I guess you are expecting that the form to submit to the Miscellaneous view by adding the url to onclick of your button. I do not think that works like that as onclick expects some javascript function. Your form submits to the url you put into the action attribute of your form, and this is your homepage.
So the simplest approach would be to change the action attribute of your form to point to your Miscellaneous view:
<form action="{% url 'loststuffapp:Miscellaneous' %}" method="GET" value="{{request.GET.q}}" class="navbar-form" role="search" style="margin-left: 25em;">
        <input type="text"placeholder="Search....." name="q">
        <button type="submit"></button>
</form>

Remark: I am not sure what you expect from the value attribute or your form
What you can do also is to return to your IndexView on submit of the form and redirect from there to the MiscellaneaousView, passing the query as an argument. However, this does not look necessary from what I read from your post.


text:
Q: Converting threaded to multi threaded code? ( task factory ?) I have the following threaded code ( i think ) form with a start and cancel button and a multilined text box, the commented sections (//) are from the working single threaded version and below i have tried to retrofit the multithreaded task.factory parts, however it seems to launch the powershell commands fine ( show in task manager ) but the program completes without waiting for the results from each "heavyOperation".
The idea is to start all the four HeavyOperation tasks at the same time (ish) and wait for each to return the results and append the results to the text box
public partial class Form1 : Form
{
    Progress<string> progressReporter = new Progress<string>();
    CancellationTokenSource cancelSource;

    public Form1()
    {
        InitializeComponent();
        progressReporter.ProgressChanged += progressManager_ProgressChanged;
    }

    async private void btnStart_Click(object sender, EventArgs e)
    {
        btnStart.Enabled = false;
        btnCancel.Enabled = true;
        cancelSource = new CancellationTokenSource();
        //textBox1.Text = await Task.Run(() => PerfromTaskAction(cancelSource.Token));
        await Task.Run(() => PerfromTaskAction(cancelSource.Token));
        lblStatus.Text = "Completed.";           btnStart.Enabled = true;
        btnCancel.Enabled = false;
    }
    //private string PerfromTaskAction(CancellationToken ct)
    static void PerfromTaskAction(CancellationToken ct)
    {
        //StringBuilder sb = new StringBuilder();

        object[] arrObjects = new object[] { "SERVER1", "SERVER2", "SERVER3", "SERVER4" };

        foreach(object i in arrObjects)
        {
            //if (ct.IsCancellationRequested) break;
            //sb.Append(string.Format("{0}: {1}\r\n", HeavyOperation(i.ToString()),i));
            //((IProgress<string>)progressReporter).Report(string.Format("Now Checking: {0}...", i));
            Task.Factory.StartNew(() => HeavyOperation(i.ToString()));
        }
        //return sb.ToString();
    }
    void progressManager_ProgressChanged(object sender, string e)
    {
        lblStatus.Invoke((Action)(() => lblStatus.Text = e));
    }
    //private string HeavyOperation(string i)
    public static void HeavyOperation(string i)
    {
        PowerShell ps = PowerShell.Create();
        ps.AddCommand("invoke-command");
        ps.AddParameter("computername", i);
        ps.AddParameter("scriptblock", ScriptBlock.Create("get-vmreplication | select State"));
        Collection<PSObject> result = ps.Invoke();
        //return result[0].Properties["State"].Value.ToString();
        Console.Write(result[0].Properties["State"].Value.ToString());
    }
    private void btnCancel_Click(object sender, EventArgs e)
    {
        cancelSource.Cancel();
    }

}

Thanks for looking

A: You also need to await for the HeavyOperations to complete.
You can use Task.WhenAll for this purpose. Here is an async version of PerformTaskAction, using Task.WhenAll
I've taken into account Scott Chamberlain's suggestions:

*

*Changed the unsafe (in async-await context) Task.Factory.StartNew() to Task.Run()

*Removed the unnecessary await in the invocation of PerformTaskAction()

*Passed the missing CancellationToken in the outer Task.Run() call
static async Task PerfromTaskAction(CancellationToken ct) {
         //StringBuilder sb = new StringBuilder();
     object[] arrObjects = new object[] { "SERVER1", "SERVER2", "SERVER3", "SERVER4" };
     IList<Task> tasks = new List<Task>(); // collect all tasks in single collection
     foreach( object i in arrObjects ) {
        //if (ct.IsCancellationRequested) break;
        //sb.Append(string.Format("{0}: {1}\r\n", HeavyOperation(i.ToString()),i));
        //((IProgress<string>)progressReporter).Report(string.Format("Now Checking: {0}...", i));
        tasks.Add(Task.Run(() => HeavyOperation(i.ToString())));
     }

     await Task.WhenAll(tasks).ConfigureAwait(false); // wait asynchronously for all tasks to complete
  }

Now that PerformTaskAction is async, you also need to await on it.
Finally you invoke PerformTaskAction, making sure you also pass the CancellationToken.
await Task.Run( ()=> PerformTaskAction(cancelSource.Token), cancelSource.Token);


text:
Q: Compare two TreeMap I have two TreeMap
The first map is:
Map<String, Double> m1 = new TreeMap();

and the second is:
Map<String,double []> m2 = new TreeMap();

I want to search the Key in first map to the second one, and then multiply the value of the first map to the list of second map values (for the similar keys).
After that I will Have an array of type double from the multiplication, then I want to sum the values for each index independent.
For Example:
Map 1:
Apple : 1.0
Cat:2.1
Dog:1.2

Map2:
Apple:{2.0,0.0,4.0}
Dog {1.1,0.0,0.0}
Moon:{0.0,5.0,2.0}

The Result will Be:
Apple{2.0,0.0,4.0}
Dog{1.32,0.0,0.0}

Then the summation :
{3.32,0.0,4.0}

This is my try, I do the search between the two matrixes, then I do the multiplication .
***My question how can I do the summation for each index and how to retrieve a value for spesfic index.
    for ( Map.Entry<String,Double> entry : m1.entrySet() ) {
 List<Double> myList = new ArrayList<Double>();
     if ( m2.containsKey(entry.getKey()) ) {
         //if the key is common in map1 and map2, compare the values
                    double y=entry.getValue();
                    double j[]=m2.get(entry.getKey());
                   for (int u=0;u<j.length;u++){
                       myList.add(j[u]);
                   }
                   for (int i=0;i<myList.size();i++){

                    System.out.println(entry.getKey()+" "+myList.get(i)*y);
                 }
               }}

A: Given the commutative property of addition, keep the total sum array outside of the loop and for every matched keys, add the current index i of the total sum array to the product of y and j[i].
Let's assume a size N for the array. Then:
double[] finalSum = new double[N];

for ( Map.Entry<String,Double> entry : m1.entrySet() ) {
     if ( m2.containsKey(entry.getKey()) ) {
         //if the key is common in map1 and map2, compare the values
         double y=entry.getValue();
         double j[]=m2.get(entry.getKey());
         for (int u=0;u<j.length;u++){
             finalSum[u] += y * j[u];
         }
     }
}


text:
Q: Using NET_DNS2 Get records I'm using pear package NET_DNS2. I can get records using the code below. But i have some confusion about the nameserver 8.8.8.8. This is Google Public name server address. Why we are using this. And how can i change this to my own name server for local host.
<?php

require "NET/DNS2.php";

$r = new Net_DNS2_Resolver(array('nameservers' => array('8.8.8.8')));
$result = $r->query('domain.com', 'A');

echo "<pre>";
print_r($result);
echo "</pre>";

?>

How can i get Domain Owner and Hosting provider information. Please help

A:
Why we are using this

Because it's fast, awesome and free*?

And how can i change this to my own name server for local host.

Replace '8.8.8.8' with 'localhost' or '127.0.0.1', maybe?  C'mon man, show some effort.
* There ain't no such thing as a free lunch; what's Google doing with our DNS queries?

A: NET_DNS2 communicate with the dns server by sending request from the specified nameserver.
You can use your own computer Ip address for this (Not 127.0.0.1 or localhost)

A: You can leave out the nameservers option, and it will default to using the nameservers in /etc/resolv.conf, just like other network software on your system.


text:
Q: Prevent Windows Explorer from interfering with Directory operations Sometimes, no "foo" directory is left after running this code:
string folder = Path.Combine(Path.GetTempPath(), "foo");
if (!Directory.Exists(folder))
    Directory.CreateDirectory(folder);
Process.Start(@"c:\windows\explorer.exe", folder);
Thread.Sleep(TimeSpan.FromSeconds(5));
Directory.Delete(folder, false);
Directory.CreateDirectory(folder);

It seems Windows Explorer keeps a reference to the folder, so the last CreateDirectory has nothing to do, but then the original folder is deleted.  How can I fix the code?
EDIT:
I'm sorry that my question wasn't clear.  My objective is to create an empty "foo" directory.  If the directory already exists, I delete it and create it anew.  The problem is that if Windows Explorer is looking at the directory, the CreateDirectory call sometimes fails silently.  No exception is raised; the directory just isn't created.
The code above reproduces the issue in my computer.  Only the last two lines belong to my actual application.  The previous lines are setup.  After you run the code, does "foo" always exist?  This is not the case half the time in my pc.
For the time being, I'm manually deleting each file and subdirectory of foo.

A: Since you did not provide details (like exceptions, errors), I will assume this is the problem.
I think the problem is that the explorer is still running when you run the command to delete the folder. This could be a locking problem.
Directory.Delete(folder, false);

Either that, or there is some other application accessing that folder or its sub-folders or files, if any by chance.
I would recommend not touching the folder via explorer or any other app, if possible, and wait for the explorer to exit first, before deleting the folder.
        Process p = Process.Start(@"c:\windows\explorer.exe", folder);
        Thread.Sleep(TimeSpan.FromSeconds(5));
        p.WaitForExit(); //<-------
        Directory.Delete(folder, false);

Also, please do not ignore the exceptions and errors thrown and paste them here, if any.
Hope it helps.


text:
Q: Log4Net output to Mongo Does anyone had the luck to have this configured correctly?

*

*Created an account on MongoHQ

*Added a new user to the database

*Created a new Collection named logs_net

*Added log4mongo-net library

*Added the configuration to the web.config
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
and
<log4net>
  <appender name="MongoAppender" type="log4net.Appender.MongoDBAppender, log4mongo-net">
     <!-- MongoDB connection options -->
     <host value="staff.mongohq.com" />
     <port value="10048" />
     <databaseName value="d1741d63-46b1-4a44-9c21-8a85cecae45b" />
     <collectionName value="logs_net" />
     <userName value="balexandre" />
     <password value="myPassWorD" />
  </appender>

*

*Added log4net.Config.XmlConfigurator.Configure(); to global.asax under Application_Start()
and added some info:
ILog logger = LogManager.GetLogger(this.GetType());
logger.Info("MainController Initialize test");

And... I can't get logs into MongoDB, any help?
By the way, the Database name is not the correct one, neither the password, and if I use log4net.Appender.RollingFileAppender it works great.

A: I suggest turning on internal debugging, this should reveal what is going wrong. It is quite possible that the log4mongo assembly is not loaded correctly. Are you sure it is copied (with all dependencies) to the bin folder?

A: I had the same symptoms for a different reason. My XML logging configuration was wrong. Here is how I found out.
1) Enable internal (not log4net) debugging in the code before logger is created:
log4net.Util.LogLog.InternalDebugging = true;
...
XmlElement conf = ...
XmlConfigurator.Configure(conf);
var logger = LogManager.GetLogger(loggerName);

2) Run your code and see output in Visual Studio Output window with Debug selected in Show output from dropdown. You should be able to see how Appenders are constructed.
In my case database url was wrong - I specified additional options in a bad format.


text:
Q: com.google.android.gms:play-services-measurement-base error when running ionic cordova run android Full error

The library com.google.android.gms:play-services-measurement-base is
  being requested by various other libraries at [[16.5.0,16.5.0],
  [16.4.0,16.4.0]], but resolves to 16.5.0. Disable the plugin and check
  your dependencies tree using ./gradlew :app:dependencies.

I have tried multiple solutions:
I've tried removing the cordova-plugin-firebase issue so I can run this
cordova plugin add https://github.com/dpa99c/cordova-plugin-firebase#GH-1057-April-05-android-build-issue

but when I do remove it I am getting:

Uninstalling cordova-plugin-firebase from android Android Studio
  project detected Error during processing of action! Attempting to
  revert... Uh oh! ENOENT: no such file or directory, open
  'C:\Users\user\Documents\app1\test\platforms\android\app\src\main\AndroidManifest.xml'

I have also tried replacing these values from project.properties from:
cordova.system.library.2=com.google.android.gms:play-services-tagmanager:+
cordova.system.library.3=com.google.firebase:firebase-core:+
cordova.system.library.4=com.google.firebase:firebase-messaging:+
cordova.system.library.5=com.google.firebase:firebase-config:+
cordova.system.library.6=com.google.firebase:firebase-perf:+

to:
cordova.system.library.2=com.google.android.gms:play-services-tagmanager:16.0.8
cordova.system.library.4=com.google.firebase:firebase-core:16.0.8
cordova.system.library.5=com.google.firebase:firebase-messaging:17.5.0
cordova.system.library.6=com.google.firebase:firebase-config:16.4.1
cordova.system.library.7=com.google.firebase:firebase-perf:16.2.4

But I am getting an error for each of the com.google.firebase line

Could not find com.google.firebase:firebase-perf:11.0.4 .   Searched in the following locations:
          file:/C:/Users/user/AppData/Local/Android/sdk/extras/m2repository/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .pom
          file:/C:/Users/user/AppData/Local/Android/sdk/extras/m2repository/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .jar
          file:/C:/Users/user/AppData/Local/Android/sdk/extras/google/m2repository/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .pom
          file:/C:/Users/user/AppData/Local/Android/sdk/extras/google/m2repository/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .jar
          file:/C:/Users/user/AppData/Local/Android/sdk/extras/android/m2repository/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .pom
          file:/C:/Users/user/AppData/Local/Android/sdk/extras/android/m2repository/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .jar
          https://maven.google.com/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .pom
          https://maven.google.com/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .jar
          https://jcenter.bintray.com/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .pom
          https://jcenter.bintray.com/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .jar
          https://dl.google.com/dl/android/maven2/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .pom
          https://dl.google.com/dl/android/maven2/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .jar
          https://repo1.maven.org/maven2/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .pom
          https://repo1.maven.org/maven2/com/google/firebase/firebase-perf/11.0.4
    /firebase-perf-11.0.4 .jar   Required by:
          project :app

A: Setting exact versions for firebase plugin dependencies is the fix you're looking for. The true reason for this issue is dependency conflicts caused by Google API update on May 7th.
But moving on, it's impossible to tell what your next exact issue is from the information you provided, however, one of your plugins is still requesting firebase-perf-11.0.4 and it really does not exist at any of the paths gradle is looking at.
What you should do is find out which other plugin might be trying to download firebase-perf-11.0.4 as a dependency. But first, open your project in Android Studio to see whether such a dependency even exists.


text:
Q: How to maintain page background image zoom fixed? CSS I know how to set page background like;
body{
  background-color: blue;
  background-image: url(imagename.ext);
  background-repeat: no-repeat;
  background-position: left;
}

The page is subject to zoom. Using the browser, user can zoom in and zoom out. But the background image may not zoom-in or zoom-out. It may remain as such, in it's default size. Is this possible?

A: html {
  background: url(images/bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

A: You can use css:
background-size: cover;

Tutorial: http://css-tricks.com/perfect-full-page-background-image/

A: Little unrelated to question but that might help someone.  I'll go with the use of a jquery plugin like http://srobbin.com/jquery-plugins/backstretch/ for this.
I have always had speed issues with having full page static background (as Anup Jangid's answer) through css. It makes scrolling of the page very slow and slugish.

A: I don't think that there is a native clean way to achieve what you're asking. This method should work but you may get some (perhaps acceptable) flickering as the size adjusts after the browser zooms.
Specify background-size:widthpx heightpx and when the browser zooms you need to detect the zoom scale (see How to detect page zoom level in all modern browsers?) and set the width px and height px of the background image accordingly.


text:
Q: Can I redirect customer back to my store from Stripe Hosted Invoice page? I'm generating Invoice object in Stripe and then redirecting customer to the hosted_invoice_url (https://stripe.com/docs/api/invoices/object#invoice_object-hosted_invoice_url)
After customer completes the payment, in the final step they are presented with two buttons - Download Invoice and Download Receipt, but there is no button/link for going back to my store. So it's a dead end. Customer can only close their browser tab.
Is there a way to specify something like success_url or home_url that would add a button for getting the customer back to my store?
Right now as a workaround I'm forcing hosted_invoice_url to open in a new tab. Customer closes the tab after they are finished and they get back to my store in the original tab.

A: From what I know, this is not possible with hosted invoices pages. I'd recommend relaying this use case/feedback directly to Stripe.
However, if you were to use Stripe Checkout you can pass success_url and cancel_url parameters which will fulfil your requirements in this case. Perhaps Checkout might be a better product for your use case?


text:
Q: How to display download file popup (not a new window)? I try to display "save as" popup on IE using javascript (jquery is ok too).
The expected result is:

I use this code:
window.open("some url on my server", "_self");

and I get:

How can I make it look like in the first picture? as a popup at the bottom of the page, and not modal like I get..

A: You can't do this with JavaScript or jQuery. You need to set the HTTP headers of the request as follows:
header('Content-disposition: attachment; filename=excel1.xlsx');
header('Content-type: application/vnd.ms-excel');

The above is a PHP example. Telling the browser to handle the request as an octet stream will prompt the user with the Save As... dialogue.


text:
Q: When to use Hibernate projections? I am a little confused about Hibernate's projections and criteria. When to use projections and when to use criteria?

A: They're not mutually exclusive, you can use both at the same time. Projections are generally used in the context of some Criteria.
To put it simple, Hibernate Projections are used in order to query only a subset of the attributes of an entity or group of entities you're querying with Criteria. You can also use Projections to specify distinct clauses and aggregate functions like max, sum and so on. It's like referring to which data you're fetching. Like modifying the select clause in an SQL query.
Hibernate Criteria are used to define conditions the data has to satisfy in order to be selected. It's like referring to how is the data you're fetching. Like modifiying the from and where clauses of an SQL query.
Note that this how and which is not strictly true, it's just an orientation aimed to aid the OP. You can change which data you're fetching with createCriteria(String associationPath) for instance.
I'd suggest to take a look at this article Hibernate: Criteria Queries in Depth

A: Projections are used to execute aggregate operations and to get single column query,with Restrictions we  can access a ROW but with PROJECTIONS we can access whole COLUMN
EX -
public static void main(String[] args) {
    SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
    Session session = factory.getCurrentSession();
    try {
        session.beginTransaction();
        Criteria c = session.createCriteria(Student.class);
        Projection p = Projections.property("lastName");
        List<String> students = c.setProjection(p).list();
        for(String s:students)
            System.out.println(s);
        session.getTransaction().commit();
        session.close();
    } finally {
        factory.close();
    }
}

In the above example i used projection call to ADD a projection property "name" to the criteria. It returns winchester winchester winchester winchester , which is the lastName COLUMN in the table.
Output =

Hibernate: select this_.last_name as y0_ from student this_
  winchester
  winchester
  winchester
  winchester

Note - We can add only one projection, if we add more than 1 projection previous one will be overridden. if you want to add more than one projection you will nedd ProjectionList class
Orignal Table -

A: Hibernate projections are useful for
1)Fetching only certain columns of the table
2)Performing aggregations like count,sum,max,min,avg.
Fetching only the columns which are needed improves the performance of the query.
Examples of projection
Projections using DTO
Projection List example

A: Projection is an Interface given in "org.hibernate.criterion" package, Projections is an class given in same package,  actually Projection is an interface, and Projections is an class and is a factory for producing projection objects.
In Projections class, we have all static methods and each method of this class returns Projection interface object.
If we want to add a Projection object to Criteria then we need to call a method setProjection()
Remember, while adding projection object to criteria, it is possible to add one object at a time.  It means if we add 2nd projection object then this 2nd one will overrides the first one (first one wont be work), so at a time we can only one projection object to criteria object
Using criteria, if we want to load partial object from the database, then we need to create a projection object for property that is to be loaded from the database
Criteria crit = session.createCriteria(Products.class);
crit.setProjection(Projections.proparty("proName"));
List l=crit.list();
Iterator it=l.iterator();
while(it.hasNext())
{
    String s = (String)it.next();
    // ---- print -----
}

If we add multiple projections to criteria then the last projection added will be considered to execute see…
Criteria crit = session.createCriteria(Products.class);

Projection p1 = Projection.property("proName");
Projection p2 = Projection.property("price");

crit.setProjection(p1):
crit.setProjection(p2):
List l=crit.list();


text:
Q: How can I use css animations to do this based on scroll position? This example works but I'm wondering if there is a better way.
Ideally a solution that would let me update a transitions keyframe based on scroll position or something. That way I don't have to handle the complex computations in javascript.
Any help or insight would be greatly appreciated.
https://jsfiddle.net/chrischilcoat/19dp24ou/
Update method called using this.
<div ref={pager} onScroll={update} class="relative w-full overflow-x-auto scrollbar-hide">

Update Method.
 const update = () => {
    const currentScrollLeft = pager.current.scrollLeft;
    currentScrollLeft < 125 ? setScrollPosition(currentScrollLeft) : setScrollPosition(125);
    toggleNextBtn();
  }

Then I update the styles needed based on scroll position.
const [scrollPosition, setScrollPosition] = React.useState();

  const pager = React.createRef();

  const addWrapperStyles = {
    'height': (215 - (scrollPosition / .75))+'px',
    'width': (130 - (scrollPosition / 1.7))+'px',
    'borderBottomLeftRadius': (0) +'px',
    'borderBottomRightRadius': (15 + (scrollPosition / 8)) +'px',
    'borderTopLeftRadius':  (0) +'px',
    'borderTopRightRadius': (15 + (scrollPosition / 8)) +'px',
    'paddingTop': (scrollPosition / 15.5)+'px',
  };
  const addImageStyles = {
    'height': (166 - scrollPosition / .92)+'px',
    'width': (166 - scrollPosition / .92)+'px',
    'borderRadius': (scrollPosition / 2)+'px'
  };
  const addPlusStyles = {
    'marginRight': (scrollPosition / 4)+'px',
    'height': (25 - scrollPosition / 16)+'px',
    'width': (25 - scrollPosition / 16)+'px',
    'borderWidth': '1px',
    'right': (scrollPosition / 7)+'px',
    'marginLeft': ( scrollPosition / 32)+'px'
  };
  const addTextStyles = {
    'opacity': '.08'
  };

React then handles inserting the new inline styles.


text:
Q: Can util:RegistrySearch variables be used with an ExePackage's SourceFile in Burn? A program I'm developing requires OBS Studio, among other dependencies, to function. For convenience, I'm building a Burn bundle that will install each dependency in proper order before installing the main application.
Uninstalling is a problem. OBS has its own uninstall executable, and telling the Burn where that executable is has proven impossible. The install directory is clearly readable in the registry (OBS stores the install directory as a default value for the key):
<util:RegistrySearch
 Variable="OBS"
 Root="HKLM"
 Key="SOFTWARE\WOW6432Node\OBS Studio" />

But I cannot get the variable into the SourceFile of ExePackage that would use it during uninstallation. The following code has failed in my attempts:
<ExePackage Id="Uninstall_OBSStudio"
 SourceFile="!(wix.OBS)\uninstall.exe"
 DetectCondition="NOT OBS_exists"
 Cache="no"
 Compressed="no" />

Passing the variable as "[OBS]" has failed as well, being read as a literal string. Using the variable in conditions works without issue, but this won't go at all. I've even tried passing the value to a WixVariable, too:
<WixVariable Id="OBS_location" Value="[OBS]" />

To no avail. So far, it looks like util:RegistrySearch is locked out of some parts of Burn, for reasons I don't understand.
What am I supposed to do to use a RegistrySearch variable within the SourceFile string? Nothing I've done to format the data has worked. Can Burn even pass around data in the way I'm trying? Is there a better way to pull information from the registry for Burn chains?
I'm really hoping this just a syntactical issue. Thanks in advance for any guidance you can provide.

A: No. The source file for all package types is resolved when you build the bundle. During runtime, Burn will hash the file to make sure it is running the same file that was specified at compile time.
There's a feature request in here somewhere, probably either a new package type for the installation framework that created that installer or the ability for an ExePackage to get its uninstall command from the registry. https://github.com/wixtoolset/issues/issues


text:
Q: Benefits of Static Functions for Class Constructions I have seen code like this, so I'm trying to find the reason.
What's the main reason for having static functions that act as constructors, instead of having actual constructors?
I mean something like:
class MyClass
{
    public:
    static MyClass CreateFrom( bar );
    static MyClass CreateFrom( foo );
    ...
}

instead of:
class MyClass
{
    public:
    MyClass( bar );
    MyClass( foo );
    ...
}

A: They are called Named Constructors.
The are basically used when you want to construct an object which requires to pass a particular set of parameters but internally you need to construct the object differently.
For example you have a class like:
class AREA
{
double area;
AREA(int x);
};

//how will you construct the object differently in case of circle and square??

For this purpose, we have named constructors which help to create a relevant object.
So we may create 2 static methods inside the class as:
static AREA square(int x)
{ return AREA(x*x); }

and
static AREA circle(int x)
{ return AREA(x*x*3.14); } //or a more accurate PI value

Thus, we may call the relevant static function to return the object initialized with the required area.
NOTE: These are static as while creating an object for a particular class you shouldn't be requiring an object to do so.
Check THIS for more details.

A: This is called the "named constructor idiom".
It's typically used when:

*

*You have a lot of ctors with similar enough enough parameter lists that overloaded ctors would be confusing (e.g., different mixtures of integer and floating point numbers, so 1, 1.0, 1 is supposed to mean something different from 1, 1, 1.0).

*You have two different sources that both provide the input as the same type. For example, let's assume you wanted to convert a distance on the surface of the earth into the angle subtended between points that distance apart -- but you might want to supply the distance in either miles or kilometers, either of which would be represented as a double.

In this case a single angle(double dist) can't distinguish between input in kilometer vs. miles, but: angle_from_miles and angle_from_kilomters can do that quite easily.

A: The most obvious benefits are:

*

*It's easy to specify the implementation which constructs the instance at the callsite, when multiple constructors are provided. This makes it easier for the class to provide multiple variants.

*These variants may also have different names, but identical parameter lists (or parameter lists which the compiler may call out as ambiguous when determining which to choose).

*It helps you because you can read which constructor your implementation calls -- at the callsite.

Another reason is that it is easier in some cases to initialize the class within a function body, rather than using an initialization list.


text:
Q: Let $x∈ℝ$ be given. By using a contradiction argument, show the equivalence of $x≤0$ $⇔$ $x<ε$, for all $ε>0$ Let $x∈ℝ$ be given. By using a contradiction argument, show the equivalence of $x≤0$ $⇔$ $x<ε$, for all $ε>0$.
Since this is an equivalence question, I know that I must prove both sides of the argument, i.e. $⇐$ and $⇒$.
For $⇒$ I started by supposing that $x≥ε$, and we know this must satisfy for all $ε>0$, thus implying that $x≥0$ ... which I know is a contradiction to what we are given on the LHS, but I'm unsure how to express this from the stage I got to, up to the end result.
For $⇐$ I started by supposing that $x>0$ but I was a bit stuck on how to progress from this point, as I don't know which other information I should use to continue.
Any help/pointing out any of my errors would be appreciated.
Thank you.

A: About $\implies$:
"For ⇒ I started by supposing that x≥ε, and we know this must satisfy for all ε>0, thus implying that x≥0 ... which...."
That's kind of garbled but you have the idea.
The opposite of "$x < \epsilon$ for all $\epsilon > 0$" is not "$x\ge \epsilon$ for all $\epsilon > 0$".  It is "there exists at least one $\epsilon > 0$ so that $x \ge \epsilon$.  And from that we can conclude that $x \ge \epsilon > 0$ so $x > 0$.  (That is a stronger result than $x \ge 0$). And that contradicts $x \le 0$. ( $x \ge 0$ and $x \le 0$ are NOT contradictions as it would be possible for $x = 0$ and both those statements would be true.)
So that's that
.....
Frankly I would not do the $\implies$ direction by a contradiction and I don't think the excercise was intending to use a contradiction for this dirction.
If $x \le 0$ then for all $\epsilon > 0$ we have by transitivity, $x \le 0 < \epsilon$ or $x < \epsilon$.
That's it.  I think the exercise intended the $\implies$ direction to be too easy and trivial to require much proof.
I think the contradiction was for proving the $\Leftarrow$ dirction:
About $\Leftarrow$
Asumme $x > 0$ and get a contradiction:
For $x > 0$ the remember that the opposite of "$x < \epsilon$ for all $\epsilon > 0$" is ""there exists at least one $\epsilon > 0$ so that $x \ge \epsilon$".  Can you find such an $\epsilon$?  What if you picked an $\epsilon $ so that $0 < \epsilon < x$?
Are there any such numbers between $0$ and $x$?  If there were, would that be a contradiction to $x \ge \epsilon$?
1:

 Well, $\epsilon = \frac x 2$ is such a number $0 < \frac x2=\epsilon < x$.  THere's infinitely many others, but this one is ... right there.

2:

 Obviously if $0 < \epsilon  = \frac x2 < x$ then that is an $\epsilon > 0$ where $x < \epsilon $ is not true.


text:
Q: EXC_BAD_ACCESS after modifying string I am manipulating a large string by removing chunks of characters, and assigning the new string back to the original string.
articleString = [articleString stringByReplacingCharactersInRange:startRange withString:@""];
articleString is an instance variable of type NSMutableString
This seems to work fine the first time I go through this code.  But when I return from the second time through, and use the variable articleString, I get an EXC_BAD_ACCESS exception.
These are long strings - up to 100K bytes.
Any ideas why I am getting the exception?

A: stringByReplacingCharactersInRange:startRange would return a copy of type NSString.  (Not NSMutableString)
you want to use:
- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString instead.
stringByReplacingCharactersInRange:startRange returns an autoreleased NSString so you would have to call retain on it if articleString is a member variable.

A: Please post the whole code block so we can figure out what's happening :)
My guess is that this is happening because of an autorelease inside your method block and then assigning it back to the original variable.  If you are creating a new string either with the static stringWithFormat, or an autorelease that string, no matter what you do with it will have it's reference counter decremented when you exit the code block.  This means that if you are assigning it back to the original string, your original string will now be released the second time in, causing your EXE_BAD_ACCESS.
The solution in that case would be to either mutate the existing NSMutableString, or retain the string and release it later when it is safe.  For example, using replaceCharactersInRange:withString: instead may fix the problem.


text:
Q: Mac Mail: Add other message as attachment I'd like to add other mail message as an attachment to a new one but Mail (On OSX Lion) does not allow me to do that.
Any workaround?
Gil

A: This might help in your case:

*

*Select the email message you want to send as an attachment.

*Click on File then Save As and select the format Raw Message Source

*Open a new email message and add the raw source file as an attachment (either copy and paste or insert).

A: Attaching other Messages in Mail.app (OS X Lion)

*

*Create a new message (⌘N)

*Return to your inbox

*Click and hold on the message you want to attach until it turns into a letter icon

*(Still holding down) drag and drop the icon into the new message window

Repeat steps 2 through 4 for as many messages as you want to attach.

A: I believe what you're looking to do is "forward" an email...

A: What I did was , composed a new email , went back to my inbox and dragged and dropped the required emails into my composed email .
I think it worked


text:
Q: Neural net with Pybrain will not converge I am trying to build a simple neural network using Python and Pybrain package.
As I am starting to learn both the method and Pybrain package. I tried to make a very simple neuralnet with some real data that I have available!
I know there is an underlying connection to my data, however the code does not converge at all, and the results after the training are basically the same for any set of real validation data that I put there. Below is my code and a small part of the data. I have over 5000 lines of data available with known g to train my network, but it does not matter the number of points added to the training.
from pybrain.tools.shortcuts import buildNetwork as bld
from pybrain.datasets import SupervisedDataSet as spds
from pybrain.supervised.trainers import BackpropTrainer as bpt
import numpy as np

u,g,r,i,z = np.loadtxt("dataset.dat",unpack=True)
data = spds(4,1)
net = bld(4,1000,1)
for i in range(0,len(umag)):
    data.addSample((u[i],r[i],i[i],z[i]),(g[i]))

trainer = bpt(net,data)
trainer.trainUntilConvergence(dataset=data,maxEpochs=300,validationProportion=0.5)
p = net.activate([17.136,15.812,15.693,15.675])
print p
#expected result 16.225
p = net.activate([19.382,17.684,17.511,17.435])
#   18.195  - expected result
print p

18.14981    15.10829    13.96468    -10.8685    13.20411
16.84580    15.17839    14.61974    14.44930     14.44493
16.70895    15.57959    15.28097    15.16538     15.19260
18.44166    16.32709    15.45345    15.14938     15.04544
18.03881    16.49129    15.96768    15.78446     15.77211
21.15679    18.66248    17.46381    16.97513     16.75475
19.25665    17.80023    17.18956    16.97563     16.94967
17.01522    16.08040    15.85172    15.81930     15.92262
19.21695    17.72263    17.17900    16.98280     16.97201
19.98507    18.56911    17.98143    17.80738     17.81714
16.94824    15.97417    15.70555    15.59221     15.64357
21.20893    19.40982    18.68114    18.46647     18.43065
18.72652    17.38880    16.93716    16.73246     16.75096
20.57421    19.55045    19.15475    18.99772     19.02503
22.48833    20.07709    18.68276    17.60561     17.09613
22.27604    20.34056    19.66521    19.37319     19.30457
20.58372    19.18035    18.64691    18.43370     18.39288
22.25103    20.74570    20.16532    19.94144     19.78580
22.49646    19.63043    18.39409    17.97594     17.77803
19.22686    17.55373    16.97127    16.76445     16.70418
20.44500    19.34502    18.96556    18.80437     18.78767
22.69331    21.19628    19.89190    19.39628     19.11377
19.51075    18.02397    17.46963    17.31436     17.27759
19.92604    18.49456    17.97421    17.83519     17.80557
19.18904    18.22256    17.84221    17.70319     17.64457
20.23186    18.43468    17.81423    17.60103 17.54677
19.86590    18.32822    17.75089    17.57386 17.53067
20.84188    19.78345    19.42506    19.27895     19.34572
22.14103    21.86670    21.74832    21.61244     21.99680
18.02018    16.69380    16.23947    16.12869     16.09864
19.92574    18.63316    18.15877    17.95703     17.90224

A: Generally speaking, I get better results if I have scaled my data to be between 0 and 1, or better yet between 0.1 and 0.9.  The neuron output is usually going to be between 0 and 1.  You might try scaling your inputs and outputs to be within this range, and see if you get better results.


text:
Q: Pay off for portfolio consisting of long call and short put both struck at K? Arbitrage construction? I'm very new to financial maths. Please can I get some help on this question, thanks!
Q: Write down the payoff of a put option with a strike of $K$. What is the payoff for a portfolio consisting of a long call and a short put both struck at $K$? Can you construct an arbitrage from this portfolio?
Here's what I have so far:
$$\operatorname{Put}(T) = \max \{ K - S(T), 0 \}$$
$$\operatorname{Call}(T) = \max\{ S(T) - K, 0 \}$$
Payoff of the portfolio is $$\operatorname{Call}(T) - \operatorname{Put}(T) = S(T) - K$$
Is this correct? If not where am I going wrong?
Also can someone explain whether an arbitrage can be constructed? I've so far only had practice in an FX environment.

A: As discussed in the comments, your portfolio payoff is correct.
However, it's impossible to tell whether there it is possible to construct an arbitrage portfolio or not. Often, when one is given prices for the stock, a call and a put striking at $K$ with the same maturity, and a risk-free rate $r$, then one wishes to use put-call parity to determine whether an arbitrage portfolio is possible. Put-call parity is given by:
$$C-P = S - e^{-rt}K$$
Without knowing the values in the expression above, it's impossible to tell whether one can construct an arbitrage.


text:
Q: Value and text shown same time on option button but i need just text In my project i need to post to value of option button but i need to display a text not the option value. Both of them shown same time. Is there a way to not display the value.
My HTML code.
        Başlangıç noktasını seçiniz
            <input list="browsers" style="border-color: rgba(1, 15, 13, 0.842); color: rgb(0, 0, 0);" name="baslangic" />
            <datalist id="browsers" >
              <option value="603">Bus Stop</option>
              <option value="276">Geomatics Engineering</option>
              <option value="649">Library</option>
            </datalist>

I tried many thing with style="" but i couldn't do that

It display bot of them

A: You can use data- attr and helper function for get value.
     <form action="/create" method="post" >
          Başlangıç noktasını seçiniz
          <input id="inpbrowsers" list="browsers" style="border-color: rgba(1, 15, 13, 0.842); color: rgb(0, 0, 0);" />
           <datalist id="browsers" >
                        <option data-value="603">Bus Stop</option>
                        <option data-value="276">Geomatics Engineering</option>
                        <option data-value="649">Library</option>
                </datalist>

                <input type="hidden" id="baslangic"  name="baslangic">

                <input type="submit" value="submit">

    </form>

Updated Now select item in datallist,baslangic get value. and submit form send value for your server[action].

you can download html page from Github


text:
Q: java.lang.NoSuchMethodError: com.sun.xml.internal.ws.api.message.Message.getHeaders I'm trying to connect to a CMIS server with Apache Chemistry,
when it is configured with an AtomPumb url it works ok, but when I swith to webservices and when it tries to create a session it throws this error:
    java.lang.NoSuchMethodError: com.sun.xml.internal.ws.api.message.Message.getHeaders()
    Lcom/sun/xml/internal/ws/api/message/HeaderList;

these are the dependencies in my POM:
    <!-- * * * * * * * * * * * * * * * * * * * * -->

    <dependency>
        <groupId>org.apache.chemistry.opencmis</groupId>
        <artifactId>chemistry-opencmis-commons-api</artifactId>
        <version>0.13.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.chemistry.opencmis</groupId>
        <artifactId>chemistry-opencmis-client-impl</artifactId>
        <version>0.13.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.chemistry.opencmis</groupId>
        <artifactId>chemistry-opencmis-commons-impl</artifactId>
        <version>0.13.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.chemistry.opencmis</groupId>
        <artifactId>chemistry-opencmis-client-bindings</artifactId>
        <version>0.13.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.chemistry.opencmis</groupId>
        <artifactId>chemistry-opencmis-client-api</artifactId>
        <version>0.13.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.chemistry.opencmis</groupId>
        <artifactId>chemistry-opencmis-workbench</artifactId>
        <version>0.13.0</version>
    </dependency>

    <!-- * * * * * * * * * * * * * * * * * * * * -->

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.21</version>
    </dependency>

what is the problem? that class is in the rt.jar, that is in the jre lib folder.

A: There is an issue with OpenCMIS 0.13.0 on Java 8. See
https://issues.apache.org/jira/browse/CMIS-917. This has been fixed in OpenCMIS 0.14.0.
Avoid the CMIS Web Services binding! The other CMIS bindings are significantly faster!


text:
Q: Ignorance OR bug on PHP's "foreach" construct? I have a dataset obtained from MySQL that goes like this:

Array
(
    [0] => Array
        (
            [views] => 14
            [timestamp] => 06/04
            [views_scaled] => 4.9295774647887
            [unix_time] => 1239022177
        )

    [1] => Array
        (
            [views] => 1
            [timestamp] => 19/04
            [views_scaled] => 0.35211267605634
            [unix_time] => 1240194544
        )

        ...
        ...
        ...

) 1

(it's post-processed, 'timestamp' was really a timestamp before, but that doesn't matter anyways)
The array is stored on $results, and in the middle of my code I do something like this:

$results = array_merge($results, $new_days);
$a = $results;
foreach ($results as $row)
{
    $unix_time[] = $row['unix_time'];
}
$b = $results;

The problem: $a and $b are both different. The first one shows the array as it's supposed to, and the second one has the same count(), but it's fourth element is a duplicate from the last one. As far as I know, I'm not passing anything by reference, so $results Isn't meant to change (maybe the pointer, but not it's content). I'm using PHP 5.2.4 on Mac OS X 10.5.2.
The obvious question: Is this somehow the intended behavior, a bug or I'm doing something wrong here? (not a boolean answer please ;)

EDIT: Thank you all for the interest, I don't know exactly how much extra code should I post, I don't do much before except for retrieving the data from the DB and a foreach to parse the timestamp and build a new array ($new_days) for the missing days. This is all working fine.

This code goes after the one I've posted early:

array_multisort($unix_time, SORT_ASC, $results);
$days = implode('|', array_pluck('timestamp', $results));
$views = implode('|',  array_pluck('views', $results));
$views_scaled = implode(',', array_pluck('views_scaled', $results));

(array_pluck() is a custom function to generate an array from a column in a typical DB-dumped dataset)

EDIT 2: Thanks again, here's the full snippet and the output from the $results array $a and $b (also referenced in the code's comments).

A: Inspecting your code snippet, really quickly (just about to leave the office for the day), it is probably to do with something passing by reference in your (first) loop. Try using normal by value and just storing everything into a fresh result array. (will remove any mysteries that could be going on). Could also try making the second $row in the second foreach a different name.. beats me - can't tell you with really looking at this more.
also this line and following block of code won't execute
if ($last_day != $day_before_this_one AND $last_day)

could have something to do with it, new days will never fill up and the merge could be doing something funky.
Wouldn't call this an answer but its a start to look at I guess

A: The problem is the first foreach loop, as was already mentioned.
Here's the reasoning...
<?
// set up an example array and loop through it using references (&)
$my_array = array(1,2,3,4);
foreach($my_array as &$item)
{
  $item = $item+.1;
}
// 1st loop, $item points to: $my_array[0], which is now 1.1
// 2nd, $item -> $my_array[1], which is now 2.1
// 3rd, $item -> $my_array[2], which is now 3.1
// 4th, $item -> $my_array[3], which is now 4.1
// looping done, but $item is still pointing to $my_array[3]

// next foreach loop
foreach($my_array as $item)
{
  var_dump($my_array);
  print $item."<br>";
}
// notice the & in the output of the var_dump, if you actually run this code.
// 1st loop: the value of $my_array[0] is assigned to $item, which is still a pointer/reference to $my_array[3]
// first loop.. array(1.1,2.1,3.1,1.1) // grabbing [0] and putting into [3]
// next loop... array(1.1,2.1,3.1,2.1) // grabbing [1] and putting into [3]
// next loop... array(1.1,2.1,3.1,3.1) // grabbing [2] and putting into [3] (here's where the magic happens!)
// last loop... array(1.1,2.1,3.1,3.1) // grabbing [3] and putting into [3] (but [3] is the same as [2] !!!)
?>

I hope this makes sense! Basically the second to last value will be repeated because the last value is replaced during the second loop.

A: I can't imagine how that is intended behavior. There must be something else going on here. Can you isolate the behavior to a piece of code that's small enough to post here? Probably if you do the bug will become obvious.

A: I would also say there's something else going on.
I wrote this:
<?php

$a = array('bob','sam','tom','harry');
$b = array();
$c = array();

foreach($a as $item) {
        $c[] = $item;
}
$b = $a;

print_r($a);
print_r($b);

And got:
php ./test.php
Array
(
    [0] => bob
    [1] => sam
    [2] => tom
    [3] => harry
)
Array
(
    [0] => bob
    [1] => sam
    [2] => tom
    [3] => harry
)

I am running PHP 5.2.8, though.

A: I think your problem is that the result set isn't really an array, it's a mysql resultset object that acts like an array.
I think if you go through each row, assigning it to a fresh array, then do the merge, it'll act properly.

A: Unless I'm mistaken, this was a PHP bug a while back. I don't know the details, but arrays and references have been screwed up for a little bit.


text:
Q: Parse error: syntax error, unexpected 'return' (T_RETURN), expecting function (T_FUNCTION) I tried to insert code into my customizer_class.php file in Wordpress. I got code from this page: http://vibethemes.com/documentation/wplms/knowledge-base/removing-instructors-profile-link-from-name-in-course-page/ and saved my file with the code.
However the code didn't work. I deleted the code and updated the file. However I got this error:

Parse error: syntax error, unexpected 'return' (T_RETURN), expecting function (T_FUNCTION)

Now practically all of my website refused to work and spits back the above error on nearly every page I access. I can't even log in as admin on my Wordpress website due to this error.
Here is the code that I have right now with the code I originally tried to put in removed.
<?php

if(!class_exists('WPLMS_Customizer_Plugin_Class'))
{
    class WPLMS_Customizer_Plugin_Class  // We'll use this just to avoid function name conflicts
    {

        public function __construct(){
            add_filter('wplms_course_nav_menu',array($this,'wplms_course_nav_menu'));
        } // END public function __construct
        public function activate(){
            // ADD Custom Code which you want to run when the plugin is activated
        }
        public function deactivate(){
            // ADD Custom Code which you want to run when the plugin is de-activated
        }

        // ADD custom Code in clas
        function wplms_course_nav_menu($menu_array){
            $units = bp_course_get_curriculum_units(get_the_ID());
            if(!is_Array($units) || !count($units)){
                unset($menu_array['curriculum']);
            }
            return $menu_array;
        }

    } // END class WPLMS_Customizer_Class
} // END if(!class_exists('WPLMS_Customizer_Class'))

?>

I think that I might have deleted necessary code when removing the ineffective extra code but I have no clue what the original file looked like. Even if I can find what it looked like, WP admin is not functioning due to the error so fixing it is difficult.


text:
Q: File's shift encryption and decryption - Code isn't working properly My code is working when I am running it in codeblocks but when I am trying to open the .exe file of it, its not working there properly. Would some one help please ?
I am a beginner learner of programming. This is the first code I am working on. A simple caesar cipher in c. I took help from web to write the code. Its running well when I am running it in codeblocks but its not working when I am running the .exe file. It stops after I input the key. I don't know what to do now.
#include <stdio.h>

#define MAXCHAR 1000

int main()
{
  int i, x, key;
  FILE *fptr;
  char str[MAXCHAR], ch, filename[MAXCHAR];

  printf("\nPlease enter a File Name: ");
  scanf("%s", &filename);
  fptr = fopen(filename, "r+");
  if (fptr == NULL){
    printf("Could not open file %s",filename);
  }
  while (fgets(str,MAXCHAR, fptr) != NULL);
  printf("\nPlease choose following options:\n");
  printf("1 = Encrypt the string.\n");
  printf("2 = Decrypt the string.\n");
  scanf("%d", &x);
  printf("Enter key: ");
  scanf("%d", &key);
  switch(x)
  {
  case 1:
    for(i = 0; str[i] != '\0'; ++i){
      ch = str[i];

      if(ch >= 'a' && ch <= 'z'){
        ch = ch + key;

        if(ch > 'z'){
          ch = ch - 'z' + 'a' - 1;
        }

        str[i] = ch;
      }
      else if(ch >= 'A' && ch <= 'Z'){
        ch = ch + key;

        if(ch > 'Z'){
          ch = ch - 'Z' + 'A' - 1;
        }

        str[i] = ch;
      }
    }
    printf("Encrypted string: %s\n", str);
    break;

  case 2:

    for(i = 0; str[i] != '\0'; ++i){
      ch = str[i];

      if(ch >= 'a' && ch <= 'z'){
        ch = ch - key;

        if(ch < 'a'){
          ch = ch + 'z' - 'a' + 1;
        }

        str[i] = ch;
      }
      else if(ch >= 'A' && ch <= 'Z'){
        ch = ch - key;

        if(ch < 'A'){
          ch = ch + 'Z' - 'A' + 1;
        }

        str[i] = ch;
      }
    }
    printf("Decrypted string: %s\n", str);
    break;

  default:
    printf("\nError\n");
  }

  return 0;
}

This is the requirement I was trying to fill up .

Implementation:

*

*File encryption

*File decryption

  Note:
Read the contents(plain text) from a file (only English letter allowed) as characters, in terms of the KEY (input from keyboard by user ) shift the corresponding character(get cipher text), and do the reverse operation when decrypting the file.
For example:
Assume the plain text is "abcdef", KEY is 5, then every single letter in the plain text will shift right by 5 positions according to the alphabet( the following letter after z is a), get the cipher text (garbled)"fghijkl".
Now decrypt the cipher text: fghijkl, KEY is 5, and then every single letter in the cipher text will be shift left by 5 positions according to the alphabet( the following letter after a is z), get the original text "abcdef".

A: There are few issues with the code you mentioned. Firstly this
scanf("%s", &filename); /* & is not needed */

is wrong, compiler could warned you like

error: format '%s' expects argument of type 'char *', but argument 2
  has type 'char (*)[1000]' [-Werror=format=]

if you had compile your code with flags like -Wall -Wstrict-prototypes -Werror. Remove & as filename is char array and array name itself address, correct one is
scanf("%s", filename);

secondly, here
while (fgets(str,MAXCHAR, fptr) != NULL); /* dummy loop */

semicolon ; at the end of while is intentional or typo ? as due to ; when loop fails str contains NULL. You may want like
while (fgets(str,MAXCHAR, fptr) != NULL) { /* some code */ }

Also fgets() stores the new line at the end of buffer, you might want to remove that trailing \n. For e.g
while(fgets(str, MAXCHAR, fptr) != NULL) {
        str[strcspn(str, "\n")] = 0; /* remove the trailing \n */
        /* some code */
 }

Finally, here
if (fptr == NULL){
    printf("Could not open file %s",filename);
  }

fopen() handling is not correct as if file doesn't exist or fopen() failed it simply print the message and proceed further & do the operation with fptr which it shouldn't, use return 0 or exit(0). For e.g
if (fptr == NULL){
    fprintf(stderr,"Could not open file %s",filename);
    return 0; /* this is must */
}

Sample code:
#define MAXCHAR 1000
int main(void) {
        int i, x, key;
        FILE *fptr;
        char str[MAXCHAR], ch, filename[MAXCHAR]/* I don't think filename will be that much big, use accordingly */;
        printf("\nPlease enter a File Name: ");
        scanf("%s", &filename); /* & is not required as filename itself address */
        fptr = fopen(filename, "r+");
        if (fptr == NULL){
                printf("Could not open file %s",filename);
                return 0; /* add this else it proceeed further */
        }
        while (fgets(str,MAXCHAR, fptr) != NULL) { /* remove semicolon, read each line from file, store into str and do the operation with str  */
                printf("\nPlease choose following options:\n");
                printf("1 = Encrypt the string.\n");
                printf("2 = Decrypt the string.\n");
                scanf("%d", &x);
                printf("Enter key: ");
                scanf("%d", &key);
                switch(x) {
                        case 1:
                                for(i = 0; str[i] != '\0'; ++i){
                                        ch = str[i];

                                        if(ch >= 'a' && ch <= 'z'){
                                                ch = ch + key;
                                                if(ch > 'z'){
                                                        ch = ch - 'z' + 'a' - 1;
                                                }

                                                str[i] = ch;
                                        }
                                        else if(ch >= 'A' && ch <= 'Z'){
                                                ch = ch + key;
                                                if(ch > 'Z'){
                                                        ch = ch - 'Z' + 'A' - 1;
                                                }

                                                str[i] = ch;
                                        }
                                }
                                printf("Encrypted string: %s\n", str);
                                break;
                        case 2:
                                for(i = 0; str[i] != '\0'; ++i){
                                        ch = str[i];
                                        if(ch >= 'a' && ch <= 'z'){
                                                ch = ch - key;
                                                if(ch < 'a'){
                                                        ch = ch + 'z' - 'a' + 1;
                                                }

                                                str[i] = ch;
                                        }
                                        else if(ch >= 'A' && ch <= 'Z'){
                                                ch = ch - key;

                                                if(ch < 'A'){
                                                        ch = ch + 'Z' - 'A' + 1;
                                                }

                                                str[i] = ch;
                                        }
                                }
                                printf("Decrypted string: %s\n", str);
                                break;

                        default:
                                printf("\nError\n");

                }
        }
        return 0;
}


text:
Q: Java Server for Android Application I need to write a server in java that will store integers that are used as stats for my android app. My app has an SQLite database that is already setup that would be useful if I could just pass those contents to the server. I need to do this so that in my multiplayer feature, a player's app will contact the server to know what level their opponent is. (This is not real time). So far I only have a TCP server that opens a client and server socket. Other than that I am not positive what I need to do to make it possible for the server to do what I need. Anyone have suggestions or good tutorials to help me with my problem?
Thanks.

A: One thing you need to keep track of:
Your SQLite DB has to be used as a player session, until the player logs in as another user. To do this, you have to have one instance of the current logged in player. If you prefer other methods, here's a good list.
I don't think you would need a TCP connection to view the stats, instead implement a REST API in PHP or any other language for back-end that would save, update and look up for a particular player. This is a recommended method. If you are familiar with PHP, this tutorial will give you an idea and full details of what I mean.

A: Indeed, building a server has many methods. For example, You can use either socket programming or app-server. If you are familiar with web programming, jsp/php/asp.net, you can communicate between your app and server with HTTP requset, which is easy to do.
To be more specific, someone (neme:abc,password:pwd) logging in with your mutiplayer app, when he or she leaves, send the data to server with HTTP request. Then when he or she logging in with other device, you can get the data from status and continues to play. Of course, you can save the data in local with SharedPrefence in Android, too.
By the way, the apache HTTPClient is recommend when using http connection with server.


text:
Q: Jenkins Pipeline Run Stage On Failure My Jenkins pipline script has a lot of try/catch blocks to notify me when there is a failure. Is it possible to have a stage that will only run if a previous stage fails?
My current script looks something like this.
stage('Stage 1') {
    steps {
        try {
            // do something
        }
        catch(Exception e) {
            bitbucketStatusNotify(buildState: 'FAILED')
            error 'FAILED'
        }
    }
}
stage('Stage 2') {
    steps {
        try {
            // do something
        }
        catch(Exception e) {
            bitbucketStatusNotify(buildState: 'FAILED')
            error 'FAILED'
        }
    }
}
stage('Stage 3') {
    steps {
        try {
            // do something
        }
        catch(Exception e) {
            bitbucketStatusNotify(buildState: 'FAILED')
            error 'FAILED'
        }
    }
}

I want to do something like this.
stage('Stage 1') {
    steps {
        // do something
    }
}
stage('Stage 2') {
    steps {
        // do something
    }
}
stage('Stage 3') {
    steps {
        // do something
    }
}
stage('Only Run On Failure') {
    steps {
        bitbucketStatusNotify(buildState: 'FAILED')
    }
}

A: To notify failures on any stage across your pipeline, use post actions.
For each pipeline result, you can then set some post actions.
Example for unsuccessful(any build that does not end with 'SUCCESS' result):
stages{
    stage('Stage 1') {
        steps {
            // do something
        }
    }
    stage('Stage 2') {
        steps {
        // do something
        }
    }
    stage('Stage 3') {
        steps {
            // do something
        }
    }
post{
    success{
        bitbucketStatusNotify(buildState: 'SUCCESS')
    }
    unsuccessful{
        bitbucketStatusNotify(buildState: 'FAILED')
    }
}


text:
Q: How to conditional format a column if the cell values are in another column if I have 2 columns(E: F:) and I want to find out if the values in one column(F:) are present in the other column(E:), using conditional formatting, how do I do this?
link

this is the conditional formatting I have tried so far:

A: Use MATCH() formula.
=ISNUMBER(MATCH(F1,E:E,0))


text:
Q: Grails findAll() fails, but only some times So, I've been banging my head against a wall trying to figure this out. We have three domain tables: Product, Group, ProdGroupState. ProdGroupState looks like this,
Class ProdGroupState{
    Product product
    Group group
    State state
    String indicator
}

We have a new page which lets users generate reports, including listing the ProdGroupState indicator for all States for a given Product/Group pair. The code that generates the list is
def prodGroupStateInstance = ProdGroupState.withCriteria{
    and{
        eq "group", groupInstance
        eq "product", productInstance
     }
}

On each page of the report we call the same method that has that code, passing it a different product each time. Testing locally shows everything fine, and the correct data is in the report.
The issue we have is that once we moved the code from our local machines to our test server (Websphere if it matters), the code above is no longer pulling in the correct data. But it does it very inconsistently. Only one of the Products is having issues, the others all get the correct data. The one that isn't working ends up with prodGroupStateInstance being [] for all but one Group used. That Group has the expected values: [Y, Y, Y, N, ...] for all 50 States
Checking the logs for debug statements shows that groupInstance and productInstance have the expected values, and if the problem was the withCriteria call then you'd expect it to occur for every Product. So I'm more or less stumped why something that was tested locally on multiple machines and was working fine would fail in such a bizarre way after being deployed.


text:
Q: JSP deny direct access to URL by non-logged in user I have a login and a user info page which is displayed after login. How can I block user info page from direct access by user? How can I implement that with session?

A: At login time, put the found User object in the session.
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user);
    response.sendRedirect("secured/userpage");
} else {
    request.setAttribute("error", "Unknown username/password combo, please try again");
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}

Then implement a Filter which just checks the presence of the logged-in user in the session.
if (((HttpServletRequest) request).getSession().getAttribute("user") != null) {
    chain.doFilter(request, response); // Logged in, so just continue.
} else {
    response.sendRedirect("login"); // Not logged in, redirect to login page.
}

Map this filter on an URL pattern of /secured/* (or anything else whatever you want) and put the secured pages like the user info page in the same folder.
To logout a user, just do session.removeAttribute("user") or, more drastically, session.invalidate().


text:
Q: can openVPN run a simple http proxy? I'm sorry for asking the shortest question on this website, but there's just not much else to it...
Can you make a simple http proxy with openVPN?

A: No.
OpenVPN is VPN software, not http software. If you want to interact with http, you'll need to get other software involved.