text:
Q: Character array and pointer The code snippet is given as:
char *s[] = {"program", "test", "load", "frame", "stack", NULL};
char **p = s + 2;

We need to find the output of following statement:
printf("%s", p[-2] + 3);

What does p[-2] refer to?

A: char *s[] = {"program","test","load","frame","stack",NULL};
char **p = s + 2
printf("%s", p[-2] + 3);

*

*The variable s is an array of char* pointers.

*The variable p is a pointer to a pointer. Pointer arithmetics downgrades the array s to a char**, initializing p to a value of two times the size of a char**. On a 32bit machine, if s points to 1000, p will point to 1008.

The expression p[-2] is equivalent to *(p - 2), returning a simple pointer to a char*. In this case, a value pointing to the first element of the strings array: "program".
Finally, since *(p - 2) is the expression pointing to the first letter of the string "program", *(p - 2) + 3 points to the fourth letter of that word: "gram".
printf("%s", *(p - 2) + 3); /* prints: gram */

A: Did you try compiling your code? Once the syntax errors are fixed, the output is gram.
#include <stdio.h>

int main()
{
    char *s[] = {"program","test","load","frame","stack",NULL};
    char **p = s + 2;

    printf("%s",p[-2] + 3);

    return 0;
};

See http://ideone.com/eVAUv for the compilation and output.


text:
Q: What is the C++ convention when I need to add a useless return statement? I was trying to write a function that returns the first non-repeated character in a string. The algorithm I made was:

*

*Assert that the string is non-empty

*Iterate through the string and add all non-repeated characters to a set

*Assert that the set be non-empty

*Iterate through string again and return the first character that's in the set

*Add a useless return statement to make the compiler happy. (Arbitrarily return 'F')

Obviously my algorithm is very "brute force" and could be improved on. It runs, anyhow. I was wondering if there's a better way to do this and was also wondering what the convention is for useless return statements. Don't be afraid to criticize me harshly. I'm trying to become a C++ stiffler. ;)
#include <iostream>
#include <string>
#include <set>

char first_nonrepeating_char(const std::string&);

int main() {

    std::string S = "yodawgIheardyoulike";

    std::cout << first_nonrepeating_char(S);

}

// Finds that first non-repeated character in the string
char first_nonrepeating_char(const std::string& str) {
    assert (str.size() > 0);
    std::set<char> nonRepChars;
    std::string::const_iterator it = str.begin();
    while (it != str.end()) {
        if (nonRepChars.count(*it) == 0) {
            nonRepChars.insert(*it);
        } else {
            nonRepChars.erase(*it);
        }
        ++it;
    }
    assert (nonRepChars.size() != 0);
    it = str.begin();
    while (it != str.end()) {
        if (nonRepChars.count(*it) == 1) return (*it);
        ++it;
    }
    return ('F'); // NEVER HAPPENS
}

A: The main problem is just getting rid of warnings.
Ideally you should be able to just say
assert( false );  // Should never get here

but unfortunately that does not get rid of all warnings with the compilers I use most, namely Visual C++ and g++.
Instead I do this:
xassert_should_never_get_here();

where xassert_should_never_get_here is a function that

*

*is declared as "noreturn" by compiler-specific means, e.g. __declspec for Visual C++,

*has an assert(false) to handle debug builds,

*then throws a std::logic_error.
The last two points are accomplished by a macro XASSERT (its actual name in my code is CPPX_XASSERT, it's always a good idea to use prefixes for macro names so as to reduce name conflict probability).

Of course, the assertion that you should not get to the end, is equivalent to an assertion that the argument string does contain at least one non-repeated character, which therefore is a precondition of the function (part of its contract), which I think should be documented by a comment. :-)
There are three main "modern C++" ways of coding things up when you do not have that precondition, namely

*

*choose one char value to signify "no such", e.g. '\0', or

*throw an exception in the case of no such, or

*return a boxed result which can be logically "empty", e.g. the Boost class corresponding to Barton and Nackmann's Fallible.

About the algorithm: when you're not intested in where the first non-repeating char is, you can avoid the rescan of the string by maintaining a count per character, e.g. by using a map<char, int> instead of a set<char>.

A: There is a simpler and "cleaner" way of doing it, but it is not computationally faster than "brute force".
Use a table that counts the number of occurrences of each character in the input string.
Then go over the input string one more time, and return the first character whose count is 1.
char GetFirstNonRepeatedChar(const char* s)
{
    int table[256] = {0};
    for (int i=0; s[i]!=0; i++)
        table[s[i]]++;
    for (int i=0; s[i]!=0; i++)
        if (table[s[i]] == 1)
            return s[i];
    return 0;
}

Note: the above will work for ASCII strings.
If you're using a different format, then you'll need to change the 256 (and the char of course).

redpajama_set_name: RedPajamaStackExchange


text:
Q: show different arrangement if image and text is in mobile screen using bootstrap I am using the following code and I am unable to get description below image in mobile screen. How can I make changes to the code ? The way it looks for full screen/desktop is correct. For size "sm" I want it to reorder text and image.
The order I'm looking for : Desktop - Title&desc left and image right.
Mobile - Title on top then image then the description.
Code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Title ....................................... more text

description ....................................... more description.................... ....................................... more description ....................................... more description.......................................

A: I have changed arrangement of html and gave classes to float image to right and text to left or you can use pull-right and pull-left classes provided by twitter-bootstrap.
Also there are some hidden classes provided by twitter-bootstrap you can use them to achieve your desired layout.
Source

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Title....................................... more text

Title....................................... more text

description.......................................more description....................       ......................................more description     .......................................                         more description.......................................

A: Is this what you want:http://jsfiddle.net/wVVbT/156/
Tried it with jQuery and it seems to work:
jQuery code:
  $(document).ready(function(){

        if($(window).width()<992){
            $('.image').after($('#description').get());
    }

    $(window).resize(function() {

   var hthree=$('#description').get();

  if($(window).width()<992)
  {

    $('.image').after(hthree);
  }else{

    $('#title').after(hthree);
  }
});
});


text:
Q: WPF Charting Vertical Chart I have WPF Toolkit and I need to do vertical chart starting at the top.
I was trying many things but always I end up with either error or chart that is going from left to right. I have no idea what to do, and I can't find any help :(
For example this is throwing an error:
<chart:Chart x:Name="LasChart" Width="764" HorizontalAlignment="Left" VerticalAlignment="Top" Height="896">
            <chart:LineSeries Name="LasData" IndependentValueBinding="{Binding Path=Key}" DependentValueBinding="{Binding Path=Value}">
                <chart:LineSeries.DependentRangeAxis>
                    <chart:LinearAxis Orientation="X" Location="Top"/>
                </chart:LineSeries.DependentRangeAxis>
            </chart:LineSeries>
        </chart:Chart>

A: You can just do a LayoutTransform. Refer below code.
 <wpfTool:Chart.LayoutTransform>
            <RotateTransform  Angle="90" />
        </wpfTool:Chart.LayoutTransform>

But not sure whether it will fit your requirement.

A: I have figured that out :)
So if anyone want to do vertical chart with proper axes here it goes:
 <chart:Chart x:Name="LasChart" HorizontalAlignment="Left" VerticalAlignment="Top" UseLayoutRounding="False" Height="686">
            <chart:Chart.LayoutTransform>
                <RotateTransform  Angle="90" />
            </chart:Chart.LayoutTransform>

            <chart:Chart.Axes>
                <chart:CategoryAxis Orientation="X"
                                  Location="Bottom"
                                  Foreground="Black">
                    <chart:CategoryAxis.AxisLabelStyle>
                        <Style TargetType="chart:AxisLabel">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate
                                      TargetType="chart:AxisLabel">
                                        <TextBlock
                             Text="{TemplateBinding FormattedContent}"
                                               TextAlignment="Center"
                                               RenderTransformOrigin="0.5,0.5">
                                            <TextBlock.RenderTransform>
                                                <RotateTransform Angle="-90" />
                                            </TextBlock.RenderTransform>
                                        </TextBlock>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </chart:CategoryAxis.AxisLabelStyle>
                </chart:CategoryAxis>

                <chart:LinearAxis Orientation="Y"
                                  Location="Left"
                                  Foreground="Black">
                    <chart:LinearAxis.AxisLabelStyle>
                        <Style TargetType="chart:AxisLabel">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate
                                      TargetType="chart:AxisLabel">
                                        <TextBlock
                             Text="{TemplateBinding FormattedContent}"
                                               TextAlignment="Center"
                                               RenderTransformOrigin="0.5,0.5">
                                            <TextBlock.RenderTransform>
                                                <RotateTransform Angle="-90" />
                                            </TextBlock.RenderTransform>
                                        </TextBlock>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </chart:LinearAxis.AxisLabelStyle>
                </chart:LinearAxis>
            </chart:Chart.Axes>

            <chart:LineSeries Name="LasData" IndependentValueBinding="{Binding Path=Key}" DependentValueBinding="{Binding Path=Value}">
            </chart:LineSeries>

            <chart:Chart.LegendStyle>
                <Style TargetType="Control">
                    <Setter Property="Width" Value="0" />
                    <Setter Property="Height" Value="0" />
                </Style>
            </chart:Chart.LegendStyle>
        </chart:Chart>


text:
Q: What to do if i get cannot find symbol class onclicklistener error? I am writing another program but this time on Android Studio as an app in Java. Now I am getting following error; error: cannot find symbol class OnClickListener
How do I fix this? Here is my code:
package tegabyte.testprogramm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    EditText firstNumber;
    EditText secondNumber;
    TextView addResult;
    Button btnAdd;

    double num1,num2,sum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        firstNumber = (EditText)findViewById(R.id.txtBase);
        secondNumber = (EditText)findViewById(R.id.txtNikotin);
        addResult = (TextView)findViewById(R.id.txtResult);
        btnAdd = (Button)findViewById(R.id.btnAdd);

        btnAdd.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                num1 = Double.parseDouble(firstNumber.getText().toString());
                num2 = Double.parseDouble(secondNumber.getText().toString());
                sum = num1 / 20 * num2;
                addResult.setText(Double.toString(sum));
            }
        });
    }
}

Any help is appreciated. Thank you!

A: You haven't imported the OnClickListener. In addition, there are multiple OnClickListeners in different SDK packages. The one I assume you're looking for is the one in View. So instead of new OnClickListener(), write new View.OnClickListener()

A: OnClickListener need to identify of which OnClickListener to perform click so add View
btnAdd.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                num1 = Double.parseDouble(firstNumber.getText().toString());
                num2 = Double.parseDouble(secondNumber.getText().toString());
                sum = num1 / 20 * num2;
                addResult.setText(Double.toString(sum));
            }
        });

or when you type btnAdd.setOnClickListener(new On
you get list of hints than select View.OnClickListener()

A: Try this instead.I think you have not imported the OnclickListener.Either import it or use like this.
btnAdd.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            num1 = Double.parseDouble(firstNumber.getText().toString());
            num2 = Double.parseDouble(secondNumber.getText().toString());
            sum = num1 / 20 * num2;
            addResult.setText(Double.toString(sum));
        }
    });

Also add import statement at the top like this for the view class import android.view.View;


text:
Q: Tkinter - I can't disable the button widget below you can see my code:
from tkinter import *
from tkinter import ttk
import time

class MainWindow:
    def __init__(self):
        self.root = Tk()
        self.root.geometry("300x200")
        self.root.title("Test")
        self.StartButton=ttk.Button(self.root, text="Start", command=self.Start)
        self.StartButton.pack()
        self.root.mainloop()

    def Start(self):
        self.StartButton.config(state = "disable")
        #input()
        time.sleep(10)
        self.StartButton.config(state = "enable")

app = MainWindow()

when you click on the OK button, the script doesn't do nothing for 10 seconds, and during these seconds, the button should be disabled, but it doesn't happen. it happens only if you block the script using for example the input() function.
I really don't understand this weird behaviour. how can I solve this issue? it seems that the button is not able to disable itself duting the process, but the instruction to disable it, comes first than the process! so what is the issue?

A: The options are 'disabled' and 'normal' (although disable also works, thanks to @Saad in the comments)
You also need to call root.update() for the changes to take place.
def Start(self):
    self.StartButton.config(state="disabled")
    self.root.update()
    time.sleep(2)
    self.StartButton.config(state="normal")

Alternatively (as also proposed in the comments by @acw1668), you should probably use root.after to reset your button after some time; this prevents the blocking effect of sleep, and makes the call to root.update() unnecessary:
def Start(self):
    self.StartButton.config(state="disabled")
    self.root.after(2000, lambda: self.StartButton.config(state="normal"))


text:
Q: Axios events when downloading large files with streams I'm using axios on server side.
I want to download big files .. technically this should be used with byte-ranges

*

*Does axios handle the byte-range request so that the callback function is only called when all the response is ready

*If 1 is not true, should I handle data chunks myself ?

In the code below :
axios({
  url: params.url,
  method: 'GET',
  responseType: 'stream' // important
}).then(function (response) {

  logger.debug('__download() : done!')
  let contentType = response.headers['content-type']
  let contentLength = response.headers['content-length']
  var writer = new streams.WritableStream()

  response.data.pipe(writer)
  // ....
})

Am I supposed to wait for something like response.on('end')?
The purpose of what I'm doing is to get the size of the buffer (which I could get by writer.getBuffer())
Thanks for any hint !

A: I found out that to download the stream, in memory in my case, I had to wait for the event on my writer (writer.on('finished',cb)  vs response.on('end', cb )) (not sure if there is something like response.on('end'))...
var stream = require('stream');
var util = require('util');
var Writable = stream.Writable;

function MemoryStream(options) {
    if (!(this instanceof MemoryStream)) {
        return new MemoryStream(options);
    }
    Writable.call(this, options); // init super
}
util.inherits(MemoryStream, Writable);

MemoryStream.prototype._write = function (chunk, enc, cb) {
    var buffer = (Buffer.isBuffer(chunk)) ?
        chunk :
        Buffer.alloc(chunk, enc);

    if (Buffer.isBuffer(this.memStore)) {
        this.memStore = Buffer.concat([this.memStore, buffer]);
    } else {
        this.memStore = buffer
    }
    cb();
};

MemoryStream.prototype.toBuffer = function () {
    return this.memStore
};

module.exports = MemoryStream

and then in my download function :
axios({
  url: params.url,
  method: 'GET',
  responseType: 'stream' // important
}).then(function (response) {

  logger.debug('__download() : done!')
  let contentType = response.headers['content-type']
  let contentLength = response.headers['content-length']
  var writer = new MemoryStream()

  response.data.pipe(writer)

    writer.on('finish', function () {

        var b = writer.toBuffer()

        let computedContentLength = b.byteLength

        if (!contentLength) { contentLength = computedContentLength }

        return callback(null, { 'foo':'bar'})

    });
})


text:
Q: Padded background image bullet with text wrap issue Take a gander at this fiddle:
fiddle sauce
And you can see that the padded bullets for the first 2 h3 elements fly all the way to the left. I am stuck on how to make the h3 elements look like the last h3 element without drastic "div-ing" or changes. Any ideas?
#hiw_bjaCopy
{
    float: left;
    width: 700px;
    margin: 20px;
}

#hiw_specTable
{
    float:left;
    margin: 0 20px 20px 0;
}

#hiw_specTable table td
{
    width: 100px;
    text-align: center;
}

#hiw_bjaPoints
{
    color: #666;
}

#hiw_bjaPoints h3
{
    background: url(http://toastedontheinside.com/wp-content/uploads/2013/09/link_arrow_bl.png) left no-repeat;
    padding-left: 15px;
    color: #516aa2;
}

A: use display:inline-block; for your h3
fiddle : http://jsfiddle.net/parslook/we8FR/2/


text:
Q: Facet geom point graphs depending on 3 factors in R I would like to recreate this graph using geom_point instead by I am struggling with the facet:

Here is what I have so far:
Where should I put my other facet so it separates by OdourTreatmnent within facet_grid?
ggplot(MazeThreat,aes(x=StressTreatment, y=log10value, colour= OdourTreatment )
)+
  geom_point(alpha=0.5)+
  geom_line(aes(group=ID), alpha=0.5)+
  facet_grid(~Sex)+
)+
  stat_summary(
    geom="point",
    fun="mean",
    size=4
)+
  stat_summary(
    geom="errorbar",
    fun.data = "mean_se",
    position= position_dodge(width=0),
    width= 0.1)


text:
Q: Timely commit to DB using Golang I successfully "batched" many statements in lots of 500-1000 rows to be Inserted at once. However this was using simple for loop and manually setting it to 500-1000 loops. Something like:
for i:=0;i<500;i++ {
   // Create a string of 500 values to be inserted at once
}
// Insert the 500 values

Is there a way I could timely commit() like: "commit each seconds" ?
Conceptually, I'd like to have something like;
// Create connection to DB
// Begin a transaction
// Prepare a statement

go timelyCommits(tx)  // spawn a commit ticker
for {
   // Constantly create string of values to be inserted like:
   // Values (1, "one"),(2,"two"),(3,"three")...(1000,"thousand")...
   // Insert without commit
}

func timelyCommits(tx){
   for {
      time.Sleep(1 * time.Second)
      tx.Commit()
   }
}

A: Optimization is not a trivial task and may also involving database tuning, etc. Without detail knowledge about the system that you're trying to implement, it is difficult to give a proper advice. In addition to what already suggested in the answer, you may need to implement a kind of buffering, e.g. with channel which has fixed capacity. Then when buffer is FULL or timer EXPIRED, build the query then perform BULK INSERT in transaction. Try it at The Go Playground.
package main

import (
    "fmt"
    "time"
)

type DataBuffer struct {
    capacity int
    duration time.Duration

    incomingData chan interface{}
    full chan bool
    mustExit chan bool
    done chan bool

    query string
    args []interface{}
}

func NewDataBuffer(capacity int, dur time.Duration) *DataBuffer {
    buf := &DataBuffer {
        incomingData: make(chan interface{}, capacity),
        full: make(chan bool),
        args: make([]interface{}, capacity),
        duration: dur,
        mustExit: make(chan bool, 1),
        done: make(chan bool, 1),
    }
    return buf
}

func (b *DataBuffer) Append(d interface{}) {
    if !b.put(d) {
        //Notify that buffer is full
        //<- will wait until space available
        b.full <- true
        b.incomingData <- d
    }
}

func (b *DataBuffer) put(d interface{}) bool {
    //Try to append the data
    //If channel is full, do nothing, then return false
    select {
    case b.incomingData <- d:
        return true
    default:
        //channel is full
        return false
    }
}

func (b *DataBuffer) execTransaction() error {
    /*
        Begin transaction
        Insert Data Group
        Commit/rollback
    */

    fmt.Print(time.Now())
    fmt.Println(b.query)
    fmt.Println(b.args)

    return nil
}

func (b *DataBuffer) clear() {
    //clear args
    nOldArg := len(b.args)
    for k := 0; k < nOldArg; k++ {
        b.args[k] = nil
    }
    b.args = b.args[:0]
    b.query = ""
}

func (b *DataBuffer) buildQuery() bool {
    ndata := len(b.incomingData)
    if ndata == 0 {
        return false
    }

    k := 0
    b.clear()

    //Build the query, adjust as needed
    b.query = "QUERY:"
    for data := range b.incomingData {
        b.query += fmt.Sprintf(" q%d", k) //build the query
        b.args = append(b.args, data)

        k++
        if k >= ndata {
            break
        }

    }
    return true
}

func (b *DataBuffer) doInsert() {
    if b.buildQuery() {
        b.execTransaction()
    }
}

func (b *DataBuffer) runAsync() {
    defer func() {
        b.doInsert()
        fmt.Println("Last insert")
        close(b.done)
    }()

    timer := time.NewTimer(b.duration)
    for {
        select {
        case <- timer.C:
            b.doInsert()
            fmt.Println("Timer Expired")
            timer.Reset(b.duration)
        case <- b.full:
            if !timer.Stop() {
                <-timer.C
            }
            b.doInsert()
            fmt.Println("Full")
            timer.Reset(b.duration)
        case <- b.mustExit:
            if !timer.Stop() {
                <-timer.C
            }
            return
        }
    }
}

func (b *DataBuffer) Run() {
    go b.runAsync()
}
func (b *DataBuffer) Stop() {
    b.mustExit <- true
}

func (b *DataBuffer) WaitDone() {
    <- b.done
}

func main() {
    buf := NewDataBuffer(5, 1*time.Second)
    buf.Run()

    //simulate incoming data
    for k := 0; k < 30; k++ {
        buf.Append(k)
        time.Sleep(time.Duration(10*k)*time.Millisecond)
    }
    buf.Stop()
    buf.WaitDone()
}

Note:

*

*You need to implement proper error handling.

*The type of incomingData may be adjusted to your need

A: You can do this using a goroutine that does the following:

*

*creates a new transaction and prepares statements

*continuously reads from an input channel (this receives the data from other parts of your program)

*times out after 10ms and commits the transaction, then creates a new one to accumulate more data

This function could look something like:
func transactionLoop(input chan Data) {
    tx := CreateNewTransaction() // This creates a new TX and prepares statements
    timeout := time.NewTimer(time.Millisecond * 10)
    for {
        select {
        case newData <- input:
            tx.Insert(newData)
        case <- timeout.C:
            // Too much time has passed: commit and create new tx.
            tx.Commit()
            // Create new transaction and launch timer.
            tx = CreateNewTransaction()
            timeout.Reset(time.Millisecond * 10)
        }
    }
}

This may do what you want, though there are quite a few details/problems left:

*

*there's absolutely no concept of passing errors back to the callers: this is a terrible idea

*shouldn't commit empty transactions

*if both channels are ready at the same time, the order is random (should be fine)

*you may want to commit in another goroutine, though you could then run into trouble if your commits take longer than 10ms.

*I haven't tested this, just jotting things down


text:
Q: How can I declare tasks inside an ada package? I'm trying to write a program for a class.  In the specifications, tasks cannot have any procedures or functions.  I must use the package name to access Tasks.  How can I go about doing this?
Can I simply write something along the lines of
package hello is
   task sample is...
   end sample;
end hello;

A: Yes.
You would of course have to put the task body in the package body.


text:
Q: Need to read in a file of any size I am creating a for loop in Python, which allows me to go through each record of a file to see whether the line is a duplicate or not. I have created a range, which reads through each line in the specified range. I was thinking of putting a range of infinity so taht literally any file size could be read in. But I do not know how to write that or if that is even possible. Below is what I currently have:
for i in range (0,10000):

A: You can just open the file and it will return you an array of strings per line:
with open(file_name) as file:
    line = file.readlines()


text:
Q: range of $3x^2-2xy$ subjected to $x^2+y^2=1$ If $x^2+y^2=1$. then the range of expression $3x^2-2xy$ without trigonometric substitution method
what i have done  try here is  use arithmetic geometric inequality
$\displaystyle x^2+y^2\geq 2xy$
$\displaystyle -2xy\geq -(x^2+y^2)$
$\displaystyle 3x^2-2xy\geq 2x^2-y^2$
this will not help more
how do i solve it help  me please

A: If you have the requisite linear algebra theorems at your disposal, then you can recognize
$$3x^2-2xy=\pmatrix{x&y}\pmatrix{3&-1\\-1&0}\pmatrix{x\\y}$$
where the $2\times2$ matrix is selfadjoint with eigenvalues satisfying $\lambda^2-3\lambda-1=0$.  For selfadjoint matrices $M$, the corresponding eigenvectors are orthogonal, and thus when the vector $\mathbf{x}$ ranges over the unit ball (in this case the unit circle), $\mathbf{x}^TM\mathbf{x}$ ranges from the smallest eigenvalue to the largest, in this case, from $(3-\sqrt{13})/2$ to $(3+\sqrt{13})/2$.

A: $3 x^2 - 2 x y$ with $y = \pm \sqrt{1-x^2}$ is $3 x^2 \pm 2 x \sqrt{1 - x^2}:$

Take derivative w.r.t. $x$, set it to zero and solve.
Note that the two functions are reflections about $x=0$, so their ranges are the same.

A: Since $x^2+y^2=1$, you can substitute for $y=\pm\sqrt{1-x^2}$ in $f(x,y)=3x^2-2xy$ to get $g(x)=f(x,\pm\sqrt{1-x^2})=3x^2\pm2x\sqrt{1-x^2},-1\le x\le1$ and find the extrema using standard techniques.

A: The range that you're after is $\left[\frac{3-\sqrt{13}}2,\frac{3+\sqrt{13}}2\right]$. In fact, if $x^2+y^2=1$, then$$3x^2-2xy=3x^2\pm x\sqrt{1-x^2}.$$So, for each $x\in[-1,1]$, let$$f(x)=3x^2-2x\sqrt{1-x^2}\text{ and let }g(x)=3x^2+x\sqrt{1-x^2}.$$Now, using that standard Calculus techniques, you can check that the range of both functions $f$ and $g$ is $\left[\frac{3-\sqrt{13}}2,\frac{3+\sqrt{13}}2\right]$.

A: For a calculs-free approach, note that
$$
\frac{3+\sqrt{13}}{2}\left[\frac{2y-(3+\sqrt{13})x}{\sqrt{26+6\sqrt{13}}}\right]^2+\frac{3-\sqrt{13}}{2}\left[\frac{2y-(3-\sqrt{13})x}{\sqrt{26-6\sqrt{13}}}\right]^2=3x^2-2xy
$$
and
$$
\left[\frac{2y-(3+\sqrt{13})x}{\sqrt{26+6\sqrt{13}}}\right]^2+\left[\frac{2y-(3-\sqrt{13})x}{\sqrt{26-6\sqrt{13}}}\right]^2=x^2+y^2
$$
So the range of $3x^2-2xy$, as $(x,y)$ varies on the unit circle, is the closed interval with endpoints $\dfrac{3\pm\sqrt{13}}{2}$.

A: Making $y = \lambda x$ and substituting we have
$$
\mbox{Variation for}\ \ \  x^2(3-2\lambda)\ \ \ \mbox{s. t. }\ \ x^2(1+\lambda^2) = 1
$$
or variation for
$$
f(\lambda) = \frac{3-2\lambda}{1+\lambda^2}
$$
now determining the stationary points with $f'(\lambda) = 0$ obtaining
$$
\lambda = \frac 12\left(3\pm\sqrt{13}\right)
$$
etc.


text:
Q: Autowiring of KafkaTemplate is not working in I have a code from someone else which basically processes an input and sends a message to Kafka. I have to write an integration test for this, and am having issues with autowiring. Below is the code, and the error I get is:
java.lang.NullPointerException: Cannot invoke "org.springframework.kafka.core.KafkaTemplate.send(String, Object)" because "this.kafkaTemplate" is null

I have tried all suggestions here on Stackoverflow, such as adding notations @RunWith(SpringRunner.class), @SpringBootTest(classes=...) and so on, but not managed to find a solution. I suspect I am missing something fundamental about dependency-injection.
@Service
class ProcessService {
  private final MsgProducer msgProducer;

  public ProcessService (MsgProducer msgProducer) {
    this.msgProducer = msgProducer;
  }

  public void sendMsg(String message) {
    // Processing of data
    msgProducer.sendMessage(message);
  }
}

@Service
@RequiredArgsConstructor
@Component
public class MsgProducer implements ProducerService {
  @Value("${app.kafka.topic}")
  private String topic;

  @Autowired
  private KafkaTemplate<String, String> kafkaTemplate;

  @Override
  public void sendMessage(String message) {
    kafkaTemplate.send(topic, message);
  }
}

public interface ProducerService {
  void sendMessage(String message);
}

@EnableKafka
@org.springframework.context.annotation.Configuration
public class Configuration {
  @Value(value="${spring.kafka.bootstrap-servers}")
  private String bootstrap;

  @Bean
  public ProducerFactory<String, String> producerFactory() {
    Map<String, Object> configProps = new HashMap<>();
    configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap);
    configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    return new DefaultKafkaProducerFactory<>(configProps);
  }

  @Bean
  public KafkaTemplate<String, String> kafkaTemplate() {
    return new Kafkatemplate<>(this.producerFactory());
  }

class ProcessServiceIT {
  private MsgProducer producer = new MsgProducer();

  @Test
  void testProducer() {
    producer.send()
  }
}


text:
Q: [SOLVED]iis rewrite rule fails when www is omitted I have searched Stackoverflow extensively. None of them are working for my problem.
Problem:
I have a dummy website hosted on local machine with hostname: gateway.com on port 443 (self signed cert) and also i have hosted a private website on localhost:9443 with same signed cert.
Below is the webconfig rewrite rule i have added for gateway.com.
<rewrite>
<rules>
<rule name="Reverse proxy to SAP" stopProcessing="true">
                    <match url="^sap/(.*)"/>
                    <action type="Rewrite" url="https://localhost:9443/sap/{R:1}" appendQueryString="true"  logRewrittenUrl="true"/>
                </rule>
</rules>
</rewrite>

The idea here is that; whenever i hit https://gateway.com/sap/getsomething; it should rewrite to https://localhost:9443/sap/getsomething
The above rule is working perfectly fine when i use https://www.gateway.com/sap/getsomething
but it fails if i omit www.
Kindly please help.
Thanks
Note: Solved it. It was a DNS correction required in hosts file as well as hostname in website config in IIS. My VM where i was testing was having issue.


text:
Q: Does make sense to use DAO pattern with ORM systems? I'm implementing data access logic in a Java application using Hibernate and I'm a little confused about this issue.
AFAIK one of the main advantages to use ORM systems is to work with attached object, but using DAO approach leads to have (in many application contexts) detached entities.
I read several posts about this issue (this for example), but I can't understand if there is a correct apporach to follow, or if the choice is left to developer. Can you help me?

A: Why do you think that not using DAOs is going to alleviate your detached objects scenarios?  I don't think it will. If you want to use ORM, you simply need to re-attach objects sometimes.
In the answer to a related question, I argue that you really should use DAOs.


text:
Q: Javascript not running as expected in ruby rails app deployed on heroku I'm using Rails 4 and have an app deployed on Heroku. I've been precompiling my assets locally, but my javascript isn't working as expected.
my application.js file looks like this('custom-scripts' has all my important functions in it):
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require jquery.slick
//= require custom-scripts
//= require_tree .

On Chrome's dev tools under the Resources tab I see that Frames/appname/Scripts/application.js exists with the code in 'custom-scripts.js' at the bottom of the file. In the Elements tab, the script tag is linking to /assets/application.js but under the Sources tab inside appname/assets/ I don't see application.js only application.css.
I'm using the <%= javascript_include_tag 'application' %> tag so it should link correctly right?
I've been reading about the Assets pipeline and everything I'm seeing says that everything should be working. I wrote a test() function that just returns a console.log function in my custom-scripts file and when called in the Console tab, it returns 'function not defined' so that tells me my functions aren't even running for some reason. Any idea what could be wrong?

A: <%= javascript_include_tag 'application' %> yes, it is correct but it only pre-compile your scripts. have you tried creating a file in the assets/javascript? If you have user_controller.rb in the controller folder, i usually create a coffee script pertaining to that controller. i.g users.js.coffee there you can create or call your custom-script:
$(document).ready ->
         ...

I hope it helps mate. gl

A: I think this is more of a dirty fix, but it works, so for now this is my solution; So I removed //= require_tree . and //= require custom-scripts from application.js and added <%= javascript_include_tag 'custom-scripts' %> to my application.html.erb file then ran rake assets:precompile again, pushed to github & heroku and bam, its working wonderfully.


text:
Q: Possible to keep the GCloud VM Instances running without connection? The title explains the question itself. My problem is every time I connect my VM machine through SSH it always timeouts after a period of time. So I'd like to let my Python script work on itself for like hours or days. Any advice? Thanks.

A: VM Instance will keep running even if your SSH times out.
You can keep the SSH session alive by adding following lines:
Host remotehost
    HostName remotehost.com
    ServerAliveInterval 240

to $HOME/.ssh/config file.
There's a similar option in PuTTy.

To keep process alive after disconnecting, you have multiple options, including those already suggested in commnets:

*

*nohup

*screen

*setsid

*cron

*service/daemon
Decision which one to choose depends on specifics of the task that is being performed by the script.


text:
Q: Cant scroll to invisible item in nested UICollectionViewCell I'm new in IOS development and I'm developing an app that uses a tableview. Within the tableviewrow I have a UICollectionView to display items in both directions(horizontal and vertical). The problem comes when I try to scroll to the last item in UICollectionView which is non visible and I want to give this item the focus and set it visible.
** cell = UITableViewCell
** tableCell = UICollectionView
I have tried this but does not work:
cell.tableCell.scrollToItem(at: IndexPath, at:.bottom, animated: true)
Please somebody help me!!
Thank you

A: The 2nd parameter for the scrollToItem function is not of type IndexPath.
open func scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool)

The type is UICollectionViewScrollPosition. So, the code sould be something like:
cell.tableCell.scrollToItem(at: IndexPath, at: UICollectionViewScrollPosition.bottom, animated: true)


text:
Q: Azure Function App(consumption plan) - Azure SQL networking I am trying to figure out how things like Azure Function App(consumption plan so no VNET) and Azure SQL Server DB are connected together.
I was checking SQL audit logs, specifically client_id field and tried to match
with outboundIpAddresses of Function App, but they differ.
Are there any gateway in between, any chance to get logs of such gateway.
ps
The idea is to understand which Function/App connects to DB within Azure

A: The outbound IP address listed on the function app are what the function will use to hit external resources, however you may find that connectivity to some resources will go over the Microsoft internal network, using private IP addresses. Unfortunately these are not IP ranges that are published.
If you need to control what IP's you functions use you would need to look at premium functions which can be vNet joined.


text:
Q: Tracing javascript's event with chrome console Is it possible to track each steps of different javascript events in my Chrome console : because I thought to use it tracing a click event with the 'event listener breakpoints' but it doesn't work (it traces only my jquery files)
Best

A: you can track any event with a simple Javascript snippet:
$(document).live('blur change click dblclick error focus focusin focusout hover keydown keypress keyup load mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup resize scroll select submit', function(event){
  console.log(event);
});

Of course, you can change your selector or the list of events.


text:
Q: Updating db with select options (Laravel 4) I have a table displayed with data from db where in the status column i have left an option to change the status using the select. I want to be able to update just the 'status' column by changing the options and i want to be able to change multiple rows with one button. Previously i can change but i have to have a button for each row.
//The view code for the status column is as follow:
  <td>
                    <select class="btn pull-left" name="status[]" id="status[]" onchange="javascript:changeStatus('{{$row->id}}','{{$arr}}')">
                        <option>{{ $row->status }}</option>
                        <option>Eligible</option>
                        <option>Not Eligible</option>
                    </select>
                </td>
            </tr>
            <input name="recordid[]" id="recordid[]" type="hidden">
            <?php $arr++;?>
            @endforeach
            <script type="text/javascript">
                function changeStatus(id,arr){
                //alert(id);
               // $('#recordid['+arr+]').val(id);
                // $("input[name='recordid']").eq(1).val(id);
                 $('[id^=recordid]').eq(arr).val(id);
                        // document.status.submit();
                }
            </script>

//The controller
 public function select(){

        $status = Input::get('status');
        $id = Input::get('recordid');
//        print_r($id);
//       print_r($status);exit;
        $user = User::find($id);
       If (isset($status)){
            $user->status = $status;
            $user->save();
        }
        return View::make('search')->with('status',$status);
    }

From the print_r of id and status i will get this output if i change the options with get the id too as in the code below where i change the status in the array one and two.
Array ( [0] => 2 [1] => 3 [2] => [3] => ) Array ( [0] => Volunteer [1] => Volunteer [2] => Volunteer [3] => Eligible )

A: You can update multiple records liker this:
User::>whereIn('id', $id)->update(['status' => $status]);

Full method:
public function select(){
    $status = Input::get('status');
    $id = Input::get('recordid');

    for ($i = 0; $i <= count($status) - 1; $i++) {
         User::where('id', $id[$i])->update(['status' => $status[$i]]);
    // Even better
    // User::find($id[$i])->update(['status' => $status[$i]]);
    }

    return View::make('search')->with('status',$status);
}


text:
Q: C# Unix timestamp What I want to do is block a user from doing something for 24 hours after they have reached a limit. I have coded the limit part, I just need to know how to block it if it hasn't been 24 hours.
Here is an example on how I want to do it. Update the user's account using a query and set the timestamp (Unix) to that time. Then I don't know how I can get another timestamp of the time they try to do it and check if the new timestamp is 24 hours between the last?
I have medium experience with C# but timestamps is one section I know nothing about with c#. Ss there anyone here that can help or provide a good tutorial? Or an idea on how I can learn more about it. I'm looking for the best way to do this. If Unix timestamps aren't it then please let me know and provide me with a better way if you can.
//Example
if (!CODE_HERE_FOR_NOT_24_HOURS)
{
    MessageBox.Show("You have reached your limit for today. Try again tomorow");
    return;
}
else
{
    //Code here
}

A: In C#, you'd typically use DateTime.UtcNow, and use a DateTime, not a unix timestamp.
You can always check to see if its been less than 24 hours via:
if (timeStamp > DateTime.UtcNow.AddDays(-1))
{
   // It's been less than 24 hours
}


text:
Q: MySQL how to query data with time now to start date and end date i want to get data from table, and example of data like this:

Event Name
Start Date
End Date

Event 1
2022-07-30 00:00:00
2022-08-06 23:59:59

Event 2
2022-08-08 00:00:00
2022-08-15 23:59:59

value of example is "2022-08-07 00:00:00", what i want is get data "Event 1" as the latest event because there is no event starting in "2022-08-07".
and when the value of example "2022-08-08 12:12:12", what i want is get data "Event 2" because there is a event starting from that date. And when the value is "2022-08-09 08:00:00" i want to still get the data "Event 2", because the date is still lower than end date.
How to query in MySQL, so i can result like that?

A: Assuming proper column names, it would be as below for your initial query (swap out the date for each of your examples):
SELECT *
FROM table
WHERE StartDate <= "2022-08-07 00:00:00"
ORDER BY StartDate desc
LIMIT 1;

Of course if you're basing it of when you run the SQL:
SELECT *
FROM table
WHERE StartDate <= now()
ORDER BY StartDate desc
LIMIT 1;

A: My approach would be the following nested SELECTs - replace the mentioned timestamp '2022-08-16 12:12:12' with NOW() or any timestamp you need in your case
SELECT * FROM
(
  (
    SELECT a.*,-1 AS mynumber
    FROM `testtest2` AS a
    WHERE start<='2022-08-16 12:12:12' AND end >='2022-08-16 12:12:12'
  )
  UNION
  (
    SELECT a.*,b.mynumber
    FROM `testtest2` AS a,
    (SELECT COUNT(*) AS mynumber FROM `testtest2` WHERE start<='2022-08-16 12:12:12' AND end >='2022-08-16 12:12:12') AS b
    WHERE end<='2022-08-16 12:12:12' ORDER BY end DESC LIMIT 1
  )
) c
WHERE mynumber<=0

Explanation
One SELECT retrieves all events currently active (start <= timestamp AND end >= timestamp) and sets the column mynumber to the fixed value -1 (which clearly is < 0).
The next SELECT retrieves events that have already passed, sorted descending by the column end and only retrieve the first (= newest/last) event. The column mynumber is filled with the numer of events that are currently running - so this column contains either a 0 (if there are no events currently running) or a positive number (> 0) if there are other events running.
These two SELECTs are combined using UNION and used as source for the outer SELECT which only retrieves events with a value <=0 for the column mynumber.
This way you get either the active events OR (in case there are no active events) the last/newest event which has already passed.


text:
Q: Can we trigger a mono-stable multi-vibrator( using 555 IC ) using mono audio signal? I'm working on a project where, a certain low frequency audio spike should trigger the mono-stable multi-vibrator. If we can trigger a mono-stable multi-vibrator using a mono audio signal, how much is the amplitude needed to trigger this multi-vibrator?

A: It depends on everything surrounding the monostable.  What voltages are available for the circuit?  What circuit or system does the output drive.  These help determine the actual monostable circuit.  For example, if it is a 12 V circuit made up of CMOS Schmitt trigger logic gates, then the input trigger levels are around 5 V and 7 V above GND.  You could bias the audio signal up to around 8 V DC with a coupling capacitor, and a negative 4 V peak would trigger the monostable.  OR, with opamps or comparators running on anything from 5 V ro 24 V, the audio could be centered about GND and trigger a comparator with a positive 0.5 V peak.

*

*What voltage or voltages are available for the monostable circuit?

*What voltage or voltages are available for an audio amplifier (if needed)?

*What does the monostable output drive?

A: By default, 555 trigger and threshold happen at 1/3 Vcc and 2/3 Vcc.
There is, however, a control voltage input, Vc, which will cause trigger and threshold to happen at 1/2Vc and Vc.  That input is often used for modulation applications.  There may be limits on what are legal values for Vc.  Check a data sheet.


text:
Q: How to find signatures in a non-COM dll for #import into c++ I have a 3rd party dll that appears to be native C ( Dumpbin shows all C functions). I don't have a lib or .h files. However when I reference this dll in a C# program it magically knows the signatures ( types and descriptions  for all of the paramters ). I need to use the DLL from a C++ app  and can use Dumpbin and Lib to create a lib file but I don't know the signatures ( unless I hand copy them from c# ). #import gives error that it cant find the typelib ( tlh ). The inf must be in the dll since c# can figure it out. How can I figure it out for ( unmanaged ) C++?
Thanks


text:
Q: Is there a way in sbt to convert compiler warnings to errors so the build fails? I want to "ban" some or all compiler warnings.

A: You can pass options from sbt to the scala compiler, including the one that turns warnings into errors.
I usually add these:
scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature", "-Xfatal-warnings"),

A: Per the scalac options documentation, you can pass either -Werror or -Xfatal-warnings.
You can do that in sbt by appending to scalacOptions.
scalacOptions += "-Werror"

A: Take a look at fatal-warnings scalac flag.
Source:
https://groups.google.com/forum/?fromgroups=#!topic/simple-build-tool/RcDnib_EGL4


text:
Q: Detection Angles in Bell-type Experiments Bell-type experiments look at the violation of this inequality: $|S|\leq 2$.
where $S=E(a,b)-E(a,b')+E(a',b)+E(a',b')$ and $E$ is the correlation function.
Mathematically, the maximal violation of the inequality is reached when $|S|=4$ (because the bounds of $\cos \theta_{ab}$ are $\pm 1$).
However, wherever I look in the literature it says that experimentally, quantum states produce a violation up to $|S|\leq 2\sqrt{2}$. That is Tsirelson's bound.
The detector settings are always given in intervals of $\frac{\pi}{8}$ radians. A very common set-up in degrees is: $a = 0$, $a' = 45$, $b = 22.5$, $b' = −22.5$.
They seem to take it for granted that this is THE configuration for maximal violation, without an explanation (I think I'm missing something).
Why can't the mathematical maximum be achieved experimentally?
Thanks in advance! :)

A: You seem to be assuming that the four correlation functions are independent, but they are not.  Usually the correlation functions will depend on differences between the angles: $(a-b), (a'-b), (a-b'),$ and $(a'-b')$.  But $(a'-b') = (a'-b) + (a-b') - (a-b)$ so you can't freely adjust the last correlation function. You could set the three positive terms to 1 but you won't then be able to make the last term -1.

A: The Bell inequality you discuss is the CHSH inequality, named after Clauser, Horn, Shimony and Holt who found it in 1969. This is not (by far !) the only Bell inequality, but it is in some sense the optimal inequality for 2 qubit systems. That's why it is the most discussed inequality.
You have several way to discuss it's maximal violation, but none of them is obvious :

*

*As @adipy told in the other answer an optimization on the two qubit direction gives you the optimal angles. In full generality, such a proof should include non-planar direction.

*A more general approach is the one taken by Tsirelson /Cirel'son / Цирельсон /  צירלסון in his 1980 paper, showing that there is now way for a 2-party quantum system with binary measurements to have $\lvert S\rvert>2\sqrt2$. This is what is known as Tsirelson's bound and you can find a proof of it on the corresponding wikipedia page. This proof relies on generic properties of quantum observables, and is not dependent of a specific implementation, using qubits or single photons.

*The last few years have seen an even more general approach to the Tsirelson bound, linking it to an axiomatic approach to quantum mechanics. The idea is similar to the one sometimes used in thermodynamics, where people used gedanken experiment using perpetual motion in order to understand the foundations of thermodynamics. Applied here, it means showing that access to machines (often called nonlocal boxes) violating Tsirelson's bound would allow to to really surprising things. This line of research doesn't use the algebraic of quantum mechanics, since it's goal is to understand why quantum mechanics is the way it is.

*

*The first paper along these lines I know is by Brassard et al., in 2005 (PRL (paywall) / arXiv (free)), where they showed that having access to boxe with $S>\frac8{\sqrt6}=3.27$ would trivialise communication complexity, $i.e.$ would allow distributed computation any boolean function $f(x,y)$ with a single bit of communication, no matter how big its inputs are or how comlex $f$ is.

*Pawłowski et al. refound in 2009 (Nature (paywall)/arXiv (free)) refound Tsirelson's bound ($2\sqrt2$) under a stronger condition they called Information causality : "If Alice send $m$ (classical) bits to Bob, then Bob has only access to $m$ bits of Alice". For example, if Alice has $N$ bits and Bob want to access some of these bits without telling Alice which ones, the only possibility for ALice is to send $N$ bits of informations to Bob.


text:
Q: My Mac switches to speaker after locking the screen When listening to music, after locking my MacBook Pro (ControlShiftPWR) and leaving, when I come back after 5 mins, I can hear the sound from the external speakers and nothing from my headphones. I have to unplug and replug to get it back to normal.
Anyone experienced this behaviour before? I'm running Sierra 10.12.1.

A: Yes, make sure that under System Preferences -> Sound that the default device (Headphones) is selected. After setting this, my Mac was remembering that I was using headphones after unlocking the screen.


text:
Q: jqGrid get current rowid I have a jgGrid in cellEdit mode. I need to get the current rowid, for some further processing (setting a cell to read-only depending on other values). I cant find a method for that, and the events I've tried does not fire.
The grid definition:
    var curRowId = -1;

    $("#grid").jqGrid({
        datatype: 'json',
        mtype: 'GET',
        colNames: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',],
        colModel: [
          { name: 'a', index: 'a', width: 30, formatter: 'checkbox', edittype: 'checkbox', editable: true },
          { name: 'b', index: 'b', width: 30, formatter: 'checkbox', edittype: 'checkbox', editable: true },
          { name: 'c', index: 'c', width: 70, formatter: 'date', editable: true, editrules: { required: true }, editoptions: { dataInit: function (elem) { $(elem).datepicker(); } } },
          { name: 'd', index: 'd', width: 65, editable: true, formatter: 'date', formatoptions: { srcformat: 'H:i:s', newformat: 'ShortTime' }, editrules: { time: true} },
          { name: 'e', index: 'e', width: 80, edittype: 'select', editable: true, formatter: 'select' },
          { name: 'f', index: 'f', width: 100, editable: true },
          { name: 'g', index: 'g', width: 80, editable: true },
          { name: 'h', index: 'h', width: 80, editable: true, editrules: { maxValue: 50} },
          { name: 'i', index: 'i', width: 120, edittype: 'select', editable: true, formatter: 'select' },
          { name: 'j', index: 'j', width: 200, edittype: 'select', editable: true, formatter: 'select' },
          { name: 'k', index: 'k', width: 70, edittype: 'select', editable: true, formatter: 'select' },
          { name: 'l', index: 'l', width: 70, editable: true, editrules: { maxValue: 10} },
          { name: 'm', index: 'm', width: 25, editable: false },
          { name: 'n', index: 'n', width: 70, editable: true, editrules: { integer: true, maxValue: 999999 }, formatter: formatPosition, unformat: unformatPosition },
          { name: 'o', index: 'o', width: 25, editable: true, editrules: { custom: true, custom_func: chkLongitudTecken} },
          { name: 'p', index: 'p', width: 80, editable: true, editrules: { integer: true, maxValue: 999999 }, formatter: formatPosition, unformat: unformatPosition },
          { name: 'q', index: 'q', width: 80, edittype: 'select', editable: true, formatter: 'select' },
          { name: 'r', index: 'r', width: 100, editable: true, editrules: { maxValue: 50} },
          { name: 's', index: 's', width: 65, edittype: 'select', editable: true, formatter: 'select' },
        ],
        cellEdit: true,
        cellsubmit: "clientArray",
        sortname: 'Datum',
        sortorder: 'desc',
        shrinkToFit: false,
        viewrecords: true,
        gridview: true,
        beforeCellEdit: function (id) {
            curRowId = id;
            alert("Here: " + curRowId);
        },
        onSelectRow: function (id) {
            curRowId = id;
            alert("test: " + curRowId);
        },
        height: 400,
        caption: 'My Cap'
    });

You can see the events I've tried with in the code above.
I need the id so that I later can do something like this:
$("#grid").setColProp("k", {
    editoptions: {
        value: data.opPadrag,
        dataEvents: [{
            type: 'change',
            fn: function (e) {
                alert(e.currentTarget.value);
                $(e).addClass("not-editable-cell");
            }
        }]
    }
});

A: Found a solution:
var selr = jQuery('#grid').jqGrid('getGridParam', 'selrow');

A: jQuery('#grid').jqGrid('getGridParam', 'selrow')

will give the column data as row id used as "key". If the "key" attribute is not set to a particular grid column then the proper row id will be returned.


text:
Q: Fit sine function to my data to find the starting and finishing points Say that I have the following data
  DataX = {{3.4`,
        2.2516679754406105`*^-8}, {3.5`, -8.796310947104858`*^-8}, {3.6`,
        3.436206296498269`*^-7}, {3.7`, -1.3422706504309448`*^-6}, {3.8`,
        5.243037187407348`*^-6}, {3.9`, -0.000020478942504723612`}, {4.`,
        0.00007998593415536338`}, {4.1`, -0.0010107167248735436`}, {4.2`,
        0.07388842736709378`}, {4.3`, 0.23004397985138975`}, {4.4`,
        0.4329573622285607`}, {4.5`, 0.6502842635718505`}, {4.6`,
        0.840613536036122`}, {4.7`, 0.9701213141038791`}, {4.8`,
        1.0002146281022952`}, {4.9`, 0.9999647772216878`}, {5.`,
        1.0002661612093822`}, {5.1`, 1.0001390743777006`}, {5.2`,
        1.0001573874093896`}, {5.3`, 1.0000670562306497`}, {5.4`,
        1.0000368355851015`}};

which represents a half wave.
I would like to place a sine function on top of my data points using the following information provided based on its analytical solution:

*

*The maximum value is 1, Which in the numerical solution (DataX) is 1.00004.

*The slope of the sine function, which according to DataX is 65.3 degree. (see the image)

*The center of the curve. This is determined by normalizing the position of DataX to its maximum. So that the maximum would be 1. And then setting the position of the center of the half sine at 0.5.

A: Let's go step-by-step with the requirements.
The model is
f[x_] := a + b Sin[c x + d]

The constraint are:
(* slope at x=0 *)
eq1 = (D[f[x], x] /. x -> 0) == Tan[65.3 Degree]

(* value at x=1/2 *)
eq2 = f[0.5] == 1

(* maximum value equals 1; we need to find local maxima & minima *)
minmax = x /. Solve[D[f[x], x] == 0, x]

f[minmax[[1]]] // Simplify
f[minmax[[2]]] // Simplify

In general, we don't know which one is the maximum and which is the minimum, so let's try both options:
Solve[{a - b == -1, a + b == 1}, {a, b}]

{{a -> 0, b -> 1}}

Solve[{a - b == 1, a + b == -1}, {a, b}]

{{a -> 0, b -> -1}}

We can't be sure about b, but for sure
a=0;

Let's start with b=1:
Block[{b = 1}, NSolve[{eq1, eq2}, {c, d}]]

doesn't return an answer. Let's make a substep:
Block[{b = 1}, Solve[eq1, c]]

{{c -> 2.17416 Sec[d]}}

and input it in eq2 (copy-paste):
NSolve[Sin[0.5` 2.1741559325614914` Sec[d] + d] == 1, d]

NSolve[Sin[d + 1.08708 Sec[d]] == 1, d]

Still no answer, so
Plot[Sin[d + 1.0870779662807457` Sec[d]], {d, -3, 3}]

Let's consider only $d\in[0,1]$:
Block[{b = 1}, Solve[eq1 && eq2 && 0 < d < 1, {c, d}]]

{{c -> 2.35424, d -> 0.393675}}

So one solution can be {a,b,c,d}={0,1,2.35424,0.393675}
Similarly, the case b=-1 leads to the plot:

but
Block[{b = -1}, Solve[eq1 && eq2 && -1.2 < d < -1, {c, d}]]

{}

Let's zoom in:

FindArgMax[Sin[d - 1.0870779662807457` Sec[d]], {d, -1.25}]>

{-1.2513}
and
Sin[d - 1.0870779662807457` Sec[d]] /. d -> -1.2513

1.

so it looks like NSolve fails on accuracy. Nevertheless,
c -> -2.1741559325614914` Sec[d] /. d -> -1.2513

c -> -6.92211

so the other set of solutions is {a,b,c,d}={0,-1,-6.92211,-1.2513}.
Note that the first two plots are plotted in a restricted range, and even in that range there are lots of (infinitely many?) local maxima, so with the given constraints there is no unique solution.

The first version of the answer
Is this what you're after?
nlm = NonlinearModelFit[DataX, a + b Sin[c x + d], {a, b, c, d}, x];
Normal@nlm

0.49297 - 0.581267 Sin[4.12402 - 2.35384 x]

Show[ListPlot[DataX], Plot[nlm[x], {x, 3.4, 5.4}], PlotRange -> All]

*

*x0 = x /. NSolve[nlm[x] == .5 && 4 < x < 5, x][[1, 1]]

4.42651

*FindMaxValue[nlm[x], {x, 5}]

1.07424

*D[nlm[x], x] /. x -> x0

1.36811

A: Consider the equation $f(x)=A\sin(Bx+C)+D$.
Since the maximum value is $1$, the position of the center is $0.5$ (meaning that $f(0)=0.5$?) we get that the amplitude is $0.5$, vertical shift is $0.5$, and phase shift is $0$.
$f(x)=0.5\sin(Bx)+0.5$.
D[0.5 Sin[B x] + 0.5, x] /. x -> 0
(*0.5 B*)

0.5 B == Tan[65.3 \[Degree]] // NSolve
(*{{B -> 4.34831186512}}*)

Therefore, your sine function is
f[x_] := 0.5 + 0.5 Sin[4.348311865122983 x]
Show[ListPlot[DataX], Plot[f[x], {x, 0, 2 Pi}]]

It doesn't seem to fit well the half sine (x from 4 to 4.8), but if we shift it 0.1 to the right it seems to be better.
Show[ListPlot[DataX], Plot[f[x - 0.1], {x, 0, 2 Pi}]]

A: This is not an answer but what happened as I started looking at your data. If I plot your data I get this:
ListPlot[DataX, PlotRange -> All]

You say this is a half wave. This is not a half sine wave. We need more information on what you are doing. This looks more like an arctan.
Can you explain more?


text:
Q: Why does this method for solving recurrence relations work in some cases and not in others? I have been reading on recurrence relations and I have seen that some of them are really easy to solve, for example:
$$a_{n+1}=a_n^2$$
Starting from $n=0$ and substituting yields a pattern that is simple enough to take advantage of, after a proof by induction we get $a_n=a_0^{2^n}$. I have some problems with this method because, even though it provides an answer, this answer springs from pattern recognition and nothing else, we know nothing more about the relation or whether other solutions exist, but at least we know one solution.

The problem comes when, three strokes later, we get this:
$$a_{n+1}=a_n^2+1$$
A single one makes the problem much harder. However, I still tried to solve it and after fruitlessly attacking it with matrices, integrals, derivatives, polynomial expansions and more pattern recognition, I tried a new method:

We set $a_n=f(n)$ such that $f(n)^2+1=f(n+1)$. To find an expression for $f(n)$ we note that $a_{n+1}-a_n^2=1$.

Assume we have a solution $(a_1,a_0)$, then $$(\sqrt{a_1}+a_0)^{g(n)}(\sqrt{a_1}-a_0)^{g(n)}=1^{g(n)}=(\sqrt{a_{n+1}}+a_n)(\sqrt{a_{n+1}}-a_n)$$
Equating coefficients and solving the system of two equations in two unknowns yields $$a_{n+1}=\frac 14 ((\sqrt{a_{1}}+a_0)^N+(\sqrt{a_{1}}-a_0)^N)^2$$
$$a_{n}=\frac 12 ((\sqrt{a_{1}}+a_0)^N-(\sqrt{a_{1}}-a_0)^N)$$
Where $N=g(n)$. We can check that these expressions satisfy the original equation but I do not know how to proceed from here.
I noticed, however, that if we define $h(N)$ to be equal to the square root of the expression for $a_{n+1}$ we have $h(N)^2=\frac {h(2N)+1}{2}$. If we use the ansatz $g(n)=2^n$ then $2h(n)^2-1=h(n+1)$ which is extremely close to the function I was searching for.
Furthermore, we can set $$f(n)=A(\sqrt{a_{1}}+a_0)^{2^n}+A(\sqrt{a_{1}}-a_0)^{2^n}$$
Which gives $f(n)^2-2A^2=Af(n+1)$.
In some way, the above approach solved an equation similar to the one I wanted to solve. My question is twofold: "Why did I end up solving a different yet similar equation?" And "Although this approach has many holes here and there (e.g. Justifying the replacement of $1/2$ with $A$, finding $g(n)$ without using an ansatz, adjusting the values of $a_1, a_0$ for different recurrence relations, etc.) is it still a promising approach?"

A: Nonlinear recurrence relations are hard.  There are very few cases where you can have a closed-form solution.  In particular, quadratic recurrences  have closed-form solutions only in a few cases.
This deserves to be put in a somewhat wider context.  There are, up to conjugacy by linear functions, two sequences $P_n$ of polynomials of degree $n$ forming  semigroups under composition (i.e. $P_{mn}(x) = P_m(P_n(x))$): the monomials $M_n(x) = x^n$ and the Chebyshev polynomials $T_n(x) = \cos(n \arccos(x))$.
See e.g. this sci.math posting from 2001 for a proof.
Each of these correspond to recurrences with closed-form solutions:
$a_n = P_{k^n}(x)$ satisfies $a_{n+1} = P_k(a_n)$.  In particular, for $k=2$ we get $a_n = x^{2^n}$ with $a_{n+1} = a_n^2$ corresponding to the monomials and $a_n = T_{2^n}(x)$ with $a_{n+1} = T_2(a_n) = 2 a_n^2 - 1$ corresponding to the Chebyshev polynomials.  Conjugating this one with multiplication by a constant gives you $a_n = c T_{2^n}(x/c)$ for $a_{n+1} = 2 a_n^2/c - c$, which is the equation you ended up solving for $c = 2A$.

A: According to this paper (which I haven't read), for any recurrence relation of a general form including yours, there is some constant $k$ such that for all sufficiently large $n,$ $a_n$ is the nearest integer to $k^{2^n}.$
A. V. Aho and N. J. A. Sloane, "Some Doubly Exponential Sequences", http://www.fq.math.ca/Scanned/11-4/aho-a.pdf

A: The only other one of type $x^2 + C$ that has a closed form solution is
$$  x_{n+1} = x_n^2 - 2 $$
where $x_0 > 2.$  Take real constants so $A+B = x_0$ and $AB=1,$ then
$$ x_n = A^{\left( 2^n \right)} +  B^{\left( 2^n \right)}   $$
Worth checking yourself. Not sure what happens if $0 < x_0 < 2$
For other $x_{n+1} = x_n^2 + C$ you can still prove an approximation $x_n \approx  H^{\left( 2^n \right)},$ however, I recall that you cannot get an explicit value for the constant $H,$ only estimates from calculating large $x_n.$ Meaning, of course, the you are just estimating $$ \frac{\log x_n}{2^n}$$ and calling that $\log H.$


text:
Q: Why won't my API's updated DbContext fetch a newly added DB column? I have an Azure SQL DB that initially had the following columns:
user name
password hash
password salt
This DB serves a .NET Core C# API that checks username and password to return a JWT token.
The API had a User object that comprised all three columns with the correct types, a DbContext with a DbSet<User>, and an IServiceCollection that used said DbContext.
The API worked fine, returning a JWT token as needed.
I have since needed to add an extra parameter to check and pass to the JWT creation - the relevant column has been created in the DB, the User object in the API has been updated to include the extra parameter and that extra parameter is observed in the Intellisense throughout the API code.
The issue is that when the API is deployed to Azure, the extra parameter isn't being recognised and populated; how do I make the API correctly update to use the new DbContext and retrieve the User with the extra parameter?
(I've omitted the interfaces for brevity, as they're essentially the corresponding classes)
User, UserRequest and MyApiDbContext Classes:
using Microsoft.EntityFrameworkCore;

namespace MyApi.Models
{
    // Basic user model used for authentication
    public class User
    {
        public string UserId { get; set; }
        public byte[] PasswordHash { get; set; }
        public byte[] PasswordSalt { get; set; }
        public string ExtraParam { get; set; } // newly added parameter
    }

    public class UserRequest
    {
        public string UserId { get; set; }
        public string password { get; set; }
    }

    public class MyApiDbContext : DbContext
    {
        public MyApiDbContext(DbContextOptions<MyApiDbContext> options)
            : base(options)
        {
        }

        public DbSet<User> Users { get; set; }
    }
}

The AuthRepository that retrieves the user:
using Microsoft.EntityFrameworkCore;
using MyApi.Interfaces;
using MyApi.Models;
using System.Threading.Tasks;

namespace MyApi.Services
{
    public class AuthRepository : IAuthRepository
    {
        private readonly MyApiDbContext _context;
        public AuthRepository(MyApiDbContext context)
        {
            _context = context;
        }
        public async Task<User> Login(string username, string password)
        {
            // my test user gets returned
            User returnedUser = await _context.Users.FirstOrDefaultAsync(x => x.UserId == username);

            if (returnedUser == null)
            {
                return null;
            }

            // the password get verified
            if (!VerifyPasswordHash(password, returnedUser.PasswordHash, returnedUser.PasswordSalt))
            {
                return null;
            }

            // this does not get changed, but the value set in the DB is definitely a string
            if (returnedUser.ExtraParam == null || returnedUser.ExtraParam == "")
            {
                returnedUser.ExtraParam = "placeholder"
            }

            return returnedUser;
        }
    }
}

The AuthService that calls the AuthRepository for the user then "creates the JWT token" (just returning a string for this example), currently set up to return the user details:
using Microsoft.Extensions.Options;
using MyApi.Interfaces;
using MyApi.Models;
using System;
using System.Threading.Tasks;

namespace MyApi.Services
{
    public class AuthService : IAuthService
    {
        private readonly IOptions<MyApiBlobStorageOptions> _settings;
        private readonly IAuthRepository _repository;

        public AuthService(IOptions<MyApiBlobStorageOptions> settings, IAuthRepository repository)
        {
            _repository = repository;
            _settings = settings;
        }

        public async Task<string> Login(string username, string password)
        {
            User returnedUser = await _repository.Login(username, password);

            if (returnedUser != null)
            {
                // currently returns "UserIdInDB,ProvidedPasswordFromLogin,"
                return $"{returnedUser.UserId},{password},{returnedUser.ExtraParam}";
            }

            return null;
        }
    }
}

The controller that calls the AuthService:
using Microsoft.AspNetCore.Mvc;
using MyApi.Interfaces;
using MyApi.Models;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace MyApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly MyApiDbContext _context;
        private readonly IAuthService _authService;

        public AuthController(MyApiDbContext context, IAuthService authService)
        {
            _context = context;
            _authService = authService;
        }

        [HttpPost("login")]
        public async Task<IActionResult> Login(UserRequest loginUser)
        {
            string token = await _authService.Login(loginUser.UserId, loginUser.Password);

            if (token != null)
            {
                return Ok(token);
            }

            return Unauthorized("Access Denied!!");
        }
    }
}

The startup class that registers everything:
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using MyApi.Interfaces;
using MyApi.Models;
using MyApi.Services;
using Microsoft.Extensions.Azure;
using Azure.Storage.Queues;
using Azure.Storage.Blobs;
using Azure.Core.Extensions;
using System;

namespace MyApi
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        private readonly ILogger<Startup> _logger;
        private readonly IConfiguration _config;
        public Startup(ILogger<Startup> logger, IConfiguration config)
        {
            _logger = logger;
            _config = config;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add dBContext for DB
            services.AddDbContextPool<MyApiDbContext>(options => options.UseSqlServer(_config.GetConnectionString("MyAzureDb")));

            // Add DI Reference for Repository
            services.AddScoped<IAuthRepository, AuthRepository>();

            // Add DI Reference for Azure Blob Storage Processes
            services.AddScoped<IBlobService, AzureBlobService>();

            // DI Reference for AuthService
            services.AddScoped<IAuthService, AuthService>();

            // Add configuration section for Constructor Injection
            services.Configure<ApiBlobStorageOptions>(_config.GetSection("MyApiBlobStorage"));

            services.AddMvc(mvcOptions => mvcOptions.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                            .GetBytes(_config.GetSection("MyApiBlobStorage:Secret").Value)),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                    options.Events = new JwtBearerEvents()
                    {
                        OnAuthenticationFailed = context =>
                            {
                                _logger.LogWarning("Token authentication failed whilst attempting to upload file");

                                return Task.CompletedTask;
                            }
                    };
                });
            services.AddAzureClients(builder =>
            {
                builder.AddBlobServiceClient(Configuration["ConnectionStrings:MyApiBlobStorage/AzureBlobStorageConnectionString:blob"], preferMsi: true);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            app.UseAuthentication();
            app.UseMvc();
        }
    }
    internal static class StartupExtensions
    {
        public static IAzureClientBuilder<BlobServiceClient, BlobClientOptions> AddBlobServiceClient(this AzureClientFactoryBuilder builder, string serviceUriOrConnectionString, bool preferMsi)
        {
            if (preferMsi && Uri.TryCreate(serviceUriOrConnectionString, UriKind.Absolute, out Uri serviceUri))
            {
                return builder.AddBlobServiceClient(serviceUri);
            }
            else
            {
                return builder.AddBlobServiceClient(serviceUriOrConnectionString);
            }
        }
        public static IAzureClientBuilder<QueueServiceClient, QueueClientOptions> AddQueueServiceClient(this AzureClientFactoryBuilder builder, string serviceUriOrConnectionString, bool preferMsi)
        {
            if (preferMsi && Uri.TryCreate(serviceUriOrConnectionString, UriKind.Absolute, out Uri serviceUri))
            {
                return builder.AddQueueServiceClient(serviceUri);
            }
            else
            {
                return builder.AddQueueServiceClient(serviceUriOrConnectionString);
            }
        }
    }
}

Let me know if there is anything else required for understanding: the only difference between before and now is the addition of ExtraParam and the corresponding references throughout for the API, and the DB getting the identically named column.
I tried adding the parameter and deploying it to Azure and making the POST request as normal, starting and stopping the app service, deploying the API while the app service was stopped and starting it again, and restarting the app service. I don't know how much I could try changing up what I'm doing, I'm trying to do exactly the same as before, but with an extra parameter getting requested from the DB.
I can also confirm that the DB contains the ExtraParam column, and that it contains values against the existing data rows, as viewed using the Azure Portal's DB Query Editor.

A: I've resolved the issue, partially because of posting this question and sanitising the code for public discussion.
In the Login Controller, in my development code the request for the user to be returned was subsequently ignored, passing through the user request details which had a null ExtraParam, not the returned user which had the ExtraParam populated.
The moral of the story is to confirm which objects are being used at which points in the code, or have one object that is passed into, updated by, then returned from functions to maintain consistency.


text:
Q: BLOB Image returning broken image I've found a lot of solutions on SO that worked for others, but not for me! Guidance in the correct direction would be appreciated.
Note: I know a lot of people may not be a fan of storing images in blobs, but for my particular application it is suffice.
Snippet of HTML Code on Upload page (this is within a form that has other data):

                    Summary Image

<input name="summaryImage" id="imgInp1" type="file" accept="image/*"  onchange="Prev1(this)" />

                    Article Image

<input name="articleImage" id="imgInp2" type="file" accept="image/*"  onchange="Prev2(this)" />

Snippet of PHP code on Upload page
//Summary Image
$summaryimage = $_FILES['summaryImage'];
if(is_uploaded_file($_FILES['summaryImage']['tmp_name']) && getimagesize($_FILES['summaryImage']['tmp_name']) != false)
{
    // Gather image info
    $size = getimagesize($_FILES['summaryImage']['tmp_name']);
    // Assign variables
    $type = $size['mime'];
    $imgfp = fopen($_FILES['summaryImage']['tmp_name'], 'rb');
    $size = $size[3];
    $name = $_FILES['summaryImage']['name'];
    $summaryimagesize = $_FILES['summaryImage']['size'];
    $maxsize = 15728640;

    // Check image file size
    if($summaryimagesize < $maxsize ) {
        //Image size checks out, insert blob into database
        mysql_query("UPDATE projects
                        SET summaryimage='$summaryimage', summaryimagesize='$summaryimagesize'
                    WHERE job='$job'") or die (mysql_error());;

        } else if($summaryimagesize > $maxsize) {
        // Image file size too big
        header("LOCATION: /projects.php?message=imagesize");
        }
    } else {
    // Any other error
    header("LOCATION: /projects.php?message=imageformat");
    }

    //Article Image
    $articleimage = $_FILES['articleImage'];
    if(is_uploaded_file($_FILES['articleImage']['tmp_name']) &&
        getimagesize($_FILES['articleImage']['tmp_name']) != false)
    {
        // Gather image info
        $size = getimagesize($_FILES['articleImage']['tmp_name']);
        // Assign variables
        $type = $size['mime'];
        $imgfp = fopen($_FILES['articleImage']['tmp_name'], 'rb');
        $size = $size[3];
        $name = $_FILES['articleImage']['name'];
        $articleimagesize = $_FILES['articleImage']['size'];
        $maxsize = 15728640;

        // Check image file size
        if($articleimagesize < $maxsize ) {
            //Image size checks out, insert blob into database
             mysql_query("UPDATE projects SET articleimage='$articleimage', articleimagesize='$articleimagesize' WHERE job='$job'") or die (mysql_error());;

            } else if($articleimagesize > $maxsize) {
            // Image file size too big
            header("LOCATION: /projects.php?message=imagesize");
            }
        } else {
        // Any other error
        header("LOCATION: /projects.php?message=imageformat");
        }

    header("LOCATION: /projects.php?message=success");

}

The database stores the blob as a longblob type, no problems:

Code I'm using to encode the image and display it:
<?php echo ''; ?>

What the page shows:

When I right click > copy image location:
data:image/jpeg;base64,QXJyYXk=

A: QXJyYXk= is base64 for array so you're storing array data instead of an image.
The fix is to grab the contents of the image and store that instead:
 $summaryimage = file_get_contents($_FILES['summaryImage']['tmp_name']);

Since you're not using prepared statements, you should escape quotes:
 $summaryimage = addslashes(file_get_contents($_FILES['summaryImage']['tmp_name']));

When displaying you should remove them again before encoding them:
base64_encode(stripslashes($post['summaryimage']))

A: Using @Xorifelse's answer, I was able to lead myself to a working solution after playing around for about an hour.
Because this was an SQL query, I can't have any ' in the binary because it will break it (who knew it would have special characters?!). So I used
$summaryimage = mysql_real_escape_string(file_get_contents($_FILES['summaryImage']['tmp_name']));
All is working now when displaying the image :)


text:
Q: Git clone with ssh works in Linux but not in Windows PowerShell I have a repo at GitHub. When cloning it in Linux using ssh it works fine:
> git clone git@github.com:henrikppersson74/frokenjennnie.git
Cloning into 'frokenjennnie'...
Enter passphrase for key '/home/----/.ssh/id_rsa':
.
.
Reinitialized existing Git repository in /home/*

When doing the same thing in Windows PowerShell it doesn't work:
> git clone git@github.com:henrikppersson74/frokenjennnie.git
Cloning into 'frokenjennnie'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

I have copied my private and public SSH keys from Linux to my Windows machine and they are stored in my ~/.ssh/ as id_rsa and id_rsa.pub.
It seems to work when I try to access github.com with ssh from PowerShell:
> ssh git@github.com
Enter passphrase for key 'C:\Users\-----/\.ssh\id_rsa':
PTY allocation request failed on channel 0
Hi henrikppersson74! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.

This is the same answer I get when doing this in Linux. I guess this means the my SSH-key par is ok?
When working in Eclipse in Windows, using the "Git Repositories" view it works fine to clone the same repo.
Previously I created new SSH keys in the PowerShell and copied the public one to GitHub, but with the same result.
My ~/.ssh/config file lookes like this:
Host github.com
    HostName github.com
    IdentityFile ~\.ssh\id_rsa
    User git
    ForwardAgent yes

I am using Git version:
> git --version
git version 2.28.0.windows.1

Unfortunately I get no extra information from using the --verbose flag:
> git clone git@github.com:henrikppersson74/frokenjennnie.git --verbose
Cloning into 'frokenjennnie'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

It doesn't help to add the key to the ssh-agent:
> ssh-add C:\Users\-----\.ssh\id_rsa
Enter passphrase for C:\Users\-----\.ssh\id_rsa:
Identity added: C:\Users\------\.ssh\id_rsa (C:\Users\-----\.ssh\id_rsa)
> git clone git@github.com:henrikppersson74/frokenjennnie.git --verbose
Cloning into 'frokenjennnie'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Could my old keys be cashed somewhere?
Does anyone have any idea about why I am not able to clone my repo in Windows PowerShell? I would be so grateful for some help.

A: The problem was that my %HOME% environment variable was set to the wrong location. When I changed it back to C:\Users\<userid> it worked like charm. Apparently SSH first looks for a key in %HOME%\.ssh\, then for en entry in %HOME%\.ssh\config\ and last it uses the keys added to the ssh-agent.


text:
Q: Apply which.min to data.table under a condition I have a data.table and need to know the index of the row containing a minimal value under a given condition. Simple example:
dt <- data.table(i=11:13, val=21:23)

#     i  val
# 1: 11   21
# 2: 12   22
# 3: 13   23

Now, suppose I'd like to know in which row val is minimal under the condition i>=12, which is 2 in this case.
What didn't work:
dt[i>=12, which.min(val)]
# [1] 1

returns 1, because within dt[i>=12] it is the first row.
Also
dt[i>=12, .I[which.min(val)]]
# [1] 1

returned 1, because .I is only supposed to be used with grouping.
What did work:
To apply .I correctly, I added a grouping column:
dt[i>=12, g:=TRUE]
dt[i>=12, .I[which.min(val)], by=g][, V1]
# [1] 2

Note, that g is NA for i<12, thus which.min excludes that group from the result.
But, this requires extra computational power to add the column and perform the grouping. My productive data.table has several millions of rows and I have to find the minimum very often, so I'd like to avoid any extra computations.
Do you have any idea, how to efficiently solve this?

A:
But, this requires extra computational power to add the column and perform the grouping.

So, keep the data sorted by it if it's so important:
setorder(dt, val)
dt[.(i_min = 12), on=.(i >= i_min), mult="first", which = TRUE]
# 2

This can also be extended to check more threshold i values. Just give a vector in i_min =:
dt[.(i_min = 9:14), on=.(i >= i_min), mult="first", which = TRUE]
# [1]  1  1  1  2  3 NA

How it works
x[i, on=, ...] is the syntax for a join.

*

*i can be another table or equivalently a list of equal-length vectors.

*.() is a shorthand for list().

*on= can have inequalities for a "non-equi join".

*mult= can determine what happens when a row of i has more than one match in x.

*which=TRUE will return row numbers of x instead of the full joined table.

A: You can use the fact that which.min will ignore NA values to "mask" the values you don't want to consider:
dt[,which.min(ifelse(i>=12, val, NA))]

As a simple example of this behavior, which.min(c(NA, 2, 1)) returns 3, because the 3rd element is the min among all the non-NA values.


text:
Q: Darkmode Store in local storage React with Material-UI How to store the value of the dark mode in localStorage?
can I even do it in this way?
can you guys give me ideas on how?
thank you cheers,
function App() {

  const [darkState, setDarkState] = useState("");
  const palletType = darkState ? "dark" : "light";
  const mainPrimaryColor = darkState ? blue[400] : blue[800];
  const mainSecondaryColor = darkState ? grey[800] : grey[100];

  const darkTheme = createMuiTheme({
    palette: {
      type: palletType,
      primary: {
        main: mainPrimaryColor,
      },
      secondary: {
        main: mainSecondaryColor,
      },
    },
  });
 function handleThemeChange() {
    setDarkState(!darkState);
  }
 return (
    <ThemeProvider theme={darkTheme}>
       <IconButton onClick={handleThemeChange()}>
            <Switch checked={darkState} />
        </IconButton>
    </ThemeProvider>
  );
}

A: to do this:

*

*in useEffect we see if there is something in localStorage and use it

*when we toggle, we keep localStorage updated also

relevant JS:
  useEffect(() => {
    const existingPreference = localStorage.getItem("darkState");
    if (existingPreference) {
     ( existingPreference === "light")
        ? setDarkState("light")
        : setDarkState("dark");
    } else {
      setDarkState("light");
      localStorage.setItem("darkState", "light");
    }
  }, []);

const handleThemeChange = () => {
    setSwitchState(switchState === true ? false : true);
    if (darkState === "light") {
      setDarkState("dark");
      setMainPrimaryColor(grey[400]);
      setMainSecondaryColor(blue[400]);
      localStorage.setItem("darkState", "dark");
    } else {
      setDarkState("light");
      setMainSecondaryColor(grey[400]);
      setMainPrimaryColor(blue[400]);
      localStorage.setItem("darkState", "light");
    }
  };

working stackblitz

A: Here is example how you can set and read from LocalStorage:
import React, {useState, useEffect} from 'react';

export default function App() {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    setTheme(localStorage.getItem("theme"));
  }, []);

  const handleClick = theme => {
    localStorage.setItem("theme", theme);
    setTheme(theme);
  };

  return (

Selected theme: {theme}

      <button onClick={() => handleClick("light")}>Light</button>
      <button onClick={() => handleClick("dark")}>Dark</button>

  );
}

A: const [darkTheme, setDarkTheme] = useState(true);
const theme = createMuiTheme({
palette: {
  type: darkTheme ? "dark" : "light"
 }
})

useEffect(() => {
  const themeType = localStorage.getItem("dark") || "dark";
  if (themeType != "dark") {
    setDarkTheme(false);
  }
}, []);

const changeTheme = () => {
  localStorage.setItem("dark", darkTheme ? "light" : "dark");
  setDarkTheme(!darkTheme);
};

return (

Selected theme: " {theme} "

        <button onClick={changeTheme}>toggle theme</button>

);


text:
Q: pip3 hangs while pip works I had Python 2.7.9 installed at D:\Python27 and running for a long time already, and today I installed Python 3.4.4 at D:\Python34. Both paths and their relevant Scripts folder are in the PATH environment variable, but whenever I try to use pip3 it just hangs (pip works just fine).
Any idea what's going on? System is windows 10 64-bit if it matters.


text:
Q: C# WPF Telerik RadCartesianChart: force a constant length of the axes despite the presence of labels I have created a very simple chart like this:
<telerik:RadCartesianChart x:Name="chartMainCandleChart" Height="350" Width="620" VerticalAlignment="Top" HorizontalAlignment="Left" ZoomChanged="chartMainCandleChart_ZoomChanged" PanOffsetChanged="chartMainCandleChart_OffsetChanged" >
    <telerik:RadCartesianChart.HorizontalAxis>
        <telerik:DateTimeCategoricalAxis SmartLabelsMode="SmartStep" IsStepRecalculationOnZoomEnabled="False" />
    </telerik:RadCartesianChart.HorizontalAxis>
    <telerik:RadCartesianChart.VerticalAxis>
        <telerik:LinearAxis HorizontalLocation="Right" SmartLabelsMode="SmartStep" IsStepRecalculationOnZoomEnabled="False"/>
    </telerik:RadCartesianChart.VerticalAxis>
    <telerik:CandlestickSeries x:Name="candleSeries" ItemsSource="{Binding SeriesCollection}" CategoryBinding="Timestamp" OpenBinding="Open" CloseBinding="Close" LowBinding="Low" HighBinding="High">
        <telerik:CandlestickSeries.DefaultVisualStyle>
            <Style TargetType="telerik:Candlestick">
                <Setter Property="StrokeThickness" Value="2" />
                <Setter Property="UpStroke" Value="GreenYellow"/>
                <Setter Property="DownStroke" Value="Red"/>
                <Setter Property="UpFill" Value="GreenYellow"/>
                <Setter Property="DownFill" Value="Red"/>
            </Style>
        </telerik:CandlestickSeries.DefaultVisualStyle>
    </telerik:CandlestickSeries>

    <telerik:RadCartesianChart.Behaviors>
        <telerik:ChartPanAndZoomBehavior x:Name="bvPanZoom" MouseWheelMode="ZoomHorizontally" DragMode="Pan" PanMode="Horizontal" ZoomMode="None" />
    </telerik:RadCartesianChart.Behaviors>

    <telerik:RadCartesianChart.Resources>
        <Style TargetType="telerik:PanZoomBar">
            <Setter Property="Visibility" Value="Collapsed"/>
        </Style>
    </telerik:RadCartesianChart.Resources>
</telerik:RadCartesianChart>

I autoscale it using this function during OffsetChanged Event:
private void ScaleChartDynamically()
{
    var viewPortWidth = chartMainCandleChart.PlotAreaClip.Width;
    var xPixelsPerElem = viewPortWidth * chartMainCandleChart.Zoom.Width / SeriesCollection.Count;
    var notVisible = -chartMainCandleChart.PanOffset.X / xPixelsPerElem; // how many candles are invisible completely (on the left of viewport)
    var visible = viewPortWidth / xPixelsPerElem; // last partially visible in viewport
    var firstElem = (int)Math.Floor(notVisible) + 1; // index is zero based
    var lastElem = (int)Math.Ceiling(notVisible + visible);
    var noElements = lastElem - firstElem + 1;

    var visibleRange = SeriesCollection.Range(firstElem, noElements).SelectMany(ohlc => new[] { ohlc.Low, ohlc.High }).Select(hl => hl.ToDouble()).ToArray();
    if (visibleRange.Any())
    {
        var yAxis = (LinearAxis)chartMainCandleChart.VerticalAxis;
        yAxis.Minimum = visibleRange.Min();
        yAxis.Maximum = visibleRange.Max();
    }
}

I experience the following problem when dragging along x-axis:

It looks like the problem has been addressed here:
https://www.telerik.com/forums/fixed-width-height-for-axis
but the provided solution doesn't solve the issue at all.
I am temporarily using workaround that takes PlotAreaClip.Width once, on LeftMouseButtonClick to prevent "jumping" while dragging:
private double _plotAreaClipWidth;

private void chartMainCandleChart_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    _plotAreaClipWidth = chartMainCandleChart.PlotAreaClip.Width;
}

The first line of ScaleChartDynamically() function is now:
var viewPortWidth = _plotAreaClipWidth;

So to clarify:
I want to remove the gap visible in the picture below, the gap is changing which causes chart to "jump" (rise an event again) whenever PlotAreaClip.Width is different. In other words I want to force the size of PlotAreaClip.Width (length of x-axis) and keep the labels, they should be cut off on both ends of the axis. To meet my general requirements, PlotAreaClip with axes should span across entire control rendering area without artificial gaps for labels. Bounty goes to the person that shows me how to do that. You can see what I mean by looking at the example below. See how length of x-axis is changing when zooming/dragging to accomodate the labels. This is the cause of the problem that resizes PlotAreaClip.Width and creates blank space on the sides of the chart. If you look closely you can see that the same issue can be visible on y-axis as well:


text:
Q: Keep getting a an error.. dont know how to finish this import java.util.Scanner;

public class homework {

    public static  void main(String[] args) {
        double Xp;
        double Yp;
        double Xq;
        double Yq;

        Scanner Point1= new Scanner(System.in);
        System.out.print("Enter the First value for Xp: ");
        Xp = Point1.nextDouble();
        Scanner Point2= new Scanner(System.in);
        System.out.print("Eneter the First valuse for Yp: ");
        Yp = Point2.nextDouble();
        Scanner Point3= new Scanner(System.in);
        System.out.println("Enter the First valuse for Xq: ");
        Xq = Point3.nextDouble();
        Scanner Point4= new Scanner(System.in);
        System.out.println("Enter the First valuse for Yq: ");
        Yq = Point4.nextDouble();
        System.out.println("Point P's Coordinates are: " + "( " + Xp + "," + Yp   + ")" );
        System.out.println("Point Q's Coordinates are: " + "( " + Xq + "," + Yq   + ")" );

        if ( Xp >= 1 &&  Yp >= 0)
        {
         System.out.println("The point P is in Quadrant 1 ");
        }
       else if ( Xp <= 0 && Yp>=0 )
       {
        System.out.println("The point P is in Quadrant 2" );
       }
       else if ( Xp<=0 && Yp<0)
       {
        System.out.println("The point P is in Quadrant 3" );
       }
       else if (Xp>= 0 && Yp<0)
       {
        System.out.println("The point P is in Quadrant 4" );
       }
       if ( Xq >= 1 &&  Yq >= 0)
       {
         System.out.println("The point Q is in Quadrant 1 ");
       }
      else if ( Xq <= 0 && Yq>=0 )
      {
        System.out.println("The point Q is in Quadrant 2" );
      }
      else if ( Xq<=0 && Yq<0)
      {
        System.out.println("The point Q is in Quadrant 3" );
      }
      else if (Xq>= 0 && Yq<0)
      {
        System.out.println("The point Q is in Quadrant 4" );
        }
    double ED=Math.sqrt((Xq-Xp)*(Xq-Xp) + (Yq-Yp)*(Yq-Yp));
    System.out.println("The Euclidean distance from p to q is :"+ ED);

    double slope= (Yp-Yq)/(Xp-Xq);
    if (Xp-Xq!=0)
    {
    double slope;
    System.out.println("The Slope of the Line is: "+ slope);
    }
    else if  (Xp-Xq==0){
    System.out.println("Slope Is Undefined");
    System.exit(1);
}} }

The error is that I duplicated variable  slope and i can't figure out how to make it work without getting an error.
What my assigment is asking for:

(Create another method that returns the slope of the line pq formed by
  connecting p and q. The slope is expressed as m = (yp − yq)/(xp − xq),
  but it must be robust to errors caused by certain inputs.If the slope
  is undefined, do not perform the calculation due to a divide-by zero
  error. Instead, print the error message "Slope is undefined." inside
  the method and call System.exit(1) to end your program)

A: The only "error" I currently see is that you have a duplicate of your variable "slope".
Another thing to mention: Don't use multiple Scanner. You can just use one and do the inputs you want. And close the Scanner after your inputs are done.

A: Just remove
    double slope;

from
    double slope= (Yp-Yq)/(Xp-Xq);
    if (Xp-Xq!=0){
        double slope;        // just remove this.
        System.out.println("The Slope of the Line is: "+ slope);

    }else if  (Xp-Xq==0){
        System.out.println("Slope Is Undefined");
        System.exit(1);
    }

Further
You can create a class and several methods to do all these operations and use the main method to get the  user inputs through Scanner and invoke functions through an object of that class. This will make your code cleaner.
For an example, create a class called Geomat
    class Geomat{
        public void getQuadrant(){
             // do your logic here
        }

        public void getSlope(){
             // do your logic here
        }

    }

then in main method after getting inputs from the Scanner use
    Geomat g = new Geomat();
    g.getQuadrant();
    g.getSlope();