text:
Q: Why is SystemModStamp missing updates? I'm a bit of a beginner with Salesforce (speciality is SQL and datawarehousing).  For the last few months I've been looking after an ETL process which pulls data out of SagePeople Cloud (which, confusingly, seems to be Salesforce inside the box).
Method is SSIS (SQL Integration Services) packages, using the Cozyroc Salesforce Source SSIS component.  The loads are deltas, so I want to get "all rows updated since [a date time]".  The component has an ObjectFilter property, which I set at runtime to
SystemModStamp>=[a date, e.g. 2020-06-30T23:00:00Z]

I've already worked out that:

*

*SystemModStamp is better than LastModifiedDate.  The former can get updated by some updates, which leave LastModifiedDate untouched.

*Internally, both these are what I (in SQL world) would call a datetimeoffset: an unambiguous date/time with a specified timezone, which can be expressed in different ways but always means the same time.  For example, the date/time above is actually midnight at the start of 1st July UK (summer) time (or 2020-07-01T00:00:00+01:00).  But when the data comes through, both are translated to UK time without any timezone information - presumably because my user is set up as located in the UK.

The date parameter passed for each delta load execution is the date/time at which the last (successful) execution of this same load sent its SOQL to Salesforce to get the data (I save this in a variable, from SQL GETUTCDATE()) - less a safety margin, which I initially set to 5 minutes.  To save confusion all these date/times are saved as datetimeoffsets at timezone Z.  Logs show that this is working correctly:
Execution 1 started talking to Salesforce at 2020-07-07T06:00:00Z
Execution 2 used date parameter 2020-07-07T05:55:00Z, and started its execution at 2020-07-07T09:00:00Z
Execution 3 used date parameter 2020-07-07T08:55:00Z.... and so on.
The problem is: the delta loads are missing updates.  New delta load runs 3-hourly.  I'm comparing to the old delta load system, which runs daily, and takes the last 2 days of updates (actually last midnight before now, rolled back 2 days: lastmodifieddate = LAST_N_DAYS:2).  That system is picking up updates - different column values - which the new system is missing: in every case, the LastModifiedDate and SystemModStamp in the pulled ETL data (old vs new) are identical, but the old system is correct (matches the current state of Salesforce).
There seem to be two types of problem cases:

*

*Rows created or updated almost exactly when a delta load starts.  e.g. at 09:00:15.  I can see how a load starting at 09:00:00 might miss these.  But why are they not picked up by the next load, which winds back to 08:55?

*Rows created/updated at other times (according to SystemModStamp/LastModifiedDate).

The solution to (1) might be to wind back 10 or 15 minutes rather than 5.  Something to do with long-running transactions inside Salesforce?  How long should be allowed for these?
(2) is more mysterious.  What I suspect is this:

*

*A row gets updated at 08:00.  SystemModStamp set, all good

*New delta load picks it up at 09:00.  All good

*Old delta load, much later (at 02:00 the following morning) also picks it up.  But it picks up other updates to the row that have happened since 08:00, but haven't updated SystemModStamp.  Some process inside Salesforce is "cheating", and updating things without setting SystemModStamp.

The only clue I have is that the columns with differences are mostly what I'd call "computed" columns: things like Months_Since_[employee]Start, which might be automatically updated in bulk periodically, rather than being instantly calculated like true computed columns.  But some other columns with fewer differences aren't of this kind: e.g. Email, Gender, Postcode.
There might be something wrong with my date logic (though from the logs, I doubt it).  The worrying possibility is that actually SystemModStamp is not reliable for getting deltas out of Salesforce, because some processes don't update it.  Can anyone comment on this?  Thanks!

A: If you want true replication, use the getUpdated and getDeleted API calls. They come in both REST and SOAP flavors. They provide a latestDateCovered attribute that you can use to start the next delta check. Unlike using SOQL, you can guarantee that you'll get the correct delta every time, as long as you use the one attribute provided.
Depending on how you wrote your query, your SystemModStamp deal could miss records, including situations where you set a cap on the upper end as well as the lower end. For example, the SystemModStamp can be off by a few seconds, or may not be updated until after you do your query, etc.
In short, Replication Is Hard. The Replication APIs are specifically designed to make a best effort to ensure that no records are ever missed, no matter what crazy things might be going on in the background. If you have the ability to use them, you should do so. Details are in the relevant documentation (SOAP and REST API docs). Note that this API also gives you deletions, which a SOQL can't do reliably.


text:
Q: How to use specific iOS version on Azure hosted agent? I have a requirement to use exactly iOS 14.5 on our pipeline.
I tried the following:
variables:
  sdk: 'iphoneos14.5' // I also tried to iphoneos

- task: Xcode@5
  inputs:
    actions: 'test'
    configuration: '$(configuration)'
    sdk: '$(sdk)'
    xcWorkspacePath: 'MyProject.xcworkspace'
    scheme: '$(secondaryScheme)'
    xcodeVersion: 'specifyPath'
    xcodeDeveloperDir: '/Applications/Xcode_13.2.1.app'
    packageApp: false
    destinationPlatformOption: 'iOS'
    destinationSimulators: 'iPhone 11,OS=14.5'
    args: '-derivedDataPath $(agent.buildDirectory)/DerivedData'

But both runs failed with
xcodebuild: error: SDK "iphoneos14.5" cannot be located.
##[error]Error: /usr/bin/xcodebuild failed with return code: 64

And
xcodebuild: error: Unable to find a destination matching the provided destination specifier:
        { platform:iOS Simulator, OS:14.5, name:iPhone 11 }

That's what I understood from reading the preinstalled software documentation. https://github.com/actions/virtual-environments/blob/main/images/macos/macos-11-Readme.md
Grateful if you could tell me what I am doing wrong

A: By using your pipeline definition, I am able to reproduce your issue.

I think below YAML file will help you understand why the official document said 'iOS 14.5' is supported but you can't use it.
pool:
  name: Azure Pipelines
#Your build pipeline references an undefined variable named 'secondaryScheme'. Create or edit the build pipeline for this YAML file, define the variable on the Variables tab. See https://go.microsoft.com/fwlink/?linkid=865972

steps:
- script: |
   xcodebuild -showsdks

   echo "========================================================="

   sudo xcode-select -switch /Applications/Xcode_12.5.1.app/Contents/Developer

   xcodebuild -showsdks
  displayName: 'Command Line Script'

When you see the result of the pipeline run, I believe you will understand everything:

After switching the version, you should be able to use the specific IOS version you want.
Reference: https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution/customizing_the_notarization_workflow

You upload your app for notarization using notarytool command line
tool. Xcode 13 or later supports this tool, so if you have more than
one version of Xcode installed on your Mac, be sure to use the
xcode-select utility to choose an appropriate version:
% sudo xcode-select -s /path/to/Xcode13.app

A: Added this step
gem install xcode-install
xcversion simulators --install='iOS 13.5'

If someone finds a way to use the installed sdk for other Xcode, please comment here

redpajama_set_name: RedPajamaStackExchange


text:
Q: prevent enter on submit button only, not the rest of the form ok, so i've been searching for a piece of code that does this, and nothing applies to my situation.
My Problem: i'm trying to prevent the form from submitting when the "ENTER" key is pressed but allowing the my search script thats inside the form to submit when the enter key is pressed.
What i've found are scripts that prevent the Enter key period, or the script doesn't work because i think i'm using a <button> instead of a <input> as my submit button, i'm not really sure.
my form
<form action="" method="post" onsubmit="return false;" id="myform">

my javascript that does my search
    function showSub(str) {
    var xmlhttp;
    if (str=="") {
      document.getElementById("txtSub").innerHTML="";
      return;
    }
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("txtSub").innerHTML=xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET","findLogo.php?q="+encodeURIComponent(str),true);
    xmlhttp.send();
}
$(document).on('change', '#searchText', function() {
// Get the search text
var searchText = $(this).val();
// Make sure it isn't empty
    if (searchText.length > 0) {
        // Send the update request
        showSub(searchText);
    }
});

my search input
<input type="text" id="searchText" value="" />

my submit button
<input type="hidden" value="Post" name="submit" />
<button type="submit" style="height:33px; width:50px">

</button>

my java-script post submit script


text:
Q: Как выполнить умножение и указать результат в input? Всем привет!
У меня есть два <input>-а. В один я ввожу цифру, во втором должен показывается результат умножения или деления этой цифры на заранее заданное число.
Как можно организовать динамический пересчёт прямо во время набора текста, без нажатия на какие-либо GUI-кнопки?

A:

(function($) {
  $(function() {
    var argument = $('input[name="argument"]')
      , result = $('input[name="result"]')
      , multiplier = 4;
    argument.on('input', function() {
      result.val($(this).val() * multiplier);
    });
  });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="argument"/>
<input type="number" name="result"/>

A: Вариант на чистом Javascript:

const input = document.getElementById("inpt");
const inputResult = document.getElementById("res");

input.addEventListener("keyup", function() {
inputResult.value = input.value *4;
})
<input type="number" name="argument"/ id="inpt">
<input type="number" id="res" name="result"/>

Вариан с JQuery:

$('#inpt').on('keyup', () => {
  $('#res').val($('#inpt').val()*4);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="number" name="argument"/ id="inpt">
<input type="number" id="res" name="result"/>


text:
Q: unmappable character for encoding ASCII What is the error  error: unmappable character for encoding ASCII. The code is:
outputWord = newWord + "ag' ,r";

A: Your ' character is not supported by ASCII. If you need just an apostrophe, use ' instead. If you need that character, you can use the Unicode escape code for it, for example \u00a9 is the copyright symbol. You'll have to find the correct Unicode code for that special character.


text:
Q: Помогите доделать переключатель света Мне нужно это зациклить (0n/off) и по кругу

$(document).ready(function() {

  $(function() {
    $('#img').click(function() {
      $('body').css('background', 'black');
      $('p').html('
off
');
      $('p').css('color', 'white');
      $('#img').replaceWith('');

    });
  });

});

On

A:

$('.switch').on('click', function() {
  $(this).toggleClass('switch-off');
  $('body').toggleClass('body-off');
});
.switch {
  background: green;
  width: 100px;
  height: 100px;
  color: #fff;
  text-align: center;
  line-height: 100px;
  cursor: pointer;
}

.switch .off,
.switch-off .on {
  display: none;
}

.switch-off {
  background: red;
}

.switch-off .off {
  display: block;
}

.body-off {
  background: #000;
}

  On
  Off


text:
Q: ergodicity in $\mathbb{Z}^d$ Fix $d \geq 1$ and let $E(\mathbb{Z}^d)$ denote the set of all edges of the graph $\mathbb{Z}^d$. Let us consider a measure
preserving system $(\mathbb{R}^{E(\mathbb{Z}^d)}, B^{E(\mathbb{Z}^d)}_\mathbb{R}, \mu, T)$ where $\mu$ is the product measure that makes the coordinate maps
$X_{e'} ((\omega_e)_{e\in E(\mathbb{Z}^d)}) := \omega_{e'}$
i.i.d. random variables and $T((\omega_e)_{e \in E(\mathbb{Z}^d)} = (\omega_{e+})_{e \in E(\mathbb{Z}^d)}$
, where $e = (x, y)$ then $e_+ = (x + (1, 0, . . . , 0), y + (1, 0, . . . , 0))$ be the edge which can be obtained by translating the
endpoints of $e (x \ \text{and} \ y)$ by unit length in the first coordinate direction. Show that $T$ is ergodic.
[ Hint: It is enough to show that if $A$ is invariant, then $P(A) = P(A)^2$. Now any set $A \in B^{E(\mathbb{Z}^d)}_\mathbb{R})$
can be approximated by some cylinder set $B \in \sigma(X_e : e \in K)$ where $K$ is a finite subset of edges. Note that $B$ and $T^{−n}(B)$ are independent for sufficiently large $n$.]
I understand that the idea here is to show that for an invariant set $A$, $P(A) = 0 \ \text{or} \ 1$ but am not able to connect to the hint to solve it.

A: Hint: Show that for any two cylinder sets $A$ and $B$ we have $\mu(T^{-n}A\cap B)=\mu(A)\mu(B)$ for any sufficiently large $n$. This readily implies that $\mu$ is ergodic.
Added later: As you say yourself, $B$ and $T^{-n}B$ are "independent" for $n$ sufficient large. This is a particular case of what I suggested above when $A=B$, that is,  $$\mu(T^{-n}B\cap B)=\mu(B)^2.$$ Now, if $T^{-1}B=B$, then this identity gives $\mu(B)=\mu(B)^2,$ that is, $$\mu(B)(\mu(B)-1)=0$$ and so either $\mu(B)=0$ or $\mu(B)=1$.


text:
Q: Как обратиться из виртуальной машины vagrant к моей локальной машине, на которой запускается vagrant ОС: Windows 10
Запускаю бекенд проекта в vagrant машине, а фронтенд - локально.
Делаю так, что бы при разработке фронтенда работал live reload. Т.к. если запускать фронтенд внутри vagrant - то система не видит производимых изменений.
Так вот. Как мне из vagrant обратиться по IP к моей локальной машине?

A: Обращайся по ip-адресу компьютера в локальной сети.

A: Да, прошу прощение. Проблема как оказалась была не в vagrant'е и здесь действительно было достаточно обратиться по IP машины. Дело было в принимающем сервере, он отклонял запросы и мне казалось, что я не могут обратиться из vagrant к своей машине.


text:
Q: update entity using java script and symfony2 I ask if there are any way to update an entity using javascript and symfony2.
when clicking on a button, a function in javascript should be called to update the entity in database
I use symfony 2.6

A: This is called Ajax. Javascript code sends a request (POST/GET/PUT) to an URL (Managed by Symfony), which can answer.
Communication between Javascript and Server is generally done using POST, and data sent back is generally done in XML/HTML or JSON.
There are plenty of tutorial and documentation, for example:
http://api.jquery.com/jquery.ajax/
You can also look at REST, that defines common API on the Server side. There is a module that helps defining this interface with Symfony:
http://symfony.com/doc/current/bundles/FOSRestBundle/index.html


text:
Q: Is it possible to control capslock light without actual capslocking? I am using windows on my laptop. I also remapped caps lock to esc for smoother vim experience.
Now my caps lock light indicator is always off and I start wondering "Is it possible to use caps lock indicator for something else?". Something like blinking on request etc.
I never did something like that so I have very basic questions:
Can light indicator be separately turned on\off without actual caps lock functionality?

A: Unless your keyboard has its own API to control the lights (gaming keyboards sometimes do), or you have a custom keyboard driver that can control the lights, then what you are asking for is generally not possible with most keyboards, as Windows simply has no API to control just a keyboard's lights without also updating its key states.
UPDATE:
Apparently, there is such an API, after all:
IOCTL_KEYBOARD_QUERY_INDICATORS IOCTL

The IOCTL_KEYBOARD_QUERY_INDICATORS request returns information about the keyboard indicators.

IOCTL_KEYBOARD_SET_INDICATORS IOCTL

The IOCTL_KEYBOARD_SET_INDICATORS request sets the keyboard indicators.

You can use DefineDosDevice() and CreateFile() to open a HANDLE to the desired keyboard, and then use DeviceIoControl() to query the keyboard for its current KEYBOARD_INDICATOR_PARAMETERS, and then update its LedFlags field to include or omit the KEYBOARD_CAPS_LOCK_ON flag to turn the CapLock key's LED light on/off as needed.
See Manipulating the Keyboard Lights in Windows NT for an example.


text:
Q: How can i rotate an image on matlab without getting the black background Checking https://www.mathworks.com/help/matlab/matlab_prog/run-sections-of-programs.html i can use imrotate but i will get an image with a black background like this:

and i want an image more like this:

basically, i don't want to add any black or white pixels or any pixels at all i just want my image to rotate without any additional background.
Kindly note that when i display the second image on matlab it also shows with black background and a bunch of 0 pixels

A: I think you could use
J = imrotate(I,angle,method,'loose')
To save in J the full image (containing the 0 pixels at the border).
Then using rgb2ind (https://it.mathworks.com/help/matlab/ref/rgb2ind.html) or bwconncomp (https://www.mathworks.com/help/images/ref/bwconncomp.html) you can identify the connected components which enclose the image (there should be 4): in this way you can change the color of those pixels in white
To avoid having 4 components you could firstly add one black rectangle yourself, so that the image J will be completely enclosed by black pixels


text:
Q: why analytics.js made pageview go down so much? my old ga.js code is:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-1']);
_gaq.push(['_setDomainName', 'mywebsite.com']);
_gaq.push(['_trackPageview']);

(function(){
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

after I upgrade to new analytics.js code like this:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXX-1', 'auto');
ga('send', 'pageview');

I notice that my pageview is decreasing about 30% ~ 50%,
and bounce rate is increasing about 130%
the obvious difference syntax between old and new is:
_gaq.push(['_setDomainName', 'mywebsite.com']);

as far as I know, actually there is no sub domain site,
I guess maybe the old analytics data is incorrect,
and the new analytics data is correct?
is there anyone can explain why the analytics data change so big?
or what am I doing wrong with?


text:
Q: Is This sequence unbounded or not? I want to check if $x_n=n(\sqrt{n+1} - \sqrt{n})$ is unbounded or not.
I tried this way. Please, tell me if it is correct or not:
I want to prove that $\forall M>0$, $\exists n>n_0$, such that $x_n > M$. So, let be $M>0$.
$x_n > M \Rightarrow n(\sqrt{n+1} - \sqrt{n}) > M \Rightarrow n^2(n+1 - 2\sqrt{n^2+n} + n) > M^2 \Rightarrow n^2(2n +1) >M^2$. Since $4n>(2n+1),  \forall n \in \mathbb N$, I can go ahead and writ out:
$n^2.4n>M^2$
$ n> \sqrt[3]{\frac{M^2}{4}}$.
Since I managed to find an "n" for the given $M>0$, it follows that $(x_n)$ is unbounded. Correct?

A: You seem to prove that "if $x_n>M$, then ...", but that is not what you need.
HINT:
$$ x_n=n(\sqrt{n+1}-\sqrt n)= n\frac{(\sqrt{n+1}-\sqrt n)(\sqrt{n+1}+\sqrt n)}{\sqrt{n+1}+\sqrt n}=n\frac{1}{\sqrt{n+1}+\sqrt n}>n\frac{1}{2\sqrt{n+1}}=\frac12\left(\sqrt{n+1}-\frac1{\sqrt{n+1}}\right)$$

A: Specifically in answer to the question, the proposed proof is incorrect.  It suggests that if $n>M^{2/3}4^{-1/3}$, then $x_n>M$.  But looking at Hagen von Eitzen's hint, for $n$ of this size, $x_n$ is approximately $\frac{1}{2} M^{1/3} 4^{-1/6}$, which is less than $M$.


text:
Q: Polynomial chaos expansion and ODEs I originally asked this question on stats.SE but I didn't even get a handful of views. So I figured that here is probably a more appropriate site to ask. I am trying to figure out how to use PCE to quantify uncertainty in solutions of ODEs.
So if I understand correctly the main idea of PCE is that we have a random variable $X$, whose distribution we do not know, and we consider this as a function of the random variable $\Xi$, whose distribution we know.
Then we write this function in an orthogonal polynomial basis $\psi_j$ to get
$$ X = \sum_{j\ge0}x_j \psi_j(\Xi). $$
There are some things regarding this expansion that people do not really explain. For example when does this thing converge? I couldn't find anything explicit on that. But my bigger problem is what happens when we multiply such series. But I will come to this in a moment.
So I am trying to understand how to use this in the setting of dynamics. I am trying to solve an example that is clearly (I think) non-trivial but it is hopefully still relatively simple.
Let's consider the dynamical system:
$$\begin{align}
\dot x &= x + y - x(x^2+y^2) \\
\dot y &= -x + y - y(x^2+y^2).
\end{align}$$
This is the standard example of a limit cycle. The origin is an unstable equilibrium and the circle centered at the origin with radius $1$ is a stable periodic orbit, which is the global attractor for the system.
So my goal is to describe the evolution of this system when the initial point is $(10,0)+Z$, where $Z$ is random variable drawn from a bivariate normal distribution with identity as covariance matrix.
My expectation was the following:
We can write the (now) random variables $X(t)$ and $Y(t)$ as
$$\begin{align}
X(t) &= \sum_{j\ge0}x_j(t) \psi_j(\Xi) \\
Y(t) &= \sum_{j\ge0}y_j(t) \psi_j(\Xi).
\end{align}$$
Then we can substitute into the ODE, collect terms and then get ODE equations for the coefficients $x_j(t)$ and $y_j(t)$. Truncate the series, plug the equations in a solver and get numerical solutions.
However, I got stuck almost immediately with this because I do not know how to deal with products of PCEs. For example
$$ X^2 = \left(\sum_{j\ge0}x_j(t) \psi_j(\Xi)\right)^2. $$
has no obvious way of grouping elements. One could circumvent this problem by adding a dummy variable $\varepsilon$ and collect terms with respect to it
$$ X^2 = \left(\sum_{j\ge0}x_j(t) \psi_j(\Xi) \varepsilon^j \right)^2 = \sum_{j\ge0}\sum_{i=0}^j x_i(t)\,x_{j-i}(t)\,\psi_i(\Xi) \,\psi_{j-i}(\Xi)\, \varepsilon^j  . $$
However this does not really solve my problem because in order to get the $k$-th coefficient we have to project on $\psi_k$ so we have to compute something like
$$\langle \psi_i \,\psi_{j-i},\psi_k \rangle,$$
Which is not $0$ in general. In this case the equations are up to third degree, so brute force could potentially work, however it is definitely something that cannot work in general.
So is there any general way to get the ODEs for the coefficients? How are this problems dealt with in general? Is there any book on these things aimed to mathematicians?


text:
Q: File Upload - Allert if occurred error without submit I have multiple upload script and I will implement it to file with bigger html formwhich shoud be fill before submit. I need to allert error if selected file is more then written megabytes or type is wrong without submit.
P.S It would be nice if you tell me how to upload file with button and do not submit bigger form.
 Here is my code:

var abc = 0; //Declaring and defining global increement variable

$(document).ready(function() {

//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() {
        $(this).before($("
", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
                $("

")
                ));
    });

//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
            if (this.files && this.files[0]) {
                 abc += 1; //increementing global variable by 1

    var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("

");

       var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);

       $(this).hide();
                $("#abcd"+ abc).append($("", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().parent().remove();
                }));
            }
        });

//To preview image
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };

    $('#upload').click(function(e) {
        var name = $(":file").val();
        if (!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }
    });
});
@import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form{
    background-color:white;
}
#maindiv{
    width:960px;
    margin:10px auto;
    padding:10px;
    font-family: 'Droid Sans', sans-serif;
}
#formdiv{
    width:500px;
    float:left;
    text-align: center;
}
form{
    padding: 40px 20px;
    box-shadow: 0px 0px 10px;
    border-radius: 2px;
}
h2{
    margin-left: 30px;
}
.upload{
    background-color:#ff0000;
    border:1px solid #ff0000;
    color:#fff;
    border-radius:5px;
    padding:10px;
    text-shadow:1px 1px 0px green;
    box-shadow: 2px 2px 15px rgba(0,0,0, .75);
}
.upload:hover{
    cursor:pointer;
    background:#c20b0b;
    border:1px solid #c20b0b;
    box-shadow: 0px 0px 5px rgba(0,0,0, .75);
}
#file{
    color:green;
    padding:5px; border:1px dashed #123456;
    background-color: #f9ffe5;
}
#upload{
    margin-left: 45px;
}

#noerror{
    color:green;
    text-align: left;
}
#error{
    color:red;
    text-align: left;
}

.abcd{
    text-align: center;
}

b{
    color:red;
}
#formget{
    float:right;

}

                <form action = "" enctype="multipart/form-data" action="" method="post">

<input name="file[]" type="file" id="file"/>

     <input type="text" required >
                    <input type="button" id="add_more" class="upload" value="Add More Files"/>
                    <input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
                </form>

                <?php include "upload.php"; ?>

And my php file:
<?php
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png", "pdf");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array

      if (($_FILES["file"]["size"][$i] < 4194304) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').Image uploaded successfully!.

';
            } else {//if file was not moved.
                echo $j. ').please try again!.

';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').***Invalid file Size or Type***

';
        }
    }}?>

A: using jquery and html5

<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />

A: Try something like this u will get
$("#aFile_upload").on("change", function (e) {

    var count=1;
    var files = e.currentTarget.files; // puts all files into an array

    // call them as such; files[0].size will get you the file size of the 0th file
    for (var x in files) {

        var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB

        if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {

            if (count > 1) {

                approvedHTML += ", "+files[x].name;
            }
            else {

                approvedHTML += files[x].name;
            }

            count++;
        }
    }
});

$("#approvedFiles").val(approvedHTML);


text:
Q: How to prevent printing error message 401 (Unauthorized) in console? When the user does not enter the correct credentials the following error appears.

I am already treating the error and do not want this to print out to the debug window.
My code:
-------------auth.service.ts-------------

 login(user: User) {

    return this.http.post(this.config.getBaseUrl()+'oauth/token', user, this.config.getHeader())
      .map(res => res.json());

  }

-------------login.component.ts-------------

login() {
    this.authService.login(this.user).subscribe(
            result => console.log(result),
            error => console.log(error)
    );

How can I prevent this error from printing out?

A: This is not something angular do. It is  a functionality of the browser. you cannot remove it by changing your client side code.


text:
Q: Paywall causing large CLS values - any way to distinguish full view vs paywall views We've had a large jump in CLS values in some of our pages with some values at 1. I ran lighthouse tests and discovered that when a user hits a page with a paywall, the resulting modal is causing this issue. When a logged in user hits the same page in a lighthouse test, the CLS value is very low - below 0.1.
Is there any work around for this? Is there any way to distinguish when a user hits a paywall in the google search console? Any suggestions for how this could be handled differently either in react or on the server side to avoid this issue?


text:
Q: How click an icon to open a video? The effect I aim to produce can be witnessed by downloading and opening the PDF at the link below.
https://www.dropbox.com/s/8sl9ymcqlr5tfdq/AcroReaderMediaIcons.pdf?dl=0
As you can see if you download it, clicking the orange 'film' icon opens a window for showing a video clip. But you must download it and run it locally for this to work since the legacy media that it uses is now blocked in browsers for security reasons, and that's one of the problems I'm hoping LaTeX will solve for me. (The other problem is that my current workflow of rebuilding PDFs from MS Word requires laboriously re-entering all my numerous videos and their parameters individually.)
One strategy I'm experimenting with is to use the orange icon as poster text, by means of code like that just below. (Notice that it uses VideoPlayer.swf instead of VPlayer.swf since that makes the video play right away, at least with this code.)
\documentclass{article}
\usepackage{media9}
\begin{document}

\includemedia[
    label=firsttry,
%    width=0.4\linewidth,
%    height=0.3\linewidth,
    addresource=40631.mp4,
    windowed,
    noplaybutton,
    activate=onclick,
%    scale=2.5,
   flashvars={source=40631.mp4}
  ]{\includegraphics[width=32px,height=32px]{filmicon32x32.png}}{VideoPlayer.swf}

\end{document}

The MP4 file, orange film icon, and resulting PDF can be found here:
https://www.dropbox.com/sh/nyja912q7zh6xkd/AAD7fP-6F6Cg7TmCBNszWI4Ka?dl=0
The problem with the above code, and variants which reinstate the commented-out lines, is that the sizes of the poster and the video itself are linked. If I don't specify the width and height of the video, I get a tiny video to match the poster; if I do specify the width and height of the video, I get a huge poster to match the video.
A media command button strategy has led to other problems, but I will place attempts with that strategy in separate post so this one will keep its focus.

A: The video size is 640x480 pixels which can be passed to the windowed option.
To make the video play right away in VPlayer.swf, add FlashVar autoPlay=true.
The code below plays the video at its original size in the top right corner of the Reader window:
\documentclass{article}
\usepackage{media9}
\usepackage{graphicx}

\begin{document}

\includemedia[
    %label=firsttry,
    addresource=40631.mp4,
    windowed=640x480@tr,
    noplaybutton,
    activate=onclick,
    flashvars={source=40631.mp4&autoPlay=true}
  ]{\includegraphics[width=32px,height=32px]{filmicon32x32.png}}{VPlayer.swf}

\end{document}


text:
Q: Given a NxN grid and an integer calculate the row and column I know this is most likely elementary school math, but I am having hard time finding a good algorithm. Given a NxN grid and a number which represents the nth tile counting left to right like a typewriter, where at the end of the row you return to column 1... e.g. given a grid of 20x20 and the number is 21, 21 would be located in column 1 row 2. Another example 36 in a 20x20 grid would be column 16 row 2. And so on.
What is the formula I can use to find the row and column.
I tried using modulo to find the column and division for the row, but it just does not work yet.

A: Let's do a similar problem, where you have indices starting from $0$. In other words, you have a grid with $m$ rows and $n$ columns and you need to find the index of some number.
For simplicity let's look at $n=10$ first, letting $m=30$. Then, entry $0$ maps to $(0,0)$, and we follow with similar relationships below:

*

*$0 \mapsto 0,0$

*$1 \mapsto 0,1$

*\ldots

*$9 \mapsto 0,9$

*$10 \mapsto 1,0$

*\ldots

*$19 \mapsto 1,9$
This may be enough to get the pattern. The entry number $N$ maps the second coordinate as $N \pmod{10}$ and the first coordinate is $\lfloor N \div 10 \rfloor$ which we will for convenience denote $N//10$.
In full generality, we map $N \mapsto N//n,N \pmod n$.

The problem you posed is slightly more tricky, since indexing is $1$-based, so given $N$ you translate it to the $N$ from the above problem by subtracting one, then map, and add 1 to compensate, so you get
$$
N \mapsto 1 + [(N-1)//n], 1+[(N-1) \pmod n]
$$

Useful to note that on most computing systems, the first operation is denoted div and the second mod. In addition, some have the faster divmod which does both.


text:
Q: Avoid resizing stroke with Raphaël scaling Following the top answer to this stack overflow question I was able to  make a draggable and resizable path-based shape using Raphaël.
jsFiddle Resizable Path
The one thing I can't figure out is how to avoid unequal scaling if the path has a stroke to it.  As long as the scaling is 1:1, the stroke width stays the same, but stretching the path in one direction or another thins the stroke in one direction. Is there a way to transform a path without affecting the stroke?

A: Not using transformations. You could try modifying the actual path, e.g. "M10,10L20,20" would become "M10,10L40,20" (equivalent of "S2,1").
Also, have a look at Raphael.FreeTransform which handles dragging/rotating/scaling (doesn't address the stroke issue though).


text:
Q: how to pass the pointer to a function and assign the value to the variable pointed to in C? I know the c always pass by values, but if I have a pointer:
int  i = 4;
int * p;
p = &i;

then I have a function, how to pass pointer p to it and change the value of variable i?
void changeValue(int *p)
{
}

how to pass the pointer and change the variable pointed by p?

A: Simply pass it by calling changeValue as
changeValue(p);

and change the value of variable pointed by it (i) by assigning a value to the *p in changeValue()
void changeValue(int *p)
{
     *p = an int value;
}

A: void changeValue( int* ) ;

int main( void )
{
    int  i = 4; // Suppose i is stored at address 1000h
    int * p;
    p = &i;     // Now p stores the address of i that is 1000h

    changeValue(p); // Can also be written as changeValue(&i);
    // Here you are passing the address of i to changeValue function

    return 0 ;
}

void changeValue( int* p ) // Accept a parameter of type int*
{
    *p = 100 ; // store the value 100 at address 1000h
    return ;
}

A: This simple example shows how to pass a pointer (i.e. not a value) and recieve back through that pointer, the new value held by the integer.   Note the reduced number of variables.  i.e. there is no need necessarily to create a separate copy of int *p;.  Nor is it necessary in this case to initialize p:  p = &i; to the address of i.
int changeValue(int *);
int main(void)
{
    int i=15;
    changeValue(&i);
    return 0;
}

int changeValue(int *p) //prototyped to accept int *
{
    return *p = 3;
}

If you do want to create a pointer in the first place, and pass that pointer, then:
int changeValue(int *);
int main(void)
{
    int i=15;
    int *p;
    p = &i;
    *p; // *p == 15 at this point
    //since p is already a pointer, just pass
    //it as is
    changeValue(p);
    return 0;
}

int changeValue(int *q) //prototyped to accept int *
{
    return *q = 3;
}

It is important to note that your statement: I know the c always pass by values is not correct.  It is more common for functions to be written such that pointers are passed because often a pointer is smaller, and more efficient to pass around than the actual variable, especially when large arrays, or structs are used.  Keep in mind though that passing &i (the address of i) works just as well as passing p if passing a pointer is called for.

A: int  i = 4;
int * p = &i;
changeValue(p);
printf("%d",*p);

void changeValue(int *p)
{
    *p = 5;
}

Full program - http://ideone.com/DCvhxE

A: If you dereference the pointer in changeValue and assign to it, it will alter the value of i in the calling frame.
e.g.:
void changeValue(int *p)
{
    *p = 0;
}


text:
Q: Is it legal to release GPL version project into FreeBSD? I could not differentiate between FreeBSD and GPL liecense. Can anyone tell me the in what respect these two liecense are different.
Is it legal to use some source based on GPL license and release the new product as FreeBSD license?
In particular, I have following scence:
I would like to follow some of the implementation module of some implentation for my use. The implementation is standard algorithm implementation. So basically i am taking some reference to implement in my own way. I am not making use of verbatim copy, some module matches with the original one. The one which i am taking reference is in FreeGPL V3 license. The new product which i will release with FreeBSD license. Is it legal to do this or I should relase my product in FreeGPL license?
[EDIT]
Moreover, my case is, I am implementing some standard algorithm. Lets say here a data structure linked list. I think,whoever implements it, he/she will have same structure and similar kind of functions for search, delete and insert.Even the operations will be seen. I saw some code in internet and i got the influence of that of code my implementation which was so unavoidable. In this case how can a
programmer can claim that the particular code is his own original code?

A: The question isn't "how can a programmer can claim that the particular code is his own original code?', the question is "did you base your code on the GPL'ed code?".  If you did, then your stuck with releasing it under the GPL.


text:
Q: How can I set the insets of a JFrame? Is there a way to set the insets of a JFrame?
I tried
frame.getContentPane().getInsets().set(10, 10, 10, 10);

and
frame.getInsets().set(10, 10, 10, 10);

but none of them seem to work.

A: Overriding the Insets of JFrame would not be the soultion to your actual problem.
To answer your question, you cannot set the Insets of JFrame. You should extend JFrame and override the getInsets method to give the insets you require.

A: JPanel contentPanel = new JPanel();

Border padding = BorderFactory.createEmptyBorder(10, 10, 10, 10);

contentPanel.setBorder(padding);

yourFrame.setContentPane(contentPanel);

So basically, contentPanel is the main container of your frame.

A: You have to create an Object of LayOutConstraint and set its Insets.
Like in below example I have used GridBagLayout() and used GridBagConstraint() object.
    GridBagConstraints c = new GridBagConstraints();
    JPanel panel = new JPanel(new GridBagLayout());
    c.insets = new Insets(5, 5, 5, 5); // top, left, bottom, right
    c.anchor = GridBagConstraints.LINE_END;

    // Row 1
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    panel.add(isAlgoEnabledLabel, c);

A: As this question does not have a definitive answer yet you can do it like basiljames said here. The correct way to do it would be to extend a JFrame and then override the getInsets() method.
For example
import javax.swing.JFrame;
import java.awt.Insets;

public class JFrameInsets extends JFrame {
    @Override
    public Insets getInsets() {
        return new Insets(10, 10, 10, 10);
    }

    private JFrameInsets()  {
        super("Insets of 10");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setMinimumSize(getSize());
        setVisible(true);
    }

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

A: you can create a main JPanel and insert everything else into it.
Then you can use BorderFactory to create EmptyBorder or LineBorder.
see this answer:
https://stackoverflow.com/a/17925693/8953378


text:
Q: Initial value for dateTextField (Apache Wicket) Iv'e been trying to add a dateTextField to a legacy code for a project i'm working on, and I did not succeed to init the value of it to empty (as initial value).
I found some examples for dateTime, but not for dateTextField, and would like to get some help with that; this is the code:
    DateTextField dateTextField = new DateTextField("dateTextField", new PropertyModel<Date>(
            this, "date"), new StyleDateConverter("S-", true))
    {
        @Override
        public Locale getLocale()
        {
            return selectedLocale;
        }
    };

    form.add(dateTextField);

    DatePicker datePicker = new DatePicker()
    {
        @Override
        protected String getAdditionalJavaScript()
        {
            return "${calendar}.cfg.setProperty(\"navigator\",true,false); ${calendar}.render();";
        }
    };

    datePicker.setShowOnFieldClick(true);
    datePicker.setAutoHide(true);
    dateTextField.add(datePicker);

and the markup:
<input type="text" wicket:id="dateTextField" />

Thanks!

A: Found the answer eventually:
    DateTextField dateTextField =new DateTextField("dateTextField", new Model<Date>(null), new DayMonthDateConverter(false));
    dateTextField.add(datePicker);
    form.add(dateTextField);

A: You can use the following code:
DateTextField dateTextField = new DateTextField("dateTextField", "yyyy-MM-dd HH:mm:ss Z");
form.addOrReplace(dateTextField.add(new DatePicker()).setVisible(true));


text:
Q: Calling 32-bit unmanaged DLL files from C# randomly failing I'm having an issue when calling 32 bit Delphi DLL files from a C# web site. The code generally runs fine, but occasionally I get an error,

*Unable to load DLL '': The specified module could not be found. (Exception from HRESULT: 0x8007007E).

This issue persists until I recycle the application pool for the site, and then it works fine again.
On the same server, there is also a web service that is calling the same set of DLL files. This web service doesn't seem to have the same issue that the web site has.
Both applications are using .NET Framework 3.5, separate application pools on IIS.
Here is the code I'm using to wrap the DLL files:
public sealed  class Mapper
{
    static Mapper instance = null;

    [DllImport("kernel32.dll")]
    private static extern bool SetDllDirectory(string lpPathName);

    private Mapper()
    {
        SetDllDirectory(ConfigManager.Path);
    }

    public static Mapper Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Mapper();
            }
            return instance;
        }
    }

    public int Foo(string bar, ref double val)
    {
        return Loader.Foo(bar, ref val);
    }
}

public static class Loader
{
    [DllImport("some.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "foo")]
    public static extern int Foo(string bar, ref double val);
}

Then I call it like this:
double val = 0.0;
Mapper.Instance.Foo("bar", ref val);

Why would it "randomly" Unable to load DLL '': The specified module could not be found. (Exception from HRESULT: 0x8007007E).?
The other problem is that I haven't been able to replicate the issue in the development environment. I thought that due to two applications calling the same DLL files, that there could be some locks occurring. To replicate this, I created an application that spawned multiple threads and repeatedly called the 32-bit DLL files, and then used the web site to call these same DLL files. I still couldn't replicate the issue.
Some possible fixes that I can think of:

*

*Wrap the 32 bit DLL files in the web service (because the web service doesn't seem to suffer from the same problem). But this may be worthless if it turns out that the web service also fails.

*Set up state server for the session state and periodically recycle the application pool for the site.This isn't fixing the problem, only avoiding it.

*Wrap the DLL files in an EXE file, and call that EXE file. Then I shouldn't get the same issue. But this also seems like a hacky solution.

*Implement the mapper class differently? But how else should I be doing the call? The other drawback is that other applications are using this mapper, so I'd need to change there code too.

What should I do?

A: I don't know what really causes this problem, but in my experience this error message can be caused by following reasons:

*

*The DLL file that you are using needed a runtime library which is not available at the time of loading it (like the Visual C++ runtime library). You need the exact version of the library. For example, if your DLL file is written with runtime Visual Studio 2008 SP1, you need exactly the same version.

*One of the dependencies of the DLL file is not available. You can check this by using Dependency Walker.

*Also, you have to be sure that your DLL file and the calling application all are 32-bit or 64-bit. Sometimes I get the same error when I want to call a 32-bit DLL file from a 64-bit application.
I know this is not truly your answer, but I hope it would help you find the solution.

A: To fix this issue (it's stopped happening now), I left the mapper code as is, but in the calling application I manually set the path (even though the mapper DLL file does it most of the time).
So in the main application, I make a call to append the path of the directory where the DLL files are located.
private static void AddEnvironmentPaths(string[] paths)
{
    string path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
    path += ";" + string.Join(";", paths);

    Environment.SetEnvironmentVariable("PATH", path);
}

What's strange is that the mapper class works most of the time, but sometimes stopped. Adding the path with the above code seems to have solved the issue.


text:
Q: Is it possible to declare a function that belongs to a singular instantiation of a template class? The application I have in mind is something akin to a Vector<size> class, in which I wish to declare
CrossProduct(const Vector<size>& other)

only for when size is 3. I know there are ways I can hack around it...

*

*Include a function definition only for size=3

*let all other sizes yield linker errors

*Do a static assert at the start of the method to check if size is 3

Is there any way to properly only declare the member function for a particular instantiation?

A: Here's one way to do it:
template <class Type, size_t Size>
struct EnableCrossProduct
{

};

template <class Type>
struct EnableCrossProduct<Type, 3>
{
  void CrossProduct(const Type & other){}
};

template <size_t Size>
struct Vector : public EnableCrossProduct<Vector<Size>, Size>
{
};

A: If you can get the size info at compile-time, you can use std::enable_if.
template<int N>
struct Vector
{
    static const int size = N;
    double data[N];
    // ...

    template<class V>
    double CrossProduct( const V& other,
        typename std::enable_if< size == 3 && V::size == 3 >::type* = 0) const
    {
        // ...
        return 0;
    }
};

void foo( const Vector<3>& v3, const Vector<4>& v4 )
{
    v3.CrossProduct( v3 ); // Ok
    v3.CrossProduct( v4 ); // Compile-time error
}

You might just want to make that condition in the enable_if size == V::size.

A: I would prefer the static_assert method.  This

*

*leads to the clearest error message

*is appropriate since there is no need for SFINAE

*is the easiest way.


text:
Q: How to avoid Group By working on every output? I have a table like this:
LocationID  CountryName  CustomerAmount
C01        Australia     500
C02        Australia     200
C03        China         100
C04        China         200
C05        Japan         50
C06        Canada        120

I want to find the "number of customers in each country" AND the total number of customers.
Now I have the following query:
select countryName, sum(CustomerAmount)
from test
group by countryName;

I obviously got this output:
 CountryName.  customerAmount
 Australia     700
 China         300
 Japan         50
 Canada        120

But I want the output like this
 CountryName.  customerAmount    totalAmount
 Australia     700               1170
 China         300               1170
 Japan         50                1170
 Canada        120               1170

My problem is how can I put two same sum(customerAmount) side by side, but one is grouped  by countryName, while the other just sum up all values in customerAmount table.
Thank you in advance!!!! I have to say sorry as my expression may be ambiguous.

A: One easy way is just to use a sub-query like
select countryName, sum(CustomerAmount) customerAmount,
  (select Sum(customerAmount) from test) totalAmount
from test
group by countryName;

If you can use window functions (MySql 8+) you can do
select countryName, sum(CustomerAmount) customerAmount,
  sum(Sum(CustomerAmount)) over() totalAmount
from test
group by countryName;

note the nested sum().

A: SELECT countryName, SUM(CustomerAmount), SUM(CustomerAmount) OVER()
FROM test
GROUP BY countryName;

I did not test this, but using the over clause should do what you are looking for as seen here.


text:
Q: How to (de)serialize a type as a key for a property, but as the full POCO when it is the root object? I'm exploring using ServiceStack and Redis to persist documents in redis for a project. It would be neat (maybe) if I could have getters and setters in a document type that refer to other document types natively in memory, but as a scalar key when being (de)serialized, to reference the redis location of the property. Something like:
public class Sport
{
    public string Key { get; set; }
    public string Name { get; set; }
    public int RandomFactNumberOfPlayers { get; set; }
    // lots of other random properties about sport I don't want to duplicate in my player serialization
}

public class Player
{
    public string Key { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Sport { get; set; }
}

would serialize a sport and a player as something like:
{key: 'a', name: 'Football', randomFactNumberOfPlayers: 123456},
{key: 'b', firstName: 'Tom', lastName: 'Brady', sport: 'b'}

And when deserializing those records I would have the chance to look into my redis repository and fetch the key of b and deser it as a Sport and assign it to the sport property of my player instance.
I've looked a bit at JsConfig (De)serializeFn and Raw(De)serializeFn, and I had the thought that I could have my types derive from a (simple) base Document type, with a key, and (de)ser documents to and from string keys, but the issue that I see there is that the function will be called for both root instances and properties.
Is there any notion of custom property (de)serializer overrides in service stack? Or is there a better way to do this?


text:
Q: Constructor Argument Forwarding through Interface I'm in need of a generic way to create an instance of any type. This task needs to be performed from a non-templated object, and so I'm currently using an interface like so:
class Interface
{
public:
  virtual void PlacementCopy( void *data, const void *src ) const = 0;
  virtual void PlacementNew( void *data ) const = 0;
  virtual void PlacementDelete( void *data ) const = 0;
  virtual void Delete( void *data) const = 0;
  virtual void Copy( void *dest, const void *src ) const = 0;
  virtual void NewCopy( void **dest, const void *src ) const = 0;
  virtual void *New( ) const = 0;
};

This is all apart of a custom reflection system, and so it is used like this:
int *p = META( int )->Interface->New( );
*p = 10;

This works by creating a templated object that derives from Interface, which holds the type to be constructed. The New operator in Interface does default construction of the type:
template <typename T>
class Derived : public Interface
{
  virtual void *New( void ) const override
  {
    return new T( );
  }
};

Problem:
All types that are to be constructed in this manner must provide a default constructor. I would like to somehow allow arbitrary arguments to be passed to the constructor of the type in question.
I somehow need to be able to do:
MetaInfo *meta = META( SomeType );
SomeType *object = meta->New( arg1, arg2 );

Which would perhaps look something like this in implementation:
template <typename T>
Derived : public Interface
{
  template <typename ... Args>
  virtual void *New( Args&& ... args ) const override
  {
    new T( std::forward<Args>( args ) ... );
  }
};

The MetaInfo object is not a templated type which makes it difficult to come up with an argument forwarding solution. I cannot simply templatize the New method in the Derived class, as you cannot templatize a virtual method.
Is what I'm asking even possible without some crazy code pre-processing?

A: I did end up gathering together a solution with the help of some friends!
So the biggest issue was that all types to be registered within reflection required a default constructor. To get around this you can use SNIFAE to check for the existence of a default constructor.
struct HasDefaultCtor
{
  template <typename U>
  static int32 SFINAE( decltype( U( ) ) * );
  template <typename U>
  static int8 SFINAE( ... );

  static const bool value = sizeof( SFINAE<T>( NULL ) ) == sizeof( int32 );
};

Beyond this all non-default constructors would have to be registered by hand within the reflection system, or generated with a pre-build step tool. Additional SNIFAE checks can be used to type-check and make sure registered constructors actually match real constructors within the class. For actually calling the New operator some run-time resolution would need to occur in order to figure out what constructor is needed to matchup with the New call.
I hope this makes sense and ends up being useful for someone in the future.
I also made a SNIFAE check for copy constructor:
template <typename T>
struct HasCopyCtor
{
  static T MakeT( void );

  template <typename U>
  static int32 SFINAE( decltype( U( MakeT( ) ) ) * );
  template <typename U>
  static int8 SFINAE( ... );

  static const bool value = sizeof( SFINAE<T>( NULL ) ) == sizeof( int32 );
};


text:
Q: Debugging a haxe based ndk app on android with gdb I am trying to debug a openfl/haxe app on android with gdb. Since haxe/openfl compiles to c++ which is then compiled using the ndk, I am basically trying to debug an ndk app.
I got gdbserver attached to the apps process and can remote debug it using arm-linux-androideabi-gdb. But as soon as I try to get a backtrace (the app is running fine at this moment), I get this:
#0  0xb6e70b10 in ?? ()
#1  0xb6e4833c in ?? ()
#2  0xb6e4833c in ?? ()
Backtrace stopped: previous frame identical to this frame (corrupt stack?)

I understand that this can happen when I corrupted the stack by using bad pointers, but since the app is running fine (am actually looking for a runtime error, not a crash), that is not the case.


text:
Q: I can't remove a class object from a list So I have this list (Sheep is a class i created, requiring one parameter):
list = [Sheep(2), Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]

However, when I try to remove Sheep(2) (list.remove(Sheep(2)) from the list, it returns ValueError: list.remove(x): x not in list
How do I fix this?

A: To test for membership in a python list with a custom class you must provide an equality (__eq__) method
class Sheep:

    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        assert isinstance(other, Sheep)
        return self.x == other.x

Now you can create instances of your class with the same "x" and they will be members of your list
foo = [Sheep(2), Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]
print(Sheep(2) in foo)  # True

And you should be able to remove them too
foo.remove(Sheep(2))
print(foo)  # [Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]

A: The two Sheep(2)s are different objects.
To let the the first Sheep(2) be found by comparing it to the second one,  define equality on your Sheep. Then
class Sheep:
    def __init__(self, camouflage_score):
       self.camo = camouflage_score

    def __eq__(self, other):
        return other and self.camo == other.camo

A: You can use index to remove your objects.
x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]

A: Look at this:
class Sheep:
    def __init__(self,v):
        self.v = v

When you create an instance:
In [3]: Sheep(1)
Out[3]: <__main__.Sheep at 0x7fa5a7614550>

In [4]: Sheep(1)
Out[4]: <__main__.Sheep at 0x7fa5a49bf4a8>

Look carefully at 0x7fa5a7614550 and 0x7fa5a49bf4a8, They are different:
In [5]: Sheep(1) == Sheep(1)
Out[5]: False

That is because of creating instance, each  time you create an instance with same value, it does not mean that they are same.
but you can do something like this:
In [6]: Sheep(1).v == Sheep(1).v
Out[6]: True

so if you want to remove item with v=2, you can do this:
list_of_sheeps = [Sheep(2), Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]

new_list = [i for i in list_of_sheeps if i.v != 2] # v is the name of inner field. (self.v)

Then the new_list will be your desired result without Sheep(2).
or using filter:
new_list = list(filter(lambda x:x.v != 2, list_of_sheeps))

Note that:

Do NOT USE list as a name of variable. list is built-in name in python, you will override its own functionality.

A: You can remove the other instances using a list comprehension by checking value like,
>>> list = [Sheep(2), Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]
>>> newl = [x for x in list if x.camo != 2] # will remove all Sheep with camo value == 2

For removing only one instance with the value, you can do something like,
>>> for idx, sheep in enumerate(list[:]):
...   if sheep.camo == 3:
...     list.pop(idx)
...     break

But i'd recommend you implement the __eq__ method in your Sheep class and just do
>>> list.remove(Sheep(3))

And now the new list will be like,
>>> newl
[Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]


text:
Q: Force IE 7 Compatiblity Mode in IE8 I have a c# asp.net website and needs to run in compatibility mode. The website runs (forced) in a popup. I have searched on google and stackoverflow about how to force compatibility mode and found scripts like:
<meta http-equiv="X-UA-Compatible" value="IE=7">
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="X-UA-Compatible" value="IE=8">

I have tried some of above but when I start the website in the browser and then pres on the F12 key, I see the following mode:
Browser Mode: IE8
Document Mode: Quirks
So the browser mode not changed to the compatibility mode.
Does someone know what my problem is?

A: Compatibility Mode is one of the Browser Mode settings; you don't have any ability to change the users browser to compatibility mode. You can only control the document mode of your page - this is what you're seeing in the examples you provided.
<meta http-equiv="X-UA-Compatible" content="IE=7" />

This will force the document into IE7 Standards Mode. If you were to use the EmulateIE7 option, that would look to your doctype to determine if it ought to be Standards, or Quirks. This is the only option offered to you regarding how your page is viewed in the users browser.
Be sure to place that within the <head> region of the page you wish to affect. Additionally, when you're checking the Document Mode, look for which options has "(Page Default)" next to it and not which options is selected.
IE will respect your manual override over the x-ua meta tag. It may be the case that you accidentally moved set the document mode to Quirks while testing, even though the default mode for the page has been adjusted to IE7 by the meta tag.
Further Reading: Defining Document Compatibility


text:
Q: "regular expression compile failed (missing operand)" issue in AWK when checking for an asterisk I am trying to create some useful aliases for myself and am trying to find a way see the current Kubernetes context namespace.
k config get-contexts

CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE
 *        kubernetes-test@kubernetes2   kubernetes2  kubernetes-test    test
          kubernetes-admin@kubernetes   kubernetes   kubernetes-admin   default

I only want the output to be 'test', so I tried:
k config get-contexts | awk '/*/{print $5}'

The error it gets:
awk: line 1: regular expression compile failed (missing operand)

A: You're getting that error message because * is a regexp repetition metachar and as such using it as the first char in a regexp is undefined behavior since there's nothing preceding it to repeat. You're also using a partial line regexp match when what you apparently want is a full word string match (see How do I find the text that matches a pattern? for the difference):
k config get-contexts | awk '$1=="*"{ print $5 }'

A: First of all, * in regex is a quantifier that means "zero or more occurrences". Since it is a regex metacharacter, it should be escaped, \*:
k config get-contexts | awk '/\*/{print $5}'

However, since you are looking for a fixed string rather than a pattern you can use index:
k config get-contexts | awk 'index($0, "*") {print $5}'

If * is found anywhere inside a "record" (the line) the fifth field will get printed.


text:
Q: Executing PostgreSQL stored procedure that returns an integer I have a stored procedure that returns an integer, and I need to execute it from PHP.
The problem is that I don't know how to retrieve the result.
I'm executing the stored procedure this way:
$result = pg_query($con, "SELECT stored_procedure('$param1', '$param2')");

Any help?

A: Retrieve the result the same way you'd retrieve any other select results. Your data will come back looking tabular, with one row and one column.


text:
Q: Generic Delegate casting [edit] the following works in C#
public class C {
    public void M() {
        Func<int,string> a = intArg => "helloWorld"; // string:object
        Test(a);
        Func<int,C> b = intArg => new C(); // C:object
        Test(b);
    }
    public void Test(Func<int,object> arg){
        Console.WriteLine(arg(1).ToString());
    }
}

how can I achieve the same thing with self declared delegate?
public class C {
    public delegate Y MyDelegate<X,Y>(X input);
    public void M() {
        MyDelegate<int,string> a = intArg => "helloWorld"; // cannot convert from 'C.MyDelegate<int, string>' to 'C.MyDelegate<int, object>'
        Test(a);
        MyDelegate<int,C> b = intArg => new C(); // cannot convert from 'C.MyDelegate<int, C>' to 'C.MyDelegate<int, object>'
        Test(b);
    }
    public void Test(MyDelegate<int,object> arg){
        Console.WriteLine(arg(1).ToString());
    }
}

I understand that the compiler cannot tell which type argument is for parameter (contravariance) and which is for return value (covariance), maybe there is way to specify it?
[update]
I have found my solution:
public delegate Y MyDelegate<X,out Y>(X input);

A: When you call this:
object delegateArg = genericMethod.Invoke();

The return value - delegateArg - is a Func<int, something>, where something could be anything. And then you want to pass that Func<int, ???> to another method which will presumably invoke it.
You can pass that it to a method that expects Func<int, object> and it will compile unless the second generic argument is a value type. When you invoke it, you'll get the result of the invocation cast as an object. The actual type of the result will be whatever that second unknown generic argument is.
But if you don't know what that second generic argument is, then the method you pass it to isn't going to know either. The only way it could find out is by using reflection, inspecting the type, and getting the second generic argument.
So you could pass in a Func<int, object> and do some reflection to find out that the object is really a string. Or you could just invoke the function, get the result, and check the type of the returned value and determine that it's a string.
The big problem is that if you don't already know what type you're going to get, how do you know what you want to do with it? If you don't know what type genericMethod.Invoke is going to return with any more certainty, then how do you know you want it at all?
It's a bit like going to the store to buy a wall-mount bracket, except you don't know what it is that you want to mount on a wall. But if you don't know what it is that you want to mount, then why are you going to the store to buy a wall mount bracket?
Sometimes there are good reasons, but this is often what happens when we have functions that return something non-specific and then pass them to other methods. It's much better if we can work it out so that our code is strongly typed. We call a method that returns a certain type because we want an object of that type. Then we pass that thing to another method that expects that type and has a specific use for it.
There are exceptions and cases where we don't really care what the type of something is, but it's less common because we don't usually write code that isn't meant to do something specific with something specific. Unless we're certain that we really don't care what the actual type is, it's good to revisit our approach and find a way to make it strongly typed. That can involve using generics or in some cases writing more classes or methods instead of one that handles a variety of inputs.


text:
Q: In cocos2d-x 3.0, how can I change the sprite of a progress timer while maintaining the percentage? The method below is called after a user action.  The intent of the code is to change the sprite of the progress timer without changing the time remaining.  My code changes the sprite, but it also increases the time remaining on the timer. The amount varies each time, but it always increases.  What am I doing wrong?
Before user action:

After user action:

void TouchScene::switchColors(CustomTimer* centerTimer)
{
    float time = myTimer->getPercentage();
    myTimer->runAction(RemoveSelf::create());
    createCenterTimer(time);
}

void TouchScene::createCustomTimer(float percentage)
{
    myTimer = CustomTimer::create();
    int iRandomColor = getNextColor();
    std::string colorName = getColorName(iRandomColor);
    myTimer->setName(colorName);
    myTimer->setAngle((float)M_PI * 2);
    /*pass the current percentage to the new timer*/
    myTimer->drawTimer(percentage);
    addChild(myTimer, 0);
}

void CustomTimer::drawTimer(float time)
{
    /*removed standard positioning code*/

    /*get the name of the next sprite*/
    std::string name = getName().c_str();
    Sprite *timerSprite = Sprite::create( name + ".png");
    timer = ProgressTimer::create(timerSprite);
    timer->setType( ProgressTimer::Type::RADIAL );
    timer->setReverseDirection(true);

    /*set the timer to pick up where the previous one left off...*/
    timer->setPercentage(time);  //gives inconsistent results
    addChild(timer);
}

A: There is no need to remove current instance of ProgressTimer, just resetting new sprite with different color using setSprite on your CustomTimer object will work fine. Here is the sample code:
void TestGame::drawTimer(float time) {
    Sprite *timerSprite = Sprite::create("blueCircle.png");
    myTimer = ProgressTimer::create(timerSprite);
    myTimer->setPosition(Vec2(100,100));
    myTimer->setType( ProgressTimer::Type::RADIAL );
    myTimer->setReverseDirection(true);
    myTimer->setPercentage(100);
    this->addChild(myTimer);

    myTimer->runAction(ProgressFromTo::create(10, time, 0));

    auto cb = CallFunc::create(CC_CALLBACK_0(TestGame::changeColor, this));
    this->runAction(Sequence::create(DelayTime::create(5), cb, NULL));

}
void TestGame::changeColor() {
    Sprite *timerSprite = Sprite::create("redCircle.png");
    myTimer->setSprite(timerSprite);
}


text:
Q: Is "How you feel about it" a correct sentence? You can see many sentences like: "How you felt when you were in love", "How you can't sleep", "How you feeling" in friends series.
My question is that are these sentences correct?
They shouldn't be "How did you feel....", "How can't you sleep", "How are you feeling" ?

A: "How you feeling" is "How're you feeling" but the "'re" is very similar in sound to the "ow" of how and tends to be reduced in speech, to the point of being inaudible, and sometimes omitted when written.
The other phrases are not questions. They are noun phrases:

How I felt when I was in love was happy and dizzy.

You can form these noun phrases that start with How, What, Where etc. Phrases starting "How" mean "the way that (you felt when you were in love)"
These could also be errors, (for something like "how is it that you can't sleep") We couldn't decide if they are errors without some more context.


text:
Q: MySql DELETING a Customer & their orders from multiple tables I am trying to delete a customer and their orders from 3 different tables by CustomerID with phpMyAdmin using a routine (cID).
My table structure is below as an image:
Tables structure
Primary keys are CustomerID, OrderID, ProductID.
Table: orders

*

*OrderID

*OrderDate

*CustomerID

Table: customers

*

*CustomerID

*CustomerName

*Customer Address

Table: products

*

*ProductID

*ProductDesc

*ProductPrice

Table: assigned

*

*ProductID (foreign key)

*OrderID (foreign key)

*Quantity

Query below:
BEGIN
INSERT INTO customersdeleted SELECT * FROM customers
WHERE CustomerID = cID; DELETE assigned
FROM assigned INNER JOIN orders
ON assigned.OrderID = orders.OrderID
WHERE orders.CustomerID = cID;
DELETE FROM customers WHERE customerID = cID;
SELECT * FROM orders;
SELECT * FROM customers; SELECT * FROM customersdeleted;
END

I have been trying for ages to get this query to work and delete the customer and their orders by CustomerID and insert them (once deleted) into the customersdeleted table I also created.
Any help would be greatly appreciated!

A: you have some issues when yo create the tables;
i am giving you a simple solution of your code:
create table order(
orderId varchar(10),
order_date date,
customerId char(7),
primary key(customerId)
);
create table customers(
customerId char(7),
customerName varchar(30),
primary key(customerId),
foreign key(customerId) references order(customerId),
on delete cascade

);

N:B:on delete cascade will delete the customerid from all the tables if you delete the customer id from your order table.so then change your query such that you have to only delete the customerid of order table others will automatically delete as they are foreign keys.

A: I was able to get the query to work and add the deleted data to a specific table. I was only missing after DELETE assigned, orders. See below.
BEGIN
INSERT INTO customersdeleted SELECT * FROM customers
WHERE CustomerID = cID;
DELETE assigned, orders
FROM assigned
INNER JOIN `orders` ON `assigned`.`OrderID` = `orders`.`OrderID`
WHERE `orders`.`CustomerID` = cID;
DELETE FROM `customers` WHERE `CustomerID` = cID;
SELECT * FROM orders;
SELECT * FROM customers;
SELECT * FROM assigned;
SELECT * FROM customersdeleted;
END


text:
Q: Creating large PDFs that can't fit in memory all at once I'm using PdfBox Android to create large PDFs.
Each page I create needs to have a number of images added to it. I can guarantee that the number of bitmaps on any one given page can fit in memory, but not for any more than that.
As a result, in certain cases the program crashes with an out-of-memory error because it can't hold all of the bitmaps in memory.
Since I only need to work on one page at a time, in theory it should be possible to flush the pages I don't need to a file (e.g. a temporary scratch file) to free up memory.
I've tried setting the PDDocument MemoryUsageSetting to use a scratch file, but that hasn't worked for me.
As far as I can tell PdfBox loads it's in-memory representation all at once and there's no way for it to flush unused objects to storage.
This is causing a lot of issues for my app, any help or suggestions would be much appreciated.

A: In the 2.0.* versions, open the PDF like this:
PDDocument doc = PDDocument.load(file,MemoryUsageSetting.setupTempFileOnly());

This will setup buffering memory usage to only use temporary file(s) (no main-memory) with not restricted size.


text:
Q: Handle http calls with errors inside a forEach - Angular 9 I'm writing a piece of code that cycles through an array and makes HTTP calls.
Most of these HTTP calls are made to non-existent resources, but I don't know which ones.
I'm currently using this piece of code:
    langs.forEach(lang => {
      this.http.get('assets/i18n/' + lang + '.json')
        .pipe(
          tap(data => console.log('server data:', data)),
          catchError(this.handleError),
        );
    });

The piece of code listed above shows me nothing in the console, when in reality a couple of data structures should be expected.
What I would not expect are error messages like:
GET http://localhost: 4205/assets/i18n/[...] 404 (Not Found), but simply the results of the successful calls.
I wonder how one can only get good data structures, and filter errors within a cycle.
Thanks in advance.
EDIT:
this.handleError is taken from the angular documentation:
private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message

    return throwError(
      'Something bad happened; please try again later.');
}

A: If you need to make multiple calls in a for loop, I recommend that you use the ForkJoin rxjs operator, in addition to being more elegant, it is also more performing by making all the calls together.
const calls = [];
langs.forEach(lang => calls.push(this.http.get('assets/i18n/' + lang + '.json')));
Observable.forkJoin(calls).pipe(catchError(this.handleError)).subscribe(responses => {...});

A: I would recommend using forkJoin to run the multiple HTTP requests in parallel. If you want to handle errors on individual requests but still return responses for the others, you can add error handling to each individual request.
service.ts
getLanguages(): Observable<any[]> {
  const observables = langs.map(lang => {
    return this.http.get(`assets/i18n/${lang}.json`).pipe(
      catchError(() => of(null))
    );
  });

  return forkJoin(observables).pipe(
    // remove empty values from the array
    map(results => results.filter(x => !!x)),
  );
}

You would then inject the service into your component and subscribe to the getLanguages() function.
component.ts
ngOnInit() {
  this.service.getLanguages().subscribe(responses => {
    console.log(responses); // [ {}, {}, {}, ... ]
  });
}


text:
Q: MySQL prepared statement vs normal query. Gains & Losses I'm in the middle of updating/reworking some database code and I was wondering, what I should really expect from using prepared statements.
Take this example code:
$values = '';
for ($i = 0; $i < $count; $i++) {
    $name = mysql_real_escape_string ($list[$i][1]);
    $voc = mysql_real_escape_string ($list[$i][3]);
    $lev = $list[$it][2];
    $lev = is_numeric ($lev)? $lev : 0;

    $values .= ($values == '')? "('$name', '$voc', $lev)" : ", ('$name', '$voc', $lev)";
}
if ($values != '') {
    $core->query ("INSERT INTO onlineCList (name, voc, lev) VALUES $values;");
}

Now, apart from the obvious gain in readability (, sanity) and the fact that max_packet_size stops being an issue, am I supposed to expect any changes in performance when I recode this to use prepared statements? I'm connecting remotely to the MySQL server, and I worry that sending multiple small packets would be significantly slower then sending one big packet. If this is the case, can MySQLi/mysqlnd cache these packets?
Another example:
$names = '';
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
    $name = mysql_real_escape_string($row['name']);

    $names .= ($names == '') ? "'$name'" : ", '$name'";
}
if ($names != '') {
    $core->query ("UPDATE onlineActivity SET online = NULL WHERE name IN ($names) AND online = 1;");
}

As above, should I expect the unexpected, after recoding this to use prepared statements? Does it make any difference for the MySQL server, if it has to run one query with a big IN clause, or multiple prepared queries with equality checks (.. WHERE name = $name AND ..)?
Assume that everything is properly indexed.

A: Normally, if you just use a prepared statement in place of a plain query, it's marginally slower since the query is prepared and executed in two steps instead of one. Prepared statements become faster only when you're preparing the statement and then executing it multiple times.
However, in this case you're using mysql_real_escape_string, which does a roundtrip to the database. Even worse, you're doing it inside a loop, so, executing it multiple times per query. So, in this case replacing all of those roundtrips with a single prepared statement is a win-win-win.
Regarding your last question, there's no reason you can't use the same query with a prepared statement as you would through the normal query parser (i.e. no reason to execute one version with an IN and the other with a bunch of ORs). The prepared statement can have IN (?, ?, ?), and then you just bind that number of parameters.
My advice would be to always use prepared statements. In cases where they add a marginal performance overhead, they're still worth it for the security (no SQL injection) and readability benefits. For sure, anytime you find yourself resorting to mysql_real_escape_string, you should use a prepared statement instead. (For simple one-off queries where there's no need to escape variable inputs, they aren't strictly necessary.)

A: *

*Prepared statements are more secure.

*Prepared statements have better performance.

*Prepared statements are more convenient to write.

Will you read all these!!
http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html
try this too
Prepared Statement vs. Stored Procedure


text:
Q: Bundle null onActivityResult I have tried a couple of different solutions already given but none works as everything seems to work fine in another activity that I am returning a result from, here is the code.
My Main activity where City activity is called:
//this method gets called on a button click and it works as other activity shows up

public void getCity(View v){
    Intent intent = new Intent(getApplicationContext(), City.class);
    startActivityForResult(intent,1);
}
//receiving the data the first data is ok  but the second one is null although doing the same thing in both files
 protected void onActivityResult(int requestCode, int resultCode, Intent data){

    if(resultCode == RESULT_OK && data != null && requestCode==0){
        initializeUI(data.getExtras());
    }
    if(resultCode == RESULT_OK && data != null && requestCode==1){
          //data is null here
    }
    super.onActivityResult(requestCode, resultCode, data);
}

My City Activity
 public void addInput(View v){
    Bundle bundle = new Bundle();

    EditText cityBox = (EditText) findViewById(R.id.cityInput);
    String cityName =  cityBox.getText().toString();
    Intent resultIntent = new Intent();
    try {
        EditText longBox = (EditText) findViewById(R.id.longitudeInput);
        String longitude =  longBox.getText().toString();

        double longi =  Double.parseDouble(longitude);

        bundle.putDouble("LONGITUDE", longi);

        EditText latBox = (EditText) findViewById(R.id.latitudeInput);
        String latitude =  latBox.getText().toString();

        double lati =  Double.parseDouble(latitude);

        bundle.putDouble("LATITUDE", lati);

    } catch (NumberFormatException e){

    }
    bundle.putString("CITY_NAME", cityName);
    resultIntent.putExtra("DATA",bundle);
    setResult(RESULT_OK, resultIntent);
    finish(); //calling finish just in case tried without finish aswell
    onBackPressed(); //calling onBackPressed tried without it as well doesn't work
}

Any help would be appreciated.

A: try this:
Then, in B, I do:
Intent intent = getIntent();
intent.putExtra("Date",dateSelected);
setResult(RESULT_OK, intent);
finish();

And, in A:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode==RESULT_OK && requestCode==1){
Bundle MBuddle = data.getExtras();
String MMessage = MBuddle .getString("Date");
}
}

the problem i have found in your code is use of wrong requestCode you are passing 1 as result code in startActivityForResult and in onActivityResult you are checking requestCode==0 means intializeUI etc. All you need to do is use this below code.
     if(resultCode == RESULT_OK && data != null && requestCode==1){
     //everything works fine
     initializeUI(data.getExtras());
    }

hope this will help you.

A: I recently faced same issue in my case. What i was doing wrong was that i was using startActivity() by mistake with  startActivityForResult() then in child activity i was calling onBackPress() and finish() before setting the result. I can suggest you that you make sure you set the result before finish() the activity and make sure you're starting activity with startActivityForResult().
Here is snippet from my code.
setResult(RESULT_OK, getIntent().putExtra("country", "some result"));

And i made sure the above written code get excuted before onBackPressed() and onFinish() and it worked for me.
Hope this will help you.


text:
Q: Sum of a Sequence Rules I've been asked to write out and simplify the following sequence:
$$ \sum_{r=1}^4 \frac{a}{m} $$
The answerbook states that the solution is $\frac{4a}{m}$, but I don't understand why.
I know that there is a rule:
$$ \sum_{1}^n c =nc $$
Why is this rule this way; what is the reasoning behind it?
EDIT: Is it simply defined to be that way, without specific reasons?

A: Hint
$$ \sum_{r=1}^n a = \underbrace{a + \ldots + a}_{n \  \text{times}}$$

A: This rule is actually quite intuitive, if you were to actually write out $\sum_{1}^n c =nc$ You would get $c+c+c+...+c$ with $n$ $c$'s, which is simply $nc$.
Remember that the summation notation is simply a shorthand for expressing long, extended sums and thus, intuitively, the notation follows the same rules as normal addition.

A: Try not to think of it as a rule, but intuitively based on the mathematical meaning. We're summing $a/m$ from $r=1$ to $4$. But r doesn't appear anywhere in $a/m$, so we're effectively just summing 4 terms, all of which are $a/m$.


text:
Q: dynamically support multiple SSL sites for one IP address For a web application running on Tomcat, to support multiple SSL sites on one Ip address, I like to add Apache in front of Tomcat.
Is it possible for user to upload its own SSL certificate and configure it dynamically without server restart?
<VirtualHost *:443>
        DocumentRoot
        ServerName

        SSLCertificateFile
        SSLCertificateKeyFile
        SSLCACertificateFile
        SSLEngine on
    </VirtualHost>

For apache, the SSL configuration above needs to be added into apache conf file,
and requires server restart. Server restart is not acceptable because there will be many users on the same server.  Any solution?
Thanks for help.


text:
Q: Creating pdf with rails I need to generate a pdf file and upload it to the AWS upon some action from my controller. I've never done this before with rails, neither created a pdf and then upload it to the aws.
So here is what I'm thinking, how to proceed.
When a action in my controller occurs and it invokes a method a, it will invoke the Job B which is a delayed job who will call the controller method c which has the respond_to and format pdf. And the job will save the .pdf file to the AWS.
The pdf that I'm using needs to be stored on the aws so it can be emailed to a user later. Not sure if this is relevant, just wanted to give more details.
I'm using prawn gem to generate the pdf
Is there a better way to do this, has anyone done something like this before?

A: I've done something similar using pdfkit. Essentially you just define your PDF layout in HTML/CSS, and when a user adds the .pdf suffic to a path, it attempts to generate the PDF. It's nice because you don't have to actually store generated PDF files, but they'll always be available if someone needs them.

A: http://rubygems.org/gems/wicked_pdf
"Wicked PDF uses the shell utility wkhtmltopdf to serve a PDF file to a user from HTML. In other words, rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would normally, and let Wicked take care of the hard stuff."


text:
Q: How to randomly change the picture of several picturebox I basically want to know how I can optimize this code. I was trying to create somehow a program that could change the photo of a picturebox, but with a randomizer. Basically, each photo would have its percentage of chance to appear in the picturebox, and after several attempts, the only thing that worked for me was this ugly and badly optimized code, but if I try to fix it, the program simply fails. Well, my code generates a random number from 1 to 100 and depending on the number that is generated, one of the six photos is chosen. It is working, however it changes the image from just one picturebox, and I have over 50 that I want to switch (still random). I put it to change everything in a single button, it took me an hour to do this, and I saw that the program gets very slow so it's out of the question. Is there any way to change them all at once using only one code, but keeping random all 50 pictureboxes?
The idea is that at the end of the 50 picturebox are randomly filled with photos, with pictures that can be repeated, but some are less likely to appear than others.
I know, it was a bit confusing, but even if someone can help me, thank you right away.
My code:
randomvalue = random.Next(1, 101)
    If randomvalue = "1" Or randomvalue = "2" Or randomvalue = "3" Or randomvalue = "4" Or randomvalue = "5" Or randomvalue = "6" Or randomvalue = "7" Or randomvalue = "8" Or randomvalue = "9" Or randomvalue = "10" Or randomvalue = "11" Or randomvalue = "12" Or randomvalue = "13" Or randomvalue = "14" Or randomvalue = "15" Or randomvalue = "16" Or randomvalue = "17" Or randomvalue = "18" Or randomvalue = "19" Or randomvalue = "20" Or randomvalue = "21" Or randomvalue = "22" Or randomvalue = "23" Or randomvalue = "24" Or randomvalue = "25" Or randomvalue = "26" Or randomvalue = "27" Or randomvalue = "28" Or randomvalue = "29" Or randomvalue = "30" Or randomvalue = "31" Then
        btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img1.png")
    End If

    If randomvalue = "32" Or randomvalue = "33" Or randomvalue = "34" Or randomvalue = "35" Or randomvalue = "37" Or randomvalue = "38" Or randomvalue = "39" Or randomvalue = "40" Or randomvalue = "41" Or randomvalue = "42" Or randomvalue = "43" Or randomvalue = "44" Or randomvalue = "45" Or randomvalue = "46" Or randomvalue = "47" Or randomvalue = "48" Or randomvalue = "49" Or randomvalue = "50" Or randomvalue = "51" Or randomvalue = "52" Or randomvalue = "53" Or randomvalue = "54" Or randomvalue = "55" Or randomvalue = "56" Or randomvalue = "57" Then
        btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img2.png")
    End If

    If randomvalue = "58" Or randomvalue = "59" Or randomvalue = "60" Or "61" Or randomvalue = "62" Or randomvalue = "63" Or randomvalue = "64" Or randomvalue = "65" Or randomvalue = "66" Or randomvalue = "67" Or randomvalue = "68" Or randomvalue = "69" Or randomvalue = "70" Or randomvalue = "71" Or randomvalue = "72" Or randomvalue = "73" Or randomvalue = "74" Or randomvalue = "75" Or randomvalue = "76" Or randomvalue = "77" Then
        btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img3.png")
    End If

    If randomvalue = "78" Or randomvalue = "79" Or "80" Or randomvalue = "81" Or randomvalue = "82" Or randomvalue = "83" Or randomvalue = "84" Or randomvalue = "85" Or randomvalue = "86" Or randomvalue = "87" Or randomvalue = "88" Or randomvalue = "89" Or randomvalue = "90" Then
        btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img4.png")
    End If

    If randomvalue = "91" Or randomvalue = "92" Or randomvalue = "93" Or randomvalue = "94" Or randomvalue = "95" Or randomvalue = "96" Or randomvalue = "97" Or randomvalue = "98" Or randomvalue = "99" Or randomvalue = "100" Then
        btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img5.png")
    End If

    If randomvalue = "36" Then
        btnOre1.Image = Image.FromFile("C:\Users\" & Environment.UserName & "\AppData\Local\imgsx\img6.png")
    End If

A: I don't know what the actual numbers are because I couldn't be bothered counting but lets' say that your six images should have 10%, 20%, 10%, 20%, 10% and 30% chances of being used respectively.  You can use a Select Case to easily filter a random number, e.g.
Select Case myRandom.Next(0, 100)
    Case Is < 10 '0-9
        'Use first image
    Case Is < 30 '10-29
        'Use second image
    Case Is < 40 '30-39
        'Use third image
    Case Is < 60 '40-59
        'Use fourth image
    Case Is < 70 '60-69
        'Use fifth image
    Case Else '70-99
        'Use sixth image
End Select

It's also worth noting that the Random class is inheritable so you can actually create your own class that allows you to specify weightings to the outcomes.  I have actually created a WeightedRandom class before but seem not to have kept it anywhere.  I think that I'll have to do that again and put it somewhere publicly accessible.
EDIT: Here's a more complete example:
Imports System.IO

Public Class Form1

    Private folderPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "imgsx")
    Private fileNames As String() = {"img1.png", "img2.png", "img3.png", "img4.png", "img5.png", "img6.png"}
    Private imagesByFileName As New Dictionary(Of String, Image)
    Private rng As New Random

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Create one Image object per file.
        For Each fileName In fileNames
            Dim filePath = Path.Combine(folderPath, fileName)
            Dim img = Image.FromFile(filePath)

            imagesByFileName.Add(fileName, img)
        Next
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'Display a random image in each PictureBox on the form.
        For Each pictureBox In Controls.OfType(Of PictureBox)
            pictureBox.Image = GetWeightedRandomImage()
        Next
    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        'Clean up the Images to release the files.
        For Each fileName In fileNames
            imagesByFileName(fileName).Dispose()
        Next
    End Sub

    Private Function GetWeightedRandomImage() As Image
        Dim fileNameIndex As Integer

        Select Case rng.Next(0, 100)
            Case Is < 10 '0-9
                fileNameIndex = 0
            Case Is < 30 '10-29
                fileNameIndex = 1
            Case Is < 40 '30-39
                fileNameIndex = 2
            Case Is < 60 '40-59
                fileNameIndex = 3
            Case Is < 70 '60-69
                fileNameIndex = 4
            Case Else '70-99
                fileNameIndex = 5
        End Select

        Return imagesByFileName(fileNames(fileNameIndex))
    End Function

End Class


text:
Q: Coffee script with erb extension gives missing template error I am using rails 3.2.11 and coffee rails 3.2.2.
Here I am trying to render a coffee script in a file /app/views/my_files/create.js.coffee.erb
Here is what my controller code looks like
class MyFilesController < ApplicationController
  respond_to :js

  def create
  end

end

On hitting create action I get missing template error. But when I rename file create.js.coffee.erb to create.js.coffee it works fine.
I am not understanding what is the problem with .erb extension over .coffee, and in this case why it gives missing template error, when template is already there?
Thanks

A: Rename your file to create.js.coffee
See
How to render new.js.coffee.erb in app/views?
Just had the same problem...

A: Is there a particular reason you are trying to render coffeescript as a view rather than using it as an asset?
.erb is a ruby script file that produces an html file when compiled.
.js.coffee results in a .js file when compiled. You should be using .erb with a create.html.erb template that in turn uses your create.js.coffee.
<%= javascript_include_tag "create" %>

This should be in your create.html.erb which will be called by the create method in your MyFilesController