text:
Q: Instead of warping spacetime, can gravity be represented by locally varying time rates? Instead of thinking of gravity as mass warping spacetime, could it be thought of as mass warping only time, whereby time would advance at faster rates at locations where more mass is present?

A: No. This kind of proposal can "control" at most one independent component of the Riemann curvature tensor (through a rate parameter), and we routinely meet metrics in gravitational theory that have pure spatial curvature as well as time components to the curvature tensor.
Witness, as an example, the FLRW metric wherefor:
$$\begin{array}{lcl}R_{tt}& =& - 3 \frac{\ddot{a}}{a}\\
R_{rr} &=&\frac{c^{-2}(a(t)\ddot{a}(t) + 2\dot{a}^2(t)) + 2k}{1 - kr^2}\\
R_{\theta\theta} &=& r^2(c^{-2}(a(t)\ddot{a}(t) + 2\dot{a}^2(t)) + 2k)\\
R_{\phi\phi} &=&r^2(c^{-2}(a(t)\ddot{a}(t) + 2\dot{a}^2(t)) + 2k)\sin^2(\theta)\end{array}$$
where one has two independent parameters, the scale factor $a(t)$ (which could be construed as the "control knob" in the OP's proposal) and the spatial curvature. It's true that one can normalize the equations, but you're still left with three fundamentally distinct possibilities $k=\pm1$ and $k=0$. Furthermore, one can of course find much more complicated, inhomogeneous metrics as valid solutions to the Einstein field equations.

A: It is difficult to answer your question for all possible configurations of gravity, but within Schwarzschild metric it is easy to show that gravity may not only be represented as curved spacetime but - exactly as you suppose - also as gravitational time dilation in flat space.
The Schwarzschild metric is the most basic description of the spacetime curvature by gravity, it is
$$ \mathrm ds^2 = -\left(1 - \frac{2GM}{c^2 r}\right) c^2~\mathrm dt^2 + \frac{1}{1 - \frac{2GM}{c^2 r} }~\mathrm dr^2 + r^2 \left(\mathrm d\Theta^2 + \sin^2 \Theta ~\mathrm d\Phi^2\right)$$
In contrast, the corresponding Minkowski metric (with flat spacetime) is
$$ \mathrm ds^2 = -~ c^2~\mathrm dt^2 + \mathrm dr^2 + r^2 \left(\mathrm d\Theta^2 + \sin^2 \Theta~\mathrm d\Phi^2\right)$$
where $\mathrm dt$ is uncurved time and $\mathrm dr$ is uncurved radial displacement.
Comparing both, you find that in the Schwarzschild metric, time $\mathrm dt$ is multiplied by the constant
$$ \sqrt{1 - \frac{2GM}{c^2 r}}$$
and space $\mathrm dr$ is divided by the same constant. It is exactly this factor which represents the spacetime curvature. The constant is gravitational time dilation.
If we set the constant = $C$, we can write Schwarzschild metric shorter in the following way:
$$ \mathrm ds^2 = -~c^2 (C~\mathrm dt)^2 + {\left(\frac {\mathrm dr}{C}\right)}^2 + r^2 \left(\mathrm d\Theta^2 + \sin^2 \Theta~\mathrm d\Phi^2\right)$$
Comparing this short form with the equation above of Minkowski metric, the Schwarzschild metric differs from uncurved Minkowski metric only by one coefficient $C$ which is identic with gravitational time dilation. That means that the curved spacetime of Schwarzschild metric may also be described in terms of gravitational time dilation - in absolute, flat space!
Curved spacetime and gravitational time dilation in flat space are two equivalent models. For the latter, gravitation is expressed by the tendency of particles to maximize their own gravitational time dilation.
Edit 1:
The Schwarzschild metric even provides a simpler answer to your question: in the Schwarzschild equation, the displacement coordinates dt and dr (as well as dΘ and dΦ) are not curved! As you see, the metric ds is the result of a multiplication of dt by C and the division of dr by C, providing a warped metric. However, the terms on the right side dt and dr are not distorted and not warped, they are flat polar coordinates, and the polar coordinate system may be transcribed into the corresponding Cartesian coordinate system of flat space.
Edit 2:
Your question may be of high importance. If what I showed for the Schwarzschild metric would be true in general (e.g. Kerr metric etc.) this would mean that gravity may be described exclusively in terms of time modulation in flat space. This could be crucial with regard to the fact that the time parameter in quantum mechanics is no operator, it is classical. In my personal opinion, here could exist a path permitting to conciliate gravity and quantum mechanics.

A: Before we answer this question, I think it is proper to discuss what is asked. As Rod explains, there are certainly solutions to the Einstein Field equations that cannot be explained by a single parameter. However, the question as framed seems to suppose there is some universal way of defining how quickly time passes. What is meant by time dilation is that the proper time along two different timelike curves connecting two events differ. This can happen in Minkowski spacetime, where the universal reference frame makes things easier for us, and it can happen in curved spacetimes. In this view, the quesion should perhaps be reframed as:

Can the effects of spacetime curvature be reconstructed from knowledge of time dilation along all different timelike paths? Possibly by introducing new dynamic equations which link time dilation to other observable effects.

If this was the case, one could say that spacetime curvature could be entirely explained only by considering time dilation. Now, proper time along a curve, $\gamma$, is found by integrating the metric along the curve
$$\Delta\tau = \int_\gamma d\tau = \int_\gamma\sqrt{g_{ab}dx^adx^b},$$
where we supposed units such that $c = 1$ and timelike signature, $(+---)$. This would in principle allow us to reconstruct the primitive of the metric components along our timelike curves, and the curvature is given by a rather lengthy expression involving second derivatives of the metric.
However, promising as this may look, the fact that we can only consider timelike curves, means that we have no way of investigating the dependency of metric components along spacelike or null curves (through time dilation). In slightly more mathematical language: we can only know the derivatives of the metric components with respect to timelike coordinates, and of those only the "timelike components:" If we choose coordinates $(t,x^1,x^2,x^3)$ such that $x^i$ ($i \in \{1,2,3\}$) are constant along a curve then
$$\Delta\tau = \int_\gamma\sqrt{g_{tt}}dt,$$
and we may in principle reconstruct the primitive of $\sqrt{g_{tt}}$ with respect to $t$ only. And this is certainly not enough to reconstruct the curvature tensor, in any spacetime, even if all possible timelike coordinates are investigated.


text:
Q: can't retrieve longblob audio file from database i was inserting audio files to my database and i was retreiving them just fine then some files just won't be retrieved even tho i'm using the same code here's the code
getAudio.php
    <?php
include 'conn.php';
// to connect with the database
  $id = $_GET['id'];
  // validation just to be safe

  $sql = "SELECT file FROM letters1 WHERE id=$id";
  // choose the column from the table where the id= the id of the audio file

  $result = mysql_query("$sql");
  //query the audio file

  $row = mysql_fetch_assoc($result);
  //Returns an associative array

  mysql_close($link);
  //closes the non-persistent connection to the MySQL

  header("Content-type: audio/mpeg");
  //audio/wav for wav files mpeg for mp3 files, we used mp3 cuz
  //wav didn't work on IE so just to be sure

 echo $row['file'];
 //calls the audio file and returns it in the src attribute
?>

returnblobfile.php
<?php include 'php/conn.php'
?>

<!DOCTYPE html>
<head><title>new</title></head>
<body>
<audio controls>
<source src="php/getAudio.php?id=14" type="audio/mpeg">
</audio>

</body>
</html>

i'm using phpMyAdmin it stopped on id 14, 16, 19, 20 and they are not empty i kept on editing them.
please help .. thanks in advance

A: SQL injection aside, you code seems ok. May be you reach some memory or storage limit:

*

*Guess 1: you are using fields of type blob but your file is bigger than that and was truncated when inserted into the table. Using a field type with more capacity could be a solution (mediumblob or longblob).

*Guess 2: the content of file field is too heavy for the php memory limit. You can try allowing more with something like this:
Using and .htaccess file:
    php_value memory_limit 128M

Or using ini_set at the top of your script:
    ini_set('memory_limit', '128M');

(32, 64, 128 or whatever number works for you)
EDIT: oops... didn't pay attention, the title already says you are using longblob ^^

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I setup nginx and uwsgi when using virtualenv? I am going to start using virtualenv for the first time. If I am going to have multiple environments with a django project in each, do I have 1 nginx instance running and have each domain point to the socket of a uwsgi instance running with a -H env parameter? Such that I would have 1 nginx instance running and multiple (1 for each environment) uwsgi instances?

A: Yes, 1 nginx instance and multiple (1 for each environment) uwsgi instances running.
If you want separate virtualenv's for each project, of course.


text:
Q: If a prime can be expressed as sum of square of two integers, then prove that the representation is unique. If a prime can be expressed as sum of two squares, then prove that the representation is unique.
My attempt:
If $a^2+b^2=p$, then it is obvious that $a,b$ of different parity.
Now, I assume the contraposition that the representation is not unique, $p=a^2+b^2=c^2+d^2$. Again, $c,d$ are of different parity.
Now, let $b,d$ be even and $a,c$ be odd.
So, $a^2+b^2=c^2+d^2 \implies a^2-c^2=d^2-b^2 \implies (a+c)(a-c)=(d-b)(d+b)$.
I cannot proceed any further. Please help.

A: Here's an answer without Algebraic Number Theory. I found it in Shanks, Solved and Unsolved Problems in Number Theory.
Assume $$p=a^2+b^2=c^2+d^2\tag1$$ with all variables positive integers. Then $$p^2=(a^2+b^2)(c^2+d^2)=a^2c^2+a^2d^2+b^2c^2+b^2d^2$$ and you can verify by just multiplying everything out that $$p^2=(ac+bd)^2+(ad-bc)^2\tag2$$ and $$p^2=(ac-bd)^2+(ad+bc)^2\tag3$$ By (1), we have $$(p-a^2)d^2=(p-c^2)b^2$$ which implies $$p(d^2-b^2)=(ad-bc)(ad+bc)\tag4$$ From (4), $p$ divides $ad-bc$, or $p$ divides $ad+bc$. If $p$ divides $ad-bc$, then from (2) we get $ad-bc=0$, so $d^2-b^2=0$, so $b=d$. If $p$ divides $ad+bc$, then from (3) we get $ac=bd$. Now $a$ and $b$ are relatively prime, so $a$ divides $d$, and $b$ divides $c$. Then by (1) we have $a=d$, and we have proved that the two representations of $p$ are the same.
This is probably something like what @Konstantinos was getting at in his answer.

A: The slickest way is via a little Algebraic Number Theory. If $p=a^2+b^2=c^2+d^2$ then $$p=(a+bi)(a-bi)=(c+di)(c-di)$$ Now ${\bf Z}[i]$ is a unique factorization domain, so these two factorizations of $p$ show that $a+bi$ can't be a prime in ${\bf Z}[i]$. We must have a non-trivial factorization $a+bi=(s+ti)(u+vi)$, whence $a-bi=(s-ti)(u-vi)$, and then $$p=(s^2+t^2)(u^2+v^2)$$ contradicting primality of $p$.
There are ways to answer your question without these advanced concepts, but I can never remember how it's done. I'm sure someone else will.

A: If $p=a^2+b^2=c^2+d^2$ then $$p=\frac{(ac+bd)(ac-bd)}{(a+d)(a-d)}$$

A: The problem is trivialized if you are given that $x^2+y^2=n$ has $r_2(n)=4\sum_{d|n} \sin(\pi d/2) $ solutions in the integers.
The number of ways $r_2(p)=4\sum_{d|p} \sin(\frac{\pi d}{2})=4(1+\sin(\pi p/2))$.
If $\sin(\pi p /2)=1$ then there are 8 solution in the integers. Namely, $(\pm a,\pm b)$ and $(\pm b, \pm a)$ satisfy $x^2+y^2=p$ where $a\neq b$. There is another way one might imagine $8$ solutions: $(0,\pm a),(\pm a,0)$ and $(\pm b,\pm b)$ but this cannot happen because it would mean that $p$ is a perfect square and therefore not prime.
If $\sin(\pi p /2)=-1$ then we cannot write $p$ as the sum of squares.
$If \sin(\pi p /2)=0$ then $p=2$.


text:
Q: Draw vertical line on histogram plot matlab Matlab R2015b. I used the following code to draw the histogram:
close all;
hold on;
ko = histograms_windows_1_0{7};
histogram(ko);
set(gca,'XLim',[0 30],'XTick',0:5:30);
xticks = [0;0.16;0.33;0.5;0.66;0.83;1];
set(gca,'XTickLabel', xticks)
xlabel('Seconds');
ylabel('Correct Transitions');

That gives me the picture:

Now I want to add vertical line showing mean value by the "seconds" axis, I already know that value and also the standard deviation. Something similar to:
I have mn and stdv values. I've tried this:
mn = mean(ko) / 30;
stdv = std(ko) / 30;
hax=axes;
line([mn mn],get(hax,'YLim'))
hold off;

But it ignores previously drawn histogram and draws vertical line but only that line is shown, no histogram anymore. How that can be achieved?

A: The problem is the line
hax=axes;

This creates a new axis object which covers the previous one.
The solution is to change into
hax=gca;

so that the subsequent line goes to the same axis that contains the histogram.


text:
Q: Windows Phone 8 read Smart card Is it possible to use pinvoke.net with Windows Phone 8?
Something like [DllImport(" winscard.dll ")]?

A: No, you cannot use DLLImport in WP8.
I've answered a similar question about reading Credit Cards on WP8 that applies to Smart Cards as well. See @ Windows 8 Phone - access to NFC reader?


text:
Q: Slide In Animation as you scroll (same time) I was searching for a very basic approach to make objects slide in from the side (images, divs etc.) as you scroll. So far I've only seen triggers which cause an animation at specific pixels and the objects slide in by themselves, but I want them to slide in the same time as you scroll and slide back as you scroll up again -> Example: http://nizoapp.com/ exactly like here :)
Thanks in advance!

A: This library may help: Animate on scroll


text:
Q: AMP in a dynamically generated classifieds sites I'm working with a client that is trying to build their mobile site using AMP.  The site is an auto classifieds site.  The content is updated constantly as new inventory is added and sold, etc. Also these sites generate millions of pages with strings for brand, year, etc. which are tens of possibilities, etc.
How can we accomplish that the content on the site remains fresh if Google is caching the data?
Thanks in advance for any suggestions!


text:
Q: Embedding a Plotly chart in a Django template I am trying to embed a plotly pie chart in a Django html template. This works fine when the chart is produced in 'online mode' (i.e. the html snippet is stored on the plotly server) but not in 'offline mode' (i.e. when the html is stored locally). In the latter case, the chart does not appear. I want to be able to store the html on my local server and embed the plots from there.
Here is the bit that works:
import plotly.plotly as py
import plotly.graph_objs as go
labels = [1,2,3,4]
values = [10,20,30,40]
ndata = 100
fig = {
    'data': [{'labels': labels,
          'values': values,
          'type': 'pie',
          'textposition':"none",
          'textinfo':"percent",
          'textfont':{'size':'12'},
          'showlegend':'false'}],
    'layout': {'title': 'Total:'+str(ndata),
           'showlegend':'false',
           'height':'200',
           'width':'200',
           'autosize':'false',
           'margin':{'t':'50','l':'75','r':'0','b':'10'},
           'separators':'.,'}
}
plotly_url = py.plot(fig, filename='myfile', auto_open=False)
pie_url = ''

Note that pie_url is passed as a string in the Http render request in Django. The template interprets the string as html using the | safe tag, i.e. {{ pie_url|safe }}.
Here is the bit that doesn't work:
from plotly.offline import download_plotlyjs, plot
import plotly.graph_objs as go
labels = [1,2,3,4]
values = [10,20,30,40]
ndata = 100
fig = {
    'data': [{'labels': labels,
          'values': values,
          'type': 'pie',
          'textposition':"none",
          'textinfo':"percent",
          'textfont':{'size':'12'},
          'showlegend':'false'}],
    'layout': {'title': 'Total:'+str(ndata),
           'showlegend':'false',
           'height':'200',
           'width':'200',
           'autosize':'false',
           'margin':{'t':'50','l':'75','r':'0','b':'10'},
           'separators':'.,'}
}
plotly_url = plot(fig, filename='file:///home/website/pie.html', auto_open=False)
pie_url = ''''''

Any advice would be appreciated.

A: Instead of writing the html to a file you can have plotly return the html part of the graph as a string. For example, using a class based TemplateView:
EDIT: Update for using recent (as of 2021/08) versions of plotly. The template does not need any changes.
import plotly.graph_objects as go

class Graph(TemplateView):
    template_name = 'graph.html'

    def get_context_data(self, **kwargs):
        context = super(Graph, self).get_context_data(**kwargs)

        x = [-2,0,4,6,7]
        y = [q**2-q+3 for q in x]
        trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 104, 'size': "10"},
                            mode="lines",  name='1st Trace')

        layout=go.Layout(title="Meine Daten", xaxis={'title':'x1'}, yaxis={'title':'x2'})
        figure=go.Figure(data=['trace1'],layout=layout)

        context['graph'] = figure.to_html()

        return context

This is the original code:
import plotly.offline as opy
import plotly.graph_objs as go

class Graph(TemplateView):
    template_name = 'graph.html'

    def get_context_data(self, **kwargs):
        context = super(Graph, self).get_context_data(**kwargs)

        x = [-2,0,4,6,7]
        y = [q**2-q+3 for q in x]
        trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 104, 'size': "10"},
                            mode="lines",  name='1st Trace')

        data=go.Data([trace1])
        layout=go.Layout(title="Meine Daten", xaxis={'title':'x1'}, yaxis={'title':'x2'})
        figure=go.Figure(data=data,layout=layout)
        div = opy.plot(figure, auto_open=False, output_type='div')

        context['graph'] = div

        return context

and the template:
{% if graph %}

{{ graph|safe }}

{% endif %}

A: There's been a couple of updates to plotly, some of which are applicable here for plotly 4+:

*

*Plotly is offline by default now

Note: No internet connection, account, or payment is required to use plotly.py. Prior to version 4, this library could operate in either an "online" or "offline" mode. The documentation tended to emphasize the online mode, where graphs get published to the Chart Studio web service. In version 4, all "online" functionality was removed from the plotly package and is now available as the separate, optional, chart-studio package (See below). plotly.py version 4 is "offline" only, and does not include any functionality for uploading figures or data to cloud services.

*Figures now have a to_html function

This allows you to do the following to embed a graph offline:
graph = fig.to_html(full_html=False, default_height=500, default_width=700)
context = {'graph': graph}
response = render(request, 'graph.html', context)

And in graph.html you can do:
{% if graph %}
{{ graph|safe }}
{% else %}

No graph was provided.

{% endif %}

A: Let's suppose that your piece of code that draws the graph, i.e.
from plotly.offline import download_plotlyjs, plot
import plotly.graph_objs as go
labels = [1,2,3,4]
values = [10,20,30,40]
ndata = 100
fig = {
    'data': [{'labels': labels,
          'values': values,
          'type': 'pie',
          'textposition':"none",
          'textinfo':"percent",
          'textfont':{'size':'12'},
          'showlegend':'false'}],
    'layout': {'title': 'Total:'+str(ndata),
           'showlegend':'false',
           'height':'200',
           'width':'200',
           'autosize':'false',
           'margin':{'t':'50','l':'75','r':'0','b':'10'},
           'separators':'.,'}
}
plotly_url = plot(fig, filename='file:///home/website/pie.html', auto_open=False)
pie_url = ''''''

is a funtion named graph_function(). Inside that one, just substitute
plotly_url = plot(fig, filename='file:///home/website/pie.html', auto_open=False)
pie_url = ''''''

with
plt_div = plotly.offline.plot(fig, output_type='div')

return plt_div

then in your views.py:
def graph_view(request):
    my_graph=graph_function()
    context={'graph':my_graph}
    return render(request, 'my_template.html', context_dict)

and then in your template:
{% if graph %}
{{ graph|safe }}
{% else %}

No graph was provided.

{% endif %}


text:
Q: Calling function on dialog button click, while creating it I am creating a button on dialog by using options.. At that time on its click I want to call a function... I know that we can write the logic there itself, but I want to share that stuff so had separate function, but couldn't make a call to that function..code is a below
//here menu is dialog..
//that is scope.
//this respective ele as this stmnt is inside the loop
menu.dialog("option", "buttons", [{ text: this.text, click: that._addClass(menu, this) }]);

my function is below.
 _addClass: function(menu, target){
      do stuff here
    }

the function never hits any work around plz......

A: Try replacing
click: that._addClass(menu, this)

with
click: function() { that._addClass(menu, target); }

(assigning this to target beforehand)


text:
Q: Swift downloadTask with request file download not working I'm trying to download a file from a server, by sending the id of the file. I tried several things but the file is getting downloaded as CFNetworkDownload.tmp file.
I want it to save as the file that exists. The file type can be PNG,JPEG,PDF,DOCX,PPTX,XLSX. Tried many things but in vain. I'm sure it must be something simple i'm missing to understand here
Tried the below. Difference being in most of the examples, the file name is in the URL. But I send id and get file in response.
How to download file in swift?
How To Download Multiple Files Sequentially using NSURLSession downloadTask in Swift
Below is my code.
func downloadFile(id : String, fileName : String) -> Void {

    let session = URLSession.shared
    let url = URL(string: qaDownloadURL+id)!

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Success: \(statusCode)")
            }

            do {

//                    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
//
//                    self.savePath = documentsUrl!.absoluteString + "/" + fileName
//
//                    let fileURL = URL(fileURLWithPath: self.savePath)
//
//                    let dataFromURL = NSData(contentsOf: tempLocalUrl)
//                    dataFromURL?.write(to: fileURL, atomically: true)

                var documentsDirectory: String?

                let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

                if paths.count > 0
                {
                    documentsDirectory = paths.first!
                }

                self.savePath = documentsDirectory!// + "/" + fileName

                let fileURL = URL(fileURLWithPath: self.savePath)

                let dataFromURL = NSData(contentsOf: tempLocalUrl)
                dataFromURL?.write(to: fileURL, atomically: true)

              //  try FileManager.default.copyItem(at: tempLocalUrl, to: fileURL)

                DispatchQueue.main.async {

                    let documentController = UIDocumentInteractionController.init(url: fileURL)
                    documentController.delegate = self
                    documentController.presentPreview(animated: true)

                }

            } catch (let writeError) {
                print("error writing file \(self.savePath) : \(writeError)")
            }

        } else {
            print("Failure: %@", error?.localizedDescription);
        }
    }
    task.resume()

}

A: You cannot write data into a location which represents a directory, you need to specify the full path including the file name.
Using modern URL related API you can replace the entire do block with
    do {
            let documentFolderURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            let fileURL = documentFolderURL.appendingPathComponent(fileName)
            try FileManager.default.copyItem(at: tempLocalUrl, to: fileURL)

            DispatchQueue.main.async {

                let documentController = UIDocumentInteractionController.init(url: fileURL)
                documentController.delegate = self
                documentController.presentPreview(animated: true)

            }
        }

or use URLSessionDataTask which returns the raw data rather than downloading the file to a temporary location and save the Data directly for example
let task = session.dataTask(with: request) { (data, response, error) in
    guard error == nil else {
        print(error!)
        return
    }
    // Success
    if let statusCode = (response as? HTTPURLResponse)?.statusCode {
        print("Success: \(statusCode)")
    }

    do {
        let documentFolderURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let fileURL = documentFolderURL.appendingPathComponent(fileName)
        try data!.write(to: fileURL)

        DispatchQueue.main.async {

            let documentController = UIDocumentInteractionController.init(url: fileURL)
            documentController.delegate = self
            documentController.presentPreview(animated: true)

        }

    } catch  {
        print("error writing file \(fileName) : \(error)")
    }
}
task.resume()

If this does not work the error is related to somewhere else.


text:
Q: Reading existing entities with multiple conditions I can get data from database by calling model factory in controller.
class Index extends \Magento\Framework\App\Action\Action{

protected $_entityFactory;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \My\Module\Model\EntityFactory $entityFactory
){
    $this->_entityFactory = $entityFactory;
    return parent::__construct($context);
}

public function execute(){
    $entity = $this->_entityFactory->create();

    // get data where entity_id = 1
    $entity->load(1);

    // get data where entity_name = Rizki
    $entity->load('Rizki', 'entity_name');
}

Now, i want get data with multiple condition. I have tried
$entity->load(['Rizki', 'entity_name'], ['Bandung' => 'address'])
But it gives me error Exception #0 (Exception): Notice: Array to string conversion.

A: Class Magento\Framework\Model\AbstractModel:
/**
 * Load object data
 *
 * @param integer $modelId
 * @param null|string $field
 * @return $this
 * @deprecated
 */
public function load($modelId, $field = null)
{
    $this->_beforeLoad($modelId, $field);
    $this->_getResource()->load($this, $modelId, $field);
    $this->_afterLoad();
    $this->setOrigData();
    $this->_hasDataChanges = false;
    $this->updateStoredData();
    return $this;
}

There is no such load method for AbstractModel instance with array parameters. Therefore, to load model using multiple conditions, my favorite method is like this:
$model = $modelFactory
    ->create()
    ->getResource()
    ->getCollection()
    ->addFieldToFilter('[field_name_1]', '[value_1]')
    ->addFieldToFilter('[field_name_2]', '[value_2]')
    ->getFirstItem()
;


text:
Q: POM (point-or-marker) in org-mode I'm trying to use functions org-entry-properties and org-id-get, both of which use an optional argument pom. For example, org-entry-properties documentation says:

Get all properties of the entry at point-or-marker POM.

Emacs manual almost doesn't mention the word "marker", however there are several functions ending with -marker. Now i have several questions about it.

*

*What is that point-or-marker?

*Is it the same as mark in a mark ring?

*How do i get a marker in an org-mode buffer?

*How do i use this marker in the above functions invocation?

A: Instead of the Emacs Manual, take a look at the Emacs Lisp Reference Manual for more information on markers:

A marker is a Lisp object used to specify a position in a buffer
  relative to the surrounding text. A marker changes its offset from the
  beginning of the buffer automatically whenever text is inserted or
  deleted, so that it stays with the two characters on either side of
  it.

The POM element to the functions you mention can thus either be a marker, i.e., a lisp object that contains both a buffer and a position in that buffer, or simply a position. In the first case, the functions will first switch to the buffer of the marker and move point to the marker's position before executing the rest of the function.
In the second case, it will stay in the current buffer, but move point to the given position before executing the rest of the function.
That is, the function is executed relative to the given buffer/position. At the end of the function's body, the original location of the point is restored.

A: An (absolute) position in a buffer is given by a number, which is roughly the number of characters that are before that position. Markers, on the other hand, allow to mark a "relative position" in the buffer : if you add text before it, it moves forward (like it were an invisible, 0-width, character).
At any time, you can convert a marker to an (absolute) position (an integer). That is why many arguments want a POM: they want a position, but accept that it is given as a marker.
The "mark" in emacs, is one specific marker which is easy to access by appropriate key chords (C-SPC sets it, C-x C-x exchanges the mark and the point, etc.).
The/a "mark ring" is the history of all previous "mark" markers (either in a given buffer, which is the local mark ring, or globally, for the so called global mark ring).
More info in the elisp manual :

*

*from within emacs : (info "(elisp) Markers")

*on the web : http://www.gnu.org/software/emacs/manual/html_node/elisp/Markers.html


text:
Q: date filter type is not working in yadcf plugin i have column which display date in it. i am using datatable for display tables.
i have render date column using datatable's column Render function and use yadcf column filter plugin for filter data. it display datepicker in filter element but not filter data after selecting date from it.
$(table_id).dataTable({
        aaData: $.parseJSON(records),
"aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [1], // <-- gets last column and turns off sorting
                "mData": null,
                "mRender": function(data, type, full) {
                    var cdate = row.date;
                    return cdate.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3-$2-$1");
}}]
}).yadcf([{column_number: 1, filter_type: "date"}]);

A: Try the latest yadcf version and also since you are using the - as date sepaartor you need to feed yadcf with the date_format:  'dd-mm-yy'
Updated code:
.yadcf([{column_number: 1,
         filter_type: "date",
         date_format:  'dd-mm-yy'
}]);

Here is a working jsfiddle (not sure if you meant to use dd-mm-yy or mm-dd-yy)


text:
Q: Support for the tomcat8 package On Ubuntu 16.04 I've been using the tomcat8 package. I enjoyed an automatic installation process and was guaranteed to receive packaged security updates for 5 years courtesy of Canonical. So, even though version 8.0 has been declared EOL, I can still use it on my Ubuntu server knowing that any vulnerabilities are going to be addressed.
$ ubuntu-support-status --show-supported
Supported until April 2021 (Canonical - 5y):
tomcat8 tomcat8-admin tomcat8-common

Much to my dismay, on Ubuntu 18.04 the tomcat8 package has been moved to Universe. In my understanding, there is no support guarantee and security patches may or may not be distributed as long as the mainstream product is supported by the Apache Foundation.
Is my understanding of things correct? Is there a convenient way to keep tomcat patched with security updates on Ubuntu 18.04 as easily as with 16.04?
Update: To be clearer, with 16.04 I could simply run apt update tomcat8 and be sure that there would be no vulnerabilities left unpatched. Running the same command today on 18.04, I get version 8.5.30-1ubuntu1 which is behind the latest available (8.5.37) and apparently affected by more than one known vulnerabilities.

A:
In my understanding, there is no support guarantee and security patches may or may not be distributed as long as the mainstream product is supported by the Apache Foundation.

Correct but it is in their best interest to keep support up as long as possible.

Is there a convenient way to keep tomcat patched with security updates on Ubuntu 18.04 as easily as with 16.04?

Nothing changes for you; it only comes from a more direct channel so if anything you should see updates appear quicker and not just security updates.
Old: update tomcat by Apache -> Ubuntu security team evaluates changes and adds patches if that specific package has Ubuntu related changes -> update to you.
New:  update tomcat by Apache -> update to you.
Canonical decided to kill the changes made to the package and as such could take it out of security. The fewer the changes to our default install means fewer issues. It is likely to happen and has happened with lots of other software since Canonical stopped with Unity: we are going back to the original source for our software.


text:
Q: I can not return an image file and show it in View using Ajax in Asp.net MVC $.ajax({
                    type: 'GET',
                    dataType: 'image/jpeg',
                    url: '/Home/GetImage/' + img ,
                    success: function (data) {
                        i = new Image();
                        i.src = data;
                        $('#imageresult').append(i);
                    },
                    error: function () {
                        alert('error');
                    },
});

[HttpGet]
public ActionResult GetImage(string img)
{
   string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
   var path = Path.Combine(imageFile, img );
   var srcImage = Image.FromFile(path);
   var stream = new MemoryStream();
   srcImage.Save(stream, ImageFormat.Jpeg);

   return File(stream.ToArray(), "image/jpeg");
}

It always falls into  error function. If i remove dataType, then it doesn't fall into error function but it just shows long strings in the view. Why doesn't that work and show image in view?

A: You can do something Like this:
public ActionResult GetImage(string img)
{
   string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
   var path = Path.Combine(imageFile, img );
   var srcImage = Image.FromFile(path);
   var stream = new MemoryStream();
   srcImage.Save(stream, ImageFormat.Jpeg);

   return Json(Convert.ToBase64String(stream.ToArray()), JsonRequestBehavior.AllowGet);
}

and the Ajax call:
$.ajax({
        type: 'GET',
        url: '@Url.Action("GetImage", "Home")',
        success: function (data) {
            $("#ItemPreview").attr('src', 'data:image/png;base64,' + data);
        },
        error: function () {
            alert('error');
        },
    });

and the view:
<img id="ItemPreview" src="" />

of course you can append img dynamically, then bind its source after.

A: You are confusing the URL of an image with its actual content (the graphic bytes).
The /GetImage call returns the bytes, but you can never put data bytes in the i.src attribute because that attribute needs to be fed a URL.
It might work if you forget about the Ajax call and just use i.src = '/Home/GetImage/' + img;.


text:
Q: Remove trailing zeros from binary result in python We have a program that changes decimals to binary.
And the goal is to run the program, input a value, and outputs the value in binary.
The problem with my code is that it has trailing zeros when outputting the binary.
I need to achieve this without using external libraries like "math", so please stick to the built-in functions.
Current output:

Insert a value:
5
The number fits in 1 byte and is in binary:
00000101
Insert a value:
100
The number fits in 1 byte and is in binary:
01100100
Insert a value:
280
The number fits in 16 bits and is in binary:
0000000100011000

Expected output:

Insert a value:
5
The number fits in 1 byte and is in binary:
101
Insert a value:
100
The number fits in 1 byte and is in binary:
1100100
Insert a value:
280
The number fits in 16 bits and is in binary:
100011000

Current code:
def dec2bin(value, number_bits):
    result = ''
    while number_bits > 0:
        bit_value = 2 ** (number_bits - 1)
        if value >= bit_value:
            result = result + '1'
            value = value - bit_value
        else:
            result = result + '0'
        number_bits = number_bits - 1
    print(result)

input_ok = False
userinput = 0
while not input_ok:
    print('Insert a value:')
    userinput = int(input())
    if userinput > 65535:
        print('invalid, cant handle that big numbers, try again')
    else:
        input_ok = True
    if userinput < 256:
        print('The number fits in 1 byte and is in binary:')
        dec2bin(userinput, 8)
    else:
        print('The number fits in 16 bits and is in binary:')
        dec2bin(userinput, 16)

A: It easy with string formatting functions (see Pranav's comment). But perhaps in this case you want the algorithm to take care of it, and see treating it as a string is cheating.
def dec2bin(value, number_bits):
    result = ''
    starting = True
    while number_bits > 0:
        bit_value = 2 ** (number_bits - 1)
        if value >= bit_value:
            result = result + '1'
            value = value - bit_value
            starting = False
        elif not starting:
            result = result + '0'
        number_bits = number_bits - 1
    print(result)

A: Since you are storing the value as a string you can use
result.lstrip('0')

to remove the leading zeros from your answer.


text:
Q: Visual statechart editor for non-programmers, with limited conditions, events and actions I'm looking for some visual statechart-editor, for my customer. I'm building for him server application, and he needs tool to build statecarts and upload them to the servers. Ofcourse, the tool needs to have the capability to export to some readable format (such as SCXML), so I could build a reader for it.
I saw some tools, like fsm-editor. But they can't be good for me, because I want to limit my customer to set of specific set of parametrized-conditions, parametrized-events and parametrized-actions.
For example, I'll define:
conditions: coIsDoorOpen, coIsThereNAppelsOnTheTree(n as uint[0..200]), ...
    events: evLightOn, evLightOff, evTimeout(ms as uint[1..10,000]), ...
   actions: acSetAlarmOn, acCloseWindowN(n as uint[1..10]), ...

and my customer could build some dozens statecharts with those explicit predefined attributes (conds, events & actions), and upload the export of them to the approperiate places.
There is no need to be strict to one statechart-standard or to another. But I need support on this things:

*

*parametrized conditions/events/actions

*before entering/exiting state actions

no need to support inner variables; I can use actions&conditions for it.
Is there any tool for it (preferably free)?
If not - is there any OpenSource (C# / JS) implementation of editor that supports all abpve without the stricting of conds/events/actions, that I could easily break in to it and add the requested strict mode?

A: Based upon your needs, my knee-jerk reaction of recommending Visio or Dia would be inappropriate here. You appear to require a tool with some form of an API or descriptive language to lock users to a constrained set of components Lemmings-style, and your needs would best be serviced by something relatively simple if possible.
I'm curious why altering the source code to SCXML-GUI (fsm-editor) or Violet would not solve your needs, however. You seem to indicate that an open source utility written in C# or JavaScript is most desirable, which I cannot easily locate.
But, in the interests of completeness, here's a comparable question that may help your search. Most notably, this appears to be exactly what you desire and may be worth purchasing.
Best of luck with your project.


text:
Q: How to use lapply function to instead of for loop in a custom function which is not vectorized in arguments Firstly, let us generate data like this:
library(data.table)
data <- data.table(date = as.Date("2015-05-01")+0:299)
set.seed(123)
data[,":="(
   a = round(30*cumprod(1+rnorm(300,0.001,0.05)),2),
   b = rbinom(300,5000,0.8)
 )]

Then I want to use my  custom function to operate multiple columns multiple times without manually typing out .Such as my custom function is add <- function(x,n) (x+n)
I provide my for loops code as following:
add <- function(x,n) (x+n)
n <- 3
freture_old <- c("a","b")
for(i in 1:n ){
  data[,(paste0(freture_old,"_",i)) := add(.SD,i),.SDcols =freture_old ]
}

Could you please tell me a lapply version to instead of for loop?

A: If all you want is to use an lapply loop instead of a for loop you really do not need to change much. For a data.table object it is even easier since every iteration will change the data.table without having to save a copy to the global environment. One thing I add just to suppress the output to the console is to wrap an invisible around it.
lapply(1:n,function(i) data[,paste0(freture_old,"_",i):=lapply(.SD,add,i),.SDcols =freture_old])

Note that if you assign this lapply to an object you will get a list of data.tables the size of the number of iterations or in this case 3. This will kill memory because you are really only interested in the final entry. Therefore just run the code without assigning it to a variable. Now if you do not assign it to anything you will get every iteration printed out to the console. So what I would suggest is to wrap an invisible around it like this:
invisible(lapply(1:n,function(i) data[,paste0(freture_old,"_",i):=lapply(.SD,add,i),.SDcols =freture_old]))

Hope this helps and let me know if you need me to add anything else to this answer. Good luck!

A: An option without R "loop" (quoted since ultimately its a loop at certain level somewhere):
data[,
    c(outer(freture_old, seq_len(n), paste, sep="_")) :=
        as.data.table(matrix(outer(as.matrix(.SD), seq_len(n), add), .N)),
    .SDcols=freture_old]

Or equivalently in base R:
setDF(data)
cbind(data, matrix(outer(as.matrix(data[, freture_old]), seq_len(n), add),
    nrow(data)))


text:
Q: Is it possible to confirm prompt alert with variable? I'm trying to do e2e test using protractor and I need to accept prompt alert ( type my API key ) for login to system.
How to type text(variable) in input and click OK in alert box using protractor? Is it possible?

A: Switch to the alert, send keys to it and then accept:
var EC = protractor.ExpectedConditions;

browser.wait(EC.alertIsPresent(), 5000);
var alert = browser.switchTo().alert();

alert.sendKeys("api key");
alert.accept();


text:
Q: Create new table that merges 2 tables together if they have the same date and time? I have 2 tables that look similar to this:
data1 <- data.frame("Metal" = c("Al", "Al", "Al", "Al", "Al", "Al", "Al"), "Type" = c("F", "F",
"F", "F", "F", "F", "F"), "Date" = c("2000-01-01", "2000-01-01", "2000-01-02", "2000-01-03",
"2000-01-03", "2000-01-07", "2000-01-07"), "Time" = c("11:00:00", "12:00:00", "15:00:00", "13:00:00", "17:00:00", "20:00:00", "20:00:00"))

data2 <- data.frame("Metal" = c("Al", "Al", "Al", "Al", "Al"), "Type" = c("P", "P",
"P", "P", "P"), "Date" = c("2000-01-01", "2000-01-01", "2000-01-03", "2000-01-03",
"2000-01-04"), "Time" = c("11:00:00", "14:00:00", "17:00:00", "13:00:00", "16:00:00"))

I want to keep data from both tables that have the same date and time. So the final table (data3) would look like this.
data3 <- data.frame("Metal" = c("Al", "Al", "Al", "Al"), "Type" = c("F", "P", "F",
"P"), "Date" = c("2000-01-01", "2000-01-01", "2000-01-03", "2000-01-03", "2000-01-03"), "Time" =
c("11:00:00", "11:00:00", "13:00:00", "13:00:00", "17:00:00"))

I've been trying various types of joins in dplyr, but none of them are doing the join the way I want them too. They either only keep data in 1 table or keep too much of the data.
Thank you for your help!!

A: You can rbind and keep only the duplicates (except from column type), i.e.
d3 <- rbind(data1, data2)
d3[duplicated(d3[-2])|duplicated(d3[-2], fromLast = TRUE),]

  Metal Type       Date     Time
1    Al    F 2000-01-01 11:00:00
4    Al    F 2000-01-03 13:00:00
5    Al    F 2000-01-03 17:00:00
6    Al    P 2000-01-01 11:00:00
8    Al    P 2000-01-03 17:00:00
9    Al    P 2000-01-03 13:00:00


text:
Q: Regex, capture one or more 6-digit numbers AFTER specific pattern my first question, so bear with me should anything no quite right. (I have read all topics suggested after entering title, but still no luck)
In words I need to capture all (i.e. one or more) 6-digits numbers following after specific keyword (here: "Customer\s"), which begins with 14 or 15
Input string:

Part Numbe
Customer PO
Description
Cust Part No: 325386
EB011036 // 175663/147667/8 ECK
5500003766 / 148266 -
WALK

between the start keyword to look after, and the following suitable 6 digit pattern any signs can be placed.
What I have come up so far:
Since the string can contain return, new lines etc.
I set the (?s) flag before:
Then a positive lookbehind:
(?s)(?<=Customer )

followed by
.+?

and then
(\D(1(4|5)\d{4})\D)+

So the whole expression:
(?<=Customer ).*?(\D(1(4|5)\d{4})\D)+

https://regex101.com/r/FEKwcY/1
But this only finds the first instance (147667) after Customer, not the second or more following.
If I change the wildcard between the groups to gready, it will find the last one, but not the first possible one.
Having played around further I added an alternation in the pos. lookbehind group:
(?s)(?<=Customer |\D\d{6}\D).*?(\D(1(4|5)\d{4})\D)+

This in fact find the two, but I am afraid, that this will also find before the Customer keyword.

A: You can use
(?s)(?<=\bCustomer\b.*?)\b1[45]\d{4}\b

See the .NET regex demo. Details:

*

*(?s) - RegexOptions.Singleline inline modifier flag

*(?<=\bCustomer\b.*?) - a positive lookbehind that matches a location that is immediately preceded with Customer as a whole word and then any zero or more chars as few as possible

*\b - a word boundary

*1 - a 1 char

*[45] - 4 or 5

*\d{4} - any four digits

*\b - a word boundary

PS demo:
PS C:\Users\admin> $s = "Part Number`r`n`r`nCustomer PO`r`n`r`nDescription`r`n`r`nCust Part No: 325386`r`n`r`nEB011036 // 175663/147667/8 ECK`r`n5500003766 / 148266 -`r`n`r`nWALK"
PS C:\Users\admin> Select-String '(?s)(?<=\bCustomer\b.*?)\b1[45]\d{4}\b' -input $s -AllMatches | Foreach {$_.matches.value}
147667
148266

A: I feel like this is more of a communal given answer as both @WiktorStribiżew and @TheFourthBird had relevant contributions that lead to the following pattern that should work in PowerShell's .Net regex flavor:
(?:^.*?\bCustomer\b|\G(?!^)).*?\b(1[45]\d{4})\b

See an online demo.

*

*(?: - Open non-capture group:

*

*^.*?\bCustomer\b - Start string anchor followed by 0+ characters (lazy) upto "Customer" inside word-boundaries.

*| - Or:

*\G(?!^) - Assert position at position of previous match and explicitly avoid to match the start of the string.

*) - Close non-capture group.

*.*?\b - 0+ Characters (lazy) upto a word-boundary.

*(1[45]\d{4}) - A capture group that start a substring with a 1 followed by either a 4 or 5 and 4 other random digits.

*\b - Another word-boundary.


text:
Q: ¿Consulta de tipo JOIN con 2 bases de datos SQL server? Estoy haciendo una comparacion entre 2 tablas del mismo nombre con PHP de una base de datos en SQL SERVER
 <?php

    $sql = "SELECT ITM1.ItemCode, OITM.ItemCode, OITM.ItemName, ITM1.Price, ITM1.PriceList FROM OITM, ITM1 WHERE ITM1.ItemCode = OITM.ItemCode AND ITM1.PriceList=1 ORDER BY ITM1.ItemCode" ;
    $sql2 = "SELECT ITM1.ItemCode, .OITM.ItemCode, OITM.ItemName, ITM1.Price, ITM1.PriceList FROM OITM, ITM1 WHERE ITM1.ItemCode = OITM.ItemCode AND ITM1.PriceList=1 ORDER BY ITM1.ItemCode ";
    $stmt = sqlsrv_query( $conn_sisT, $sql );
    $stmt2 = sqlsrv_query( $conn_sisM, $sql2 );

       if( $stmt === false) {
        die( print_r( sqlsrv_errors(), true) );
        }
       if( $stmt2 === false) {
     die( print_r( sqlsrv_errors(), true) );
            }

        while ( $rowT = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
              while ($rowM = sqlsrv_fetch_array( $stmt2, SQLSRV_FETCH_ASSOC) ) {
                $itemcode = $rowM['ItemCode'];

                 if (array_search($itemcode,$rowT)) {//son iguales

                 if ($rowT['Price']==$rowM['Price']) {//mismo precio
                        $p=$rowT['Price']+0;
                        echo "
".$rowT['ItemCode']."  	 ".$rowT['ItemName']." 	 ".$p." MXN
";
                        break;
}
if ($rowT['Price']!=$rowM['Price']) {

$p=$rowT['Price']+0;
echo "
".$rowT['ItemCode']."  	 ".$rowT['ItemName']." 	 ".$p." MXN MASTER: ".$rowM['Price']."
";
break;
    }
 }
else {
$p=$rowT['Price']+0;
$m=$rowM['Price']+0;
echo "
".$rowT['ItemCode']." | ".$rowM['ItemCode']."
	 ".$rowT['ItemName']." | ".$rowM['ItemName']."
	 ".$p." MXN | ".$m." MXN
";
break;
 }

}
}

?>

el Problema es que compara linealmente, necesito hacer un INNER JOIN pero las tablas de encuentran en diferentes bases de datos. Ya intente con nombreDB.dbo.nombretabla pero no me da ningún resultado.

A: no me dio ningún error, comente este código e implemente el otro solo necesito que los precios sean diferentes y si no existe se imprima.  son el mismo servidor Usuario y contraseña. solo diferentes bases de datos.

$sql = "SELECT SBO_TRANSMISIONES.dbo.ITM1.ItemCode, SBO_TRANSMISIONES.dbo.OITM.ItemCode, SBO_TRANSMISIONES.dbo.OITM.ItemName, SBO_TRANSMISIONES.dbo.ITM1.Price, SBO_TRANSMISIONES.dbo.ITM1.PriceList, SBO_MASTERS.dbo.ITM1.Price,SBO_MASTERS.dbo.ITM1.ItemCode

FROM SBO_TRANSMISIONES.dbo.OITM, SBO_TRANSMISIONES.dbo.ITM1, SBO_MASTERS.dbo.OITM, SBO_MASTERS.dbo.ITM1

WHERE SBO_TRANSMISIONES.dbo.ITM1.ItemCode = SBO_TRANSMISIONES.dbo.OITM.ItemCode
AND SBO_MASTERS.dbo.OITM.ItemCode = SBO_TRANSMISIONES.dbo.ITM1.ItemCode
AND SBO_TRANSMISIONES.dbo.ITM1.PriceList=1

ORDER BY SBO_TRANSMISIONES.dbo.ITM1.ItemCode" ;

Lo pongo directo por para que se entienda de donde es cada dato.


text:
Q: Fourier series, instantly determining $b_n$ once $a_n$ is found. Find the Fourier series of the following function:
$f(x) = \left\{\begin{align} 1+x,\quad -1\lt x \lt 0 \\ 1-x,\;\;\;\quad 0\lt x \lt 1\end{align} \right.$
$f(x+2) = f(x),\quad\quad -\infty \lt x \lt \infty$

So we have a periodic function of period, $p=2$
$a_0=\frac1{2L}\int_{-L}^Lf(x)dx=\cfrac12\left[\large\int_{-1}^0 1+x \, dx+\large\int_0^11-x\, dx\right]=\frac12$
$a_n = \large\int_{-1}^0 (1+x)\cos\left(n\pi x\right) \, dx + \large\int_{0}^1 (1-x)\cos\left(n\pi x\right) \, dx$
$$=-\frac{\sin(-n\pi)}{n\pi}+\frac{\sin(-n\pi)}{n\pi}+\frac{1}{n^2\pi^2}-\frac{\cos(-n\pi)}{n^2\pi^2}-\frac{\sin(-n\pi)}{n\pi}-\frac{\sin(n\pi)}{n\pi}-\frac{\cos(n\pi)}{n^2\pi^2}+\frac{1}{n^2\pi^2}$$
Noting that $\sin$ is an odd function, we can eliminate some terms from above.
$$=\frac{2}{n^2\pi^2}-\frac{2\cos(n\pi)}{n^2\pi^2}$$
$$b_n = \large\int_{-1}^0 (1+x)\sin\left(n\pi x\right)  dx + \large\int_{0}^1 (1-x)\sin\left(n\pi x\right) dx$$

Is there a way to instantly construct $b_n$ based on my $a_n$ result?

A: This is not based ob the computation of $a_n$ but note that
$$
\int_{-1}^0 (1+x)\sin\left(n\pi x\right) \, dx =
- \int_0^1 (1-u)\sin\left(n\pi u\right) \, du
$$because the function $\sin$ is odd.

A: There is no way of determining $b_n$ from $a_n$. For instance, if $a_n=0$ for al $n\ge0$, $\{b_n\}$ can be any sequence such that $\sum|b_n|^2<\infty$. With the same $a_n$ you have an infinitude of possible $b_n$'s.


text:
Q: Group time intervals by times in which they are occurring Let's say I have startTime and endTime given and between these are half an hour intervals. For example startTime=8:00, endTime=12:00 so possible times are 8:00, 8:30, 9:00, 9:30, 10:00, 10:30, 11:00, 11:30, 12:00
Now I have rows of Actions with time periods during which my Actions are happening. There are rowStartTime and rowEndTime for each row. They are of type TIME
The thing I'm trying to achieve is to return GROUPed results by times with count of rows that are happening in that specific time.
Demo data
name    rowStarTime  rowEndTime
--------------------------------
action1  6:00        10:00
action2  9:00        13:00
action3  10:00       11:30
action4  12:00       13:00
action5  11:30       15:00

Expected result
Time      Action count    (actions in that time, this is just comment)
---------------------------------------------------------------------
8:00      1               //1
8:30      1               //1
9:00      2               //1, 2
9:30      2               //1, 2
10:00     3               //1, 2, 3
10:30     2               //2, 3
11:00     2               //2, 3
11:30     3               //2, 3, 5
12:00     4               //2, 4, 5

I'd like to do the most of it on the database level (using SQL). Is it doable? Or do I have to get a bit of help of PHP (I'm using Doctrine DQL, but I can use a lot of special SQL functions https://github.com/orocrm/doctrine-extensions & https://github.com/beberlei/DoctrineExtensions)?
I was only able to achieve this for rowStartTime, not the whole period:
SELECT `rowStartTime` AS sclr_0, COUNT(o.id) AS sclr_1
FROM orders o
GROUP BY sclr_0

(if selecting times only between startTime and endTime would make it difficult, it's not core, this condition can be omitted)

A: DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(name    VARCHAR(12) NOT NULL PRIMARY KEY
,start_time TIME NOT NULL
,end_time TIME NOT NULL
);

INSERT INTO my_table VALUES
('action1', '6:00:00','10:00:00'),
('action2', '9:00:00','13:00:00'),
('action3','10:00:00','11:30:00'),
('action4','12:00:00','13:00:00'),
('action5','11:30:00','15:00:00');

SELECT * FROM my_table;
+---------+------------+----------+
| name    | start_time | end_time |
+---------+------------+----------+
| action1 | 06:00:00   | 10:00:00 |
| action2 | 09:00:00   | 13:00:00 |
| action3 | 10:00:00   | 11:30:00 |
| action4 | 12:00:00   | 13:00:00 |
| action5 | 11:30:00   | 15:00:00 |
+---------+------------+----------+

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT SEC_TO_TIME(1800*(i2.i*10+i1.i)) time
     , COUNT(*) total
     , GROUP_CONCAT(x.name) actions
  FROM ints i1
 CROSS
  JOIN ints i2
  LEFT
  JOIN my_table x
    ON SEC_TO_TIME(1800*(i2.i*10+i1.i)) BETWEEN x.start_time AND x.end_time
 WHERE SEC_TO_TIME(1800*(i2.i*10+i1.i)) BETWEEN '08:00:00' AND '12:00:00'
 GROUP
    BY time;
+----------+-------+-------------------------+
| time     | total | actions                 |
+----------+-------+-------------------------+
| 08:00:00 |     1 | action1                 |
| 08:30:00 |     1 | action1                 |
| 09:00:00 |     2 | action1,action2         |
| 09:30:00 |     2 | action1,action2         |
| 10:00:00 |     3 | action1,action2,action3 |
| 10:30:00 |     2 | action2,action3         |
| 11:00:00 |     2 | action2,action3         |
| 11:30:00 |     3 | action2,action3,action5 |
| 12:00:00 |     3 | action2,action4,action5 |
+----------+-------+-------------------------+

A: Create action table
CREATE TABLE actions (a VARCHAR(50), start TIME, end TIME);
INSERT INTO actions (a,start,end) VALUES
('action 1', '6:00', '10:00'),
('action 2', '9:00', '13:00'),
('action 3', '10:00', '11:30'),
('action 4', '12:00', '13:00'),
('action 5', '11:30', '15:00');

Create times table
CREATE TABLE times (t TIME);
INSERT INTO times (t) VALUES
('5:00'), ('5:30'),
('6:00'), ('6:30'),
('7:00'), ('7:30'),
('8:00'), ('8:30'),
('9:00'), ('9:30'),
('10:00'), ('10:30'),
('11:00'), ('11:30'),
('12:00'), ('12:30'),
('13:00'), ('13:30'),
('14:00'), ('14:30'),
('15:00'), ('15:30');

Select by time
SELECT
times.t as t,
count(CASE WHEN actions.a IS NOT NULL THEN 1 ELSE NULL END) as c
FROM times
LEFT JOIN actions ON actions.start <= times.t AND actions.end >= times.t
GROUP BY times.t

Results
t           c
05:00:00    0
05:30:00    0
06:00:00    1
06:30:00    1
07:00:00    1
07:30:00    1
08:00:00    1
08:30:00    1
09:00:00    2
09:30:00    2
10:00:00    3
10:30:00    2
11:00:00    2
11:30:00    3
12:00:00    3
12:30:00    3
13:00:00    3
13:30:00    1
14:00:00    1
14:30:00    1
15:00:00    1
15:30:00    0

A: Create temporay table with time intervals and use
CREATE TEMPORARY TABLE TEMP (half TIME);
DROP PROCEDURE IF EXISTS insertTEMP;
DELIMITER //
CREATE PROCEDURE insertTEMP (first TIME, last TIME) begin
WHILE first <= last DO
INSERT INTO TEMP  Values (first);
SET first = ADDTIME(first, "00:30");
END WHILE;
END //
DELIMITER ;

CALL insertTEMP("04:00", "12:00");
SELECT TEMP.half `Time`, COUNT( actions.name ) `count`, GROUP_CONCAT(actions.name) actions  FROM (TEMP,  actions) WHERE TEMP.half between  actions.rowStarTime AND actions.rowEndTime GROUP BY half

As you can see, times with no action does not included in result
Time, count, actions
06:00:00, 1, action1
06:30:00, 1, action1
07:00:00, 1, action1
07:30:00, 1, action1
08:00:00, 1, action1
08:30:00, 1, action1
09:00:00, 2, action1,action2
09:30:00, 2, action1,action2
10:00:00, 3, action1,action2,action3
10:30:00, 2, action2,action3
11:00:00, 2, action2,action3
11:30:00, 3, action2,action3,action5
12:00:00, 3, action2,action4,action5


text:
Q: I can't resize partition with GParted I tried to resize my partition with GParted. But I can't resize the ext4 partition.
I tried to look at other question on this site, but it doesn't seem like I can find the solution.

The ext4 partition is on /dev/sda6. When I try to resize it, I can't change the size.

A: Your partition is locked as indicated by the key
symbol, because / is currently mounted. You can boot from a Linux Live USB and run GParted from there or boot a GParted Live CD/USB to resize your partition.


text:
Q: Interfacing RFID reader module with PC Sorry it may seem stupid but I think my confusion is drifting me away from the solution so I wanted to ask.
I am trying to build a fixed RFID reader. But the project has some other complex work to be done, so I am using a mini PC as the main hub.
I need to connect an RFID reader through a port on the PC (there are RS232, Ethernet and USB) I am trying to select the cheapest solution for the reader module I have found. This is the RFID reader module I want to use but the thing is I am confused with the Fixed RFID readers with this module/the development kit and the RFID reader module.
Datasheet says there is a serial port on the module I have linked. If I just, say, connect this serial pins directly to RS-232 and use the API (which is compatible with the OS) will that be enough?

A: This device is USB 2.0 compatible. This means that you can connect it directly to your PC via USB. I have no access to the datasheet, however the fact that the maximum speed is 12 Mbps makes me believe that the device is interfaced through an FTDI chip; if I am right you can send/recieve data from the module using the serial port (RS232/Uart), this can be done easily using most programming tools.

A: It looks like the module can talk either serial or USB.  I didn't see any mention of Ethernet in the quick writeup.
Either will work, and there are issues both ways.
RS-232
The serial will need a converter that goes between the logic level signals of the module and the RS-232 signals of the PC.  There are chips that do this, so this is no real issue if you are making your own PCB anyways.  For more details, see the RSLink2 product that I sell.  That page also links to the datasheet of the converter chip used in the product (Yes I know google complains about that page.  It's a false positive.  There is no malware on our site.).
In software, you communicate via a COM port.  Your application can directly talk to the device.  There is no library or driver needed.  However, you need really good specs on the serial communication protocol.
USB
Electrically, USB will "just work".  In this case, the complication is in the software.  A driver in the OS for the device will be needed.  If the company supplies you with a driver and then gives you proper specs for calling it, then this may be the best solution.  However, in my experience a lot of such drivers are of questionable quality and they almost never give you proper specs to communicate with the driver.
Usually you get a host library and a driver as one package.  That by itself is reasonable enough, but often, even usually, the library is of poor quality and the documentation no better.
Some hardware vendors will add USB support by slapping on a FTDI or equivalent chip to a existing serial interface.  That gives you the worst of both worlds.  You still have the issue of knowing the COM port, and you don't get the inherent device ID and enumeration features of USB.  If USB is supported as a afterthought like this, you might as well connect directly to the real underlying serial port.
Conclusion
Electrically, USB should just work and RS-232 can be made to work easily enough.  The decision comes down to how good the documentation of the low level protocol, the driver interface, and the library interface are.  Have a private talk with a field engineer and try to determine how solid each interface is, how the company plans to proceed in the future, a honest assessment of the driver and library quality, etc.  And of course ask for all the documentation up front and read it carefully from the point of view of writing a embedded app trying to drive this device.  That alone may dictate one interface over the other.


text:
Q: Can I turn on IE 10 Compatibility View using JavaScript or HTML? How can I turn on IE 10 Compatibility View programmatically in Javascript or HTML?
I just added the following meta tag within the <head> tag, but it is not working.
<meta http-equiv="x-ua-compatible" content="IE=EmulateIE7" >

Is there any way to do the same thing in JS?

A: You say "I just added the following meta tag within the header tag". Do you mean:

*

*The <header> tag

*The <head> tag?

The x-ua-compatible meta tag does need to go inside the <head> tag, not a <header> tag.

A: I checked the compatibility mode article on msdn - here.
Your meta tag is still the method for enabling compatibility mode in IE 10 and IE 9.
As long as you have:
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
    <!-- Other meta tags etc. -->
<head>

Then it should work. You could try making the http-equiv value  case sensitive (at the moment you've set it to lowercase).
Also, to answer your question about JS, you can detect whether the browser is in compatibility mode by comparing the browser engine with the browser version for IE. However, this involves browser version detection, which tends to be a bit unreliable. Also, there isn't a way for you to set the user's compatibility mode in JS. So, for the moment at least, you'll have to stick with the meta tags.
I hope this helps.

A good plugin to allow you to view http header information is IEhttpheaders. Just download it from that link & install. Then, when you start IE, go to the tools menu and select 'DisplayIEhttpHeaders...'. When you visit your site it will list the header response. If you modify your answer to include the response, then we can see if it's the problem.


text:
Q: check if value is null laravel 5 I'm trying to check if a set of fields, has at least one empty field. If there is empty field and alert should pop, if not it should do something else.
Code
public function updatePerfil() {
    $file = Input::file('imagem');
    $email = Input::get('email');
    $profileData = Input::except('_token');
    $validation = Validator::make($profileData, User::$profileData);
    if ($validation->passes()) {
        $update = Input::only('name','imagem','data_nascimiento');
        if ($file == null || $email == null) {
            User::where('id', Input::get('id'))->update($profileData);
            Session::flash('message', 'Perfil editado com sucesso');
            return view('backend/perfil.index');
        }
        $file = array_get($profileData,'imagem');
        $destinationPath = 'imagens/perfil/';
        $extension = $file->getClientOriginalExtension();
        $filename = Auth::user()->id . '.' . $extension;
        $profileData['imagem'] = $filename;
        Image::make($file)->resize(400, 400)->save($destinationPath.$filename);
        User::where('id', Input::get('id'))->update($profileData);
        Session::flash('message', 'Perfil editado com sucesso');
        return Redirect::to('backend/perfil');
    } else {
        return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
    }
}

public static $profileData = array(
        'email' =>  'email|unique:users',
        'name' =>  'required|min:5|max:25',
        'data_nascimento' => 'date',
        'imagem' => 'image|max:1000|mimes:jpeg,jpg,png'
        );

Form
{!! Form::open(array('class' => 'form-horizontal', 'url' => 'backend/perfil', 'name' => 'updatePerfil', 'role' => 'form', 'files'=> true))!!}

    <input type="hidden" name="id" value="{{Auth::user()->id}}">

            @if (count($errors) > 0)

                    Ups! Existe algum problema com o formulário.

                        @foreach ($errors->all() as $error)

{{ $error }}

                        @endforeach

            @endif

            @if (Session::has('message'))

                    {{ Session::get('message') }}

            @endif

            {!! Form::label('name', 'Utilizador', ['class' => 'label_perfil']) !!}

            {!! Form::text('name', Auth::user()->name, ['class' => 'form-control input-md' , 'placeholder' => 'Utilizador']) !!}

            {!! Form::label('data_nascimento', 'Data de nascimento', ['class' => 'label_perfil']) !!}

            {!! Form::date('data_nascimento', Auth::user()->data_nascimento, ['class' => 'form-control input-md']) !!}

            {!! Form::label('genero', 'Sexo', ['class' => 'label_perfil']) !!}

            {!! Form::select('genero', ['Masculino' => 'Masculino', 'Feminino' => 'Feminino'], Auth::user()->genero, ['class' => 'form-control input-md']) !!}

            {!! Form::label('email', 'Email', ['class' => 'label_perfil']) !!}

            {!! Form::text('email', Auth::user()->email, ['class' => 'form-control input-md', 'placeholder' => 'Email']) !!}

            {!! Form::label('imagem', 'Imagem', ['class' => 'label_perfil']) !!}

            {!! Form::file('imagem', ['class' => 'input-file']) !!}

            {!! Form::submit('Alterar perfil', ['class' => 'btn btn-primary']) !!}

{!! Form::close() !!}

When I try to update the email field without entering anything he actualizame in the database as empty field and I want to continue with what the user does.
With the image works right. I do not know if you are fetching the get. Someone knows how to solve this problem?

A: You can use Validation of Laravel with a bit of laravel magic to check if email is not null, try this:
public function updatePerfil() {
    $profileData = Input::except('_token');
    $validation = Validator::make($profileData, User::$profileData);
    if ($validation->passes()) {
        $update = Input::only('name','imagem','data_nascimiento');
        if(Input::has('email')){
            $update['email'] = Input::get('email');
        }
        User::find(Input::get('id'))->update($update);
        Session::flash('message', 'Perfil editado com sucesso');
        return view('backend/perfil.index');
    } else {
        return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
    }
}

public static $profileData = [
    'email' =>  'sometimes|required|email|unique:users',
    'name' =>  'required|min:5|max:25',
    'data_nascimento' => 'date',
    'imagem' => 'image|max:1000|mimes:jpeg,jpg,png',
    'id'=>'required|integer'
];

Don't forget, $$ is variable of variable in php...
UPDATE
Use this code instead:
public function updatePerfil(Request $request) {
    $rules = [
        'email' =>  'sometimes|required|email|unique:users',
        'name' =>  'required|min:5|max:25',
        'data_nascimento' => 'date',
        'imagem' => 'image|max:1000|mimes:jpeg,jpg,png',
        'id'=>'required|integer'
    ];
    $validation = Validator::make($request->except('_token'), $rules);
    if ($validation->passes()) {
        $update = $request->only('name','data_nascimiento');
        if($request->has('email')){
            $update['email'] = $request->input('email');
        }
        if($request->hasFile('imagem')){
            $file = $request->file('imagem');
            $destinationPath = 'imagens/perfil/';
            $extension =  $request->file('imagem')->getClientOriginalExtension();
            $fileName = Auth::user()->id . '.' . $extension;
            $request->file('imagem')->move($destinationPath, $fileName);
            $update['imagem'] = $fileName;
        }
        User::find($request->input('id'))->update($update);
        Session::flash('message', 'Perfil editado com sucesso');
        return view('backend/perfil.index');
    } else {
        return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
    }
}

A: There is $$email on third line and in the if condition its $email. Please check if its a typo. Apart from this, isset() in php should help with checking with NULL values or to check if a value is set or not.


text:
Q: WebApi Switch Connectionstring related on HeaderValue - Request is null We have different Customers and each of them own a Database.
the client send an Request with an HttpHeader DatabaseOwner:Samsung
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("DatabaseOwner", "Samsung");

In my ApiController i would like that my Context is based on that Value and connects to the correct Database
public class AuthController : ApiController
    {
        public CmpContext db { get; set; }

        public AuthController(): base()
        {

            db = new CmpContext(VcsCmpConnectionstring.GetCMPConnectionString(this.Request));
        }

        // GET api/Auth
        public IQueryable<DealerModel> GetDealer()
        {

            return db.Dealer;
        }

 public static string GetCMPConnectionString(HttpRequestMessage request)
        {

            string returnvalue;

            if (request.Headers.Contains("DatabaseOwner"))
            {
                SqlConnectionStringBuilder ConnStringBuilder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["CMPContext"].ConnectionString);
                ConnStringBuilder.InitialCatalog = "vcs_cmp_" + request.Headers.GetValues("DatabaseOwner").First();
                returnvalue = ConnStringBuilder.ToString();
            }
            else
            {
                throw new MissingFieldException("Header DatabaseOwneris null");
            }

            return returnvalue;
        }

When i try to get this.Request it is always null
When is Request access able or is there a better way to switch between Databases?
Greetings from Bavaria
Patrick

A: Request object is only initialized after APIController's Initialize function is called. So you cannot access Request before base.initialize is called. Try doing this:
public class AuthController : ApiController
    {
        protected override void Initialize(
        System.Web.Http.Controllers.HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            db = new CmpContext(
            VcsCmpConnectionstring.GetCMPConnectionString(this.Request));
        }
    }


text:
Q: Sending Array of Object from SendMessage I have an application which utilises two version of projects one is MFC based and other is win32 based project. For communicating between these two projects I am using SendMessage() with only one input in LPARAM. Is there any way I can send multiple input or array of inputs/object in LPARAM  of SendMessage().
I will write the code if required

A: Use WM_COPYDATA. The documentation also contains a sample.


text:
Q: Centering pie charts with Plotly I already plot this two pie charts on the same plot with plotly. Below you can see code and my data:
suppressPackageStartupMessages(invisible(
                             lapply(c("plotly", "dplyr"), require, character.only = TRUE)))

                           Share <- structure(list(Y = c(2018, 2018, 2019, 2019),
                                                   Categorie = c("Before","After", "Before","After"),
                                                   Share = c(1.0,99., 3, 97)),
                                              row.names = c(NA,-4L), class = c("tbl_df", "tbl", "data.frame"))

p <- plot_ly() %>%
                             add_pie(data=Share, labels = ~Categorie , values = ~Share, hole = 0.6,
                                     name = "fig1", domain = list(x = c(0, 0.4), y = c(0.4, 1))) %>%
                             add_pie(data=Share, labels = ~Categorie , values = ~Share, hole = 0.6,
                                     name = "fig2", domain = list(x = c(0.6, 1), y = c(0.4, 1)))  %>%
                             layout(title = "Donut sub-plots", showlegend = FALSE,
                                    font=list(family="sans serif", color="#000"),
                                    plot_bgcolor="#f0f0f0",
                                    legend = list(orientation = 'h',font=list(size=28)),
                                    xaxis = list(title="", showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
                                    yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
                           p

You can see from plot that both pie chart are in in the upper part of the image.But I want to have two equal pie charts with position of center of the image. So can anybody help me how to do that in plotly ?


text:
Q: gnome-shell high cpu usage with disabled extensions I am aware of the similar sounding question: Ubuntu 18.04 gnome-shell high CPU usage
However my issue is a bit different, since it is not related to the mouse/ clock/animations because I deactivated all of those features and did not move the mouse and still could observe my issue:
If I disable gnome-extensions completely via gnome-tweak-tools the following happens with my idle CPU usage of gnome-shell:

*

*Alt+F2+R: 10%

*Reboot: 0%-2%

Why is there a difference between a reboot and gnome-shell replace?
If I don't disable gnome-extension as such but deactivate every extension the following happens with the idle CPU usage of gnome-shell:

*

*Alt+F2+R: 10%

*Reboot: 10%

Why is there a such a big difference between disabling all extensions and the extension functionality itself?
The CPU usage of gnome-shell is taken when everything was idle (no mouse movement/ no seconds in clock/ no animation)


text:
Q: Mathematical inconsistencies with await Delay () I'm having some trouble with setting a timer.
If this takes approximately 5 seconds:
Delay = (ms) => new Promise(res => setTimeout(res, ms));

showCoins = 0

setTick(() => {
  if (IsControlJustPressed(2, 48)) {
    showCoins = 5
    setTimer()
  }
});

async function setTimer() {
  while (showCoins != 0) {
    await Delay(1000)
    --showCoins
    print(showCoins)
  }
}

Why does this take 01:24 minutes, instead of also 5 seconds?:
Delay = (ms) => new Promise(res => setTimeout(res, ms));

showCoins = 0

setTick(() => {
  if (IsControlJustPressed(2, 48)) {
    showCoins = 5000
    setTimer()
  }
});

async function setTimer() {
  while (showCoins != 0) {
    await Delay(1)
    --showCoins
    print(showCoins)
  }
}

I need the second one because I need something for 4.3 seconds.
And I can't use setTimeout and bools, because if I used it and pressed the key twice it would set to false before the five seconds of the second press had passed.


text:
Q: Usability issue for navigator.geolocation: how to know if the user is being asked for location? Does HTML's navigator.geolocation have an event handler for 'Currently asking the user if they will share their location'?
I would like to show some text instructing the user to share their location if and only if they are actually being asked to share their location.
Currently I have this code, but it's broken.
It looks smooth the first time, but the second time (when the browser knows this is a trusted site, so doesn't ask the user about sharing their location), 'Share your location' flashes up quickly when the page loads, then disappears behind the map.
    // map.js
    function gpsSuccess() {
        // We have a location - although we don't know whether this is
        // because the user has already agreed to share with this domain,
        // or whether they have just this second been asked.
        $('#sharelocation').hide();
        // load map, etc
    }
    if (navigator.geolocation) {
        watchId = navigator.geolocation.watchPosition(gpsSuccess, gpsFail);
    }

    // map.html

Share your location

Any suggestions for a smooth way to give the user some instructions in the body of the page if and only if they are actually being asked to share their location?

A: I'd consider not showing the "Share Location" message unless the failure callback gets executed.
function gpsFail() {
  $('#sharelocation').show();
}

You can include a message in the sharelocation block which explains how to enable location sharing, what you'll do with the information, etc.

A: Sounds like you might just have a timing issue with the brief delay between getCurrentPosition and your callback. What if you delay the show by a second or so? (I don't know what the jquery-specific method is) Keep a reference to the task so in gpsSuccess you can call clearTimeout with it.


text:
Q: I need to move a dived CSS module into the center of the page I'm building a website for someone and they wanted the text and bulk of the information to be centered on the page. Problem is I can get everything contained in a  tag and then assign the class, but I can't get the whole thing to center. It always hangs to the left even if I apply centering to the div class.
I guess you could say that it is stuck on the left side of the page when I want everything to be centered. I would just make everything format larger but they want some space left in the background for the color and maybe some imagery later on. They haven't made up their minds.
If you want to take a look here is the link where I'm building or testing stuff. I know the header and such needs to be re proportioned to fit with everything, but just as a frame of reference. Don't worry about the header, just know that I want the white text information area with the purple border to stay the same size, but just move to the center and if some one could tell me how to do that I would appreciate it greatly.

A: just add margin: 0 auto; to that class CSS, for this to work, that object needs to have a width

A:

About The Book

Mable's Magic Spell Features 28

  of the most commonly misspelled words by children.

Through rhyming, a visual clue, or a word association,

Mable and her dog Mixie take a close look at these words.

Mable's Magic Spell is a book children should read many times.
 Through repetition, children can succeed at spelling these everyday words.

A: For your div set the css margin: auto;


text:
Q: mvc validation message - correct localized on localhost, english on server on my dev pc the message are shown correctly in dutch.
but on the server, all the validaton messages are english ???
to be sure the current culture is 'forced' correctly, i've placed this in my controller:
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("nl-BE")

to check which culture is active, i've placed this in my view:

Culture: @Threading.Thread.CurrentThread.CurrentCulture

my model has following fields:
<Required(ErrorMessage:="BlaBla {0}")>
<StringLength(1)>
Public Property Verkoper As String

<Required()>
<StringLength(1)>
Public Property Herkomst As String

the following is shown in the browser (after submitting an empty form, thus having validation errors for the 'required' attribute.)
on localhost:
Culture: nl-BE
BlaBla Verkoper
Het veld Herkomst is vereist.

this is the correct behaviour. culture is nl-BE and validation messages are dutch.
a special errormessage is used for the 'Verkoper' field, as defined via the data-annotations.
the error message for the 'herkomst' field is shown in dutch, as wanted.
on server:
Culture: nl-BE
BlaBla Verkoper
The Herkomst field is required.

this is NOT correct. the field 'Verkoper' with data-annotations is shown correctly,
but the error message for the 'herkomst' field is shown in english?
what's wrong? can i have the correct validation messages on the server also?

A: You can direct set the Thread culture on the server, like this:
CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("nl-BE");
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;


text:
Q: php - plus one to xml node value I have an XML file held on a server as below.
I then have an HTML file with a button that when pressed must plus one (+1) to one of my XML node values.
Im not too clued up on php so any help would be great.
but i need a simple script that is stored on the server that will take in an html request and add 1 to my chosen XML node value.
<?xml version="1.0" encoding="UTF-8"?>

<object1>
    <value>10</value>
</object1>

<object2>
    <value>6</value>
</object2>

A: Try something like this:
$objectX = "2"; // You get this value with $_POST or $_GET ...
$xmlFileName = 'my.xml'; // You're XML file

$xmlFile = file_get_contents($xmlFileName); // Saving the XML contents in a variable
$objects = new SimpleXMLElement($xmlFile);

$objectX = "object".$objectX; // The object name
$objects->$objectX->value++; // Incrementing the value
$objects->asXML($xmlFileName); // Saving the XML

echo $objects->$objectX->value; // echo the value

You have to add <objects></objects> to your XML file:
<?xml version="1.0" encoding="UTF-8"?>
<objects>
    <object1>
        <value>10</value>
    </object1>
    <object2>
        <value>6</value>
    </object2>
</objects>


text:
Q: How do I make the product image smaller on a WooCommerce product page? The template in WooCommerce for product pages makes my product images huge. I have a portrait-style picture of a book cover on each product page. Is there any way to make the image smaller, not changing the size of the picture itself but its "frame" on the page? I want to change the template.
I have already tried making the picture smaller through Appearance and then Customize. If I make the pixels less, it turns the picture grainy. It doesn't shrink the frame of the picture on the product page.
I have researched free plugins to make pictures smaller, and they optimize photos, not the WooCommerce template.
I read about child themes, but I don't know code.
Is there anyway to override the product page template to shrink the picture?


text:
Q: Can we have a computer with just registers as memory? Registers are the fastest memories in a computer. So if we want to build a computer with just registers and not even caches is it possible? I think of even replacing the magnetic discs with registers although they are naturally volatile memories. Do we have some nonvolatile registers for that use? It would become so fast! I'm just wondering if that could be happen or not?

A: Registers are fast because most of the registers are connected directly to most of the functional units. While a program is loading one register, another register is feeding the ALU and yet another register is writing a result from some other functional unit.
Registers are made with logic elements such as flip-flops, so that most of the values from most of the registers are all available at the same time, all the time. This is different from a memory where only a selected address is available at any one time and only a very limited number of read ports is available. Typically, it's just one read circuit.
However this kind of implementation and interconnection is what uses up the die space on the microprocessor. When that is used up, you start adding memory for additional storage.
There have been architectures with extra banks of registers. (SPARC!)

A: Modern GPUs have about 5MB of registers and very little caches (comparing to CPUs). So yes it is possible to have a processor with lots of registers.
But you still need a memory hierarchy (registers -> scratchpad/caches -> device memory -> CPU memory). Note also that GPUs are completly different beasts in the sense that they are build with massive parallelism goals from day one and that GPUs are not general purpose but coprocessors.
Each GPU thread eats up some registers - the whole GPU program is register allocated - resulting in thousand of threads that can execute/pause/resume in parallel. Threads are used for hiding memory latency on GPUs whereas on CPUs huge caches are used for that purpose. Think of it like Hyper-Threading pushed to the extrem.

A: The problem with that is registers are present inside the cpu. Since its present in the cpu, its having minimum latency. Also because its lesser in size. When you increase the size, say you consider you build one big processor with lot of transistors (flip-flops) that holds the registers, then the heat dissipation, the energy consumption, the cost, etc will be enormous. Also when the space increase, the latency also increases. So basically there isn't much difference in doing so. Its worse actually.

A: The very short answer is yes, you could in theory, but it doesn't really work in real life. Let me explain...
The reason the memory hierarchy exists is because those small and fast memory stores are very expensive per a bit (registers), while the big and slow memory stores are very cheap per a bit (hard drives).
Another reason why huge numbers of registers are highly impractical is because the instructions need to reference the memory location. When you only have a handful of registers, you can store the register (or registers) number and an opcode in a handful of bits, which means that low numbers of registers make for short and fast instructions. If you're going to have a multi-gigabyte collection of registers, you will need to be able to reference them in instructions, and these will be much longer (and therefore slower) instructions. Keep in mind that if everything was a register, some things would be much faster, but by having a smaller number of registers, certain things (i.e., most of what you do with a computer) are much faster.
Having vast numbers of registers would also add a great amount of complexity to the hardware which processes the reading and writing to registers, which would make everything slower.
Of course, while most of us think in terms of computers, there are surely simple devices which do only have registers, but they would also only have a very limited amount of memory, and aren't made for general purpose computation.
You may also be interested to my answer to Assembly: Why are we bothering with registers?

A: for each register of 32 bit you need at least 9x32 gates of xor. that is a lot of gates.
the bigger problem comes when you want the register data to pass over the bus. which one will hold the bass? you want to add more bass?
lets say we have 10 register, do we do a 10 line bus? meaning we have 10 bus connectors which connects to most of the system? that is a lot of wireing, now you want the register to mean somthing right?
lets just hink how much bass we need for 1kb of data?
1024 bit = 1024*9*32 gates and 1024 bass lines in the cpu.
we know intel is working with 30 nm for one gate.
thats 30 million gates , which the gate problem more redandent, but how do you intend to solve the bass problem?

A: Most of these answers address whether it would be practical.  David Johnstone's also mentions the fact that a register name needs to be mentioned in each instruction that touches it.  Further to this, in most modern instruction sets an instruction always has its operand registers coded in it.  E.g. there's the mov %eax, %ebx instruction, and there's the mov %eax, %ecx instruction.  It may so happen that their binary representation appears to look like:
| mov | source reg | dest reg |
|  2  |     3      |     3    |

and differs only in that dest reg is equal to 3 rather than 2 -- but it also may not!  (I haven't checked how these particular instructions are represented in 386, but I recall there are examples in that instruction set of instructions easily broken down into fields like this, and examples where they aren't.)
The problem is that most interesting programs are going to want to operate on locations of information, determined at runtime.  E.g. in this iteration of the loop, we want to look at byte 37; the next iteration we will be interested in byte 38, etc.
I won't prove it but I suspect that in order to get anything approaching Turing completeness, your programs would need either:

*

*instructions that address registers based on the value in some other register, e.g. "Move from register X to register Y where X and Y are indicated by the values in registers 1 and 2.", or

*self modifying code.

At school we had a theoretical computer with 100 registers (plus accumulator), and 10 instructions, each of which was a three digit decimal number.  The first digit indicated the operation (load, save, arithmetical, jump, conditional jump, halt), and the last two the register to operate on.  Many sample programs could be written for this, like the factorial function.  But it soon became apparent that a static program could only operate on a fixed set of data.  If you wanted to write a loop to sum the values in a list, you would need a LOAD instruction that pointed to a different input register on each iteration.  This meant you would arithmetically calculate the new code for the load instruction each time, and patch the code just prior to running that instruction.

A: You don't need even registers - it's possible to create something like Turing machine that takes stream of input code and data and produces output stream. This is something like what computers started with.

A: It is possible, but utterly impractical - even low-end computers today have 2 gigabytes of RAM. How would you handle two billion registers in code (and where would you stuff them, physically)?
Also, what would you do with it, that the speed of RAM (and even processor caches) is a concern? Either run the system off RAM (fast enough), or build a special-purpose processor.

A: Hot off the rouncer hardware theory plate->
If you manage to link every permutation of the address bits, to the individual words - then you could have a ram register system.      imagine if you use nand to make the address groups. (in other words link the opposite of the address to the flop)  One not,  and youve done the addressing with wires alone + the little not switch,  which could be a solenoid type coil which will not the value.   then every register ors into the same output - the content pins.  And only the address that was past, will get power to the output content pins.
simples.

A: The reason you get so little register memory is because it is incredibly expensive. This is why we have the memory hierarchy.


text:
Q: Why use both Dovecot and Postfix? Just out of curiosity, there are dozens / hundreds of tutorials helping you setup a dovecot - postfix mail server. On the surface, both of them are email servers, why use both? Mail servers are complicated enough, why have 2 things to manage and troubleshoot?
Makes about as much sense on the surface as running CentOS inside Ubuntu and always wondering why ./configure is confused :)
http://www.dovecot.org/

Dovecot is an open source IMAP and POP3 email server for
  Linux/UNIX-like systems, written with security primarily in mind.
  Dovecot is an excellent choice for both small and large installations.
  It's fast, simple to set up, requires no special administration and it
  uses very little memory.

http://www.postfix.org/

What is Postfix? It is Wietse Venema's mail server that started life
  at IBM research as an alternative to the widely-used Sendmail program.
  Now at Google, Wietse continues to support Postfix.

I followed one of those many guides and got it all working with TLS authentication to Postfix and ISPConfig, then realized at the end that I really never had to touch Dovecot, but wasn't sure if it had to be there for the spam filters, antivirus or some other thing I am not thinking of.

A: Postfix and Dovecot do different things.
Postfix is an MTA, or Mail Transfer Agent.
It accepts mail from the outside world and from local sources, and routes it to its destination. This may involve an smtp connection to another machine, or it may involve delivering it to a local delivery agent or writing it directly to an mbox. When an MTA goes wrong, things get ugly; your machine may be used to bounce huge amounts of spam, for instance.
However, because of the way that our email system works, an MTA has to interact constantly with both legitimate and unwanted mail sources.
Dovecot is mailbox interface software.
Specifically, it allows users to access their mailboxes using the IMAP interface. If configured correctly, it only interacts with authenticated users. This means that in general, dovecot doesn't have to "talk to the bad guys."
The view from 50,000 feet: Postfix "knows about" SMTP. Dovecot "knows about" IMAP.
(Yes, Postfix can use Dovecot to perform authentication, and Dovecot's LDA to put mail in mboxes, so there's definitely more to the story.)

A: Postfix just concerns itself with sending off client emails and temporarily storing incoming emails without sorting them according to recipient email address.
Dovecote's principal task is sorting the emails received by the mail transfer agent (MTA), e.g. Postfix, and delivering them on demand by each recipient. It separates the mass of emails arriving to Postfix's single mailbox into individual mail boxes for each recipient address and simultaneously listens for requests for new email from recipients' email client packages, e.g. Outlook or Thunderbird.
The reason Linux systems have this separation of responsibilities may be related to the historical development of both Unix and email. The early adopters of email - and this was before the internet - were large organizations with existing (and labor intensive) internal post systems. Yes, universities and government departments used to have their own post rooms, postmen and delivery cycles up to the 1980s at least.
MTAs of the 1980s could effect immediate email delivery when operating on a local network that each client was always connected to: there was no need to store undelivered emails for later delivery - they were transferred to the recipient's email Inbox in his/her user's filespace.  That was also in the days of Unix being an op system for mainframe servers to individual users' terminals. As soon as a user logged into a terminal of the organization's mainframe, they saw a new mail message on their monitor.
With PCs getting more powerful and remote network connecting of info systems becoming possible, there began an evolution of email into a means of communication between people separated by long distances. Network connections then were via phone lines so they could not afford to remain switched on at all times. Hence the need to store emails undeliverable at an arbitrary time owing to the likely absence of a recipient from their workstation. Thus happened the birth of dedicated web/email/data/application server machines that were always connected to an external network and client machines (i.e. desktops and laptops) that only connected externally on occasions they needed data from a server.
In the meantime Unix had morphed from a mainframe op system feeding terminals from a server to an integrated standalone op system for PCs - although Unix was usually an alternative op sys to MS-DOS/Windows, Mac OS, OS1, OS2. Yet Unix's inherent serving capabilities made it a good choice for web server machines. The early 1990s saw the entry of a free open source op system, Linux, that was modelled on Unix. Linux soon became the preferred op system in web server machines as many people contributed kernel and application code to it and since it cost nothing; it was eventually felt to be even a better op system than Unix.
The Sendmail MTA is around since 1983 when it replaced the Delivermail package used by the ARPANET to communicate between various parts of the US Dept of Defense. With widening consumer use of email after the internet became available, people started using different email addresses for work, home and leisure arenas. All this led to a need by PC users to deliver from the server separately all emails to all their addresses - a mail delivery agent (MDA) package. Sendmail remained focused on improving transfer of email on Unix and Unix's free displacer op system, Linux servers. To create an integrated transfer/delivery mail agent would take a huge amount of time from the open source community that had already provided Sendmail and then its superseder, Postfix. It made much more sense to simply write a basic mail delivery agent that bolted on to proven MTAs like Sendmail or Postfix. And that's what happened. Dovecot and other MDAs were developed to work with existing MTAs and their output directories' contents became the input for the MDA.
While many of us trying to configure mail on a VPS might find it gauche to be dealing with both an MTA and an MDA plus various other things to enable spam filtering, web mail access, etc, we have to recall that we are getting so much for free in all this. That some compromises need to be made for the sake of easier development or more reliable mail service is something that we ought to manfully accept sometimes.
Unless you want us all to go back to Microsoft Exchange Server and Outlook . . . Anyway just look inside MS Exchange Server and you will doubtless see separate modules for mail transfer, mail proxying, spam elimination, delivery and so on. The principles of building a good software system won't change when you choose a new supplier: separation of concerns enables simultaneous development of various packages within the system as long as their interfaces remain fixed; it also allows for easier bug tracking.
At least with Linux you can choose different individual or combinations of mail server packages depending on your needs and preferences. Then you can immediately "go configure" each of the component packages.