text:
Q: Fixed to window, but contained inside container I have some HTML set up like this:

Welcome!

The cover element is uses background-attachment: fixed; to create a parallax effect. What I'm trying to achieve is have the overlay element behave the same way, where the text in it is fixed to the viewport, but still contained inside the mediasection div, so that when the user scrolls the page the cover and overlay stay in the same position, but disappear as the mediasection element goes out of view.
Is there any way to achieve this?
tl;dr; Some sort of background-attachment: fixed; to regular elements, not just the background.
Thanks!

A: Honestly, I think the easiest way is to just to use photoshop / [your favourite image editing software] to put the overlay text over the background image. I made this jsfiddle which hopefully demonstrates your desired behavior.
The HTML

Overlay Text

With an interesting paralax effect

Where sr-only is a class that hides elements visually while maintaining screen reader accessibility
The CSS

.media-screen {
    position: relative;
    height: 250px;
    background-image: url('path/to/your/image.png');
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
}

.sr-only {
    position: absolute;
    overflow: hidden;
    clip: rect(0 0 0 0);
    height: 1px; width: 1px;
    margin: -1px; padding: 0; border: 0;
}

Mobile Support

If you are supporting multiple screen sizes you will probably need a few different versions of the image to suit different orientations. You can use media queries to substitute the image that is displayed for various sizes / orientations

/*Example media query for view port width*/
@media screen only and (min-width: 1024px){
    .media-screen {
        background-image: url('path/to/your/image-large.png');
    }
}

/* Example media query for view port orientation */
@media screen only and (orientation: portrait){
    .media-screen {
        background-image: url'path/to/your/image-narrow.png');
    }
}

Note: Embedding content in the background image obviously means that the content is not interactive so this is only really any good for basic display elements.

A: I have found a jQuery based solution myself. I'm still not a fan of relying on JavaScript, so any other answers are welcome, but it works.
Here it is:
var oldScroll = 0;
$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    var scrollOffset = scroll - oldScroll;

    // Overlay positions
    var offset = $(".overlay").offset();
    $(".overlay").offset({top: offset.top + scrollOffset});

    oldScroll = scroll;
});

This offsets the overlay while scrolling.
But as I said, other answers are welcome.


text:
Q: image of differentiable manifold is again a manifold Let $1\leq \mu <n,\, M\subset \mathbb{R}^n$ be a $\mu$-dimensional differentiable submanifold of $\mathbb{R}^n$ (that is, all the charts $\varphi$ are immersions: $\phi\in C^1$ and the rank of $D\varphi$ equals $\mu$). Now let $f\in C^1(\mathbb{R}^n,\mathbb{R}^n)$ be invertible with $f^{-1}\in C^1(\mathbb{R}^n,\mathbb{R}^n)$.
Show that $f(M)$ is a $\mu$-dimensional submanifold of $\mathbb{R}^n$.

The fact that given $x\in f(M)$ we can find a $C^1$-homeomorphism $\psi:=f\circ\varphi$ follows almost immediately from the assumptions. However, my problem is showing that such a $D(f\circ\varphi)$ has rank $\mu$ and I haven't been able to show this so far.

A: By the chain rule, $D(f\circ \varphi) = Df\circ D\varphi$. Since $f$ is $C^1$ with $C^1$ inverse, by the chain rule, $D(\mathrm{Identity})= D(f\circ f^{-1}) = Df\circ D(f^{-1})$, so $Df$ is an isomorphism. The rest is a question about linear algebra: if $T$ is an isomorphism, and $S$ is a linear map of rank $\mu$ then $T\circ S$ has rank $\mu$. Apply this to $T = Df$ and $S = D\varphi$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the SQL query that caused an event in the past I have a database in which I noticed that one of my tables is missing.
I haven't used this database for over three months and now I want to find out who caused this, when this happened, how it happened and what code was used (or generated by SQLMS) for this action.
How can I do that?

A: This data might still be in the default trace, which can roll over and phase out files based not only on activity but also based on service restarts (so I say it might be there because you may have restarted SQL Server more than 5 or 6 times in three months, even if there hasn't been a lot of activity).
Anyway, it is one of the examples I included in this answer, which I'll repeat a portion of here:

Question: Who deleted the dbo.EmployeeAuditData table and when?

This will return any DROP events for an object named EmployeeAuditData. If you want to make sure that it only detects DROP events for tables, you can add a filter: ObjectType = 8277 (the full list is documented here). If you want to restrict the search space to a specific database, you can add a filter: DatabaseName = N'db_name'.
DECLARE @path NVARCHAR(260);

SELECT
   @path = REVERSE(SUBSTRING(REVERSE([path]),
   CHARINDEX(CHAR(92), REVERSE([path])), 260)) + N'log.trc'
FROM    sys.traces
WHERE   is_default = 1;

SELECT
  LoginName,
  HostName,
  StartTime,
  ApplicationName
FROM sys.fn_trace_gettable(@path, DEFAULT)
WHERE EventClass = 47    -- Object:Deleted
AND EventSubClass = 1
AND ObjectName = N'EmployeeAuditData'
ORDER BY StartTime DESC;

Please also see the other answer for additional caveats (e.g. details around the lack of recording of the schema of an object that has been dropped, and also the fact that TextData will never be populated - not that it will ever be anything varying far from DROP TABLE dbo.whatever;).


text:
Q: Image to text android app Trying to use TextFairy code on GitHub to create an android app which converts image to text as one of its features:  (https://github.com/renard314/textfairy/tree/master/app/src/main/res), but it is throwing this error:
Please help!
or suggest some other image to text api/android app code
 Executing tasks:      [:app:generateAV5DebugSources,:app:generateAV5DebugAndroidTestSources, :tesstwo:tess-two:generateDebugSources, :tess-two:tesstwo:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
Returning version 640
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 240
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 140
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
signing.properties not found
:app:preBuild UP-TO-DATE
:app:preAV5DebugBuild UP-TO-DATE
:app:checkAV5DebugManifest
:app:preAV5ReleaseBuild UP-TO-DATE
:app:preAV7DebugBuild UP-TO-DATE
:app:preAV7ReleaseBuild UP-TO-DATE
:app:preX86DebugBuild UP-TO-DATE
:app:preX86ReleaseBuild UP-TO-DATE
:tess-two:tess-two:compileLint
:tess-two:tess-two:copyReleaseLint UP-TO-DATE
:tess-two:tess-two:mergeReleaseProguardFiles
:tess-two:tess-two:preBuild UP-TO-DATE
:tess-two:tess-two:preReleaseBuild UP-TO-DATE
:tess-two:tess-two:checkReleaseManifest
:tess-two:tess-two:prepareReleaseDependencies
:tess-two:tess-two:compileReleaseAidl
:tess-two:tess-two:compileReleaseRenderscript
:tess-two:tess-two:generateReleaseBuildConfig
:tess-two:tess-two:generateReleaseAssets UP-TO-DATE
:tess-two:tess-two:mergeReleaseAssets
:tess-two:tess-two:generateReleaseResValues
:tess-two:tess-two:generateReleaseResources
:tess-two:tess-two:packageReleaseResources
:tess-two:tess-two:processReleaseManifest
:tess-two:tess-two:processReleaseResources
:tess-two:tess-two:generateReleaseSources
:tess-two:tess-two:ndkBuild FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':tess-two:tess-two:ndkBuild'.
> A problem occurred starting process 'command '/Users/renard/devel/android-ndk-r9c//ndk-build''

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 29.02 secs
Executing tasks: [:app:assembleAV5Debug]

Configuration on demand is an incubating feature.
Returning version 640
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 240
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 140
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
signing.properties not found
:app:preBuild UP-TO-DATE
:app:preAV5DebugBuild UP-TO-DATE
:app:checkAV5DebugManifest
:app:preAV5ReleaseBuild UP-TO-DATE
:app:preAV7DebugBuild UP-TO-DATE
:app:preAV7ReleaseBuild UP-TO-DATE
:app:preX86DebugBuild UP-TO-DATE
:app:preX86ReleaseBuild UP-TO-DATE
:tess-two:tess-two:compileLint
:tess-two:tess-two:copyReleaseLint UP-TO-DATE
:tess-two:tess-two:mergeReleaseProguardFiles UP-TO-DATE
:tess-two:tess-two:preBuild UP-TO-DATE
:tess-two:tess-two:preReleaseBuild UP-TO-DATE
:tess-two:tess-two:checkReleaseManifest
:tess-two:tess-two:prepareReleaseDependencies
:tess-two:tess-two:compileReleaseAidl UP-TO-DATE
:tess-two:tess-two:compileReleaseRenderscript UP-TO-DATE
:tess-two:tess-two:generateReleaseBuildConfig UP-TO-DATE
:tess-two:tess-two:generateReleaseAssets UP-TO-DATE
:tess-two:tess-two:mergeReleaseAssets UP-TO-DATE
:tess-two:tess-two:generateReleaseResValues UP-TO-DATE
:tess-two:tess-two:generateReleaseResources UP-TO-DATE
:tess-two:tess-two:packageReleaseResources UP-TO-DATE
:tess-two:tess-two:processReleaseManifest UP-TO-DATE
:tess-two:tess-two:processReleaseResources UP-TO-DATE
:tess-two:tess-two:generateReleaseSources UP-TO-DATE
:tess-two:tess-two:ndkBuild FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':tess-two:tess-two:ndkBuild'.
> A problem occurred starting process 'command '/Users/renard/devel/android-ndk-r9c//ndk-build''

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 8.917 secs
Executing tasks: [:app:assembleAV5Debug]

Configuration on demand is an incubating feature.
Returning version 640
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 240
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 140
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
signing.properties not found
:app:preBuild UP-TO-DATE
:app:preAV5DebugBuild UP-TO-DATE
:app:checkAV5DebugManifest
:app:preAV5ReleaseBuild UP-TO-DATE
:app:preAV7DebugBuild UP-TO-DATE
:app:preAV7ReleaseBuild UP-TO-DATE
:app:preX86DebugBuild UP-TO-DATE
:app:preX86ReleaseBuild UP-TO-DATE
:tess-two:tess-two:compileLint
:tess-two:tess-two:copyReleaseLint UP-TO-DATE
:tess-two:tess-two:mergeReleaseProguardFiles UP-TO-DATE
:tess-two:tess-two:preBuild UP-TO-DATE
:tess-two:tess-two:preReleaseBuild UP-TO-DATE
:tess-two:tess-two:checkReleaseManifest
:tess-two:tess-two:prepareReleaseDependencies
:tess-two:tess-two:compileReleaseAidl UP-TO-DATE
:tess-two:tess-two:compileReleaseRenderscript UP-TO-DATE
:tess-two:tess-two:generateReleaseBuildConfig UP-TO-DATE
:tess-two:tess-two:generateReleaseAssets UP-TO-DATE
:tess-two:tess-two:mergeReleaseAssets UP-TO-DATE
:tess-two:tess-two:generateReleaseResValues UP-TO-DATE
:tess-two:tess-two:generateReleaseResources UP-TO-DATE
:tess-two:tess-two:packageReleaseResources UP-TO-DATE
:tess-two:tess-two:processReleaseManifest UP-TO-DATE
:tess-two:tess-two:processReleaseResources UP-TO-DATE
:tess-two:tess-two:generateReleaseSources UP-TO-DATE
:tess-two:tess-two:ndkBuild FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':tess-two:tess-two:ndkBuild'.
> A problem occurred starting process 'command '/Users/renard/devel/android-ndk-r9c//ndk-build''

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 8.946 secs
Executing tasks: [:app:assembleAV5Debug]

Configuration on demand is an incubating feature.
Returning version 640
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 240
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 140
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
signing.properties not found
:app:preBuild UP-TO-DATE
:app:preAV5DebugBuild UP-TO-DATE
:app:checkAV5DebugManifest
:app:preAV5ReleaseBuild UP-TO-DATE
:app:preAV7DebugBuild UP-TO-DATE
:app:preAV7ReleaseBuild UP-TO-DATE
:app:preX86DebugBuild UP-TO-DATE
:app:preX86ReleaseBuild UP-TO-DATE
:tess-two:tess-two:compileLint
:tess-two:tess-two:copyReleaseLint UP-TO-DATE
:tess-two:tess-two:mergeReleaseProguardFiles UP-TO-DATE
:tess-two:tess-two:preBuild UP-TO-DATE
:tess-two:tess-two:preReleaseBuild UP-TO-DATE
:tess-two:tess-two:checkReleaseManifest
:tess-two:tess-two:prepareReleaseDependencies
:tess-two:tess-two:compileReleaseAidl UP-TO-DATE
:tess-two:tess-two:compileReleaseRenderscript UP-TO-DATE
:tess-two:tess-two:generateReleaseBuildConfig UP-TO-DATE
:tess-two:tess-two:generateReleaseAssets UP-TO-DATE
:tess-two:tess-two:mergeReleaseAssets UP-TO-DATE
:tess-two:tess-two:generateReleaseResValues UP-TO-DATE
:tess-two:tess-two:generateReleaseResources UP-TO-DATE
:tess-two:tess-two:packageReleaseResources UP-TO-DATE
:tess-two:tess-two:processReleaseManifest UP-TO-DATE
:tess-two:tess-two:processReleaseResources UP-TO-DATE
:tess-two:tess-two:generateReleaseSources UP-TO-DATE
:tess-two:tess-two:ndkBuild FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':tess-two:tess-two:ndkBuild'.
> A problem occurred starting process 'command '/Users/renard/devel/android-ndk-r9c//ndk-build''

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 7.68 secs
Executing tasks: [:app:assembleAV5Debug]

Configuration on demand is an incubating feature.
Returning version 640
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 240
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
Returning version 140
WARNING [Project: :app] Current NDK support is deprecated.  Alternative will be provided in the future.
signing.properties not found
:app:preBuild UP-TO-DATE
:app:preAV5DebugBuild UP-TO-DATE
:app:checkAV5DebugManifest
:app:preAV5ReleaseBuild UP-TO-DATE
:app:preAV7DebugBuild UP-TO-DATE
:app:preAV7ReleaseBuild UP-TO-DATE
:app:preX86DebugBuild UP-TO-DATE
:app:preX86ReleaseBuild UP-TO-DATE
:tess-two:tess-two:compileLint
:tess-two:tess-two:copyReleaseLint UP-TO-DATE
:tess-two:tess-two:mergeReleaseProguardFiles UP-TO-DATE
:tess-two:tess-two:preBuild UP-TO-DATE
:tess-two:tess-two:preReleaseBuild UP-TO-DATE
:tess-two:tess-two:checkReleaseManifest
:tess-two:tess-two:prepareReleaseDependencies
:tess-two:tess-two:compileReleaseAidl UP-TO-DATE
:tess-two:tess-two:compileReleaseRenderscript UP-TO-DATE
:tess-two:tess-two:generateReleaseBuildConfig UP-TO-DATE
:tess-two:tess-two:generateReleaseAssets UP-TO-DATE
:tess-two:tess-two:mergeReleaseAssets UP-TO-DATE
:tess-two:tess-two:generateReleaseResValues UP-TO-DATE
:tess-two:tess-two:generateReleaseResources UP-TO-DATE
:tess-two:tess-two:packageReleaseResources UP-TO-DATE
:tess-two:tess-two:processReleaseManifest UP-TO-DATE
:tess-two:tess-two:processReleaseResources UP-TO-DATE
:tess-two:tess-two:generateReleaseSources UP-TO-DATE
:tess-two:tess-two:ndkBuild FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':tess-two:tess-two:ndkBuild'.
> A problem occurred starting process 'command '/Users/renard/devel/android-ndk-r9c//ndk-build''

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 6.703 secs

A: You can use this code.
    Drawable d = imageView.getDrawable();

    Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
    byte[] ba;
    do {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        Log.e("BEFORE REDUCING",
                bitmap.getHeight() + " " + bitmap.getWidth() + " "
                        + bitmap.getRowBytes() * bitmap.getHeight());

        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);

        ba = bao.toByteArray();
        if ((ba.length / 1024) >= 650) {
            bitmap = Bitmap.createScaledBitmap(bitmap,
                    (int) (bitmap.getWidth() * 0.95),
                    (int) (bitmap.getHeight() * 0.95), true);

        }

        Log.e("BYTE LENGTH", "" + ba.length / 1024);

    } while ((ba.length / 1024) >= 650);

    String ba1 = Base64.encodeToString(ba, Base64.DEFAULT);

this code converts images to 64 bit string. For more follow this link enter link description here
1: how to convert an image into base64 string and enter link description here


text:
Q: Adm Zip zipping files as directories I am trying to pack files into a zip file using Adm-Zip
var AdmZip = require('adm-zip');

var pathToZip = 'build/release/Ext.zip';

var zip = new AdmZip();

zip.addLocalFile('background.js');
zip.addLocalFile('chrome_ex_oauth.html');
zip.addLocalFolder('images');
zip.writeZip(pathToZip);

However, all the files are getting added as folders inside the zip and the actual content is not getting zipped.

The Getting Started reference is below and this seems to be a very simple example which is not working as expected. What am I doing wrong?
https://github.com/cthackers/adm-zip/wiki/ADM-ZIP-Introduction

A: var zip = new admZip();
var fs=require('fs-extra');
zip.addFile('NGINX/app.js',fs.readFileSync('./app.js'),'',0644);
zip.writeZip("./files.zip");

A: So I did some digging:
https://github.com/cthackers/adm-zip/blob/master/adm-zip.js#L275
addFile is ultimately called by addLocalFile, and that seems to be where the error is occurring, specifically on line 281 where it checks if the ZipEntry is a directory. The wrong flags are getting applied.
To get around this, I ended up calling addFile manually and specified the attributes myself, so that it wouldn't rely on auto-detection and incorrectly flag files as directories.
addFile(filePathInArchive, fileBuffer, '', 0644 << 16);

To get a fileBuffer yourself, you can use fs.readFile or fs.readFileSync

A: From the wiki of adm-zip:

[void] addLocalFile(String localPath, String zipPath)

Adds a file from the disk to the archive.

[void] addLocalFolder(String localPath, String zipPath)

Adds a local directory and all its nested files and directories to the archive
As it seems you miss the second parameter that is the zipPath.


text:
Q: How to union two python dictionaries to such two pair lists? for example,I have two dictionaries as below.
>>> x = {'a':1, 'b': 2}

>>> y = {'b':10, 'c': 11}

after some operation, Could I have such two lists? Thank you in advance.
x=['a','b','c']

y=[1,2,0]

z=[0,10,11]

That means 'c' in x list does not occur in y list, so there is zero in the corresponding place of y list.

A: Create a set of the unified keys of the dictionaries, by converting their keys to sets and using the | sets union operator.
Then use the .get method of the dictionaries (see here) to select only the keys that are contained within them (or 0 if not contained):
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> s = sorted(set(x) | set(y))
>>> a = [x.get(k, 0) for k in s]
>>> b = [y.get(k, 0) for k in s]
>>> s
['a', 'b', 'c']
>>> a
[1, 2, 0]
>>> b
[0, 10, 11]

Or, as simple code:
s = sorted(set(x) | set(y))
a = [x.get(k, 0) for k in s]
b = [y.get(k, 0) for k in s]

You could use also the .keys() method to get the unified list of keys (x.keys() == set(x)) as @wim noted:
s = sorted(x.keys() | y.keys())


text:
Q: Injectivity of the Fourier transform on $L^1$ without inversion Is there a proof of the injectivity of the Fourier transform on $L^1({\bf R})$ that does not rely on an inversion formula?
The proofs I have seen in the literature ultimately rely either on the Fourier inversion formula for $L^2$ or Schwartz functions, on the Plancherel formula in $L^2$ which is more or less equivalent to the inversion formula, or on some inversion formula in $L^1$ using the Fejer kernel.

A: Following the comment of Denis Chaperon de Lauzières, I had a look at the book of Rudin, which indeed leads to a proof of the injectivity based on the Stone-Weierstrass theorem and does not rely on the $L^2$ theory.
One needs an integrable function $k$ with compactly supported transform. W. Rudin uses the inversion formula here but this can be obtained by a direct explicit computation if we are on ${\bf R}$, e.g. with $k(x) = {\sin^2 x\over x^2}$. Then, using Fubini theorem,
$$\langle e^{i\xi x}, \overline{\hat{k}} f \rangle  = \langle \hat{k}, e^{-i\xi x} f \rangle = \langle k, \hat{f}(.-\xi)\rangle = 0.$$
From the Stone-Weierstrass theorem (wrt the compact-open topology), we see that $\langle g, \overline{\hat{k}} f \rangle = 0$ for all continuous $g$ and by density, $\overline{\hat{k}} f = 0$. We get the result by dilating the support of $\hat{k}$.
Answering Alexandre Eremenko's comment, this gives a way to solve quickly the heat equation without needing to set up the whole $L^2$ theory. Indeed, denoting the heat kernel by $K_t$, and assuming we know how to compute its transform, getting to the heat equation in the phase space
$$\hat{u} = \widehat{K_t}\widehat{u_0} = \widehat{K_t * u_0}$$
only uses the most basic properties of the Fourier transform on $L^1$ and injectivity gives the result. The inverse formulas are not needed here.


text:
Q: Wrong output in simple c++ program implementing copy     #include<iostream>
#include<vector>
using namespace std;
class test{
    int a,b;
    public:
    test():a{0},b{0}{}
    test(int,int);
    void copy(test);
    void print();
};
test::test(int a,int b){
    a=a;
    b=b;
}
void test::copy(test obj)
{
    a=obj.a;
    b=obj.b;
}
void test::print()
{
    cout<<test::a<<" <========> "<<b<<endl;
}
int main()
{
    test t1(4,15);
    t1.print();
    test t2=t1;
    t2.print();
}

The above code should print
4 <========> 15
4 <========> 15
but it is printing
1733802096 <========> 22093
1733802096 <========> 22093
I am not getting the problem.
if I change the parameter name in the constructor it is giving correct output.
What could be the reason for such behavior??

A: You are reassigning your parameters here:
test::test(int a,int b){
    a=a;  // You just set parameter a to its own value!
    b=b;
}

is not the same as:
test::test(int a,int b){
    this->a=a;
    this->b=b;
}

and should be replaced with:
test::test(int a,int b) : a(a), b(b) {}

all together.


text:
Q: How to map a Map into another Map using Java Stream? I'm learning Java with Stream and I have this Map<String, List<Customer>> map1 and I want to map it into this Map<String, List<CustomerObj>> map2. How can I do this especially using Java Stream? Any feedback will be apreciated!

A: You can stream the entries of map1 and collect with Collectors.toMap, using key mapper Map.Entry::getKey. For the value mapper you can get the entry value list, then stream and map from Customer to CustomerObj, and finally collect to List.
Here's and example using Integer instead of Customer and String instead of CustomerObj:
Map<String, List<Integer>> map1 = Map.of(
        "A", List.of(1, 2),
        "B", List.of(3, 4),
        "C", List.of(5, 6));

Map<String, List<String>> map2 = map1.entrySet().stream().collect(
        Collectors.toMap(Map.Entry::getKey,
                entry -> entry.getValue().stream()
                        .map(String::valueOf).toList()));

A: You may do it like so:
Customer c1 = new Customer("İsmail", "Y.");
Customer c2 = new Customer("Elvis", "?.");

Map<String, List<Customer>> customerList = new HashMap<>();
customerList.put("U1", Arrays.asList(c1));
customerList.put("U2", Arrays.asList(c1, c2));

Map<String, List<CustomerObj>> customerObjList = customerList
        .entrySet().stream().collect(
                Collectors.toMap(Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .map(CustomerObj::new)
                                // or .map(c -> new CustomerObj(c))
                                .collect(Collectors.toList())
                )
        );
    }

private static class Customer {

    private String firstName;
    private String lastName;

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

private static class CustomerObj {

    private String fullName;

    public CustomerObj(Customer customer) {
        this.fullName = String.join(" ",
                customer.getFirstName(), customer.getLastName()
        );
    }

    public String getFullName() {
        return fullName;
    }
}

@Oboe's answer works in Java 16+ and this answer is similar to your models and easier to understand.


text:
Q: How to change permit parameter before saving in Rails? I have the next code:
permitted = params.permit(:url, :title, :description, :post_type, :category_id)

and I want to change params[:url] before saving process. I did try:
params[:url] = "abc"

but it didn't change this value. How can I catch and change it before saving? It's into feed controller. I also tried:
params[:feed][:url]

but again nothing. Can anyone gives me some tips?

A: You can initialize the model with permitted parameters, then change any of them how you wish:
m = Model.new(permitted)
m.url = "abc"
m.save

A: I use the following ways, depending on what I need.
before_save callback
Define in your model. Good when there is a general rule on what data should be in the given field. In most other cases too, actually, but that's slightly more complicated.
params.require(...).permit(...).merge(url: 'whatever')
This takes your parameters and writes (overwriting) the ones given inside merge. It doesn't have to be one key-value pair. I use that sometimes for writing in timestamps. It's a rather clean trick, but befoe_save should be favored: I only use it when I don't think writing a separate one-use-case method on a model is worth it.


text:
Q: How to use Buildship with existing Gradle projects I've got several projects in my Eclipse workspace that use Gradle as their build system. Up to now, I'm running the Gradle commands from the command line.
I've installed Buildship in order to run Gradle tasks more conveniently from the "Gradle Tasks" view. But Buildship doesn't recognize the projects in my workspace as Gradle projects.
How to use Buildship with existing Gradle projects in the Eclipse workspace?

A: The only way at the moment to make buildship pick up a project is to use the import wizard.

*

*delete your project from eclipse (doesn't remove your files)

*File -> import -> gradle -> gradle project

follow the wizard and your project should now show up as a gradle project. If you find you still don't have any dependencies in eclipse then it is probably picking up an existing non-buildship .project file, In which case the following post should help:

*

*How do I refresh project dependencies using Buildship in Eclipse?


text:
Q: sending email through webpack vuejs I'm a beginner in vuejs2 and I'm trying to make a simple contact form (using webpack and vuejs2).
I've created my form with the send button pointing to the following method:
<button @click.prevent="sendemail" class="btn btn-xl">Send</button>

And the method:
methods: {
sendemail () {
  var mailgun = require('mailgun.js')
  var mg = mailgun.client({username: 'MYUSERNAME', key: MYAPIKEY})
  mg.messages.create('MYDOMAIN', {
    from: 'FROMEMAIL',
    to: ['TOEMAIL'],
    subject: 'SUBJECT',
    text: 'TEXT'
  })
  .then(msg => console.log(msg)) // logs response data
  .catch(err => console.log(err)) // logs any error
}
}

When I press send button I get the following error:
XMLHttpRequest cannot load https://api.mailgun.net/v3/MYDOMAIN/messages. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Any suggestions or any other way to do it?

A: The mailgun-js docs specify a way on how can we do this:
var api_key = 'key-XXXXXXXXXXXXXXXXXXXXXXX';
var domain = 'www.mydomain.com';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'serobnic@mail.ru',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomness!'
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

Also a word of caution, I would not put the api_key in my frontend as anyone can use it and send emails. Instead, try opting for a backend which will send emails for you.


text:
Q: Replacing the to_s method in Ruby. Not printing out desired string So, I am just beginning to learn Ruby and I included a to_s method in my Class so that I can simply pass the Object to a puts method and have it return more than just the Object ID. I made a mistake and defined it as such:
def to_s
    puts "I'm #{@name} with a health of #{@health}."
end

instead of:
def to_s
    "I'm #{@name} with a health of #{@health}."
end

So, when I do this while using the first code block:
player1 = Player.new("larry")
puts player1

I get an object ID and a string when I execute the above two lines of code and not just the string. Why is this? I get this output:
I'm Larry with a health of 90.
#<Player:0x007fca1c08b270>

I am trying to think about why the first version of the program doesn't just print out the string to console, but instead returns the object ID and the string. I thought that when I pass the object to puts, all that is happening is that puts turns around and calls the to_s method to get the player's string representation. Right?

A: When given arguments that are not strings or arrays puts calls rb_obj_as_string to turn its arguments into strings (see rb_io_puts)
If you search for rb_obj_as_string through the ruby codebase (I find http://rxr.whitequark.org useful for this) you can see it's defined as
VALUE rb_obj_as_string(VALUE obj)
{
  VALUE str;

  if (RB_TYPE_P(obj, T_STRING)) {
    return obj;
  }
  str = rb_funcall(obj, id_to_s, 0);
  if (!RB_TYPE_P(str, T_STRING))
    return rb_any_to_s(obj);
  if (OBJ_TAINTED(obj)) OBJ_TAINT(str);
  return str;
}

In brief this:

*

*returns straightaway if the argument is already a string

*calls to_s

*if the result is not a string, call rb_any_to_s and return that.

rb_any_to_s is what implements the default "class name and id" result that you're seeing: for any object it returns a string of the form #<ClassName: 0x1234567890abcdef>
Returning to your code, when you run puts player1 it calls  rb_obj_as_string to convert your player to a string.
This first calls your to_s method, which uses puts to output your message. Your method then returns nil (because that's what puts always returns) so ruby calls rb_any_to_s, and that is what the outermost puts ends up using.

A: That's because the puts returns nil, so does that version of to_s:
def to_s
  puts "I'm #{@name} with a health of #{@health}."
end

With puts player1, player1.to_s method is called, which prints the String "I'm ...", but the return value is that of the puts call inside to_s, which is nil.
So player1 is an object of which to_s returns nil, thus puts player1 in the end prints the result of the inherited to_s method.

A: Experiential Rule: If the result of to_s is not a String, then ruby returns the default.
Application of Rule: puts() returns nil, which means your to_s method returns nil, and nil is not a String, so ruby returns the default.
Another example:
class Object
  def inspect
    'obj-inspect'
  end

  def to_s
    'obj-to_s'
  end
end

class Dog
  def inspect
    'dog-inspect'
  end

  def to_s
    nil
  end
end

puts Dog.new

--output:--
#<Dog:0x1001b6218>

Once to_s fails to return a String, ruby does not continue along the method lookup path to call another to_s method.  That makes some sense: the method was found, so there is no need to look up the method in a parent class.  Nor does ruby alternatively call inspect() to get a result.
Where does the default come from?  I think ruby must directly call the Object#to_s method which is a method written in C--thereby bypassing ruby's method overriding mechanism.

A: The first example using puts will write to stdout and return nil. It does not actually return a String.
The second example returns a String.
If you want to write to the console you can, but you will need to also return the value.
#or put it in a variable first and return that after you print it
def to_s
  puts "I'm #{@name} with a health of #{@health}."
  "I'm #{@name} with a health of #{@health}."
end


text:
Q: Matching on "broken" strings Lets say I have this image. It is supposed to say "Box Logo Hooded Sweatshirt" and "Red", but obviously they have messed it up.
How would I deal with this insertion of random characters when trying to scrape and match on keywords?
Currently this is how I am matching (I match on a list of strings):
        product_name = piece.contents[0].contents[1].text
        product_color = piece.contents[0].contents[2].text

        print(product_name)
        print(product_color)
        if all(i in product_name.lower() for i in keywords) and all(i in product_color.lower() for i in color):
            found = True
            log('Found Product: ' + product_name + ' - ' + product_color, 'success')


text:
Q: Notation for number sets Variables a and b assume values of two number sets as part of a grid search.
a assumes the first 21 multiples of 1440, b assumes values from 0 to 1 in steps of $\dfrac{1}{100}$. To clarify ... $$a = [1440 \cdot 0,~1440 \cdot 1,~...,~1440 \cdot 21]$$
$$b = [0,~0.01,~...,~1]$$
I formulated this as seen below, which I am very unsure about.
$$a \in  \{i \in \mathbb{Z} \cap [1,21] | 1440\}$$
$$b \cdot 10^{2} \in \mathbb{Z} \cap \frac{1}{100}\cdot [0,100]$$
Is this correct?

A: Notation is convention, and depending on your background and your target audience, some conventions maybe different.
Usually in mathematics, we list set elements in between curly braces $$\{\text{set,elements,here,between,commas,}\cdots \text{,lots,of,elements}\}$$
and we reserve the bracket notation $[x,y]$ to denote all real numbers between $x$ and $y$: $$[x,y] = \{ r \in \mathbb{R} \mid x \leq r \leq y\}$$

In some contexts (as in some programming languages) brackets are used to denote a range of integers, for instance, $[0,5]$ could denote the set $\{0,1,2,3,4,5\}$. Without warning, though, the common mathematician would look at this set as the set of real numbers greater than or equal to $0$, and lesser than or equal to $5$. A more common notation for the set of non-negative integer numbers less than or equal to $n$ is $I_n = \{ m \in \mathbb{Z} \mid 0 \leq m \leq n\} = \{0,1,\cdots,n\}$. This isn't a universal convention even in mathematics though, but let's assume it for this answer.

So let's look at this set: $\mathbb{Z} \cap \dfrac{1}{100} \cdot [0,100]$.  Considering $[0,100]$ as the real number interval, we have that $$\frac{1}{100}\cdot [0,100]
 = \left\{\frac{r}{100}\mid r \in [0,100]\right\} = [0,1]$$
So that set is the interval $[0,1]$. Intersecting it with the integers would yield the binary set $\{0,1\}$. So saying that $b\cdot 10^2$ belongs to this set states that $b\cdot 10^2$ equals $0$ or $1$ (i.e., $b = 0$ or $b = 0.01$).
Let's say that we want to refer to all values of $b$ ranging from $0$ to $1$ in steps of $\dfrac{1}{100}$. One way of doing this in the notation we established is simply by stating: $$b \in \frac{1}{100} I_{100}\,.$$
Another way, this time using the set-builder notation:
$$b \in \left\{\frac{x}{100} \mid 0\leq x \leq 100\right\}$$
More compactly: $b = \dfrac{x}{100}$ for $0 \leq x \leq 100$ an integer. I leave the analysis of the multiples of $1440$ for you. Also, even if $[0,100]$ meant $I_{100}$, intersecting it with $\mathbb{Z}$ would also yield you a set with only $2$ elements (why?).


text:
Q: python function use multiple defaults or no defaults at all I am defining a class that represents a vector:
'''
An entity with size and direction
'''
UNINITIALIZED = -1

class myVector():
    def __init__(self,direction = UNINITIALIZED,size = UNINITIALIZED):
        self.direction = direction
        self.size = size

For using the class I imagine 2 scenarios : Either I know the vector's charecharistics on initiation and then initiate it with these values:
v = myVector(4,2)

Or I do not know these on intiation and then I'm happy it will get the default values.
However, with the above implementation a third scenario is realized - initiating a vector using only
the first argument :
v = myVector(4)

In this case only the second parameter (size) would be assigned the default value and the resulting object would not make much sense.
As I see it, the desired behavior in this case is either use both parameters or none. One way to implement this would be to raise an exception if this is the case.
def __init__(self,direction = UNINITIALIZED,size = UNINITIALIZED):
    if (direction != UNINITIALIZED) and (size == UNINITIALIZED):
        raise Exception('Use both parameters or none')
    self.direction = direction
    self.size = size

What do you think would be the pythonic way of doing this elegantly?

A: Size and direction sound like a tuple to me:
class myVector():
    def __init__(self, sd=(UNINITIALIZED, UNINITIALIZED)):
       try:
           self.size, self.direction = sd
       except (ValueError, TypeError) as e:
           raise ValueError('two values of size and direction must be specified')

It is then called with a tuple of both size and direction if the defaults aren't wanted.
If you didn't want to change the semantics to require passing a tuple, an alternative if you're not using other arguments is to change sd to *args and do the same thing - that seems less explicit to me though and means you can't use optional args for anything else.

A: You can also define the class like this:
class myVector():
    def __init__(self,*direction_and_size):
        if not len(direction_and_size):
            direction_and_size = [UNINITIALIZED, UNINITIALIZED]
        assert len(direction_and_size) == 2, "Please provide both parameters"
        self.direction,  self.size = direction_and_size

>>> v = myVector()
>>> v = myVector(4,2)
>>> v = myVector(4)
AssertionError: Please provide both parameters

A: Something like this?
class myVector():
    def __init__(self, direction = -1, size = -1):
        if (-1 in (direction, size)):
            self.size, self.direction = (-1, -1) #do your own fault/error handling here
                                                 #this just makes the example easier
        else:
            self.size = size,
            self.direction = direction

c1 = myVector(1, 1)
c2 = myVector(1)
c3 = myVector()

print(c1.direction, c2.direction, c3.direction)

Outputs:
    1 -1 -1


text:
Q: What is the difference between << and += while injecting elements to Hash.new([])? This code:
[{:id => 1,:key => 3},{:id => 2,:key => 4},{:id => 3, :key => 5}].
     inject(Hash.new([])){|h,i| h[i[:key]] << i; h}

returns:
{}

While this:
[{:id => 1,:key => 3},{:id => 2,:key => 4},{:id => 3, :key => 5}].
     inject(Hash.new([])){|h,i| h[i[:key]] += [i]; h}

returns:
{3=>[{:id=>1, :key=>3}, {:id=>3, :key=>3}], 4=>[{:id=>2, :key=>4}]}

Why doesn't the first case work same way?

A: In your first example, you are modifying the array that is returned as the default of the hash, but that array is not defined as the value to the hash, and is thrown away.
In your second example, you are modifying the default array as well as assigning the result as the value to the hash by the method Hash#[]=. Notice that foo += bar is syntax sugar for foo = foo + bar, which means that hash[foo] += bar is the same as hash[foo] = hash[foo] + bar.


text:
Q: Deserialize error with Jackson (png encoding) I have following string to parse (string to object) :
{   "langues" :
    [
        {"iso":"en", "id":1, "flag":[0,144,255,62,1,152,84,62,1,104,50,63,1,32,90,61,1,172,110,66,1,216,...]}
        ,
        {"iso":"fr", "id":2, "flag":[0,208,0,63,1,208,106,62,1,120,49,63,1,32,90,61,1,60,110,...]}
        ,
        { etc... }
    ],
    "when" : 133111... // timestamp
}

The flag is an array of byte for a png image
And following objects :
public class Langues {
    private Long when;
    private ArrayList<Langue> langues;

    public Long getWhen(){ return when; }
    public void setWhen(Long when) { this.when=when; }
    ...
}

public class Langue {
    private int id;
    private String iso;
    private byte[] flag;

    // getters / setters
}

this throw me an error :
ObjectMapper mapper = new ObjectMapper();
Langues node = mapper.readValue(myString, Langues.class);

JsonParseException
Numeric value (144) out of range of Java byte

maybe byte[] is not the right container for it or can i set jackson parser encoding somewhere ?
thanks in advance !!
[EDIT]
maybe editing each field of the array of byte with -128 could have done it but kind of tricky and a real waste of time...
i contacted codehaus thanks to mailing list and i ended in no time with an AnsiString instead of UNICODE or Bytes, and voilà !
{"langues":[{"iso":"zh","id":7,"flag":"iVBORw0KGgoAAAANSUhEUgAAAIAAAABpCAYAAADy...

with same simple code
ObjectMapper mapper = new ObjectMapper();
Langues node = mapper.readValue(myString, Langues.class);

A: Maybe editing each field of the array of byte with -128 could have done it but kind of tricky and a real waste of time...
i contacted codehaus thanks to mailing list and i ended in no time with an AnsiString instead of UNICODE or Bytes, and voilà !
{"langues":[{"iso":"zh","id":7,"flag":"iVBORw0KGgoAAAANSUhEUgAAAIAAAABpCAYAAADy...

with same simple code
ObjectMapper mapper = new ObjectMapper();
Langues node = mapper.readValue(myString, Langues.class);


text:
Q: perl non-greedy replace not working at the start I am having a XML similar to this
<Level1Node>
.
.
    <Level2Node val="Retain"/>
.
.
</Level1Node>
<Level1Node>
.
.
    <Level2Node val="Replace"/>
.
.
</Level1Node>
<Level1Node>
.
.
    <Level2Node val="Retain"/>
.
.
</Level1Node>

I need to remove only the below node,
<Level1Node>
.
.
    <Level2Node val="Replace"/>
.
.
</Level1Node>

To have it replaced in non-greedy manner, I used the below regex,
perl -0 -pe "s|<Level1Node>.*?<Level2Node val="Retain"/>.*?</Level1Node>||gs" myxmlfile

But the non-geedy terminates the match only at the end of the pattern, not at the start. How to get it started at the last match of <Level1Node>

A: You will need to use a negative lookahead to make sure you do not match closing Level1Node tags where you don't want to:
perl -0 -pe 's|<Level1Node>(?:(?!<\/Level1Node>).)*<Level2Node val="Retain"\/>(?:(?!<\/Level1Node>).)*<\/Level1Node>||gs' tmp.txt

Details:
<Level1Node>
(?:(?!<\/Level1Node>).)* # Everything except </Level1Node>
<Level2Node val="Retain"\/>
(?:(?!<\/Level1Node>).)* # Everything except </Level1Node>
<\/Level1Node>

?: is only here so that the parenthesis are not interpreter as a capturing group.
If you plan to run this on a large file, you should probably check the cost of the negative lookahead, it might be high.

A: Use a proper parser! It's way simpler.
perl -MXML::LibXML -e'
   my $doc = XML::LibXML->new->parse_file($ARGV[0]);
   $_->unbindNode() for $doc->findnodes(q{//Level1Node[Level2Node[@val!="Retain"]]});
   $doc->toFH(\*STDOUT);
' tmp.txt


text:
Q: relation between function and derivatives If there are two non-negative functions $\psi_1(\theta)$ and $\psi_2(\theta)$, for $\theta \in (0, \infty)$, such that $\psi_1(\theta)$ is decreasing, then is is possible to have $\psi_1(\theta) > \psi_2(\theta)$ and $\psi_1'(\theta) < \psi_2'(\theta)$???

A: $\psi_1(\theta) = 1$
$\psi_2(\theta) = 1 - \frac 1 {\theta}$


text:
Q: как нажать по координатам в python у меня есть бот который должен очень быстро нажать по координатам если заметит изменение цвета, но pyautogui.click(x, y) выполняется 100мс, без него условие выполняется очень быстро. Есть ли способ который заменит pyautogui.click(x,y)?

A: import win32api
import win32con
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, 0, 0)


text:
Q: caffe: average of conv layer filters (over channel) I have a conv layer of dimension nXmx16x1 and I want to calculate mean or sum of the 16 filters, so the result is 1 filter of dim nxmx1x1.
something like mean(A,3) in matlab

A: Use a constant 1x1 "Conv" filter:
layer {
  name: "avg"
  type: "Convolution"
  bottom: "input"
  top: "output"
  param { lr_mult: 0 decay_mult: 0 }  # fix this layer, do not train
  convolution_param {
    num_output: 1
    kernel_size: 1
    bias: false  # no bias
    weight_filler: { type: "constant" value: 0.0625 }  # 1/16.
  }
}


text:
Q: Strange Streaks on Samsung CJG50 Monitor all!
I have two Samsung CJG50 monitors, which I mounted to an arm last night. One's 6 months old, the other right out of its packaging.
When going from dark grey to a lighter colour, streaks will appear across the screen along the top of the area of lighter colour. These streaks move with the content onscreen. While it's more noticeable on the older monitor (it wasn't before), I'm surprised it's showing on both, as it's fairly unlikely that something was done which would damage both. I have since tried the monitor with a Fire Stick to ensure it wasn't the computer or cables - same effect was noticeable. I haven't found any videos or mentions of this phenomenon anywhere online, which makes its appearance in two monitors even stranger.
I recreated the effect in Photoshop as I couldn't get a good photo.
Any help would be much appreciated!


text:
Q: Image text wrap not working properly on frontend I've been tearing my hair out trying to get this fixed. I can't figure out what's going wrong. It looks fine in the Visual Editor (though I usually use the text version instead - and NEVER use Gutenburg (so this is referencing the Classic Editor).
Images aligned left or right just do not properly wrap the text. I have added the following CSS to my stylesheet, and it makes no difference.
.alignnone {
    margin: 5px 20px 20px 0;
}

.aligncenter,
div.aligncenter {
    display: block;
    margin: 5px auto 5px auto;
}

.alignright {
    float:right;
    margin: 5px 0 20px 20px;
}

.alignleft {
    float: left;
    margin: 5px 20px 20px 0;
}

a img.alignright {
    float: right;
    margin: 5px 0 20px 20px;
}

a img.alignnone {
    margin: 5px 20px 20px 0;
}

a img.alignleft {
    float: left;
    margin: 5px 20px 20px 0;
}

a img.aligncenter {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

It wraps only with the paragraph it was added next to. But subsequent paragraphs do not continue the wrap. They start below the image, as seen in this screenshot:

Can anyone help me here?

A: Your container div for the content area has a class of .row, which is set to display:flex in Bootstrap. Direct children of a parent with display:flex can't be floated.
To fix this you'll either need to update the .row class so it's not set to display:flex (display:block works for me), or add an interior wrapper div so that the image and paragraphs not direct children of the .row div.


text:
Q: Почему не работает input file при загрузке через ajax Проблема в следующем:
Загружаю форму через AJAX, в форме есть поле input[type=file], но при нажатии на поле - не открывается диалоговое окно для выбора файла... При входе на форму на прямую - всё открывается.
В целом выяснил, если добавлять input[type=file] динамически через jQuery - он не работает.
$(".clkfile").append('<input name="image" type="file">');

Как добиться работоспособности, не теряя при этом функционал подгрузки формы через ajax?

A: Перепроверьте Ваш код.
Сделал как Вы описали - все работает.
Возможно Вы напутали с классами в js.
<form class="clkfile">

</form>

<button id="handler_btn" type="button">add file input</button>

$('#handler_btn').on('click', function() {

    $('.clkfile').append('<input name="image" type="file">');

});

A: Ошибка была не в jQuery и не в input'e, а копипасте чужого кода.
Надо внимательнее смотреть наследование при определении click...
Получалось так, что при click на input - выполнялось действие родительского элемента, у которого if(e.target == this){ e.preventDefault(); }
Спасибо всем кто подключился.


text:
Q: Expectation of stochastic integral, martingale I have to show that
$$\mathbb{E}\left[ \int_0^t a B_s^{a-1} \ dB_s \right] = 0$$
I started with the fact that, if I show that the inner integral $\int_0^t a B_s^{a-1} \ dB_s$ is a martingale I get the wanted result.
One way to show that the stochastic integral is a martingale is to show that:
$$\mathbb{E}\left[ \int_0^t (a B_s^{a-1})^2 \ ds \right] < \infty$$
which is basically saying $aB_s^{a-1} \in \Lambda^2(t)$ (to have this we also need the process to be progressive, but it follows by BM properties I guess).
Using Fubini I can interchange expectation and integral, bring outside constants and write:
$$\mathbb{E}\left[ \int_0^t (a B_s^{a-1})^2 \ ds \right] =  \int_0^t a^2 \ \ \mathbb{E}\left[ B_s^{\ 2(a-1)} \right] ds< \infty$$
any hint to show this? I should not use results on Brownian motion moments.
NOTE: edited after @surb comment!!

A: Here is a proof for $\int_0^{t} aEB_s^{a-1}ds <\infty$ which you wanted . You need to modify this based on the comment of Surb.
$B_s \sim \sqrt s X$ where $X$ has standard  normal distribution. Hence, your integral $\int_0^{t} aEB_s^{a-1}ds <\infty$ is a constant times $\int_0^{t} s^{(a-1)/2}ds$ and this last integral equals $\frac {t^{(a+1)/2}} {(a+1)/2}$ if $a>-1$.


text:
Q: calculate the weekday information based on date information In a dataframe created using Pandas, there is one column, i.e., 'date', storing the value of date, i.e., 2012-10-8, how can I create another column, each entry of which stores the weekdays for the corresponding date entry.
In other words, I would like to have two columns
date         weekday
2012-10-8    Tuesday

The weekday entry need to be computed based on the date column.

A: IIUC, use .dt accessor and strftime using %A
>>> df.date.dt.strftime('%A')

0    Monday
Name: date, dtype: object

ps: Note that 2012-10-08 was a Monday, and not Tuesday

A: Use pandas.Series.dt.day_name.
df.date.dt.day_name()

0    Monday
Name: date, dtype: object

While not necessary here, it also takes locale as a parameter
df.date.dt.day_name(locale='es')

0    Lunes
Name: date, dtype: object

pandas.Series.dt.day_name is new in pandas 0.23.0, if you are using a previous version, use weekday_name instead:
df.date.dt.weekday_name

0    Monday
Name: date, dtype: object

Using weekday_name has been deprecated in 0.23.0 in favor of day_name()


text:
Q: How to just get text BeautifulSoup I am a first time poster. I'm making a program to tell the weather with requests and BeautifulSoup that is formatting the proper information wrong. I have
import requests
from bs4 import BeautifulSoup

url = 'https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c'

def getdata(url):
    r = requests.get(url)
    return r.text

htmldata = getdata(
    "https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c")

soup = BeautifulSoup(htmldata, 'html.parser')

precip = soup.find('div', id='WxuTodayWeatherCard-main-486ce56c-74e0-4152-bd76-7aea8e98520a')

currentPrecip = precip.find('li')

for j in currentPrecip:
    showPrecip = currentPrecip.get_text()

result = f"Current Temp: {showPrecip}"

print(result)

The program is outputting Current Temp: Morning-5°Snow-- and I want it to output Current Temp: -5°C, Sky Snow
Any help is appreciated and thanks in advance

A: Your question is not that clear, your taking the forecast and expect the current data. This may should be improved.
Current:
live = soup.select_one('div.styles--card--3aeCQ a')
print(f"Current Temp: {live.find('span').get_text()}, Sky: {live.find('svg').get_text()}")

Forecast (Morning):
morning = soup.select_one('section[data-testid="TodayWeatherModule"] ul>li')
print(f"Current Temp: {morning.div.span.get_text()}, Sky: {morning.find('title').get_text()}")

Example
import requests
from bs4 import BeautifulSoup

url = 'https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')

live = soup.select_one('div.styles--card--3aeCQ a')
print(f"Current Temp: {live.find('span').get_text()}, Sky: {live.find('svg').get_text()}")

morning = soup.select_one('section[data-testid="TodayWeatherModule"] ul>li')
print(f"Current Temp: {morning.div.span.get_text()}, Sky: {morning.find('title').get_text()}")

Output
Current Temp: -2°, Sky: Snow
Current Temp: -5°, Sky: Snow


text:
Q: Multinomial logit with random effects does not converge using mblogit I would like to estimate a random effects (RE) multinomial logit model.
I have been applying mblogit from the mclogit package. However, once I introduce RE into my model, it fails to converge.
Is there a workaround this?
For instance, I tried to adjust the fitting process of mblogit and increase the maximal number of iterations (maxit), but did not succeed to correctly write the syntax for the control function. Would this be the right approach? And if so, could you advise me how to implement it into my model which so far looks as follows:
meta.mblogit <- mblogit(Migration  ~ ClimateHazard4 , weights = logNsquare,
data = meta.df,   subset= Panel==1,  random = ~1|StudyID,
)

Here, both variables (Migration and ClimateHazard4) are factor variables.
Or is there an alternative approach you could recommend me for an estimation of RE multinomial logit?
Thank you very much!


text:
Q: Internal server error when uploading large files in php I'm using codeIgniter and I'm getting internal server error when trying to upload large files (might be 1Mb and up)
The file upload script is working because it uploads to the folder in the server. But saving the file into the database it doesn't work anymore. I've already tried changing the following but still doesn't work:
php.ini

*

*post_max_size = 50M

*upload_max_filesize = 20M

my.ini

*

*max_allowed_packet = 2048M

*max_execution_time = 150

Where else do I have to check to ensure that the file upload to the database works.

A: Save the files do the directory, not on the database. You might want to save the path though in the databse.
If you want to know WHY, here are some previous post you should check.

*

*Storing Documents as Blobs in a Database - Any disadvantages?

*Storing Images in DB - Yea or Nay?

A: Restart your apache server and try again.

A: I think think you should save files to Database ..but if you insist try NoSQL Solutions instead .. such as MongoDB .. its faster and better


text:
Q: iOS8 incorrrect value of UIView.systemLayoutSizeFittingSize with Size Classes I've faced strange issue with method UIView.systemLayoutSizeFittingSize when Size Classes are being on on iOS 8.
As example I'm usign Paul's tutorial project for auto height cell. Also project with mine modifications for demonstrate purpose, can be found here
So on iOS 7 it looks like nice.

But on iOS 8 method return much more lesser value and then cells are starting to breaking apart.

This issue is gone when Size Classes is being off. I don't know how to aproach this and at this point only solution I know is turn of Size Classes.
Code
ViewController.m (108 lines)
#import "ViewController.h"
#import "CustomTableViewCell.h"

@interface ViewController () <UITableViewDataSource, UITableViewDelegate> {

    NSMutableArray *_fontArray;
    NSMutableArray *_quoteArray;

}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) CustomTableViewCell *customCell;

@end

@implementation ViewController

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

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

//    self.navigationItem.rightBarButtonItem = self.editButtonItem;

    _fontArray = [[UIFont familyNames] mutableCopy];
    for(int i = 0; i < 100; i++) {
        [_fontArray addObjectsFromArray:[UIFont familyNames]];
    }
    NSLog(@"Size: %d", [_fontArray count]);

    _quoteArray = [@[@"For the past 33 years, I have looked in the mirror every morning and asked myself: 'If today were the last day of my life, would I want to do what I am about to do today?' And whenever the answer has been 'No' for too many days in a row, I know I need to change something. -Steve Jobs",
                     @"Be a yardstick of quality. Some people aren't used to an environment where excellence is expected. - Steve Jobs",
                     @"Innovation distinguishes between a leader and a follower. -Steve Jobs"] mutableCopy];

    // Use iOS 8 new auto sizing feature for heights (don't need to calculate yourself)
//    _tableView.rowHeight = UITableViewAutomaticDimension;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [_fontArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CustomTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomCell"];

    cell.fontNameLabel.text = _fontArray[indexPath.row];

    int quoteIndex = indexPath.row % [_quoteArray count];
    cell.quoteLabel.text = _quoteArray[quoteIndex];
    cell.quoteLabel2.text = _quoteArray[quoteIndex];
    NSString *fontName = _fontArray[indexPath.row];
    cell.quoteLabel.font = [UIFont fontWithName:fontName size:17];
    cell.quoteLabel2.font = [UIFont fontWithName:fontName size:17];
    return cell;

}

// NOTE: in iOS 8 you can use the automatic height calculations from AutoLayout,
//  and you can avoid writing this height method. Just comment it out, and uncomment
//  the line in viewDidLoad for
//  _tableView.rowHeight = UITableViewAutomaticDimension;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Calculate a height based on a cell
    if(!self.customCell) {
        self.customCell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    }

    // Configure the cell
    self.customCell.fontNameLabel.text = _fontArray[indexPath.row];

    int quoteIndex = indexPath.row % [_quoteArray count];
    self.customCell.quoteLabel.text = _quoteArray[quoteIndex];
    self.customCell.quoteLabel2.text = _quoteArray[quoteIndex];
    NSString *fontName = _fontArray[indexPath.row];
    self.customCell.quoteLabel.font = [UIFont fontWithName:fontName size:17];
    self.customCell.quoteLabel2.font = [UIFont fontWithName:fontName size:17];

    // Layout the cell

    [self.customCell layoutIfNeeded];

    // Get the height for the cell

    CGFloat height = [self.customCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    // Padding of 1 point (cell separator)
    CGFloat separatorHeight = 1;
    NSLog(@"%f",height);

    return height + separatorHeight;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 140;

}

@end

CustomTableViewCell.h (10 lines)
#import <UIKit/UIKit.h>

@interface CustomTableViewCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *quoteLabel;
@property (weak, nonatomic) IBOutlet UILabel *fontNameLabel;
@property (strong, nonatomic) IBOutlet UILabel *quoteLabel2;

@end

CustomTableViewCell.m (39 lines)
#import "CustomTableViewCell.h"

@implementation CustomTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

// CODE FIX layouts by setting the maxPreferredWidth on any UILabel that can be
//  multiline – you may have to do similar settings to other UI elements
//  This logic fixes the layout for any UILabels that don't go up to the margins, they
//  might be offset by a constraint that isn't the standard.

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.contentView layoutIfNeeded];
    self.fontNameLabel.preferredMaxLayoutWidth = self.fontNameLabel.frame.size.width;
    self.quoteLabel.preferredMaxLayoutWidth = self.quoteLabel.frame.size.width;
    self.quoteLabel2.preferredMaxLayoutWidth = self.quoteLabel2.frame.size.width;
}

@end

A: Your issue is likely because when you use a prototype cell created with dequeueReusableCellWithIdentifier, the cell returned has no size class because it is not part of a view hierarchy and thus does not have a traitCollection associated with it.
I worked around this by temporarily adding the cell to the table view, doing the sizing and then removing it. While added, the customCell acquires the size class of the controller and layout then uses any size class related fonts, constraints etc... The real cells do not have the same issue as they have a size class by being part of the UITableView.
So try changing your height calculation as follows:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Calculate a height based on a cell
    if(!self.customCell) {
        self.customCell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    }

    // ***
    // *** Add custom cell to the table view so it obtains a size class
    // *** for layout. Also mark it as needing layout.
    // ***
    [self.tableView addSubview:customCell];
    [customCell setNeedsLayout];

    // Configure the cell
    self.customCell.fontNameLabel.text = _fontArray[indexPath.row];

    int quoteIndex = indexPath.row % [_quoteArray count];
    self.customCell.quoteLabel.text = _quoteArray[quoteIndex];
    self.customCell.quoteLabel2.text = _quoteArray[quoteIndex];
    NSString *fontName = _fontArray[indexPath.row];
    self.customCell.quoteLabel.font = [UIFont fontWithName:fontName size:17];
    self.customCell.quoteLabel2.font = [UIFont fontWithName:fontName size:17];

    // Layout the cell

    [self.customCell layoutIfNeeded];

    // Get the height for the cell

    CGFloat height = [self.customCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    // Padding of 1 point (cell separator)
    CGFloat separatorHeight = 1;
    NSLog(@"%f",height);

    // ***
    // *** Remove cell from the table view
    // ***
    [customCell removeFromSuperview];

    return height + separatorHeight;
}


text:
Q: Highcharts Line Chart Drill down not working properly In my application I have a Line chart showing employee head count variation in several departments over several years. Then when I click on a one data series(Ex: Department A) I need to show a drill down of that selected department. I have added the drill dwon code and drill down data to the chart definition. Seems it's not working properly. I couldn't find what's wrong here. Is there a workaround for this one. Sample code is as following.
http://jsfiddle.net/yasirunilan/qja2s3rb/9/
 var chart = new Highcharts.Chart({
    chart: {
      renderTo: "container-main-bar",
      type: "line"
    },
    title: {
      text: null
    },
    series: [{
      "name": "Department A",
      "data": [{
          "name": "Month1",
          "y": 27,
          "drilldown": "levelA2"
        },
        {
          "name": "Month2",
          "y": 24,
          "drilldown": "levelA2"
        },
        {
          "name": "Month3",
          "y": 22,
          "drilldown": "levelA2"
        },
        {
          "name": "Month4",
          "y": 26,
          "drilldown": "levelA2"
        },
        {
          "name": "Month5",
          "y": 21,
          "drilldown": "levelA2"
        },
        {
          "name": "Month6",
          "y": 22,
          "drilldown": "levelA2"
        },
        {
          "name": "Month7",
          "y": 23,
          "drilldown": "levelA2"
        },
        {
          "name": "Month8",
          "y": 24,
          "drilldown": "levelA2"
        },
        {
          "name": "Month9",
          "y": 21,
          "drilldown": "levelA2"
        },
        {
          "name": "Month10",
          "y": 20,
          "drilldown": "levelA2"
        },
        {
          "name": "Month11",
          "y": 22,
          "drilldown": "levelA2"
        },
        {
          "name": "Month12",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month13",
          "y": 23,
          "drilldown": "levelA2"
        },
        {
          "name": "Month14",
          "y": 24,
          "drilldown": "levelA2"
        },
        {
          "name": "Month15",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month16",
          "y": 26,
          "drilldown": "levelA2"
        },
        {
          "name": "Month17",
          "y": 24,
          "drilldown": "levelA2"
        },
        {
          "name": "Month18",
          "y": 23,
          "drilldown": "levelA2"
        },
        {
          "name": "Month19",
          "y": 23,
          "drilldown": "levelA2"
        },
        {
          "name": "Month20",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month21",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month22",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month23",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month24",
          "y": 25,
          "drilldown": "levelA2"
        }
      ],
      "drilldown": {
        "series": [{
          "name": 'Headcount',
          "id": 'levelA2',
          "data": [{
              "name": "Month1",
              "y": 10,
            },
            {
              "name": "Month2",
              "y": 12,
            },
            {
              "name": "Month3",
              "y": 11,
            },
            {
              "name": "Month4",
              "y": 10,
            },
            {
              "name": "Month5",
              "y": 9,
            },
            {
              "name": "Month6",
              "y": 8,
            },
            {
              "name": "Month7",
              "y": 10,
            },
            {
              "name": "Month8",
              "y": 12,
            },
            {
              "name": "Month9",
              "y": 11,
            },
            {
              "name": "Month10",
              "y": 13,
            },
            {
              "name": "Month11",
              "y": 14,
            },
            {
              "name": "Month12",
              "y": 10,
            },
            {
              "name": "Month13",
              "y": 9,
            },
            {
              "name": "Month14",
              "y": 8,
            },
            {
              "name": "Month15",
              "y": 11,
            },
            {
              "name": "Month16",
              "y": 10,
            },
            {
              "name": "Month17",
              "y": 9,
            },
            {
              "name": "Month18",
              "y": 10,
            },
            {
              "name": "Month19",
              "y": 11,
            },
            {
              "name": "Month20",
              "y": 12,
            },
            {
              "name": "Month21",
              "y": 13,
            },
            {
              "name": "Month22",
              "y": 10,
            },
            {
              "name": "Month23",
              "y": 11,
            },
            {
              "name": "Month24",
              "y": 12,
            }
          ]
        }]
      }
    }, ],
    xAxis: {
      categories: [{
          "name": "2013",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2014",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2015",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2016",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2017",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2018",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        }
      ]
    },
    yAxis: [{ // Primary yAxis
      title: {
        text: 'No. of Employees'
      },
    }],
  });

A: first you have to add drilldown.js in your HTML

and drilldown object is wrongly entered in the input JSON object. it should come out of series. below is the correct format. Please have a look in the code snippet.

$(function() {
  var chart = new Highcharts.Chart({
    chart: {
      renderTo: "container-main-bar",
      type: "line"
    },
    title: {
      text: null
    },
    series: [{
      "name": "Department A",
      "data": [{
          "name": "Month1",
          "y": 27,
          "drilldown": "levelA2"
        },
        {
          "name": "Month2",
          "y": 24,
          "drilldown": "levelA2"
        },
        {
          "name": "Month3",
          "y": 22,
          "drilldown": "levelA2"
        },
        {
          "name": "Month4",
          "y": 26,
          "drilldown": "levelA2"
        },
        {
          "name": "Month5",
          "y": 21,
          "drilldown": "levelA2"
        },
        {
          "name": "Month6",
          "y": 22,
          "drilldown": "levelA2"
        },
        {
          "name": "Month7",
          "y": 23,
          "drilldown": "levelA2"
        },
        {
          "name": "Month8",
          "y": 24,
          "drilldown": "levelA2"
        },
        {
          "name": "Month9",
          "y": 21,
          "drilldown": "levelA2"
        },
        {
          "name": "Month10",
          "y": 20,
          "drilldown": "levelA2"
        },
        {
          "name": "Month11",
          "y": 22,
          "drilldown": "levelA2"
        },
        {
          "name": "Month12",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month13",
          "y": 23,
          "drilldown": "levelA2"
        },
        {
          "name": "Month14",
          "y": 24,
          "drilldown": "levelA2"
        },
        {
          "name": "Month15",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month16",
          "y": 26,
          "drilldown": "levelA2"
        },
        {
          "name": "Month17",
          "y": 24,
          "drilldown": "levelA2"
        },
        {
          "name": "Month18",
          "y": 23,
          "drilldown": "levelA2"
        },
        {
          "name": "Month19",
          "y": 23,
          "drilldown": "levelA2"
        },
        {
          "name": "Month20",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month21",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month22",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month23",
          "y": 25,
          "drilldown": "levelA2"
        },
        {
          "name": "Month24",
          "y": 25,
          "drilldown": "levelA2"
        }
      ]
 } ],

      "drilldown": {
        "series": [{
          "name": 'Headcount',
          "id": 'levelA2',
          "data": [{
              "name": "Month1",
              "y": 10,
            },
            {
              "name": "Month2",
              "y": 12,
            },
            {
              "name": "Month3",
              "y": 11,
            },
            {
              "name": "Month4",
              "y": 10,
            },
            {
              "name": "Month5",
              "y": 9,
            },
            {
              "name": "Month6",
              "y": 8,
            },
            {
              "name": "Month7",
              "y": 10,
            },
            {
              "name": "Month8",
              "y": 12,
            },
            {
              "name": "Month9",
              "y": 11,
            },
            {
              "name": "Month10",
              "y": 13,
            },
            {
              "name": "Month11",
              "y": 14,
            },
            {
              "name": "Month12",
              "y": 10,
            },
            {
              "name": "Month13",
              "y": 9,
            },
            {
              "name": "Month14",
              "y": 8,
            },
            {
              "name": "Month15",
              "y": 11,
            },
            {
              "name": "Month16",
              "y": 10,
            },
            {
              "name": "Month17",
              "y": 9,
            },
            {
              "name": "Month18",
              "y": 10,
            },
            {
              "name": "Month19",
              "y": 11,
            },
            {
              "name": "Month20",
              "y": 12,
            },
            {
              "name": "Month21",
              "y": 13,
            },
            {
              "name": "Month22",
              "y": 10,
            },
            {
              "name": "Month23",
              "y": 11,
            },
            {
              "name": "Month24",
              "y": 12,
            }
          ]
        }]
      },

    xAxis: {
      categories: [{
          "name": "2013",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2014",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2015",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2016",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2017",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        },
        {
          "name": "2018",
          "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        }
      ]
    },
    yAxis: [{ // Primary yAxis
      title: {
        text: 'No. of Employees'
      },
    }],
  });
});


text:
Q: swap values between two String values in minimum iterations I have :
String a1 = "Hello";
String a2 = "World";

I want a2 becomes a1 and a1 becomes a2 i.e. they interchange values.
Doing to without writing a function:
a1 = "World";
a2 = "Hello";

want to write a function that can do it in minimum number of iterations.

A: Since String is immutable in Java,
you cannot change the value of a1 and a2,
and the question is quite confusing.
What you can do is swap the variables:
String tmp = a1;
a1 = a2;
a2 = tmp;

But I suspect this is an exercise, and perhaps it was intended more like this:

Given char[] a1 = {"h", "e", "l", "l", "o"} and char[] a2 = ..., swap their values in the minimum number of steps without reassigning these variables.

Then you would iterate over the elements of the arrays,
and perform swapping character by character just like I did earlier with the strings.

A: Here's another way:
x = new String[] { y, y = x }[0];

I tested it, and it's just as fast as the other method. Take a look:
data <- read.csv("~swapVars.csv")

dim(data)[1] #Size of dataset
# [1] 3799582

head(data) # Preview of data (Nano Seconds)
#    oldWay newWay
# 1     75     75
# 2     82     83
# 3     67     67
# 4     75     67
# 5     98     60
# 6     75     75

summary(data)
# oldWay             newWay
# Min.   :      52   Min.   :     52
# 1st Qu.:      60   1st Qu.:     60
# Median :      60   Median :     60
# Mean   :      84   Mean   :     78
# 3rd Qu.:      67   3rd Qu.:     67
# Max.   :16032716   Max.   :8381087

t.test(data$oldWay, data$newWay)

# Welch Two Sample t-test
#
# data:  data$oldWay and data$newWay
# t = 0.7796, df = 7237880, p-value = 0.4356
# alternative hypothesis: true difference in means is not equal to 0
# 95 percent confidence interval:
#   -9.516198 22.087260
# sample estimates:
#   mean of x mean of y
# 83.96287  77.67734

So what this means is, I tested both methods 3,799,582 times with random placement and random text to eliminate third variables. I then did a t-test on the two datasets and found no significant difference between my way or with the old way, regarding latency of time (Nano Seconds).
The times do vary, but it's safe to say that not only is my method shorter, but is also just as fast as the old way.

A: Here is a solution:
a1 +=  a2;
a2 = a1.replaceFirst(a2 + "$", "");
a1 = a1.replaceFirst("^" + a2, "");


text:
Q: Use RTMP over port 80 or RTMPT over HTTP, what would be best? We currently use CloudFront Streaming distribution with JW Player 6 and the RTMP protocol. However, some of our corporate users have told us that they can't see the videos and is because they have RTMP's port 1935 blocked.
CloudFront support RTMP streaming over port 1935 and 80. And it also supports RTMPT streaming tunneled over HTTP.
So I could choose to stream RTMP over port 80 or RTMPT that uses HTTP.
Between these two, what option would be best to have better performance (and less problematic and error-prone) while avoid being blocked by firewalls?
Thanks!

A: I don't see any obvious problems of running RTMP on port 80.
Using RTMPT potentially and in theory will increase the latency, (see this from Adobe: http://blogs.adobe.com/connectsupport/tunneling-with-rtmp-encapsulated-in-http-rtmpt-should-be-avoided-as-it-causes-latency/).
Although in my real experience the difference was not that huge.
However, what I would do is always try port 1935 first, and if it failed then try port 80 by using Cluster plugin.
But again, there should be no issues in running on port 80.

A: RTMPT that uses HTTP, that is better overall for firewalls and the performance is fine too.

A: One problem that we've encountered with RTMPT is that web filtering may drop HTTP packets that it deems suspicious. When an RTMPT packet is dropped, this can result in loss of the whole connection. And if you are streaming content, sooner or later the web filter will find a suspicious packet, just by random chance.
The solution, if possible, would be to get your IT department to white list your server so that web filtering is bypassed. This would eliminate the problem of dropped connections.


text:
Q: How to pre-load data in the background (Angular Web App) Our (Angular) app uses  ~15 APIs to get data from the backend. Each API is used to get data for a specific page. The APIs are not very fast unfortunately, some of them take 5-10 seconds to return. The amount of data that we get is about 1 MB for all pages. Some pages might not be used every day but several of them are guaranteed to be used all the time.
Considering all of these, I am thinking to preload (almost) all the data in the background when the app starts, so when a page is loaded we won't wait for 5-10 seconds for the data.
The way I am thinking to do that is: when the app starts, wait for 10 seconds or so and then call all the APIs and save the data in the store (NGRX). However I have a few questions:

*

*When the app starts, it displays Page-1 which starts getting Data-1 using API-1. Sometimes this request takes more than 10 seconds, and the Get-Data-In-Background kicks in and it calls API-1. The previous call for API-1 is canceled (by the browser) and now we wait 10 more seconds for Data-1 to be retrieved. Is there a way to specify "do not cancel a previous request if there is one"?

*Currently we get approximative 1MB of data. If, I don't know for what reason, in the future the app will get a lot more data (1GB) from the backend, is the browser smart enough to handle big data by saving/loading it from the disk? Or we will get into an out-of-memory situation?

*Is that the right way to pre-load data?

A: I ended up implementing a 'can-load-in-the-background-trigger' (Subject) that is triggered by each page after it received the data. Only when this trigger is true I start loading the rest of the data in the background.
This way I mitigated issue-#1, but I would still like to get some answers if possible.


text:
Q: React: Render components that are properties of an object To build a navigation menu I want to sender a set of MenuItemComponents that have label and icon
I want to import those icons from an external library and then pass them as a propery of an object (that come from external library).
This is the interface for that item
export interface MenuItem {
  id: number
  name: string
  icon?: ReactNode,
  path: string,
}

On the page I want to map this array with labels and icons.
{
   headerMenuItems.map((item: MenuItem) => (
     <MenuItemComponent item={item}/>
   ))
}

And here's my <MenuItemComponent />
import React from "react"
import { MenuItem } from "./items"

export interface MenuItemProps {
  item: MenuItem
}

export const MenuItemComponent = ({item}: MenuItemProps) => {
  const Icon = () => <>{item.icon}</>

  return (

        <Icon />

{item.name}

  )
}

But I'm getting an error

Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead.
      in Icon (at MenuItem.tsx:14)

How can I get the desired result?
And a link to CodeSandbox

A: You have invalid values for MenuItem. icon is component not node.
You could change it like this Demo
export interface MenuItem {
  id: number
  name: string
  icon?: React.FC,
  path: string,
}

And then
export const MenuItemComponent = ({ item }: MenuItemProps) => {
  const { icon: Icon } = item;

  return (

        {Icon && <Icon />}

{item.name}

  );
};


text:
Q: I am trying to put in const data = to the ${body.email}. To be simple, it's for sending e-mail while just typing in the front const mail = require('@sendgrid/mail');

mail.setApiKey(process.env.SENDGRID_API_KEY);

export default async (req, res) => {
  const body = JSON.parse(req.body);

  const message = `
    Name : ${body.name}\r\n
    Prenom : ${body.prenom}\r\n
    Adresse : ${body.adresse}\r\n
    Téléphone : ${body.telephone}\r\n
    email : ${body.email} \r\n
    Type de bien : ${body.message}\r\n
    Année de construction : ${body.annee}

  `;

 const data = {
    to: ??????
    from: 'souleymanportfolio@souleymanportfolio.com',
    subject: 'Nouveau Lead!',
    text: message,
    html: message.replace(/\r\n/g, '
')

  };

  mail.send(data);

  res.status(200).json({ status: 'Ok' });

Plz help, I am trying to put in const data = to the ${body.email}. To be simple, it's for sending e-mail while just typing in the front.
Thank you.

A: Twilio SendGrid developer evangelist here.
You can set the to property on the data object to body.email like so:
 const data = {
    to: body.email,
    from: 'souleymanportfolio@souleymanportfolio.com',
    subject: 'Nouveau Lead!',
    text: message,
    html: message.replace(/\r\n/g, '
')
  };


text:
Q: How to use an Angular service to share data across controllers/pages? I am creating a "Web Planner" where the user has to complete a number of steps on different pages in order to create an order for our service.  I know that I need to use a service in order to share certain data around the entire Planner, but I am still not sure how do go about it.
The problem is that the user will not necessarily go in-order every time. They can stop on any page, then come back later and resume, therefore I need a way to manage some API data so that if the user is on 1 of 2 pages that share the same data, the data will fetched from the server via API or simply assigned if the data was already taken.
Right now the only method I thought of is to place the API requests inside my Service as well, and then when I run something like OrderService.get() the service will handle logic to check if the data was already grabbed from the server. If it was then it is just a simple assignment like $scope.model = OrderService.get(), but then the problem is that if the data isn't loaded yet, then I need to use a promise somewhere to wait for the data, so a simple assignment operation won't suffice.
This service may look something like this:
app.factory('OrderService', function(){
    var orders = []; // This is the actual data

    var service = {};

    service.get = function(id){
        if(orders.length){
             return orders; // This means there is already data available
        }else{
             // This is where I am not sure what to do...
             // Maybe...
             var promise = API.Orders.getAllOrders({id : id}, function(res){
                    // Not sure about how to implement this part
             }).$promise;

             return promise;
        }
    }

})

Does anyone have any other ideas?

A: Just return a promise all the time, whether the data is already there, or fetched by a call to a server. In your example..
   if(orders.length){
         return $q.when(orders); // This means there is already data available
    }else{
         // This is where I am not sure what to do...
         // Maybe...
         var promise = API.Orders.getAllOrders({id : id}, function(res){
                // Not sure about how to implement this part
         }).$promise;

         return promise;
    }

A: Since your calls are asynchronous, the only way to do this is via promises
app.service('OrderService', function($q){ // import $q ; the angularjs promise

    var orders = []; // This is the actual data

    var service = {};

    service.get = function(id){
        var deferred = $q.defer(); // create a unit of work to be done; a promise

        if(orders.length){ // if data is already available, resolve the promise
             deferred.resolve(orders); // This means there is already data available, so mark as resolved and successful
        }else{
             // make your async call since you don't have data
             API.Orders.getAllOrders({id : id}, function(response){
                // here you can actually modify the response before it goes back to your controller
                deferred.resolve(response);
             }, function(reason){ // failure scenario
                deferred.reject(reason);
             })

        }
        return deferred.promise; // always return promise
    }
})

A: Please bear in mind that I'm still a beginner (reading through a lot of documentation) so this might not be 100% correct.
Your service would be something like this:
app.factory('OrderService', function($q){
    var orders = []; // This is the actual data

    return {
      getData: function(id){
        var deferred = $q.defer();

        if(orders.length){
             deferred.resolve(orders); // This means there is already data available
        }else{
             $http.get('/api/get/data/' + id)
               .success(function(data) {
                  deferred.resolve(data);
               })
               .error(function(){
                  deferred.reject();
               });
        }

        return deferred.promise;
     }
})

And then on your controllers you just need to use it like this:
app.controller('MainCtrl', function($scope, OrderService) {
   var id = 1;
   $scope.data = OrderService.getData(id);
});


text:
Q: How to invoke the popup menu for the tab page (not for the tab control) and select Cut opt in powerbuilder? I am using a tabcontrol in powerbuilder and i need to invoke the popupemnu for the tabpage for deletion purpose.can any one help me with this problem?

A: Look at the PopMenu() function.

A: In the IDE click the tab to make sure the correct page is showing. Then right-click in the body of the tab to get the page popup.


text:
Q: How to download from JavaScript rendered webpage? How can I download from links on a JavaScript rendered webpage? Python is the preferred language.
So far, I've tried using the Python bindings for Selenium on a headless server. This approach is terribly slow, fraught with error, and is incapable of reliably determining download progress or success. Additionally, the headless server interferes with my clipboard (which is a problem). I used Firefox as it can be configured to download to a default directory, but I don't think the Chrome situation is any better.
Alternatively, I've tried using WebKit.
def render(url):
    """Fully render a webpage (JavaScript and all) and return the HTML."""

    import subprocess
    from textwrap import dedent

    script = dedent("""\
    import sys
    from PyQt4.QtCore import QUrl
    from PyQt4.QtGui import QApplication
    from PyQt4.QtWebKit import QWebPage

    class Render(QWebPage):

        def __init__(self, url):
            self.app = QApplication(sys.argv)
            QWebPage.__init__(self)
            self.loadFinished.connect(self._loadFinished)
            self.mainFrame().load(QUrl(url))
            self.app.exec_()

        def _loadFinished(self, result):
            self.frame = self.mainFrame()
            self.app.quit()

    render = Render(sys.argv[1])
    print render.frame.toHtml().toAscii()""").encode()

    process = subprocess.Popen(['python2', '-', url],
                               stderr=subprocess.PIPE,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE)

    # pipe script into Python's stdin
    return process.communicate(script)[0].decode('latin1')

This would be great if not for the fact that I need the download to be in the same session. Is there any way to preserve the session used to render the page? PyQt4 and WebKit are just a bunch of shared libraries. I'm not sure how to tear up the guts of them or whether such a thing even possible.
Right now I'm just doing the following:
with requests.Session() as session:
    html = session.get(url).text
    link = get_url(html)
    download(link, session=session)

Without getting into the details, get_url(html, url) simply extracts the JavaScript from the page, hacks away any calls to the DOM, then executes it in node. Really nasty stuff...
Any way I can safely render a webpage and keep the session?
I'm also open to doing it completely in node if Python is not appropriate or the JavaScript alternative is much more elegant. It looks like perhaps node-dom might suffice? I'm not really familiar with it enough to tell but I'm interested in any suggestions.

A: If a direct command-line option is suitable for you instead of going through Python and/or Selenium, Google Chrome can be run in headless mode.  It will do all the javascript rendering before dumping the DOM.
/usr/local/bin/google-chrome \
  --headless \
  --virtual-time-budget=10000 \
  --timeout=10000 \
  --run-all-compositor-stages-before-draw \
  --user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36" \
  --disable-gpu \
  --dump-dom "https://example.com/index.html" > rendered.html

A: PyQt5 in Python 2 or 3 does the trick in this case. Note the function is overly complex so as to support earlier versions of PyQt5 that use WebKit as well as later versions that use WebEngine.
import sys

def render(source_html):
    """Return rendered HTML."""
    try:
        from PyQt5.QtCore import QEventLoop
        from PyQt5.QtWebEngineWidgets import QWebEngineView
        from PyQt5.QtWidgets import QApplication

        class Render(QWebEngineView):
            """Render HTML with PyQt5 WebEngine."""

            def __init__(self, html):
                self.html = None
                self.app = QApplication(sys.argv)
                QWebEngineView.__init__(self)
                self.loadFinished.connect(self._loadFinished)
                self.setHtml(html)
                while self.html is None:
                    self.app.processEvents(
                        QEventLoop.ExcludeUserInputEvents |
                        QEventLoop.ExcludeSocketNotifiers |
                        QEventLoop.WaitForMoreEvents)
                self.app.quit()

            def _callable(self, data):
                self.html = data

            def _loadFinished(self, result):
                self.page().toHtml(self._callable)
    except ImportError:
        from PyQt5.QtWebKitWidgets import QWebPage
        from PyQt5.QtWidgets import QApplication

        class Render(QWebPage):
            """Render HTML with PyQt5 WebKit."""

            def __init__(self, html):
                self.html = None
                self.app = QApplication(sys.argv)
                QWebPage.__init__(self)
                self.loadFinished.connect(self._loadFinished)
                self.mainFrame().setHtml(html)
                self.app.exec_()

            def _loadFinished(self, result):
                self.html = self.mainFrame().toHtml()
                self.app.quit()

    return Render(source_html).html

Or PyQt4 in Python 2.
import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebPage

class Render(QWebPage):

    """Fully render HTML, JavaScript and all."""

    def __init__(self, html):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().setHtml(html)
        self.app.exec_()

    def _loadFinished(self, result):
        self.frame = self.mainFrame()
        self.app.quit()

render = Render(html)
result = str(render.frame.toHtml().toAscii())


text:
Q: Truly drawing cards at random, and not just a random group? visual basic 2010 I realized a flaw on my coding for picking cards from my structure group arrays this morning for a tabletop card game I'm converting to computer.
Currently the code is set up to randomly pick an array of a specific card, but if quantity of cards in the group is < 1, then the group is skipped. For my deck this isn't being truly random because each card has its own quantity. Some cards have 10 cards, others 6, most 4. How can I code it to where it looks at all these quantity numbers as a whole and picks a random card out of these numbers.
If GameSize >= 3 Then
    For StartHands = 10 To 14
        Number = (DeckGroup(Rnd.Next(0, DeckGroup.Count)).ID)
        'Cardslots Player3
        If CardTypeArray(StartHands) = "" Then
            If DeckGroup(Number).QuantityInteger > 0 Then
                DeckGroup(Number).QuantityInteger -= 1
                Player1HandGroup(Number).QuantityInteger3 += 1
                CardTypeArray(StartHands) = Player1HandGroup(Number).CardType
                Me.NumberArray(StartHands) = Number
            Else
                'Recall Procedure if Generated Random Number is not allowed
                'due to QuantityInteger <= 0
                Call StartButton_Click(sender, e)
            End If
        End If
    Next StartHands
End If

when playing a card, and drawing a new card, I use this coding scheme, to prevent stackoverflow, but is virtual the same.
Dim temp As IEnumerable(Of LunchMoneyGame.LunchMoneyMainForm.Group) = From r In DeckGroup Where r.QuantityInteger > 0 Select r

If temp IsNot Nothing AndAlso temp.count > 0 Then
    Number = (temp(Rnd.Next(0, temp.Count)).ID)

    DeckGroup(Number).QuantityInteger -= 1
    'Select the Player depending value of T
    Select Case T
        Case 0
            Player1HandGroup(Number).QuantityInteger += 1
        Case 1
            Player1HandGroup(Number).QuantityInteger2 += 1
        Case 2
            Player1HandGroup(Number).QuantityInteger3 += 1
        Case 3
            Player1HandGroup(Number).QuantityInteger4 += 1
        Case 4
            Player1HandGroup(Number).QuantityInteger5 += 1
    End Select

Edit:
Improved question:
How can I weight the probably of drawing a card based on how many of a particular card are left in the decks quantity integer for each card?

A: The idea of my solution is to generate a random number over the total number of availables cards in all deck groups. Finally we find the deck group this number targets within a loop:
Dim totalNumerOfCards As Integer = DeckGroup.Sum(Function(d) d.QuantityInteger)
Dim Number As Integer = Rnd.Next(totalNumerOfCards)
Dim numCards As Integer = 0
Dim groupIndex As Integer = 0
Dim cardIndex As Integer = 0
Dim i As Integer = 0
While i < DeckGroup.Length AndAlso numCards <= Number
    groupIndex = i
    cardIndex = Number - numCards
    numCards += DeckGroup(i).QuantityInteger
    i += 1
End While
Console.WriteLine("Your card is in DeckGroup({0}), card index {1}",
                  groupIndex, cardIndex);