text:
Q: Side Effects Breaking Referential Transparency Functional Programming in Scala explains a side effect's impact on breaking referential transparency:

side effect, which implies some violation of referential transparency.

I've read part of SICP, which discusses using the "substitution model" to evaluate a program.
As I roughly understand the substitution model with referential transparency (RT), you can de-compose a function into its simplest parts. If the expression is RT, then you can de-compose the expression and always get the same result.
However, as the above quote states, using side effects can/will break the substitution model.
Example:
val x = foo(50) + bar(10)

If foo and bar do not have side effects, then executing either function will always return the same result to x. But, if they do have side effects, they will alter a variable that disrupts/throws a wrench into the substitution model.
I feel comfortable with this explanation, but I don't fully grok it.
Please correct me and fill in any holes with respect to side effects breaking RT, discussing the effects on the substitution model as well.

A: Imagine that you are trying to build a wall and you have been given an assortment of boxes in different sizes and shapes.  You need to fill a particular L-shaped hole in the wall; should you look for an L-shaped box or can you substitute two straight boxes of the appropriate size?
In the functional world, the answer is that either solution will work.  When building your functional world, you never have to open the boxes to see what is inside.
In the imperative world, it is dangerous to build your wall without inspecting the contents of every box and comparing them to the contents of every other box:

*

*Some contain strong magnets and will push other magnetic boxes out of the wall if improperly aligned.

*Some are very hot or cold and will react badly if placed in adjacent spaces.

I think I'll stop before I waste your time with more unlikely metaphors, but I hope the point is made; functional bricks contain no hidden surprises and are entirely predictable.  Because you can always use smaller blocks of the right size and shape to substitute for a larger one and there is no difference between two boxes of the same size and shape, you have referential transparency. With imperative bricks, it isn't enough to have something the right size and shape - you have to know how the brick was constructed.  Not referentially transparent.
In a pure functional language, all you need to see is a function's signature to know what it does.  Of course, you might want to look inside to see how well it performs, but you don't have to look.
In an imperative language, you never know what surprises might hide inside.

A: Let's begin with a definition for referential transparency:

An expression is said to be referentially transparent if it can be
  replaced with its value without changing the behavior of a program (in
  other words, yielding a program that has the same effects and output
  on the same input).

What that means is that (for example) you can replace 2 + 5 with 7 in any part of the program, and the program should still work.  This process is called substitution.  Substitution is valid if, and only if, 2 + 5 can be replaced with 7 without affecting any other part of the program.
Let's say that I have a class called Baz, with the functions Foo and Bar in it.  For simplicity, we'll just say that Foo and Bar both return the value that is passed in.  So Foo(2) + Bar(5) == 7, as you would expect.  Referential Transparency guarantees that you can replace the expression Foo(2) + Bar(5) with the expression 7 anywhere in your program, and the program will still function identically.
But what if Foo returned the value passed in, but Bar returned the value passed in, plus the last value provided to Foo?  That's easy enough to do if you store the value of Foo in a local variable within the Baz class.  Well, if the initial value of that local variable is 0,  the expression Foo(2) + Bar(5) will return the expected value of 7 the first time you invoke it, but it will return 9 the second time you invoke it.
This violates referential transparency two ways. First, Bar can not be counted on to return the same expression each time it is called. Second, a side-effect has occurred, namely that calling Foo influences the return  value of Bar.  Since you can no longer guarantee that Foo(2) + Bar(5) will equal 7, you can no longer substitute.
This is what Referential Transparency means in practice; a referentially transparent function accepts some value, and returns some corresponding value, without affecting other code elsewhere in the program, and always returns the same output given the same input.

A:
As I roughly understand the substitution model (with referential transparency(RT)), you can de-compose a function into its simplest parts. If the expression is RT, then you can de-compose the expression and always get the same result.

Yes, the intuition is quite right. Here are a few pointers to get more precise:
Like you said, any RT expression should have a single "result". That is, given a factorial(5) expression in the program, it should always yield the same "result". So, if a certain factorial(5) is in the program and it yields 120, it should always yields 120 regardless of which "step order" it is expanded/computed -- regardless of time.
Example: the factorial function.
def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

There are a few considerations with this explanation.
First of all, keep in mind the different evaluation models (see applicative vs. normal order) may yield different "results" for the same RT expression.
def first(y, z):
  return y

def second(x):
  return second(x)

first(2, second(3)) # result depends on eval. model

In the code above, first and second are referentially transparent, and yet, the expression at the end yields different "results" if evaluated under normal order and applicative order (under the latter, the expression does not halt).
....which leads to the use of "result" in quotes. Since it is not required of an expression to halt, it may not produce a value. So using "result" is kind of blurry. One can say an RT expression always yields the same computations under an evaluation model.
Third, it may be required to see two foo(50) appearing in the program in different locations as different expressions -- each one yielding their own results that might differ from each other. For instance, if the language allows dynamic scope, both expressions, though lexically identical, are different. In perl:
sub foo {
    my $x = shift;
    return $x + $y; # y is dynamic scope var
}

sub a {
    local $y = 10;
    return &foo(50); # expanded to 60
}

sub b {
    local $y = 20;
    return &foo(50); # expanded to 70
}

Dynamic scope misleads because it make it easy for one to think x is the only input for foo, when in reality, it is x and y. One way to see the difference is to transform the program into an equivalent one without dynamic scope -- that is, passing explicitly the parameters, so instead of defining foo(x), we define foo(x, y) and pass y explicitly in the callers.
The point is, we are always under a function mindset: given a certain input for an expression, we are given a corresponding "result". If we give the same input, we should always expect the same "result".
Now, what about the following code?
def foo():
   global y
   y = y + 1
   return y

y = 10
foo() # yields 11
foo() # yields 12

The foo procedure breaks RT because there are redefinitions. That is, we defined y in one point, and latter on, redefined that same y. In the perl example above, the ys are different bindings though they share the same letter name "y". Here the ys are actually the same. That's why we say (re)assignment is a meta operation: you are in fact changing the definition of your program.
Roughly, people usually depict the difference as follows: in a side-effect free setting, you have a mapping from input -> output. In an "imperative" setting, you have input -> ouput in the context of a state that can change through time.
Now, instead of just substituting expressions for their corresponding values, one also has to apply transformations to the state at each operation that requires it (and of course, expressions may consult that same state to perform computations).
So, if in a side-effect free program all we need to know to compute an expression is its individual input, in an imperative program, we need to know the inputs and the entire state, for each computational step. Reasoning is the first to suffer a big blow (now, to debug a problematic procedure, you need the input and the core dump). Certain tricks are rendered impractical, like memoization. But also, concurrency and parallelism becomes much more challenging.


text: Q: Calculus 3, Stokes' Theorem So I'm trying to solve this by using Stokes' :$F(x,y,z)=2y\cos(z)i+e^x\sin(z)j+xe^yk$, where $S$ is the hemisphere $x^2+y^2+z^2=9$ oriented upward, $z$ larger than or equal to $0$. I do this by letting $r(t)=3\cos ti+3\sin tj+0k$ , and then evaluate integral $F\cdot dr$ from $0$ to $2\pi$. Lo and behold and I get $-18\pi$. Now, that ain't right. What am I doing wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show "Open with" dialog with one app included? In Windows 11, when I try to double-click a .pptx file, I will see the following "Open with" dialog:

This is a little different from the standard "Open with" dialog, as it has included PowerPoint as the candidate.
I try to simulate such an action via ShellExecute in Delphi, as below:
  Value := ShellExecute(Handle, 'openas', PChar(txtFile.Text), nil, nil, SW_SHOWNORMAL);

  if (Value <= 32) then
    MessageDlg(Format('openas Error code %d', [Value]), mtError, [mbOK], 0);

  Value := ShellExecute(Handle, nil, PChar(txtFile.Text), nil, nil, SW_SHOWNORMAL);

  if (Value <= 32) then
    MessageDlg(Format('nil Error code %d', [Value]), mtError, [mbOK], 0);

  Value := ShellExecute(Handle, 'open', PChar(txtFile.Text), nil, nil, SW_SHOWNORMAL);

  if (Value <= 32) then
    MessageDlg(Format('open Error code %d', [Value]), mtError, [mbOK], 0);

I try 'openas', 'open', nil as the verb, but all of them fail and return error code 31.


text:
Q: Apply date format in multiple dataframes I have 3 data frames, as shown in the code below.
code_1000 <-
  as.data.frame(cbind(
    c("3", "3", "7", "7", "7", "7", "2", "2", "4", "4"),
    c("344", "344", "73", "73", "71", "72", "21", "27", "42", "43"),
    c("9-02-2017", "10-01-2016","9-02-2014", "25-03-2015", "9-02-2017",
      "10-06-2017", "8-04-2017", "25-08-2016", "07-08-2017", "15-11-2016"
    )
  ))
code_2430 <-
  as.data.frame(cbind(
    c("3", "3", "7", "7", "7", "7", "2", "2", "4", "4"),
    c("344", "344", "73", "73", "71", "72", "21", "27", "42", "43"),
    c("9-02-2017", "10-01-2016","9-02-2014", "25-03-2015", "9-02-2017",
      "10-06-2017", "8-04-2017", "25-08-2016", "07-08-2017", "23-09-2016"
    )
  ))
code_3453 <-
  as.data.frame(cbind(
    c("3", "3", "7", "7", "7", "7", "2", "2", "4", "4"),
    c("344", "344", "73", "73", "71", "72", "21", "27", "42", "43"),
    c("9-02-2017", "10-01-2016","9-02-2014", "25-03-2015", "9-02-2017",
      "10-06-2017", "8-04-2017", "25-08-2016", "07-08-2017", "13-06-2016"
    )
  ))
names(code_1000) <- c("number", "code", "date")
names(code_2430) <- c("number", "code", "date")
names(code_3453) <- c("number", "code", "date")

I want to apply a date format on the column date of each dataframe (code_1000, code_2430 and code_3453).
The desired date format is:
   code_1000$date<-lubridate::dmy(as.character(code_1000$date)

Which gives a date format "yyyy-mm-dd" as output (see figure in the link below).

The code above shows 3 samples to make it simpler. Actually I have 50 dataframes, and I am using Shiny to plot some scatter graphs, which the x axis is the date column.
USing for, I tried the following code:
 list<- as.data.frame(c("1000","2430","3453"))
    names(list) <- c("code.ID") # list of the codes dataframes ID

    date.format<-function(df){
    lubridate::dmy(as.character(df[,"date"]))
    }  # function to apply the desired date format

    for (m in 1:nrow(list)){
      loop.df<-eval(parse(text=paste0("code_",list$code.ID[m]))) # for each m, it returns a code_xxxx date frame

    assign(loop.df[,3],date.format(loop.df)) # apply the date format on the dataframe, storing the results
    }

I got the following error:
Error in `[.default`(loop.df, , 3) : incorrect number of dimensions

When I apply the isolated date.format function on the dateframes, it works fine.
I would like to learn how to do this using for and lapply() function, as I have read that in R lapply() is an easier approach most of times.
Thank you in advance!

A: <rant on> I've been trying to get people to abandon the as.data.frame(cbind(...)) strategy for years. It forces everything to be the same atomic type and then when that type happens to be character the results is all factors. A big mess in my opinion. In this case there is a dmy method for factors, but some authors have not provided for that typical user expectation<rant off> (Just use data.frame().)
Assemble the items with the first 5 characters "code_" in a character vector and then loop over them to build a list. Then loop (with lapply again) over that list of R objects to convert the 3rd column to date format:
> objects(pattern="code_.+")
[1] "code_1000" "code_2430" "code_3453"
> obj_list <- lapply(objects(pattern="code_.+"), get)
> str(obj_list)
List of 3
 $ :'data.frame':   10 obs. of  3 variables:
  ..$ number: Factor w/ 4 levels "2","3","4","7": 2 2 4 4 4 4 1 1 3 3
  ..$ code  : Factor w/ 8 levels "21","27","344",..: 3 3 8 8 6 7 1 2 4 5
  ..$ date  : Factor w/ 9 levels "07-08-2017","10-01-2016",..: 9 2 8 5 9 3 7 6 1 4
 $ :'data.frame':   10 obs. of  3 variables:
  ..$ number: Factor w/ 4 levels "2","3","4","7": 2 2 4 4 4 4 1 1 3 3
  ..$ code  : Factor w/ 8 levels "21","27","344",..: 3 3 8 8 6 7 1 2 4 5
  ..$ date  : Factor w/ 9 levels "07-08-2017","10-01-2016",..: 9 2 8 5 9 3 7 6 1 4
 $ :'data.frame':   10 obs. of  3 variables:
  ..$ number: Factor w/ 4 levels "2","3","4","7": 2 2 4 4 4 4 1 1 3 3
  ..$ code  : Factor w/ 8 levels "21","27","344",..: 3 3 8 8 6 7 1 2 4 5
  ..$ date  : Factor w/ 9 levels "07-08-2017","10-01-2016",..: 9 2 8 5 9 3 7 6 1 4

> obj_list <- lapply(obj_list , function(dfrm) {
                      dfrm[[3]] <- lubridate::dmy(as.character(dfrm[,"date"]))
                      dfrm} )
> str(obj_list)
List of 3
 $ :'data.frame':   10 obs. of  3 variables:
  ..$ number: Factor w/ 4 levels "2","3","4","7": 2 2 4 4 4 4 1 1 3 3
  ..$ code  : Factor w/ 8 levels "21","27","344",..: 3 3 8 8 6 7 1 2 4 5
  ..$ date  : Date[1:10], format: "2017-02-09" "2016-01-10" ...
 $ :'data.frame':   10 obs. of  3 variables:
  ..$ number: Factor w/ 4 levels "2","3","4","7": 2 2 4 4 4 4 1 1 3 3
  ..$ code  : Factor w/ 8 levels "21","27","344",..: 3 3 8 8 6 7 1 2 4 5
  ..$ date  : Date[1:10], format: "2017-02-09" "2016-01-10" ...
 $ :'data.frame':   10 obs. of  3 variables:
  ..$ number: Factor w/ 4 levels "2","3","4","7": 2 2 4 4 4 4 1 1 3 3
  ..$ code  : Factor w/ 8 levels "21","27","344",..: 3 3 8 8 6 7 1 2 4 5
  ..$ date  : Date[1:10], format: "2017-02-09" "2016-01-10" ...


text:
Q: Queued job stuck, table possibly locked in Laravel I am using queues to send email notifications in my Laravel application. I am using the database as a queue driver so there is a jobs DB table that looks something like:
id | queue | payload | attempts | reserved_at

I now have a bunch of unsent messages in the queue, but it's the first one that's causing all the trouble: it has 255 in the attempts column and when I try to delete the row in phpMyAdmin nothing happens - it hangs for about 30 seconds, then gives a blank screen.
After I restarted MySQL, it let me delete the row, and all the other messages sent correctly.
The content of the row (I looked closely in the payload field) is, on the surface, the same as all the other rows.
This is the job that is being executed:
public function handle()
{
    try {

        $this->order->sendOrderConfirmation();

    } catch( Exception $e ){

        Log::info('Unable to dispatch order confirmation email.', [
            'order'   => $this->order->id,
            'message' => $e->getMessage(),
            'code'    => $e->getCode(),
            'line'    => $e->getLine(),
            'file'    => $e->getFile()
        ]);

        $this->release();
    }
}

The log message above is nowhere to be found in the logs, but what I did find in the logs is this:
SQLSTATE[22003]: Numeric value out of range: 1264 Out of range value for column 'attempts' at row 1 (SQL: update `jobs` set `reserved_at` = 1550737859, `attempts` = 256 where `id` = 1638) in /home/truvisi3/public_html/secure/vendor/laravel/framework/src/Illuminate/Database/Connection.php:647

It looks like it's trying to increment the attempts counter, but the field is limited to 255. Ok, but why is this breaking the whole queue and not just this process? And what can I do to stop this from happening in the future (besides manually changing the format of the attempts column to accept huge numbers)?
EDIT: here is the job class
class DispatchOrderConfirmationEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * @var Order
     */
    protected $order;
    public $tries = 10;

    /**
     * Create a new job instance.
     *
     * @param Order $order
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {

            $this->order->sendOrderConfirmation();

        } catch( Exception $e ){

            $this->release();
        }
    }
}

A: You need to define the maximum number of attempts for a queued job, otherwise it will be tried indefinitely. When using the database driver this means the  number of attempts can exceed the maximum value for a MySQL TINYINT UNSIGNED field, causing a database exception to be thrown on the 256th attempt.
There are two ways to do this.
Using --tries when starting the worker process:
$ php artisan queue:work --tries=10

Or define a $tries property on your job class:
public $tries = 10;

When both exist, the $tries property takes precedence.
It's a good idea to always specify a max attempts with your worker process using --tries so that queued listeners, mail, and anything else using your queues will eventually fail after too many attempts, and use the $tries property to override the limit when it makes sense for a specific job.
The reason your custom error message doesn't appear in your logs is because the database queue driver updates the attempts and reserved_at fields when it pops a job from the queue, and then sends the job to the worker class. Since incrementing attempts throws an uncaught database exception before the worker runs, your code is never called.


text:
Q: What is "to cram pearls onto a handful of pages" when making an application to a College?
You can't believe that after 12 years of education your future
  depends on what pearls of genius you can cram onto a handful of
  pages – or that complete strangers will sit in a room and determine
  if you will be "worthy" of attending their institution.

Making the Most of Your College Applications By Melissa Algranati and Jennifer Gioia
How should I understand the phrase in bold?

A: First of all, you need to understand the meaning of the key words:

*

*pearl - a thing of great worth

*genius - a very high level of skill or ability

*to cram - to put things into a space that is too small

So, here's how we can paraphrase the sentence:

You can't believe that after 12 years of education your future depends
  on a few pages (of your college admission essay) on which you should write something truly extraordinary, or
  that complete strangers will sit in a room and determine if you will
  be "worthy" of attending their institution.


text:
Q: Can I dynamically link a binary build for linux to work with .Net and Mono I am trying to build an .Net application for Raspberry pi that uses SPI. The SPI driver for Windows 10 IoT was to slow. Therefore am I migrating the project to Linux using Mono (as my code is allready written in .Net)
Since I had a problem with SPI speed on Windows IoT I am thinking about writing the SPI code in c++ and link them dynamically to the .Net application. But I am having a hard time finding info online on how to do this. Does anyone here know?
To sum up the question. I want to run my .Net application on Linux with mono and dynamically link a library that I will write in c++.
Thx for any help!

A: Yes, you can. Just make sure your C++ compiled .so is findable on the system (maybe by making sure LD_LIBRARY_PATH env variable can find it). Then in your C# code:
[DllImport("LibraryName")]
private static extern void Foo();

// Call Foo() from C#

In your C++ code:
extern "C" void Foo()
{
    // do C++ stuff
}

At runtime, when you call Foo() from C#, mono will load the .so and find the function and invoke it.
All of the gory details are here: http://www.mono-project.com/docs/advanced/pinvoke/


text:
Q: Animation is not working on a matplotlib gridspec I have reviewed the answer to the question:
how to use GridSpec() with FuncAnimation in matplotlib?
however I believe I am doing something wrong but do not know what, my mission here is to create multiple animations for each of the grids and I also used a code mode for a gauge to animate the count of used data.
x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)
xrand = np.random.random(size = 10000)
x = [x1, x2, x3, x4]
plt.figure()

gspec = gridspec.GridSpec(3,3, wspace = 0.25)
GS1 = plt.subplot(gspec[0, 0])
GS2 = plt.subplot(gspec[0, 1])
GS3 = plt.subplot(gspec[1, 0])
GS4 = plt.subplot(gspec[1, 1])
GS5 = plt.subplot(gspec[0:,2:])
GS6 = plt.subplot(gspec[2,:2])
GS = [GS1, GS2, GS3, GS4,  GS5, GS6]

bins1 = np.arange(-7.5, 2.5, 0.2)
bins2 = np.arange(0, 10, 0.2)
bins3 = np.arange(7, 17, 0.2)
bins4 = np.arange(12, 22, 0.2)
bins = [bins1, bins2, bins3, bins4]

axis1 = [-7.5, 2.5, 0, 0.6]
axis2 = [0, 10, 0, 0.6]
axis3 = [7, 17, 0, 0.6]
axis4 = [12, 22, 0, 0.6]
axis  = [axis1, axis2, axis3, axis4]

GS1.hist(x1, bins = 1000)
GS2.hist(x2, bins = 1000)
GS3.hist(x3, bins = 1000)
GS4.hist(x4, bins = 1000)
GS5.scatter(x1, xrand, norm = True, c = 'r', s= 0.7)
GS5.scatter(x2, xrand, norm = True, c = 'g', s= 0.7)
GS5.scatter(x3, xrand, norm = True, c = 'b', s= 0.7)
GS5.scatter(x4, xrand, norm = True, c = 'y', s= 0.7)

for s in GS:
    s.spines['right'].set_visible(False)
    s.spines['top'].set_visible(False)
gspec.update(wspace = .6, hspace = .6)

fig, ((GS1,GS2),(GS3, GS4)) = plt.subplots(2, 2, sharey = True)
GS = [GS1, GS2, GS3, GS4]

def update(curr):
    if curr == 500:
        a.event_source.stop()
    for i in range(0, len(GS)):
        GS[i].hist(x[i][:curr], bins = bins[i], normed = True)
        GS[i].axis(axis[i])
        GS[i].gca().set_title('Sampling random distribution')
        GS[i].gca().set_ylabel('Frequency')
        GS[i].gca().set_xlabel('Value')
        GS[i].annotate('n = {}'.format(curr), [3,27])
    plt.tight_layout()
    plt.show()

fig = plt.gcf()
a = animation.FuncAnimation(fig, update, interval = 10) #, blit = True, repeat = True)

I do not understand what is the problem with the code.

A: Problems:

*

*You cannot use plt.show() inside the updating function.

*GS[i].gca().set_title does not make sense, because GS[i] already is an axes, which does not have any gca() method. Same for set_ylabel and set_xlabel.

*You need to call tight_layout() only once outside the loop.

*You will need to remove the old histogram before plotting a new one on the axes.
Possibly the following is what you're after:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation

x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)
xrand = np.random.random(size = 10000)
x = [x1, x2, x3, x4]

bins1 = np.arange(-7.5, 2.5, 0.2)
bins2 = np.arange(0, 10, 0.2)
bins3 = np.arange(7, 17, 0.2)
bins4 = np.arange(12, 22, 0.2)
bins = [bins1, bins2, bins3, bins4]

axis1 = [-7.5, 2.5, 0, 0.6]
axis2 = [0, 10, 0, 0.6]
axis3 = [7, 17, 0, 0.6]
axis4 = [12, 22, 0, 0.6]
axis  = [axis1, axis2, axis3, axis4]

fig, ((GS1,GS2),(GS3, GS4)) = plt.subplots(2, 2, sharey = True)
GS = [GS1, GS2, GS3, GS4]

def update(curr):
    if curr == 500:
        a.event_source.stop()
    for i in range(0, len(GS)):
        GS[i].clear()
        GS[i].hist(x[i][:curr], bins = bins[i], normed = True)
        GS[i].axis(axis[i])
        GS[i].set_title('Sampling random distribution')
        GS[i].set_ylabel('Frequency')
        GS[i].set_xlabel('Value')
        GS[i].annotate('n = {}'.format(curr), [3,27])

plt.tight_layout()
fig = plt.gcf()
a = animation.FuncAnimation(fig, update, interval = 10)

plt.show()


text:
Q: Pass context data from generic.DetailView How can i pass the context data which is coming from a forms.py to my views class which is using generic detailView, i need to pass forms.py to my product detail page.
Here is the code for my view class
class ProductView(generic.DetailView):
model = Product
cart_product_form = CartAddProductForm()
context = {'cart_product_form': cart_product_form}
template_name = 'shopping/product.html'
query_pk_and_slug = True

Please let me know if this is incorrect

A: Override get_context_data, and add the form to the context before returning it.
class ProductView(generic.DetailView):
    model = Product
    template_name = 'shopping/product.html'
    query_pk_and_slug = True

    def get_context_data(self, **kwargs):
        context = super(ProductView, self).get_context_data(**kwargs)
        cart_product_form = CartAddProductForm()
        context['cart_product_form'] = cart_product_form
        return context


text:
Q: Secure login page and user session My first question is about standard steps to take in order to provide secure login page. Two things I am familiar with is putting password field to protect against someone watching over out shoulder, as well as transmitting data over https. Are there any other things one should include to have a fully secure login site?
Furthermore, once we log in, how is the session maintained i.e. when the user clicks sth our server knows that it should again generate user-based content? Considering whe are logged in, do we still need to maintain https and other security measures?
Thanks for your responses

A: I'm afraid one could write a book about it...
Addressing just the session question: session is usually maintained by some cookie that is sent with each consecutive request. And as information whether user is logged on not is based on the session cookie (or standalone user cookie) then the stolen cookie can be used to impersonate login. Therefore you would need to maintain https connection for the rest of the session (to protect the cookie) or at least take some minor security precautions (such as verify if session comes from the same IP address as before).

A: There are all sorts of things one can do to make a site more secure, but even if you did all of them, you have no guarantee that your site is "fully" secure.
For instance, if you're storing user login information in a database: did you put in protection against SQL injection? If your login page also contains a registration form: do you have protection against XSS exploits? Are there minimum requirements that the passwords must meet, or can users make their own (often very bad and easy to guess) passwords? There are some matters you can take into your own hands, but there are always things that, unfortunately, you won't think to protect against (because no one would've thought of them) until they're actually exploited. There are innumerable routes of attack for a site, and an equal amount of ways to protect against them, and it would take me far too long to delve into all of them (not that I'm all that security-savvy myself).
As the other answers have pointed out, sessions are maintained by a session ID, which is stored in a cookie on the client's side. When a session is started, the ID is generated; this ID is then used by the client's browser to identify data stored on the server side as belonging to that browser. To prevent this ID from being stolen, the connection should be encrypted using HTTPS; however, something to keep note of is that if you have any references to external resources in your page (e.g.: an image from another site, a script from another site, etc.), the connection will only be partially encrypted (namely, the parts that aren't external resources). This is less secure than full encryption for obvious reasons; to prevent this, I download all external resources into the local directory whenever possible.

A: Yes, password fields and https are definitely good approaches to the login.
I can't think of anything else to do right now either, except for maybe a Captcha, to make sure that it's not a robot script, trying to guess passwords.
Regarding the session management:
There is the '$_SESSION' variable, that is unique to every connection and gets maintained by PHP automatically, AFTER you called 'session_start();' at the beginning of the script.
This command is very important, otherwise $_SESSION will be empty at all times...if I'm not mistaken, it asks the browser for identification information (a SessionID or something of the likes), and then matches the stored information to that SessionID.
You use this session variable, like any other Superglobal.
$_SESSION['ID'] = $ID;
$_SESSION['AccessRights'] = $AR;

and so on.
The actual session data is stored at server side exclusively and cannot be altered from anything but the PHP script. Store everything you need to know about the user in $_SESSION and you should be fine.
Regarding the 'keeping up HTTPS': That should not be necessary, simply because all 'crucial data' has already been transferred.
Mind you though, once you're dealing with sensitive, or personal data (like changing password or anything the likes), you may want to go back to HTTPS again.
From experience, however, the actual overhead of HTTPS is rather minor in todays systems, and unless you're expecting a LOT of traffic, it's never a bad idea to keep it 'on'.
Now, I may be wrong concerning this issue, but that's my opinion on the matter.

A: as @Kuba said  - it's a huge topic. sessions fixation, session storing, protecting cookies, password security, response time to invalid login, accessing login page in non-secured way, XSS, sql injection and probably thousand more of which i have no idea.
my advice: don't do it on your own. there are plenty of security frameworks for every possible language. pick one, read their howto page and just use it. it will help you with most common tasks. but security of application does not end on login page. whole application should be secured written properly to be secured.


text:
Q: What is causing browser throttling event listener to frame rate? Listener on events like mousemov it should call the function every time the position updates, the frequency should match the polling rate of mice. But in the images shown below, both Firefox and Chrome is throttling the listener(144fps and 60fps), only in Edge the listener behaves as expected. Can someone tell me the reason.
firefox
edge
chrome


text:
Q: Networking communication sending keyboard shortcut Can I send a keyboard shortcut ALT+P to a computer, in order to awaken an application which is stopped by a pause.
Can I break this pause also by sending a string with the echo service?
Thanks
programming language java on windows os

A: Why don't you create an actionListener which receives some command from network and awake the application?
Any communication via the network is basically packets and packet can only contain data. So there has to be code on receiving end itself which breaks the pause based upon some message received from the network.
As such you cannot directly pass a keyboard interrupt over the network. The closet to achieving this (as already mentioned in comments) is something like VNC, Teamviewer etc.


text:
Q: Java script to download multiple .pdf files from a same domain My friend introduced me to my school domain that has learning materials in .pdf format. Though, the site contains hundreds of addresses for each .pdf. For example:
-http://ste.csh.nordtic.net/IMG/pdf/-2.pdf
-http://ste.csh.nordtic.net/IMG/pdf/-3.pdf
Each of the address represents one file
The files I want to download are all the files from
ste.csh.nordtic.net/IMG/pdf/-2.pdf
to
ste.csh.nordtic.net/IMG/pdf/-164.pdf
Please make this script and help me out with your expansive knowledge in Java!

A: if you have access to bash, use this one liner to download all the pdfs to the current terminal directory:
for i in {2..164}; do wget http://ste.csh.nordtic.net/IMG/pdf/-$i.pdf; done


text:
Q: Sublime-text command as keybinding I want to add a keybinding for Reindent(Edit>Line>Reindent).
I have tried adding
"keys": ["ctrl+shift+i"], "command": "reindent"

But this does nothing even after restarting sublime
Other answers seems to be outdated.
Full Settings-User file:
// Settings in here override those in "Default/Preferences.sublime-settings",
// and are overridden in turn by file type specific settings.
{
    "update_check":false,
    "font_size":11,
    {"keys": ["ctrl+shift+i"], "command": "reindent"},
}

A: I believe you are adding the config to the wrong file. It has to go into Key Bindings - User , not in the Settings - User.
Also you don't need the comma at the end of the last line in the list.
According to the information you have provided, here is what I recommend:
Edit the contents of your Settings - User to the following:
// Settings in here override those in "Default/Preferences.sublime-settings",
// and are overridden in turn by file type specific settings.
{
    "update_check":false,
    "font_size":11
}

Edit the contents of your Key Bindings - User to the following:
[
    {"keys": ["ctrl+shift+i"], "command": "reindent"}
]

Note, if you want to always reindent the entire contents of the open file regardless the selection you can edit your Key Bindings - User to the following:
[
    {"keys": ["ctrl+shift+i"], "command": "reindent", "args": {"single_line": false}}
]


text:
Q: EAGLContexts sharing EAGLSharegroup giving error when subclassing GLKView i am trying to create a player using FFMPEG which can display frame using OpenGl. The player class has three threads: one for rendering (Runs a runloop and handles a render event triggered every N ms.) - it fetches GLKTextureInfo stored in pictureQueue and renders.
 one for reading packets from VideoStream and putting them in a videoQueue, the third one fetches the packets from the videoQueue and decodes them and creates a GLKTextureInfo and stores it in pictureQueue.
Case 1:
The player class subclasses GLKView and creates a EAGLContext sets it as its context and also as currentContext in rendering thread (it's the first thread that starts).
EAGLContext *mycontext = [self createBestEaglContext];
if (!self.mycontext || ![EAGLContext setCurrentContext:mycontext]) {
    NSLog(@"Could not create Base EAGLContext");
    return;
}
[self setContext:mycontext];

and then starts the stream decoding thread which in turn starts the Video Packet Decoding Thread if it finds a video stream.then
// set's the params for the GLKBaseEffect
// set's up VBO's
// run's runloop

The Video Packet Decoding Thread also creates EAGLContext which shares the earlier created contexts EAGLSharegroup.
self.videoPacketDecodeThreadContext = [self createEaglContextForOtherThread];
if (!self.videoPacketDecodeThreadContext || ![EAGLContext setCurrentContext:self.videoPacketDecodeThreadContext])
{
    NSLog(@"Could not create video packet decode thread context");
}

texture part
UIImage* image = [self ImageFromAVPicture:*(AVPicture*)pFrameRGB width:self.is.video_stream->codec->width height:self.is.video_stream->codec->height];

NSError *error = nil;
GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithCGImage:image.CGImage
                                                               options:nil
                                                                 error:&error];
if (error)
{
   NSLog(@"Texture loading Error: %@\n", error.description);
   //return -1;
}
else
{
   [self.is.pictQueue_lock lock];
   [self.is.pictQueue enqueue:textureInfo];
   [self.is.pictQueue_lock unlock];
}

i get a error saying: Failed to bind EAGLDrawable: <CAEAGLLayer: 0x156f7e50> to GL_RENDERBUFFER 1 and Failed to make complete framebuffer object 8cd6 and glerror 1280.
Case 2: The Player doesn't subclass GLKView instead it is set as a delegate to the GLKView created in storyboard.
-(void)initPlayerWithView:(GLKView*)v
{
   self.view = v;
}

and set everyThing as above (sets self.view context to mycontext) everything runs fine.
-(void)drawRect:(CGRect)rect And -(void)glkView:(GLKView *)view drawInRect:(CGRect)rect are both called on Rendering Thread. Rendering code:
    {
      [self.is.pictQueue_lock lock];
      GLKTextureInfo *textureInfo = (GLKTextureInfo*)[self.is.pictQueue dequeue];
      [self.is.pictQueue_lock unlock];

      // delete the previous texture
      GLuint index = self.baseEffect.texture2d0.name;
      glDeleteTextures(1, &index);

      self.baseEffect.texture2d0.name = textureInfo.name;
      self.baseEffect.texture2d0.target = textureInfo.target;

      [self.baseEffect prepareToDraw];
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

      // Enable vertex buffer
      glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
      glEnableVertexAttribArray(GLKVertexAttribPosition);

      //Enable texture buffer
      glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, textureCoords));
      glEnableVertexAttribArray(GLKVertexAttribTexCoord0);

      glDrawElements(GL_TRIANGLES, sizeof(Indices)/sizeof(Indices[0]), GL_UNSIGNED_BYTE, 0);
    }

How do i resolve the error in Case 1 ?. Also if their are other things i can do in a different way please suggest like:

*

*Am i using to many threads ?

*I am converting the decoded frame to a UIImage and then creating a texture from it. can it be done differently ?

A: I don't about GLKView, I've written a player using NSOpenGLView in OSX, and subclassing works fine there, but I let it create the context for me.

Am i using to many threads ?

By default, for most codecs, ffmpeg uses frame multithreading, which means the main decoding thread does nothing, it creates subthreads and waits for them to finish decoding frames. (For realtime communication, you can also use slice multithreading, which decreases latency, but scales less well, and requires bitstream support.) If you're not doing anything specific to tell it otherwise, ffmpeg uses frame multithreading, and your frame decoding thread does nothing. So you don't need it. The player thread can decode video directly.

I am converting the decoded frame to a
  UIImage and then creating a texture from it. can it be done
  differently ?

UIImage is in RGB, and most video decoders output YUV, so this suggests some other code is doing software YUV-RGB conversion. This RGB conversion will be slow, very slow.
Instead, consider that openGL can draw YUV directly. So I would not use UIImage, but instead draw the YUV planes directly using a shader to do the YUV-RGB conversion inside the hardware.


text:
Q: High CPU usage caused ec2 to go down but cloudwatch shows CPU usage within limits Recently, we faced downtime for our website. The two ec2 instances on which the website is hosted are behind ELB. We received 2 alerts from ELB that the latency is high and both the nodes are unhealthy. Luckily, I was able to ssh the ec2.
Command "ps aux --sort=-%cpu" on the ec2 showed that one of the process had taken up 97% of the CPU. I killed that process and the server passed the health check of the ELB and the website was up.
The major concern here is AWS Cloudwatch showed that the maximum CPU usage was around 70%. As a result, it did not trigger my alarm which was set for 80%.
I understand that the CPU metrics shown by ps and top commands will always be different from that of cloudwatch due to virtualization. Reading other posts about it, all the posts have discussed about top command showing less CPU usage than cloudwatch. However, in my case it has been the reverse. I need some help understanding the reason behind it.
Also, I checked and found that there were no memory/network issues.
Can anyone help me here. What can I do here so that I am alerted before things go wrong.
EDIT :
Below are the CPU credit usage and balance charts
CPU Credit usage
CPU credit balance


text:
Q: Sorting a List of integers based on a List of strings in Java I have a Data Set something like this:
85 [Italy, France]
95 [Italy]
91 [Israel, Jordan]
85 [France, Italy, Switzerland]
80 [USA]
84 [Mongolia, China]
95 [Antarctica]
84 [African Union]
82 [Argentina]
95 [Tibet, Nepal]
...

Which I have sorted based on based on the integers using below code (defining the class model):
public class Wonder implements Comparable<Wonder> {
    int hostility;
    List<String> countries;
    //some other data members

    //constructor
    //getters

    @Override
    public int compareTo(Wonder other) {
        if(hostility == other.hostility) {
            return 0;
        } else if(hostility < other.hostility) {
            return -1;
        } else if(hostility > other.hostility) {
            return 1;
        } else {
            return 0;
        }
    }
}

Sorting Code (PS: getAllData method will return a list of wonders, loading from Text file):
List<Wonder> wonders = getAllData(filePath);
wonders.sort((c1,c2)->c1.compareTo(c2));
Collections.reverse(wonders); // ordering highest to lowest

After sorting the Data Set (sorted based on integers) looks something like this:
95 [Antarctica]
95 [Italy]
95 [Tibet, Nepal]
91 [Israel, Jordan]
85 [France, Italy, Switzerland]
85 [Italy, France]
84 [Mongolia, China]
84 [African Union]
82 [Argentina]
80 [USA]
...

Now, there is need to sort newly generated Data Set to alphabetically which are the List of countries (strings). For example, in new Data Set there're two records with the same integer 84 (1st integer has country Mongolia and 2nd integer has country African Union), so the second record should come first as African Union is alphabetically before the Mongolia.
...
84 [African Union]
84 [Mongolia, China]
...

Question: How to sort a List of integers based on a List of strings?

A: You can further specialize the compareTo function to enact a secondary comparison. I'm assuming that every list contains at least one country; if such is not the case, you must handle empty lists. The altered compareTo is as so:
@Override
public int compareTo(Wonder other) {
    if(this == other) {
        return 0;
    } else if(hostility < other.hostility) {
        return -1;
    } else if(hostility > other.hostility) {
        return 1;
    } else {
        return -countries.get(0).compareTo(other.countries.get(0));
    }
}

Alternatively you may be looking for this:
wonders.sort(Comparator.comparingInt(Wonder::getHostility).reversed()
    .thenComparing(wonder -> wonder.getCountries().get(0)));
//don't reverse afterwards!

according to @Andrew's style
A repl.it with the best of all answers

A: If you do, what accepted answer suggested:
wonders.sort(Comparator.comparingInt(Wonder::getHostility).reversed()
    .thenComparing(wonder -> wonder.getCountries().get(0)));

on text file, that you provided, you will get next result:
95 [Antarctica]
95 [Italy]
95 [Tibet, Nepal]
91 [Israel, Jordan]
85 [France, Italy, Switzerland]
85 [Italy, France]
84 [African Union]
84 [Mongolia, China]
82 [Argentina]
80 [USA]
70 [Australia]
69 [Japan]
69 [USA, Canada]
65 [The Hawaiian Islands]
65 [USA]
55 [Russia]
50 [Brazil, Argentina]
19 [Tanzania]
17 [Northern Ireland]
16 [China]
12 [African Union]
10 [Australia]
10 [Brazil]
2 [USA]

But, if you first sort countries and then do accepted answer:
wonders.forEach(wonder -> Collections.sort(wonder.getCountries()));
wonders.sort(Comparator.comparingInt(Wonder::getHostility).reversed().
    thenComparing(wonder -> wonder.getCountries().get(0)));

then you will get:
95 [Antarctica]
95 [Italy]
95 [Nepal, Tibet]
91 [Israel, Jordan]
85 [France, Italy]
85 [France, Italy, Switzerland]
84 [African Union]
84 [China, Mongolia]
82 [Argentina]
80 [USA]
70 [Australia]
69 [Canada, USA]
69 [Japan]
65 [The Hawaiian Islands]
65 [USA]
55 [Russia]
50 [Argentina, Brazil]
19 [Tanzania]
17 [Northern Ireland]
16 [China]
12 [African Union]
10 [Australia]
10 [Brazil]
2 [USA]

Pay attention on hostility with values 85 and 69 in these two list. The order is not the same. Don't know if this is relevant to you.
P.S. If you implemente Comparable#compareTo(), you should also implement equals() because there is contract between them:
(x.compareTo(y) == 0) == (x.equals(y))

If this is not the case you should make note: This class has a natural ordering that is inconsistent with equals.
Last thing:
compareTo() must throw NullPointerException if current object get compared to null object as opposed to equals() which return false on such scenario.

A: Not sure I understood what is your issue. Does below pseudo code solve your problem ?
@Override
public int compareTo(Wonder other) {
    if(hostility == other.hostility) {
       // let's compare the strings list when hostility integer are equals (84, 84)
       String firstOtherCountry = other.countries.SortAlphabetically().get(0);
       // we sort the countries list for current line and other wonder
       // you compare alphabetically first element of each list :
       // return 1, 0 or -1 here.
    } else if(hostility < other.hostility) {
        return -1;
    } else if(hostility > other.hostility) {
        return 1;
    } else {
        return 0;
    }
}

How can I sort a List alphabetically?


text:
Q: How to fix wrong audio profile (on Skylake/Realtek ALC1150)? I have a Skylake system (ASRock Z170 Gaming-ITX/ac) with (x)Ubuntu 16.04.
My speakers are connected via the SPDIF port, but there is a problem.
When I inspect the audio profile (in pavucontrol), I see that Analog Stereo Output (unplugged) is selected.
The speakers play regularly, even if this profile is wrong, but the volume doesn't work correctly - anything above mute will cause the speakers to play at maximum volume.
If I choose the Digital Stereo (IEC958), the speakers won't receive any signal at all.
How can I fix this?
Debug info:
~$ grep "Codec:" /proc/asound/card*/codec*
/proc/asound/card0/codec#0:Codec: Realtek ALC1150
/proc/asound/card0/codec#2:Codec: Intel Skylake HDMI

~$ lspci -vv # extract
00:1f.3 Audio device: Intel Corporation Sunrise Point-H HD Audio (rev 31)
  Subsystem: ASRock Incorporation Sunrise Point-H HD Audio
  Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+
  Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
  Latency: 32
  Interrupt: pin A routed to IRQ 140
  Region 0: Memory at df140000 (64-bit, non-prefetchable) [size=16K]
  Region 4: Memory at df120000 (64-bit, non-prefetchable) [size=64K]
  Capabilities: <access denied>
  Kernel driver in use: snd_hda_intel
  Kernel modules: snd_hda_intel

~$ dmesg | grep 00:1f.3
[    0.181004] pci 0000:00:1f.3: [8086:a170] type 00 class 0x040300
[    0.181034] pci 0000:00:1f.3: reg 0x10: [mem 0xdf140000-0xdf143fff 64bit]
[    0.181062] pci 0000:00:1f.3: reg 0x20: [mem 0xdf120000-0xdf12ffff 64bit]
[    0.181091] pci 0000:00:1f.3: PME# supported from D3hot D3cold
[    0.181176] pci 0000:00:1f.3: System wakeup disabled by ACPI
[    0.579846] iommu: Adding device 0000:00:1f.3 to group 8
[    3.126041] snd_hda_intel 0000:00:1f.3: bound 0000:00:02.0 (ops i915_audio_component_bind_ops [i915_bpo])
[    4.185983] input: HDA Intel PCH Front Mic as /devices/pci0000:00/0000:00:1f.3/sound/card0/input11
[    4.186034] input: HDA Intel PCH Rear Mic as /devices/pci0000:00/0000:00:1f.3/sound/card0/input12
[    4.186081] input: HDA Intel PCH Line as /devices/pci0000:00/0000:00:1f.3/sound/card0/input13
[    4.186135] input: HDA Intel PCH Line Out as /devices/pci0000:00/0000:00:1f.3/sound/card0/input14
[    4.186188] input: HDA Intel PCH Front Headphone as /devices/pci0000:00/0000:00:1f.3/sound/card0/input15
[    4.186228] input: HDA Intel PCH HDMI/DP,pcm=3 as /devices/pci0000:00/0000:00:1f.3/sound/card0/input16
[    4.186267] input: HDA Intel PCH HDMI/DP,pcm=7 as /devices/pci0000:00/0000:00:1f.3/sound/card0/input17
[    4.186304] input: HDA Intel PCH HDMI/DP,pcm=8 as /devices/pci0000:00/0000:00:1f.3/sound/card0/input18

A: The Linux Kernel 4.10 solves this problem.


text:
Q: Textboxes still showing in the UpdatePanel I want to hide the textboxes in the Updatepanel according to the user's choice in the Combo boxes.  It works well outside of the UpdatePanel but it stops working and no longer hiding textboxes when I put inside the UpdatePanel.  Could you please help me about this?  Thanks.
My Codings are as follow:

        <asp:UpdatePanel runat="server">
            <contenttemplate>
        <asp:DropDownList runat="server" id="ddlType" AutoPostBack="True"
                    onselectedindexchanged="ddlType_SelectedIndexChanged">
            <asp:ListItem>T1</asp:ListItem>
            <asp:ListItem>T2</asp:ListItem>
        </asp:DropDownList>

                Row 1

                From: <asp:TextBox ID="TextBox1" runat="server" CssClass="dtpicker"></asp:TextBox>  To: <asp:TextBox ID="TextBox2" runat="server" CssClass="dtpicker"></asp:TextBox>

                <asp:Literal ID="ltStatus" runat="server" Text="You haven't selected."></asp:Literal>

        </contenttemplate>
        </asp:UpdatePanel>

A: What happens is as follows - you are toggling the textboxes visibility in the client side, but then a postback occurs. When the textboxes are inside an UpdatePanel, they are being rendered again and that toggling action is lost.
Two things you can do:
1) If you all you are doing when the drop-down value is change is toggling the textbox visibility, you can lose the AutoPostBack="True" and the OnSelectedIndexChanged event.
2) If you are doing more than that and need the server side call, you can set the textbox visibility in the server side event.

A: Usually, it's safer to use live() jQuery method when adding handlers for controls inside updatepanel
However, I'm not sure whether it will solve your problem


text:
Q: SeekBar pointer not in the centre Android Studio Java I am making a SeekBar in my Android Java application for the first time, but the slider circle is not in the middle of the line as I would expect, but a little above it. I can't figure out why this is the case.
There is an image of the slider at http://i.stack.imgur.com/AAGkM.jpg
My layout for the slider is:
    <SeekBar
    android:layout_width="match_parent"
    android:id="@+id/seekBar"
    android:layout_height="0dp"
    android:layout_weight="0.5"
    android:background="#ffff4007"
    android:progress="0"
    android:max="100"/>

A: You can post the code of your layout to better help you, maybe you can try this
android:gravity="center"

A: To do this use
android: progress=0
In java use
Seekbar.setmax(to set maxm value..as integer);


text:
Q: affect only the clicked element in jquery for multiple elements with same class i've been looking all over for a solution to this but i just can't figure out how.
what i want is for the specific header that was clicked to be the only one to expand.
demo is here: http://jsfiddle.net/bm92L0eg/1/
html:

header a

item

item

item

header b

item

item

item

header c

item

item

item

jquery:
$('.click-list').click(function() {
    $(this).find('.open-list').slideToggle(600);
});

that jquery code didn't work while this code below is the one that acivates all headers:
$('.open-list').slideToggle(600);

A: Use .next() to select the adjacent .open-list element.
It should be:
$('.click-list').click(function () {
    $(this).next('.open-list').slideToggle(600);
});

Updated Example


text:
Q: Error running MongoDb on MacOSX I am trying to run mongo with rails i get the following Error
Harshas-MacBook-Pro:~ harshamv$ mongo
MongoDB shell version: 2.6.1
connecting to: test
2014-06-14T12:07:46.356+0530 warning: Failed to connect to 127.0.0.1:27017, reason: errno:61 Connection refused
2014-06-14T12:07:46.357+0530 Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
exception: connect failed

When i try to repair MongoDB
Harshas-MacBook-Pro:nomad harshamv$ mongod --repair
2014-06-14T11:06:52.964+0530 [initandlisten] MongoDB starting : pid=5504 port=27017 dbpath=/data/db 64-bit host=Harshas-MacBook-Pro.local
2014-06-14T11:06:52.964+0530 [initandlisten]
2014-06-14T11:06:52.964+0530 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2014-06-14T11:06:52.964+0530 [initandlisten] db version v2.6.1
2014-06-14T11:06:52.964+0530 [initandlisten] git version: nogitversion
2014-06-14T11:06:52.964+0530 [initandlisten] build info: Darwin minimavericks.local 13.1.0 Darwin Kernel Version 13.1.0: Wed Apr  2 23:52:02 PDT 2014; root:xnu-2422.92.1~2/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
2014-06-14T11:06:52.964+0530 [initandlisten] allocator: tcmalloc
2014-06-14T11:06:52.964+0530 [initandlisten] options: { repair: true }
2014-06-14T11:06:52.964+0530 [initandlisten] exception in initAndListen: 10309 Unable to create/open lock file: /data/db/mongod.lock errno:13 Permission denied Is a mongod instance already running?, terminating
2014-06-14T11:06:52.964+0530 [initandlisten] dbexit:
2014-06-14T11:06:52.964+0530 [initandlisten] shutdown: going to close listening sockets...
2014-06-14T11:06:52.964+0530 [initandlisten] shutdown: going to flush diaglog...
2014-06-14T11:06:52.964+0530 [initandlisten] shutdown: going to close sockets...
2014-06-14T11:06:52.964+0530 [initandlisten] shutdown: waiting for fs preallocator...
2014-06-14T11:06:52.964+0530 [initandlisten] shutdown: closing all files...
2014-06-14T11:06:52.964+0530 [initandlisten] closeAllFiles() finished
2014-06-14T11:06:52.964+0530 [initandlisten] shutdown: removing fs lock...
2014-06-14T11:06:52.964+0530 [initandlisten] couldn't remove fs lock errno:9 Bad file descriptor
2014-06-14T11:06:52.964+0530 [initandlisten] dbexit: really exiting now

This is the Error i get when i am trying to run my Rails app
Moped::Errors::ConnectionFailure in VenuesController#index
Could not connect to a primary node for replica set #<Moped::Cluster:70100620147140 @seeds=[<Moped::Node resolved_address="127.0.0.1:27017">]>

A: Error Unable to create/open lock file can be caused by these three things:

*

*MongoDB process is running and is un-responsive

*Your previous MongoDB process didn't shutdown cleanly.

*You don't have write permissions on that folder / file.

Case 1:

You need to check if mongod process is active. In your terminal console, enter:
ps aux | grep mongod

If you can see a process you can kill it with:
kill $(pidof mongod)
or kill -2 $(pidof mongod)
Use -9 option only as a last resort.
You will also need to remove the old mongod.lock file and then start mongod.

Case 2:

If there wasn't an active process, then MongoDB didn't shut down cleanly.
You just need to remove mongod.lock file and then then start mongod.

Case 3:

If you removed the mongod.lock file and you're getting the same error, you should check the permissions on your dbpath folder (/data/db/). This can happen if you started mongod with sudo.
Your user or mongod should be the owner of the folder. You can change it with:
chown -R $(id -u) /data/db

A: Another process/instance of mongodb is running in background, so terminate it first. Even if no such process is running, you need to go to where your mongodb data directory is and clear the content in a file that has the end extension in its name .lock (mongod.lock). Only then you will be able to run mongodb properly.
Steps to terminate a process:

*

*Browse to the location /Applications/Utilities and double click on 'Terminal'.

*Run ps aux | grep mongo.

*Then run kill -9 <PROCESS-ID> for process number you get in the first line (I believe there would be two lines in total unless more processes with similar names are running. )


text:
Q: Django custom login form validation with AJAX I am not that experienced writing Python/Back-end, but trying to improve. In development/localserver I am trying to validate a user's email and password in my login form... right now almost 100% of things work, for example, alert messages for mandatory inputs; however, from the Utils.py file if user "elif not object_user.allow_private_access:" validation is not working and, most importantly, validation is not checking user's password (also commented out in Utils.py). The "post" part in Views.py might have to be updated.
I have included my custom Login form from Forms.py, Views.py (for Login page) and Utils.py (which does the validation and sends error messages to the front-end) and Urls.py. I did not add my AJAX because that is working well.
Forms.py
class UserLoginForm(forms.ModelForm):
    helper = FormHelper()
    helper.add_input(Submit('login_form_submit',
                            numeratio_static_textLanguage['global_input_alert_maxCharacters_32'],
                            css_class='global_component-button'))

    class Meta:
        model = CustomUser
        fields = ['email', 'password']
        widgets = { 'email': forms.EmailInput(attrs={
                    'maxlength': '256',
                    'style': 'text-transform: lowercase',
                    'id': 'input-email',
                    'class': 'global_component-input box'}
                    ),
                    'password': forms.PasswordInput(attrs={
                    'type': 'password',
                    'maxlength': '128',
                    'id': 'input-password',
                    'class': 'global_component-input box'}
                    )
        }

    def __init__(self, *args, **kwargs):
        super(UserLoginForm, self).__init__(*args, **kwargs)
        self.helper.form_action = ''
        self.helper.form_method = 'post'
        self.helper.form_id = 'login_form'
        self.helper.form_class = 'login_form'

Views.py
@csrf_exempt
@anonymous_required(redirect_url='page__home')
@require_http_methods(["GET", "POST"])
def view_userLogin(request, *args, **kwargs):
    template_name = '../frontend/templates/frontend/templates.user/template.page_login.html'
    form_class = UserLoginForm

    if request.method == 'GET':
        return render(request, template_name, { 'userLogin_form': form_class(),
                                                'json_textGlobal': static_textGlobal,
                                                'json_textLanguage': static_textLanguage})
    elif request.method == 'POST':
        bound_user_login_form = form_class(request.POST)
        data_validation = validation_userLogin_form(bound_user_login_form)
        print('Before validation', data_validation)
        if data_validation['result']:
            email = bound_user_login_form.cleaned_data['email'].lower()
            password = bound_user_login_form.cleaned_data['password']
            check_exists_email = get_user_model().objects.filter(email__iexact=email).count() > 0
            if check_exists_email:
                object_user = get_user_model().objects.get(email__iexact=email)
                if object_user.allow_private_access:
                    print(object_user.allow_private_access)
                    email_to_authenticate = get_user_model().objects.filter(email__iexact=email)[0].email
                    user = authenticate(request, username=email_to_authenticate, password=password)
                    print(email_to_authenticate, user)
                    if user is not None:
                        user.save()
                        login(request, user)
                        data_validation['redirect'] = True
                        data_validation['redirect_url'] = reverse('page__home')
                        return HttpResponseRedirect(reverse('page__home'))
                    else:
                        object_user.save()
            else:
                data_validation['redirect'] = False
        return render(request, template_name, { 'userLogin_form': form_class(),
                                                'json_textGlobal': static_textGlobal,
                                                'json_textLanguage': static_textLanguage})
    else:
        return HttpResponseRedirect(reverse('page__error_404'))

@require_http_methods(["POST"])
def validate_userLogin(request, *args, **kwargs):
    response_user_login_validate = validate_field_userLogin(request.POST)
    return HttpResponse(json.dumps(response_user_login_validate), content_type="application/json")

@require_http_methods(["POST"])
def validate_userLogin_email(request, *args, **kwargs):
    entered_email = request.POST['email'].lower()
    response_user_login_validate = {'check_exists_email': not NumeratioUser.objects.filter(email=entered_email).count() == 0}
    return HttpResponse(json.dumps(response_user_login_validate), content_type="application/json")

@require_http_methods(["POST"])
def validate_userLogin_unique_token(request, *args, **kwargs):
    entered_unique_token = request.POST['unique_token']
    response_user_login_validate = {'unique_token_exists': not NumeratioUser.objects.filter(unique_token=entered_unique_token).count() == 0}
    return HttpResponse(json.dumps(response_user_login_validate), content_type="application/json")

Utils.py
def validation_userLogin_form(bound_user_login_form):
    if bound_user_login_form.is_valid():
        return {'result': True}
    else:
        error_messages = {}
        if bound_user_login_form.errors:
            error_messages.update(bound_user_login_form.errors)
        return {'result': False, 'error_messages': error_messages}

def validate_field_userLogin(post_request):
    error_messages = []
    response = {'is_valid_field': False}
    if 'email' in post_request:
        validate_login_email(post_request, error_messages)
    elif 'password' in post_request:
        validate_login_password(post_request, error_messages)
    if len(error_messages) < 1:
        response['is_valid_field'] = True
    else:
        response['error_messages'] = error_messages
    return response

def validate_login_email(post_request, error_messages):
    entered_email = post_request['email'].lower()
    try:
        object_user = get_user_model().objects.get(email__iexact=entered_email)
        print(object_user)
        if entered_email == '':
            error_messages.append(numeratio_static_textLanguage['global_input_alert_mandatoryField'])
        elif not object_user.allow_private_access:
            error_messages.append(numeratio_static_textLanguage['global_input_alert_noAccess'])
    except NumeratioUser.DoesNotExist:
        if entered_email == '':
            error_messages.append(numeratio_static_textLanguage['global_input_alert_mandatoryField'])
        elif not is_valid_format_email(entered_email):
                error_messages.append(numeratio_static_textLanguage['global_input_alert_emailIncorrect'])
        elif len(entered_email) > 256:
            error_messages.append(numeratio_static_textLanguage['global_input_alert_maxCharacters_256'])

def validate_login_password(post_request, error_messages):
    entered_password = post_request['password']
    if entered_password == '':
        error_messages.append(numeratio_static_textLanguage['global_input_alert_mandatoryField'])
    # elif entered_password != check_password:
    #     error_messages.append(numeratio_static_textLanguage['global_input_alert_passwordNotValid'])
    elif len(entered_password) > 128:
        error_messages.append(numeratio_static_textLanguage['global_input_alert_maxCharacters_128'])

Urls.py
urlpatterns = [
    path('login/', views.view_userLogin, name='page__user_login'),
        path('login/validate/', views.validate_userLogin, name='page__user_login_validate'),
        path('login/validate_email/', views.validate_userLogin_email, name='page__user_login_validateEmail'),
        path('login/validate_unique_token/', views.validate_userLogin_unique_token, name='page__user_login_validateUniqueToken'),
    .......
]


text:
Q: Apache wont start after copy zend library xampp after copying zend library in my zend proj and refresh the page Apache wont start.
it show me this error : Appache Http Server has stopped working
i use of xampp , version 1.7

A: Your question is really vague. There can be a number of things that went wrong and you didn't give us enough background information on the install. (like config files you changed, directories you renamed, etc.)
If you cannot start Apache, the first place to check is the Apache error log file for problems. It will most likely have an error that we can help you troubleshoot.
I am not familiar with xampp directory paths but will take a guess that you need to look here: /xampp/apache/logs/error.log.

A: i`ve change my xampp version to 1.7.3 , now it work nice


text:
Q: Where is Firefox's URL processor? After 3 days digging in this Mozilla NSS and the Firefox source codes (and some extensions and running the SSLsample codes too), I'm clearly lost now.
My intention is just to do simple thing. To divert any https request from Firefox to my very own callback functions. In which, my callbacks here have some information for the NSS/SSL to work with.
My only problem is, where is Firefox's code for processing the https URL. I mean, when we key in the https address at the address bar, we press Enter. I just need access to the source that triggers at that point (after we press Enter). Somehow, I can intercept any request for https URLs.
Thanks.

A: So, you want to intercept the data, right?  You'll want to play around with this interface.

A: not sure, if it helps, but I asked this question:
XULRunner: Prevent links to arbitrary domains
Maybe it could be sufficient for your task to use the method explained in the first answer. However, it is an all-JavaScript solution.
Cheers,


text:
Q: Save image somewhere and use it in another ViewController (iOS) I've written some code to make a screenshot of the view. I write that image to the photo library. But the thing is, I want to use that image in an other imageView in another ViewController. How can I save the image somewhere in the app and use it in another ViewController?
My code:
UIView* captureView = self.view;

UIGraphicsBeginImageContextWithOptions(captureView.bounds.size, captureView.opaque, 0.0);
[captureView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGRect cropRect = CGRectMake(0 ,0 ,640,1136);
UIGraphicsBeginImageContextWithOptions(cropRect.size, captureView.opaque, 1.0f);
[screenshot drawInRect:cropRect];
UIImage * customScreenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageWriteToSavedPhotosAlbum(customScreenShot , nil, nil, nil);

A: You first need to save your image on the disk:
NSString *documentDirectory =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
                                                                        objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:@"%@/myImage.png",documentDirectory];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(customScreenShot)];
[imageData writeToFile:pngFilePath atomically:YES];

And then you can create an UIImageView with the file:
UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage
imageWithContentsOfFile:pngFilePath]];
[self.view addSubview:myImageView];

A: If you are using Storyboards, you could pass it to the next view controller like so; in the prepareForSegue method ( this relieves you from having to save it to disk ):
Note:  the name of the segue is set by you in MainStoryboard.storyboard.  - mySegue.
kMySegue is just a key for that. i.e. #define kMySegue @"mySegue"
imageInOtherViewController is a UIImage in the other view controller.
// TheFirstViewController.m

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    id destinationViewController = [segue destinationViewController];

    if ([[segue identifier] isEqualToString:kMySegue]){
        if ([destinationViewController respondsToSelector:@selector(setImageInOtherViewController:)]){
            [destinationViewController setImageInOtherViewController:[UIImage imageNamed:@"myImage.png"]];
            FastCameraViewController *viewController = segue.destinationViewController;
            viewController.delegate = self;
        }
    }

    // OtherViewController.h

    @interface OtherViewController : UIViewController
    {
    }
    @property (nonatomic, strong) IBOutlet UIImageView *otherViewControllerImageView;
    @property (nonatomic, strong) UIImage *imageInOtherViewController;

    // OtherViewController.m
    @implementation OtherViewController
    @synthesize otherViewControllerImageView;
    @synthesize imageInOtherViewController;

    - (void)viewDidLoad{
        [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

        [[self otherViewControllerImageView] setImage:imageInOtherViewController];

   }

A: To cache your images I recommend using the NSCache class first ie
NSCache* imagesCache = [[NSCache alloc] init];
[imagesCache setName:@"imagesCache"];

[imagesCache setObject:customScreenShot forKey:@"image1"];

the good news is that NSCache accepts any object of type id so you can store images, mp3s, whatever you want.
If you would like to use the phone's file directory (which is more expensive to use than NSCache..) I recommend you use the Library/Caches directory instead of the Documents directory.. so building on iDevzilla's answer:
NSString *documentDirectory =
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)
 objectAtIndex:0];


text:
Q: Django REST framework: 'WSGIRequest' object has no attribute 'query_params' I am learning DRF, and trying to print print request.query_params. But got error:
    print request.query_params
AttributeError: 'WSGIRequest' object has no attribute 'query_params'

Codes:
class CourseDetailView(generics.RetrieveAPIView):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

    def dispatch(self, request, *args, **kwargs):
        print request.user
        print 'CourseDetailView dispatch:', request.META
        #print request.data
        """
        print 'parsers', request.parsers
        print request.accepted_renderer
        print 'authenticators', request.authenticators
        """
        #print 'accepted_media_type', request.accepted_media_type
        print request.META['HTTP_ACCEPT']
        print 'method', request.method
        print 'content_type', request.content_type
        print 'query_params'
        print request.query_params # Here

        return super(CourseDetailView, self).dispatch(request, *args, **kwargs)

Part of my settings:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api',
]

# DJANGO REST FRAMEWORK
REST_FRAMEWORK = {
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

A: dispatch is the first method called in a class based view, and it's where all the setup happens - including, in the case of an API view, the wrapping of the Django request object with the DRF extensions. By overriding it you've prevented any of that code from running, so you just have the basic Django request.
Generally you should avoid overriding dispatch. Use a more appropriate method, eg get.


text:
Q: Show a legend for each panel in ggplot2? Given this data:
  mtcars %>%
     gather(-mpg, -hp, key = "var", value = "value") %>%
  mtcars %>%
  gather(-mpg, -hp, key = "var", value = "value") %>%
  ggplot(aes(x = value, y = mpg, color = hp)) +
  geom_point() +
  facet_wrap(~ var, scales = "free") +
  theme_bw()

As you can see, there is one legend for hp (which hide low values). I want a legend for each panel.

A: As stefan already mentioned in his comment we could use patchwork package:
library(ggplot2)
library(dplyr)
library(patchwork)

mtcars_list <- mtcars %>%
  gather(-mpg, -hp, key = "var", value = "value") %>%
  group_split(var)

gg_list = lapply(mtcars_list, function(x) {
  ggplot(x, aes(x = value, y = mpg, color = hp)) +
    geom_point() +
    facet_wrap(~ var, scales = "free") +
    theme_bw()
})

# patchwork
wrap_plots(gg_list)


text:
Q: access a mysql db and displaying it in a gridview or table I am trying to access a Mysql DB and display it in a Gridview in .Net
I can get it to connect to the DB, but it displays nothing and there is records in the DB, this is the code i am using.
Dim MysqlConn As MySqlConnection
Dim ContactsCommand As New MySqlCommand
Dim ContactsAdapter As New MySqlDataAdapter
Dim ContactsData As New DataTable
Dim SQL As String

Private Sub btnGrabData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabData.Click

    MysqlConn = New MySqlConnection()
    SQL = "SELECT AffID FROM toutcome"

    MysqlConn.ConnectionString = "Server=localhost;Database=merrywoodtest;UID=MerryWoodTest;PWD=H0r$hamTest;"

    Try

        MysqlConn.Open()

        ContactsCommand.Connection = MysqlConn
        ContactsCommand.CommandText = SQL

        ContactsAdapter.SelectCommand = ContactsCommand
        ContactsAdapter.Fill(ContactsData)

        DataGridView1.DataSource = ContactsData

    Catch myerror As MySqlException

        MessageBox.Show("Cannot connect to database: " & myerror.Message)

    Finally

        MysqlConn.Close()

    End Try
End Sub

A: Please make sure that you will call DataBind() method of DataGridView after the data source is assinged.
You may also set the Connection property of the ContactsCommand object and the SelectCommand property of the  ContactsAdapter object.


text:
Q: Extjs DataView store.reload re-adds items I have an extjs dataview:
    var dv = Ext.create('Ext.view.View', {
        store: this.eventInstanceImagesStore,
        tpl: [
            '<tpl for=".">',
            '
',
            '

',
            '{shortName:htmlEncode}',
            '
',
            '</tpl>',
            '

'
        ],
        multiSelect: true,
        trackOver: true,
        overItemCls: 'x-item-over',
        itemSelector: 'div.thumb-wrap',
        emptyText: 'No images to display',
        plugins: [
           // Ext.create('Ext.ux.DataView.DragSelector', {}),
            Ext.create('Ext.ux.DataView.LabelEditor', { dataIndex: 'name' })
        ],
        prepareData: function (data) {
            Ext.apply(data, {
                shortName: Ext.util.Format.ellipsis(data.name, 15),
                sizeString: Ext.util.Format.fileSize(data.size),
                dateString: Ext.util.Format.date(data.lastmod, "m/d/Y g:i a")
            });
            return data;
        }
    });

I also have a file upload form which, when the image has been successfully uploaded I am reloading the dataview:
 dv.store.reload({
      params: {
          id: eid
      }
 });

However, when the reload happens it seems to re-add the images twice. So I end up with 2 dataviews... Has anyone seen this before?

A: Try doing dv.store.removeAll(); first before doing a
dv.store.reload({
      params: {
          id: eid
      }
 });


text:
Q: Account forgot password handle I am using the layout handle customer_account to add CSS to the account pages like this:
<customer_account>
    <reference name="head">
        <action method="addCss">
            <name>css/parts/account.css</name>
        </action>
    </reference>
</customer_account>

But it seems that this CSS is not added to the forgot password page, while it does have the same type of url as the other account pages: domain.com/customer/account/forgotpassword/
My question: What is the layout handle for this page, or is there a way to add this page to the customer account handle?

A: The customer_account handle is only used for logged in account pages:

*

*Customer Dashboard

*Customer Account Edit

*Customer Address

*Customer Address Form

*Customer Downloadable Products

*Customer Newsletter Subscriptions

*Customer OAuth applications

*Customer Product Reviews

*Customer Product Reviews Details

*Customer Order History

*Customer Order View

*Customer Invoice View

*Customer Shipment View

*Customer Creditmemo View

*Customer Reorder

*Customer Tags List

*Customer Tag View

*Customer Wishlist

*Customer Wishlist Sharing Form

*Customer Billing Agreements

*Customer Billing Agreements View

*Customer Recurring Profile

*Customer Recurring Profile View

*Customer Recurring Profiler Orders

The handle for the forgot password page is customer_account_forgotpassword


text:
Q: Angular Highcharts-ng how to set additional data series as tooltip I have an array of data for values and an array of data for sample counts and I would like to display both in the tooltip for the point on the line chart.
I am using a web call to populate the arrays of data using an angular.forEach loop. I then set the data series of the chart as:
var all_values= [];
var all_samples= [];
var timespan= [];

angular.forEach($scope.data, function (value, key) {
  all_values.push(value.All_Values); //y axis values
  all_samples.push(value.All_Samples); //additional tooltip data
  timespan.push(values.TimeSpan); //this is for the x axis
});

$scope.chartConfig.series[0].data = all_values;

All of this works fine but how can I get my all_samples to be included in the data series so that I can display it on the tooltip?

A: If you want to display extra info in tooltip, then you need to set custom pointFormat / pointFroamtter / format / formatter - depends how much you would like to change tooltip display. Next, you could have external array for extra info or you could just add more properties to each data point. If you are using arrays for data points, then use keys.
Example: http://jsfiddle.net/ge2rbgt9/


text:
Q: RadioButtonList selected value binding in aspx I got this RadioButtonList with defined ListItems:
<asp:RadioButtonList ID="RblSpouseLocation" runat="server" RepeatDirection="Horizontal">
        <asp:ListItem Text="In Country" Value="0"></asp:ListItem>
        <asp:ListItem Text="Outside of Country" Value="1"></asp:ListItem>
  </asp:RadioButtonList>

I have a field "SpouseLocation" of type bit in my database. I need to bind the selected value of the RadioButtonList to this field.
I found tutorials of how to do it in the code-behind, but can it be done in aspx ?

A: I changed my database field type to int and added "SelectedValue='<%# Bind("SpouseLocation") %>" to my radiobuttonlist
The answer to this questions helped me


text:
Q: Downsides of Twitter bootstrap I have been building website using my custom CSS and HTML for along time now. Just a minute ago I discovered Bootstrap.
So, I want to here from the people who have experienced hair pulling issues with bootstrap.
P.S. If you had to make a site responsive, would you use Bootstrap or Restive.JS?

A: I just finished re-skinning a site using Bootstrap over custom classes.
Overall, I'm now a Bootstrap fan.  what I found was

*

*First thing to keep in mind is to do things the Bootstrap way.  It uses css classes to define what needs to be done.  Then the framework's JavaScript will sense those classes and add the appropriate actions.

*Using the grid makes it easy to have a consistent layout across each page.

*You probably need to tweak some of the layout classes on a page to solve local layout issues.

I haven't used Restive.JS, but it appears to solve the responsive design issues completely differently from Bootstrap.
Overall, I would suggest you try both and see which meets your needs best.


text:
Q: How to correct my over fitted spline curve in python I have a data set and I've been asked to assign a smooth curve over its bar graph.
However my created graph seems very overfitted. they asked me to assign some sort of graph which can join some adjacent minimums and maximums and I don't know how to do that. Any help would be appreciated.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import spline

fig, ax = plt.subplots()
fig.set_size_inches(13,7, forward=True)

width=1.0

data=pd.DataFrame({'x':[-29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
                   'y':[0.002383790226460071, 0.002383790226460071, 0.005164878823996822, 0.004370282081843465, 0.005164878823996822, 0.002383790226460071, 0.003178386968613429, 0.005959475566150178, 0.005959475566150178, 0.006754072308303536, 0.007945967421533572, 0.003575685339690107, 0.001986491855383393, 0.003575685339690107, 0.003972983710766786, 0.00278108859753675, 0.005959475566150178, 0.007151370679380214, 0.004767580452920143, 0.005164878823996822, 0.003575685339690107, 0.004370282081843465, 0.007945967421533572, 0.01311084624553039, 0.01072705601907032, 0.01430274135876043, 0.01231624950337704, 0.01589193484306714, 0.02264600715137068, 0.09654350417163289, 0.05164878823996821, 0.0166865315852205, 0.01549463647199046, 0.01350814461660707, 0.01191895113230036, 0.01191895113230036, 0.00874056416368693, 0.01152165276122368, 0.007151370679380214, 0.009137862534763607, 0.006356773937226857, 0.007151370679380214, 0.00834326579261025, 0.006356773937226857, 0.005562177195073501, 0.006754072308303536, 0.005164878823996822, 0.005164878823996822, 0.005959475566150178, 0.004767580452920143, 0.00278108859753675, 0.007945967421533572, 0.001589193484306714, 0.00278108859753675, 0.003178386968613429, 0.003575685339690107, 0.003178386968613429, 0.004370282081843465, 0.005562177195073501, 0.004370282081843465]})

plt.bar(data['x'],data['y'],width, color='r',  alpha=0.95)
x=data['x']
y=data['y']

x_new = np.linspace(x.min(),x.max(),300)

y_smooth =spline(x,y,x_new, order=3,kind='smoothest')

plt.plot(x_new,y_smooth, color='b')

A: Here is my fitting and plotting code for a variation of the Lorentzian peak equation from equation search of over 80 peak equations. This code uses scipy's differential_evolution genetic algorithm to estimate initial parameters for the non-linear solver in curve_fit(). That scipy genetic algorithm module uses the Latin Hypercube algorithm to ensure a thorough search of parameter space and requires bounds within which to search, here those bounds are taken from the data max and min values.
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings

xData = numpy.array([-29.0, -28.0, -27.0, -26.0, -25.0, -24.0, -23.0, -22.0, -21.0, -20.0, -19.0, -18.0, -17.0, -16.0, -15.0, -14.0, -13.0, -12.0, -11.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0])
yData = numpy.array([0.002383790226460071, 0.002383790226460071, 0.005164878823996822, 0.004370282081843465, 0.005164878823996822, 0.002383790226460071, 0.003178386968613429, 0.005959475566150178, 0.005959475566150178, 0.006754072308303536, 0.007945967421533572, 0.003575685339690107, 0.001986491855383393, 0.003575685339690107, 0.003972983710766786, 0.00278108859753675, 0.005959475566150178, 0.007151370679380214, 0.004767580452920143, 0.005164878823996822, 0.003575685339690107, 0.004370282081843465, 0.007945967421533572, 0.01311084624553039, 0.01072705601907032, 0.01430274135876043, 0.01231624950337704, 0.01589193484306714, 0.02264600715137068, 0.09654350417163289, 0.05164878823996821, 0.0166865315852205, 0.01549463647199046, 0.01350814461660707, 0.01191895113230036, 0.01191895113230036, 0.00874056416368693, 0.01152165276122368, 0.007151370679380214, 0.009137862534763607, 0.006356773937226857, 0.007151370679380214, 0.00834326579261025, 0.006356773937226857, 0.005562177195073501, 0.006754072308303536, 0.005164878823996822, 0.005164878823996822, 0.005959475566150178, 0.004767580452920143, 0.00278108859753675, 0.007945967421533572, 0.001589193484306714, 0.00278108859753675, 0.003178386968613429, 0.003575685339690107, 0.003178386968613429, 0.004370282081843465, 0.005562177195073501, 0.004370282081843465])

def LorentzianPeakG_Offset(x_in, a, b, c, Offset): # from zunzun.com peak equation search
    temp = 0.0
    temp = a/ (1.0 + numpy.power((x_in-b)/c, 2.0))
    temp += Offset
    return temp

# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
    val = LorentzianPeakG_Offset(xData, *parameterTuple)
    return numpy.sum((yData - val) ** 2.0)

def generate_Initial_Parameters():
    # min and max used for bounds
    maxX = max(xData)
    minX = min(xData)
    maxY = max(yData)
    minY = min(yData)

    parameterBounds = []
    parameterBounds.append([minX, maxX]) # seach bounds for a
    parameterBounds.append([minX, maxX]) # seach bounds for b
    parameterBounds.append([minX, maxX]) # seach bounds for c
    parameterBounds.append([0.0, maxY]) # seach bounds for Offset

    # "seed" the numpy random number generator for repeatable results
    result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
    return result.x

# generate initial parameter values
geneticParameters = generate_Initial_Parameters()

# curve fit the test data
fittedParameters, pcov = curve_fit(LorentzianPeakG_Offset, xData, yData, geneticParameters)

print('Parameters', fittedParameters)

modelPredictions = LorentzianPeakG_Offset(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData), 250)
    yModel = LorentzianPeakG_Offset(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)

This is the result:

A: This is the answer that I ended up with:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline

fig, ax = plt.subplots()
fig.set_size_inches(13,7, forward=True)

width=1.0

#data=pd.read_excel("h:/projects/psc/output/data.xlsx")

data=pd.DataFrame({'x':\[-29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30\],
                   'y':\[0.002383790226460071, 0.002383790226460071, 0.005164878823996822, 0.004370282081843465, 0.005164878823996822, 0.002383790226460071, 0.003178386968613429, 0.005959475566150178, 0.005959475566150178, 0.006754072308303536, 0.007945967421533572, 0.003575685339690107, 0.001986491855383393, 0.003575685339690107, 0.003972983710766786, 0.00278108859753675, 0.005959475566150178, 0.007151370679380214, 0.004767580452920143, 0.005164878823996822, 0.003575685339690107, 0.004370282081843465, 0.007945967421533572, 0.01311084624553039, 0.01072705601907032, 0.01430274135876043, 0.01231624950337704, 0.01589193484306714, 0.02264600715137068, 0.09654350417163289, 0.05164878823996821, 0.0166865315852205, 0.01549463647199046, 0.01350814461660707, 0.01191895113230036, 0.01191895113230036, 0.00874056416368693, 0.01152165276122368, 0.007151370679380214, 0.009137862534763607, 0.006356773937226857, 0.007151370679380214, 0.00834326579261025, 0.006356773937226857, 0.005562177195073501, 0.006754072308303536, 0.005164878823996822, 0.005164878823996822, 0.005959475566150178, 0.004767580452920143, 0.00278108859753675, 0.007945967421533572, 0.001589193484306714, 0.00278108859753675, 0.003178386968613429, 0.003575685339690107, 0.003178386968613429, 0.004370282081843465, 0.005562177195073501, 0.004370282081843465\]})

plt.bar(data\['x'\],data\['y'\],width, color='r',  alpha=0.95)

x=data\['x'\]
y=data\['y'\]
x_new = np.linspace(x.min(),x.max(),300)
spl=UnivariateSpline(x,y)
spl.set_smoothing_factor(0.001)
y_smooth =spl(x_new)
plt.plot(x_new,y_smooth, color='b', alpha=0.95)][1]


text:
Q: How to mock string class in Moq I have a Test method which is like this
[Test]
public void VerifyRedirectedTempCodeWithAnEmptyString()
{
    var mockStringLength = new Mock<string>();
    mockStringLength.Setup(x => x.Length).Returns(0);
    Boolean returnValue = VerifyRedirectedTempCode(mockStringLength.Object);
    Assert.AreEqual(returnValue, false);
}

There is no compilation error, but when I run this test its giving
System.NotSupportedException : Type to mock must be an interface or an abstract or non-sealed class. here is my actual method
    public virtual Boolean VerifyRedirectedTempCode(string tempAuthCode)
    {
        if (tempAuthCode != null && tempAuthCode.Length > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

So, how to mock the string.length property.So that even in future if they update the length method it should not affect my test method. How to mock?

A: You don't need to mock the string length here. The method you're testing expects an integer, so just pass it an integer! If you really want you can pass it string.Empty.Length, in case this changes in a future version of the framework.
With a unit test, you're testing the behaviour of a method given its inputs and the state of its dependencies. If your method takes an int and returns a bool then all you need to do to test it is to pass in an int. The method shouldn't care where it came from. This is a matter of separation of concerns.

Following your update, given your method takes a string you just need to test its behaviour given different string inputs. At least null, string.Empty, and some valid string.
You can't expect your test to never fail as you change your method's  implementation. In fact, you should change your test first so it DOES fail, the change your code so the tests pass, then refactor. This is called the red, green, refactor cycle.

It seems like your validator is probably part of a larger piece of work and maybe what you're really interested in testing is how the rest of your code behaves given the different potential validation results. In this case, I would recommend that you extract your validation logic into a separate class whose interface you can then mock. Supply the validator as a dependency to the code that needs it. Then, in your tests you can supply a mock validator that behaves in a predetermined way. That way you can write your tests without worrying that a future change to the validator logic will break them. This seems to be the essence of your question.


text:
Q: Can I use Spreedly to assign a subscription to a venue as well as a user? In my app a user has an account, and many venues can belong to each account. The venues are on either a free or premium subscription.
I would like to use Spreedly to sort out recurring billing for each venue. So a user can own multiple venues where some are free and some are premium. Can I do this with Spreedly? All the documentation I have seen assigns a subscription to a user only.
Thanks for any help its much appreciated!

A: Spreedly doesn't know or care about the difference between a User or a Venue. These are just names of models that you have determined. So yes, you can do that. If you are following a guide, just apply it to your venue model instead of your user model.


text:
Q: Variable file in Expect script I'm using this expect script as an answerfile to a interactive shell script:
#!/usr/bin/expect

spawn ./interactivescriptname
expect "Question 1?"
send "something\r"
expect "Question 2?"
send "yes\r"
expect "Password?"
send "somepassword\r"
interact

above works, but i want to use variables from a inputfile.
my variables files look like this:
var1="something"
var2="yes"
var3="somepassword"

Normally in bash i would use the source command, but this doesn't work in expect.
Any ideas?

A: One method would be to set TCL variables in a file (here, vars) and then source that file from the main script.
$ cat vars
set var1 something
set var2 yes
set var3 Hunter2
$ cat script
#!/usr/bin/env expect
source vars
puts $var3
$ chmod +x script
$ ./script
Hunter2
$

It may be good to use more informative variable names than varN ...


text:
Q: What is the specific heat of steam, when Latent heat of vaporization decreases at the rate of $0.64 \:\rm Cal/K$
specific heat of water at $100° C = 1.01\:\rm Cal/gm$ degree, latent heat of vaporization decreases at the rate of $0.64\:\rm  Cal/K$, latent heat of vaporization of $54\:\rm  C \:Cal/gm$. What is the specific heat of steam?

I am confused in the units given and I tried to solve it by comparing latent and specific heat to get $L = C\Delta T$, but unable to solve it, since I don't know what will be the temperature difference, Please tell me how to solve it.

A: With regard to the problem with units:
Specific heat should be in units of "calories/ gram/Celsius degree";
Latent heat of vaporization should be in "calories/gram" ;
Temperature change in Latent heat should be in "calories/gram/Celsius degree"
"calories" should be spelled here with a lower-case "c".  The capitalized version is $1000$ times bigger i.e $1$ Calorie is $1$ kilo-calorie.
There is a typo in the OP:  the latent heat of vaporization of water at $100 ^o$ C is $540$ calories/gram.
To solve the question, you should apply Hess's Law https://chem.libretexts.org/Bookshelves/Physical_and_Theoretical_Chemistry_Textbook_Maps/Supplemental_Modules_(Physical_and_Theoretical_Chemistry)/Thermodynamics/Thermochemistry/Hess's_Law%3A_The_Principle_of_Conservation_of_Energy
Simply put, the energy change involved in going from A to B does not depend on the specific route you take.
In this case:
First, take one gram of boiling hot liquid water, warm it as liquid water to $101^o$ C, and then vaporize it.  You have all the information needed to calculate  the energy needed to do this.
Secondly, take the same gram of boiling hot liquid water, vaporize it at $100^o$ C, and warm the resulting steam to $101^o$ C.  You have one unknown in the calculation of the energy needed:  the specific heat of the steam.
Set these two calculations equal (Hess's Law), and solve for the unknown.


text:
Q: Sample size references For calculating sample size in clinical research, I have encountered different ways. For example, using lognormal distributions or calculating using ICC. I am confused which method to apply. Could anyone point to the some references to calculate sample size pertaining to clinical research?

A: This is a broad question and there are books on the subject. Here is one that many have found accessible.
See also the link Good text on Clinical Trials?  provided in a comment.


text:
Q: File handle variable? I get a bad record number error when I use this:
Put #filehandle, (i * 100) + x, buf(x)

when filehandle is an integer, that I opened via this.
filehandle = FreeFile
Open (App.Path & "\" & BufferFileRootName & "A") For Binary As filehandle

How could I fix this and what am I doing wrong?

A: You should check out the values of i and x that you are using. A bad record number on put usually indicates that the record number is less than or equal to zero.
If you print out the values of i and x (as well as the result of that calculation), it should hopefully tell you what's wrong.
Keep in mind that record numbers are 1-based so, if both your i and x variables are zero, that would cause this problem.