text:
Q: How to plot several curves with an offset on the same graph I read a waveform from an oscilloscope. The waveform is divided into 10 segments as a function of time. I want to plot the complete waveform, one segment above (or under) another, 'with a vertical offset', so to speak. Additionally, a color map is necessary to show the signal intensity. I've only been able to get the following plot:

As you can see, all the curves are superimposed, which is unacceptable. One could add an offset to the y data but this is not how I would like to do it. Surely there is a much neater way of plotting my data? I've tried a few things to solve this issue using pylab but I am not even sure how to proceed and if this is the right way to go.
Any help will be appreciated.
import readTrc #helps read binary data from an oscilloscope
import matplotlib.pyplot as plt

fName = r"...trc"
datX, datY, m = readTrc.readTrc(fName)

segments = m['SUBARRAY_COUNT'] #number of segments

x, y = [], []

for i in range(segments+1):
    x.append(datX[segments*i:segments*(i+1)])
    y.append(datY[segments*i:segments*(i+1)])

plt.plot(x,y)
plt.show()

A: A plot with a vertical offset sounds like a frequency trail.

Here's one approach that does just adjust the y value.
Frequency Trail in MatPlotLib
The same plot has also been coined a joyplot/ridgeline plot. Seaborn has an implementation that creates a series of plots (FacetGrid), and then adjusts the offset between them for a similar effect.
https://seaborn.pydata.org/examples/kde_joyplot.html
An example using a line plot might look like:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

segments = 10
points_per_segment = 100

#your data preparation will vary
x = np.tile(np.arange(points_per_segment), segments)
z = np.floor(np.arange(points_per_segment * segments)/points_per_segment)
y = np.sin(x * (1 + z))

df = pd.DataFrame({'x': x, 'y': y, 'z': z})

pal = sns.color_palette()
g = sns.FacetGrid(df, row="z", hue="z", aspect=15, height=.5, palette=pal)
g.map(plt.plot, 'x', 'y')
g.map(plt.axhline, y=0, lw=2, clip_on=False)
# Set the subplots to overlap
g.fig.subplots_adjust(hspace=-.00)
g.set_titles("")
g.set(yticks=[])
g.despine(bottom=True, left=True)

plt.show()

Out:


text:
Q: Audio thread SIP Android I have a connection with SIP server(Asterisk), but micro and dynamics doesn't work. Asterisk  kicks client in 31 seconds(Empty RTP thread). Documentation by Google says:

Android provides an API that supports the Session Initiation Protocol (SIP). This lets you add SIP-based internet telephony features to your applications. Android includes a full SIP protocol stack and integrated call management services that let applications easily set up outgoing and incoming voice calls, without having to manage sessions, transport-level communication, or audio record or playback directly.

Activity + Receiver:
public class MainActivity extends AppCompatActivity {

public String domain = "192.168.10.37";
public String name = "111";
public String password = "123456";
public String sipAddress = "100@192.168.10.37";
public IncomingCallReceiver receiver;
public SipManager sipManager;
public SipProfile sipProfile;
public SipAudioCall call;

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

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.USE_SIP)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.USE_SIP)) {

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.USE_SIP},
                    0);
        }
    }

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("zlotnikov.SIPexample.INCOMING_CALL");
    receiver = new IncomingCallReceiver();
    this.registerReceiver(receiver, intentFilter);

    initManager();
}

private void initManager() {
    if (sipManager == null) {
        sipManager = SipManager.newInstance(this);
    }

}

private void initializeLocalProfile() {
    if (sipProfile != null) {
        closeLocalProfile();
    }
    try {
        SipProfile.Builder builder = new SipProfile.Builder(name, domain);
        builder.setPassword(password);
        builder.setSendKeepAlive(true);
        builder.setAutoRegistration(true);
        sipProfile = builder.build();
        Intent intent = new Intent();
        intent.setAction("zlotnikov.SIPexample.INCOMING_CALL");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
        SipRegistrationListener listener = new SipRegistrationListener() {
            @Override
            public void onRegistering(String s) {
                System.out.println("voip onRegistering " + s);
            }

            @Override
            public void onRegistrationDone(String s, long l) {
                System.out.println("voip onRegistrationDone " + s + " " + l);
                //initCall();
            }

            @Override
            public void onRegistrationFailed(String s, int i, String s1) {
                System.out.println("voip onRegistrationFailed " + s);
            }
        };
        sipManager.open(sipProfile, pendingIntent, null);
        //sipManager.register(sipProfile, 40, listener);
        sipManager.setRegistrationListener(sipProfile.getUriString(), listener);
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (SipException e) {
        e.printStackTrace();
    }
}

@Override
protected void onStart() {
    super.onStart();
    initializeLocalProfile();
}

@Override
protected void onStop() {
    super.onStop();
    closeLocalProfile();
}

private void closeLocalProfile() {
    try {
        if (sipProfile != null) {
            sipManager.close(sipProfile.getUriString());
        }
    } catch (Exception ee) {
        ee.printStackTrace();
    }
}

private void initCall() {
    try {
        SipAudioCall.Listener listener = new SipAudioCall.Listener() {
            @Override
            public void onCallEstablished(SipAudioCall call) {
                super.onCallEstablished(call);
                System.out.println("voip onCallEstablished");
                call.startAudio();
                call.setSpeakerMode(true);
            }

            @Override
            public void onCallEnded(SipAudioCall call) {
                super.onCallEnded(call);
                System.out.println("voip onCallEnded");
            }
        };

        call = sipManager.makeAudioCall(sipProfile.getUriString(), sipAddress, listener, 30);

    } catch (SipException e) {
        closeLocalProfile();
        call.close();
        e.printStackTrace();
        System.out.println("voip MainActivity Конец соединения");
    }
}

public class IncomingCallReceiver extends BroadcastReceiver {

    private MediaPlayer mediaPlayer;
    @Override
    public void onReceive(Context context, Intent intent) {
        SipAudioCall incomingCall = null;
        System.out.println("voip Пришел звонок " + intent.toString());
        try {

            SipAudioCall.Listener listener = new SipAudioCall.Listener() {
                @Override
                public void onRinging(SipAudioCall call, SipProfile caller) {
                    System.out.println("voip onRinging()");
                    try {
                        startRinging();
                    } catch (Exception e) {
                        stopRinging();
                        System.out.println("voip onRinging exception");
                        e.printStackTrace();
                    }
                }

                @Override
                public void onCallEstablished(SipAudioCall call) {
                    super.onCallEstablished(call);
                    System.out.println("voip onCallEstablished()");
                    stopRinging();
                }

                @Override
                public void onCallEnded(SipAudioCall call) {
                    super.onCallEnded(call);
                    System.out.println("voip onCallEnded()");
                }
            };

            incomingCall = sipManager.takeAudioCall(intent, listener);
            incomingCall.startAudio();
            incomingCall.setSpeakerMode(true);
            /*if (incomingCall.isMuted()) {
                incomingCall.toggleMute();
            }*/

            //call = incomingCall;

            incomingCall.answerCall(30);

        } catch (Exception e) {
            if (incomingCall != null) {
                incomingCall.close();
                System.out.println("voip IncomingCallReceiver конец соединения");
            }
        }

    }

    private synchronized void startRinging() {
        long[] pattern = {0, 1000, 1000};
        ((Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(pattern, 0);
        Uri defaultRingtoneUri = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE);
        mediaPlayer = MediaPlayer.create(getApplicationContext(), defaultRingtoneUri);
        mediaPlayer.setLooping(true);
        mediaPlayer.start();

    }

    private synchronized void stopRinging() {
        ((Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE))
                .cancel();
        if (mediaPlayer != null || mediaPlayer.isPlaying()) mediaPlayer.stop();
    }
}

}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="zlotnikov.sipexample">

<uses-permission android:name="android.permission.USE_SIP" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

<uses-feature android:name="android.hardware.sip.voip" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".MainActivity$IncomingCallReceiver" android:label="Call Receiver" />
</application>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spam Registrations I've found multiple threads with this issue but no solution yet.
I have a constant stream of user account being created using the domain @qq.com. All different email addresses and just gibberish as their details.
I got the IP from session logs and added the following to .htaccess:
Deny from 172.69.134.186

But the registrations continued.
I tried adding captcha to my registration form but when I do, it fails to show the captcha at all but still looks for it when the form is submitted, this preventing anyone from registering!
Any help would be greatly appreciated. I have tried various solutions and I'm getting thousands of registrations a day!
Thank you.

A: I had faced the issue of these spam customers on our store too. The store was on magento 1.x . I could not say that a single solution will work 100% as it depends on how the attack has been implemented. Let me share some of my thoughts.
1. Implement google recaptcha
You are going in the right direction of implementing the google recaptcha. This could prevent the case if it is the default vulnerability. I am not sure which version of Magento you are using but here is a quick tutorial of implementing the google recaptcha for magento 1
You can also implement the custom code for recaptcha implementation. Please confirm what you have implemented does the both frontend and server side validation. For me doing the clientside as well as server side validation worked and the spam customer was prevented.
But if you still seeing this issue after implementing the google recaptcha see check point 2.
2. Look for customization and loop holes
Yes if google recaptcha doesn't prevent the issue. There could be a case where any custom extension has the loop hole which may have the code that creates the customer and not well sanitized like form key validation and all. Look for that too.
3. Try implementing honeypot
If these customers are created by submitting the customer registration form with auto fill data, you can add a hidden text field, which normal customer won't see, but these scripts will fill it and then you can check on your controller if value presents in that field. If yes, prevent the customer addition else create the customer. This is my version of the implementation. I think there are other better approaches too.
Hope this will help you solve your issue.

A: Use Google reCaptcha on your submit form and add server side validation. use below code to validation google reCaptcha on server side.
public function checkCaptcha(array $post)
{
    if ($post['g-recaptcha-response']) {
        $captcha = $post['g-recaptcha-response'];

        $secretKey = Mage::helper('gorilla_recaptcha')->getRecaptchaPrivateKey(); // replace this with private key
        $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secretKey . "&response=" . $captcha);
        $responseKeys = json_decode($response, true);

        if (intval($responseKeys["success"]) !== 1) {
            return "failed";
        } else {
            return "success";
        }
    }
    else {
        return "failed";
    }
}


text:
Q: Please help me convert this script to a simple image slider Can some please, PLEASE! help me with this problem. Okay so I have a code that at first I thought worked well but I forgot that when the default  content is loaded the first of the three buttons below the image should take the active css state that I've specified for the active buttons to take. Now what I want is for this little code to behave like a normal slider by loading in the css hidden contents into the ".image-area" div and it works when I click on the buttons. Problems only surface when I am I trying to give the first loaded content an active state. One way I believe can fix this (I can't implement it) is to let the first immediate default content be this inline hidden div: (

) while somehow letting the first button be set to active. I should also mention that I'm not the best with jquery. Please help me fix this someone!
Here is a fiddle to get a better understanding: http://jsfiddle.net/pyrot/84sU4/
If my way of going about this is totally absurd please let me know.
this is my code:

this is my html:

and this is my css:
#image-slider-container {

  width: 100%;
  height: auto;
  background-color: #ffffff;
  padding: 5% 0px 0% 0px;

}

.image-slider-inner {

  width: 100%;
  height: auto;
  max-width: 1040px;
  margin: 0px auto;
  padding: 0px 20px 0px 20px;

}

#image-area2,
#image-area3 {

  width: 100%;
  height: auto;
  display: none;

}

#image-area {

  width: 100%;
  height: auto;

}

#image-area .img-area-wrapper {

  width: 80%;
  height: auto;
  max-width: 1140px;
  margin: 0px auto;

}

.actual-img {

  width: 100%;
  height: 100%;

}

.slider-buttons {

  width: 100%;
  height: auto;
  max-width: 1140px;
  margin-top: 0px;

}

.slider-buttons-container {

  width: 100%;
  height: auto;
  max-width: 1140px;
  margin: 10px auto 0px auto;
  text-align: center;

}

.slider-buttons-container a {

  border-radius: 360px;
  border: 1px #C5C5C5 solid;
  padding: 0px 5px 0px 5px;
  margin: 0px 5px 0px 5px;
  background-color: #efefef;
  outline: 0px;
  text-decoration: none;
  font-size: 12px;
  box-shadow: -2px 1px 2px 0px #ADADAD;

  transition: 0.5s;
  -moz-transition: 0.5s;
  -webkit-transition: 0.5s;
  -o-transition: 0.5s;

}

.slider-buttons-container a:hover {

  border: 1px #C5C5C5 solid;
  padding: 0px 5px 0px 5px;
  background-color: #DAD8D8

}

.slider-buttons-container a:active {

  position: relative;
  top: 2px;

}

.O_Nav_Current {

  border: 1px #999999 solid !important;
  background-color: #DAD8D8 !important;

}

A:
Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) {
  // ...
}).first().addClass('O_Nav_Current');

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area {
    width: 100%;
    height: auto;
    display: none;
}

.image-area:first-of-type {
    display: block;
}

JavaScript:
var $slides = $('.image-area'),
    $btns = $('a.o-links');

$btns.on('click', function (e) {
    var i = $btns.removeClass('O_Nav_Current').index(this);
    $(this).addClass('O_Nav_Current');

    $slides.filter(':visible').fadeOut(1000, function () {
        $slides.eq(i).fadeIn(1000);
    });

    e.preventDefault();

}).first().addClass('O_Nav_Current');

http://jsfiddle.net/RmF57/


text:
Q: Changed my display manager to lightdm-gtk-greeter. Now I can't login Last night I edited the default-display-manager file and changed my default display manager from lightdm to lightdm-gtk-greeter. Then I edited the lightdm-gtk-greeter config file and changed the wallpaper. Now, when I reboot the computer I get a whole string of messages where the computer is booting up but it freezes and won't boot into the system. It just hangs there. How do I get back into my system? I'm running Xubuntu 12.04 64-bit.

A: Ok, this is what did the trick for me. I received this advice from someone else. When the system hung up I pressed Ctrl-Alt-F1 and got to a virtual terminal. Then, I issued the command sudo dpkg-reconfigure lightdm. That reset my display manager back to lightdm and I was able to sign in as normal. Everything works fine now.

A: You can give it a try, if you are using internet connection using Wired LAN then these may work for you:
Installing GDM (a display manager like lightdm) can fix your problem:
Method 1:

*

*This method works when you are able to go to at least the command line interface.

Press CTRL+ALT+F1 or CTRL+ALT+F2 when your system starts and starts freezing or black screen appears. It will let you to use Command Line Interface. Then login using your username and password, and try following commands:
$ sudo apt-get install gdm
$ sudo dpkg-reconfigure gdm

then selected gdm from the list, and restarted your system:
$ sudo reboot

Your system will be restarted with a login screen which will let you to access your system.
Method 2: If 1st didn't work for you then you can try this method. But it would be very long for you:
Here are the steps how to install using 2nd method

*

*Go to following link and download gdm for Ubuntu 12.04.2 amd64. (chose ubuntu
proposed universe out of three listed there.)
http://pkgs.org/download/gdm

*Put the *.deb file just installed to any pendrive.

*Then login in save mode or Recovery Mode. After a lot of text displayed in black
screen one window will come which list some options. First go to option Grub, it
will mount your file system in read/write mode. Then chose root option in order
to login as root. Then go to the pendrive where you saved the deb file. The drive
should be listed in in /media. I am assuming that you saved the file in gdm
directory inside pendrive (pendrive is the name of your pendrive)
# cd /media && ls

(which will list your pendrive if you don't get pendrive
 folder then go to Mount Pendrive Section at last, then come back here and continue to next step.)
# cd /media/pendrive/gdm

(go to gdm directory where .deb file is saved.)
# dpkg -i *.deb

(installing gdm)
While installing gdm one window will come which will ask your to chose lightdm or gdm
from the list. Chose gdm. If this window doesn't appear then try following command:
# dpkg-reconfigure lightdm

(chose gdm) Then finally execute following command:
# reboot (reboot your system)

Mount Pendrive Section

*

*Mounting pendrive while working in recovery mode.

Run this command:
    # fdisk -l

Find your device in the list, it is probably something like /dev/sdb1. Then execute other commands one by another:
    # mkdir /media/pendrive

*

*Run this command if your pendrive is formatted in FAT/FAT32.
# mount -t vfat /dev/sdb1 /media/pendrive -o uid=1000,gid=1000,utf8,dmask=027,fmask=137

*Or this command if your pendrive is formatted in NTFS
# mount -t ntfs-3g /dev/sdb1 /media/pendrive

Hope it will work for you.. For any further assistance please reply..


text:
Q: how can I change the data in a reactable table inside Rmd using javascript only? I have created an .qmd file in R which contains a table created using the excellent reactable package.
How can I change the data contained in this table using only javascript?
I know that something similar can be done using crosstalk or shiny, but I want to know specifically how to do this using only javascript.
Here is a example .qmd reprex that describes the problem:
---
title: "update reactable"
format: html
---

```{r}
library(reactable)

ojs_define(iris1 = iris[1:5,],
           iris2 = iris[51:52,],
           iris3 = iris[101:104,])

reactable(iris[1:5,],
          elementId = 'iris')

```

```{ojs}
viewof choice = Inputs.radio(['a','b','c'], {label: 'choose a dataset', value: 'a'})

```

```{ojs}
datasets = ({'a': iris1,
            'b': iris2,
            'c': iris3
            })

dataset = datasets[ choice];

dataset

```

```{ojs}
"update reactable instance based on user's choice here"
// update reactable instance based on user's choice here

```

Thanks

A: Reached out to the maintainer of the reactable package who has graciously added this functionality in v0.3.0.9000
See this example: https://glin.quarto.pub/observable-reactable/


text:
Q: How to see phase difference of two pendulum i want to see the simulation of two uncoupled Simple Harmonic Motion (SHM) pendulum with different Lengths and released at different initial displacement angles. in this case adding one more pendulum in my code
also, How to plot the graph of phase difference between these two pendulums vs time. for a fixed initial displacement.
this is my code so far with single pendulum.
theta0 = 15 Degree; L = 2.01; g = 9.81;
omega = Sqrt[g/L];
T = 2 Pi/omega;
theta[t_] := theta0*Cos[omega*t];
x[t_] := L*Sin[theta[t]]; y[t_] := -L*Cos[theta[t]];

Manipulate[
 line := Line[{{0, 0}, {x[t], y[t]}}];
 Graphics[
  {Point[{x[t], y[t]}],
   line}, PlotRange -> {{-5, 5}, {-5, 0}}, Frame -> True], {t, 0, 2 T,
   0.05 T}]

All help is much appreciated.

A: This allows you to watch two pendulums swing in time,
g = 9.81;
pendulumTrajectory[L_, theta0_, t_] := With[
   {theta = theta0 Cos[Sqrt[g/L] t]},
   {L Sin[theta], -L Cos[theta]}
   ];
Manipulate[
 point1 = pendulumTrajectory[2.01, 15 Degree, t];
 point2 = pendulumTrajectory[3.01, 25 Degree, t];

 line2 = Line[{{0, 0}, point2}];
 Graphics[{{Red, {PointSize[Large], Point[point1]},
    Line[{{0, 0}, point1}]},
   {Blue, {PointSize[Large], Point[point2]},
    Line[{{0, 0}, point2}]}},
  PlotRange -> {{-5, 5}, {-5, 0}}, Frame -> True], {t, 0, 10, 0.05}]

A: Here is a generalization to many pendula. The phase differences in this case are revealed by the special points in time at which "revivals" occur, i.e., where the pendula that have all been launched with the same angle all group back together:
pendulum[α_, l_] :=
 Module[{radius = .03,
   p = -l {Sin[α], Cos[α]}}, {{Brown,
    Line[{{0, 0}, p}]}, {Orange, Disk[p, radius]}}]

pendulumArray[t_, α0_] :=
 Graphics[{{Cyan, Disk[{0, 0}, .03]},
   Table[pendulum[α0 Cos[2 Pi ν t], 1/ν^2], {ν,
     51/60, 65/60, 1/60}]}, Background -> Black,
  PlotRange -> {1.8 {-Sin[α0], Sin[α0]}, {-1.45, .05}}]


text:
Q: Finding indexes, intersection and then ranking in a matrix? I have a matrix like as follows:
a = [1 0 0 0 0 0 0;
     1 1 0 0 0 0 0;
     1 0 1 0 0 0 0;
     1 1 0 1 1 0 0;
     1 1 0 1 1 0 0;
     1 0 1 0 0 1 1;
     1 0 1 0 0 1 1]

of which i wish to create following table:
X - For each Rows index of cols having 1
Y - For each cols index of rows having 1
Z - Intersection set

S.No      X               Y               Z       Rank(Comparing X & Z)
1        1          1,2,3,4,5,6,7        1                 I
2        1,2           2,4,5             2                 II
3        1,3           3,6,7             3                 II
4       1,2,4,5         4,5             4,5                III
5       1,2,4,5         4,5             4,5                III
6       1,3,6,7         6,7             6,7                III
7       1,3,6,7         6,7             6,7                III

Of the above table, X and Y columns have been easily found with the help of Matlab code as provided by Sir Luis Mendo to my previous question.
Code was as follows:
[ii jj] = find(a); %// find row and col indices (ii and jj respectively)
rows = accumarray(ii,jj,[], @(v) {sort(v).'}); %'// group jj as per ii, and sort
cols = accumarray(jj,ii,[], @(v) {sort(v).'}); %'// group ii as per jj, and sort
rows{:}
cols{:}

Now i wish to find intersection set i.e. Z but i m not able to find using intersection command.
Further Ranking is to be done on comparing columns X and Z in such a manner that with minimum of elements in both columns, maximum of common elements should be there and each time that common element should be emitted from the whole X column for further comparison so that again with minimum of elements in both sets max common elements can be found.
Please help.

A: For the intersection, just work with a & a.':
[ii jj] = find(a & a.');
z = accumarray(ii,jj,[], @(v) {sort(v).'});


text:
Q: convergence to standard brownian motion Could you help me with the following:
I have that $$T(x):=\frac{X(nx)-E[X(nx)]}{\sqrt{n}} \xrightarrow{d} N(0, \frac{x^k}{k})$$ for each fixed $x>0$, where we also have that $\frac{X(nx)}{t}$ is the empirical Distribution function of a Distribution, where $\frac{E[X(nx)]}{t}$ is the Distribution function.
Then, it is meantioned that this proves that $T(x) \xrightarrow{d} W(\frac{x^k}{k})$, where W is a Standard brownian Motion.
Why? Is there any reference for that? As reference, it is mentioned the following Theorem, which does not help me:
Suppose the $\xi_n$ are Independent and have a common Distribution function $F(t)$. Then, with  $$Y_n(t,\omega)=\sqrt{n} (F_n(t,\omega)-F(t)),$$
$Y_n \xrightarrow{d} Y$, where $Y$ is the Gaussian random element of $D$ specified by
$E[Y(t)]=0$, $E[Y(s)Y(t)]=F(s)(1-F(t))$ for $s\leq t$.
Thus, what really is my question: What has a Standard brownian Motion to do with a Gaussian random element? Could you explain this to me? I would really appreciate any help!!
(DEFINITION STANDARD BROWNIAN MOTION:
$W(0)=0$ and $t \mapsto W(t)$ is continuous with probability 1 and
$W(t)$ has stationary, jointly Independent increments and the increment $W(t_1+t_2)-W(t_1)$ is normal-distributed $N(0,t_2)$.)

A: For every nonnegative $u$, the distribution of $W(u)$ is $N(0,u)$ hence, for any parameter $u(x)$, the assertion that $T(x)\stackrel{d}{\to}N(0,u(x))$ and the assertion that $T(x)\stackrel{d}{\to}W(u(x))$ are logically equivalent.


text:
Q: How to create a Flow chart? Javascript or Flash? I want to create a simple graph as this screeshot :
: alt text http://s6.imagestime.com/out.php/i417041_grapha.jpg
the nodes must be clickablea nd they must have various forms. the arcs must have various colours and arrows!
I found this javascript library :Raphael
but I can't write into the nodes.
Can anybody help me to find a library, javascript or flash, that create a sample graph as the screenshot?
Thanks

A: You can use RaVis in Flash. Watch a demo here


text:
Q: Convert ArrayList to Double Array in java How to Convert ArrayList to Double Array in Java6?
 List lst = new ArrayList();
 double[] dbl=null;
 lst.add(343.34);
 lst.add(432.34);

How convert above list to array?

A: You can directly convert the List to an Array of the wrapper class.
Try the following:
List<Double> lst = new ArrayList<>();
Double[] dblArray = new Double[lst.size()];
lst.add(343.34);
lst.add(432.34);
dblArray = lst.toArray(dblArray);

A: List<Number> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42);
double[] dbl = lst.stream()
    .map(Number::cast) // Or possibly Double::cast when List lst.
    .mapToDouble(Number::doubleValue)
    .toArray();

List<Double> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42.0);
double[] dbl = lst.stream()
    .mapToDouble(Double::doubleValue)
    .toArray();

The mapToDouble transforms an Object holding Stream to a DoubleStream of primitive doubles.

A: With this you will make the list and add what you like. Then make the array the same size and fill front to back.
public static void main(String[] args){
        List lst = new ArrayList();
        lst.add(343.34);
        lst.add(432.34);
        System.out.println("LST " + lst);

        double[] dbl= new double[lst.size()];
        int iter = 0;
        for (Object d: lst
             ) {
            double e = (double) d;
            dbl[iter++] = e;
        }
        System.out.println("DBL " + Arrays.toString(dbl));
    }

Result: LST [343.34,432.34] DBL [343.34,432.34]


text: Q: In Yii2 dirtyAttributes() get only string fields? Need to take number fields and relation fields I get dirty attributes in after save method. but it only gives fields which are in string type. Not gets fields are in Number type and foreign key fields.


text:
Q: What's happens in Ruby and Python? Why the variable wil be nil in if block in ruby ,but undefined in python? This question already has an answer Confusion with the assignment operation inside a falsy `if` block
  if false
      y = 'hi'
   end

  puts y

In ruby y has been "defined" in the if block,it will be nil(why?). Remove that block and this gives an error.
But, in python
 if False:
   y = 'hi'

 print y

It will gives an error.
What's happens in Ruby and Python?

A: Yukihiro Matsumoto states

The local variables are created in compile time [...]

That's why y is defined in Ruby, whereas Python uses a dictionary to store local variables in runtime. This can be accessed directly through locals() as well.
The Ruby part also came up here.


text:
Q: Laravel File Upload Issue I want to upload a file in Laravel but it displays an error like...

FileException in UploadedFile.php line 251: The file "April.xlsx" was
  not uploaded due to an unknown error.

I already use 'files'=>true in my form tag and in my controller code I have...
<?php

$mandatoryDocument = $input['mandatoryDocument'];
if ($mandatoryDocument != null) {
    $mandatoryFile = time() . '-' . $mandatoryDocument->getClientOriginalName();
    $mandatoryDocument->move(public_path() . '/files/mandatory_documents/', $mandatoryFile);
    $achievement->file_path = $mandatoryFile;
}

When I dd($input['mandatoryDocument']) in the controller I get the error...

UploadedFile {#27 ▼   -test: false   -originalName: "April.xlsx"
  -mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  -size: 12297   -error: 0 }

The file successfully moved to /public/files/mandatory_documents
but with that error. Where is the problem? Thank you.


text:
Q: Requests Python: Query the data and change using using payload requests I want to change the 'is_app_enabled' to true into the particular filterd market,
Statement: query the particular market, then change the value of is_app_enabled to true,
The web network request which i got is as below:
General:
Request URL: http://10.76.98.167:5000/api/v1/apps/settings/dcp/
Request Method: PUT
Status Code: 200 OK
Remote Address: 10.76.98.167:5000
Referrer Policy: no-referrer-when-downgrade

Response Headers

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://10.76.98.167:5000
Cache-Control: no-store
Connection: keep-alive
Content-Length: 16
Content-Type: application/json
csrf-token: 8303a69ba4cfe891e7595f15b76f9ecfed1e2c96f75349533dae12faf2460248
Date: Mon, 01 Apr 2019 09:53:36 GMT
Server: nginx/1.15.0
Set-Cookie: session=.eJyrVopPK0otzlCyKikqTdVRis9MUbKqVlJIUrJSisryrPR18azyzQ018XcPNIzMSjbyzcrI9HVJN_J3yTbxcwk19A_xNPY1CrVVqgXqLUgtyk3MS80rgZlWWpxaBDZRKTEvMaeyJDO5WKkWAFXsJa0.D4NxIA.3hVVx9L-fUj7hAePOz4-aXWY3eQ; Expires=Mon, 01-Apr-2019 10:23:36 GMT; HttpOnly; Path=/
X-Frame-Options: SAMEORIGIN

Requests Headers:

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 72
Content-Type: application/json;charset=UTF-8
Cookie: session=.eJyrVopPK0otzlCyKikqTdVRis9MUbKqVlJIUrJSisryrPR18azyzQ018XcPNIzMSjbyzcrI9HVJN_J3yTbxcwk19A_xNPY1CrVVqgXqLUgtyk3MS80rgZlWWpxaBDZRKTEvMaeyJDO5WKkWAFXsJa0.D4Nw3A.9lXgT0AhT5QFmmK6HJK9_G7aTTg
csrf-token: 8303a69ba4cfe891e7595f15b76f9ecfed1e2c96f75349533dae12faf2460248
Host: 10.76.98.167:5000
Origin: http://10.76.98.167:5000
Referer: http://10.76.98.167:5000/explorer/v2/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36

Request Payload :

{query: "market == 'Austin'", is_app_enabled: true, tz: "Asia/Kolkata"}
is_app_enabled: true
query: "market == 'Austin'"
tz: "Asia/Kolkata"

I Have tried with the below code:
import requests
import json

s=requests.session()
report_url= 'http://10.76.98.167:5000/api/v1/apps/settings/dpo/'

payload = {query: "market == 'DEL'", is_app_enabled: true, tz: "Asia/Kolkata"}
r = s.post(report_url,data=paylaod)

print("second",report_url)

it's throwing an error : payload = '{query: "market == 'DEL'", is_app_enabled: true, tz: "Asia/Kolkata"}
NameError: name 'query' is not defined,
How to query the data and update the particular field?

A: it's because without the quotes, it's looking at that as a variable, which is not defined. try:
payload = {"query": "market == 'DEL'",
           "is_app_enabled": "true",
           "tz": "Asia/Kolkata"}

Also, check your spelling of payload here:
r = s.post(report_url,data=paylaod)


text:
Q: How to Fix MySQL Count Function Error In Java? I am trying to create a method that will count the number of records I have in a certain table when the method is called.  But for some reason, I keep getting an error saying I have a problem in my SQL code.  Looking over everything, I couldn't find the problem.  I even went as far to as to copy parts of another person's solution online, but this failed too. To better show where the error seems to be ocurring, I inserted two print statements in the code. I think Java and SQL must hate me!  Any help would be most appreciated.
 int tableCounter(String tableName) {
                int num = 0;
                String sql = "SELECT COUNT(*) AS total FROM ?";
                try(Connection conn = letConnect(); PreparedStatement ps = conn.prepareStatement(sql)){
                    ps.setString(1, tableName);
                    System.out.println("test");
                    ResultSet rs = ps.executeQuery();//error ocurrs here
                                                     //when the SQL code is executed
                    System.out.println("test");
                    num = rs.getInt("total");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return num;
            }

Output:
test
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Country'' at line 1
    at mysql.connector.java@8.0.30/com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
    at mysql.connector.java@8.0.30/com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at mysql.connector.java@8.0.30/com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)
    at mysql.connector.java@8.0.30/com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:972)
    at Database_Interactor.tableCounter(Database_Interactor.java:25)
    at MainClass.main(MainClass.java:10)

A: Based on the answer given above, the code should look something like this:
int tableCounter(String tableName) {
    int num = 0;
    String sql = "SELECT COUNT(*) AS total FROM "+ tableName;
    Connection conn = letConnect();
    try{Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()){
            num = rs.getInt("total");}
    }catch (SQLException e) {
        e.printStackTrace();}
    return num;}


text:
Q: Can I add more than on button to a java JFrame? I am facing a problem, I want to add more than a button to a JFrame, but it only takes the last one and puts it into the frame, a sample of my code is below:
String isName = "";

JFrame frame = new JFrame(isName);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

String childAmb = "PDA276";

for (int j=0; j<3; j++){

    if (childAmb.matches("Phone\\w\\w\\w"))
        fancyButtonCreator(childAmb, new ImageIcon ("src/phone.gif"), frame);

    else if (childAmb.matches("PDA\\w\\w\\w"))
        fancyButtonCreator(childAmb, new ImageIcon ("src/pda.gif"), frame);

    else if (childAmb.matches("PC\\w\\w\\w"))
        fancyButtonCreator(childAmb, new ImageIcon ("src/pc.gif"), frame);
    }

   frame.setVisible(true);
   frame.setBounds(100, 200, 200, 200);

Thank you.

A: If you don't have a layout-manager, only one, the last component added will show up.
frame.setLayout (new FlowLayout ());
frame.add (new JButton ("foo"));
frame.add (new JButton ("bar"));

A: Read the section from the Swing tutorial on Using Layout Managers for examples.
You can start with the FlowLayout.


text:
Q: how to permanently add raster to satellite image in qgis As  mentioned in the title i need to integrate a raster to a satellite image but have no idea as to how to do this.
I tried the add grid function and it works nice but is not permanent. I insert it via map composer but as this inhibits zooming I need to save it on the image. The person who will use the image as a map wishes to be able to zoom just as in any image.
How is it possibly to permanently add the a raster with 10 square kilometre grid size permanently to a satellite image I have as TIFF format?

A: The problem you have to solve is that a vector grid is displayed in a scale-independent pixel size, while a raster image is defined by a fixed cell size.
You could rasterize your vector grid, and merge it with the satellite image, but zooming out the grid will get smaller until it can not be seen anymore.
The other way round, a 10km, 1-pixel-wide grid will lead to a screen full of lines hiding the satellite image completely.
So you can only make a grid for a most wanted scale.


text:
Q: Display Badges depending on Points Laravel 5.2 I'm having a hard time displaying correct badges in a users view. I have a points system where users can earn points depending on various tasks that they do. I implemented a @if, @elseif system in my view to display certain badges(a image) depending on how many points a user has. So if a user has 100 points, one badge will display, if a user has 250 points another badge will display with the old badge too.
here is the view:
@if ($user->points->points >= 100)
     ShowPointsFor100() }}" class="ui small circular image">
@elseif ($user->points->points >= 250)
     ShowPointsFor100() }}" class="ui small circular image">
     ShowPointsFor250() }}" class="ui small circular image">
@endif

My problem is even if a user has more than 250 points or greater only the first badge(image) will show. How do I make it so that 2 badges show?
Here is an image:


text:
Q: Use ImageMagick with python. (on a linux system) I want to define a function that "call" imagemagick to convert an image.
def convert(filein,fileout):
#imagemagick>convert filein fileout

How can I call and use imagemagick with Python?
I'm running on a linux system, imagemagick is installed, and I'm not using PIL.module because it doesn't handle PPM[p3].

A: Either use one of the shell interfaces of Python (os.system, subprocess.Popen) to call the imagemagick binary, or try out PythonMagick.

A: I would suggest u use subprocess it is safer
import subprocess
params = ['convert', 'src_file', 'result_file']
subprocess.check_call(params)

A: I have not used image magic but you could use os.system to call a shell command:
import os
os.system('imagemagick-converting-command filein fileout')

I suggest you go with PythonMagic as Creshal said. It is provided by ImageMagic and thus must be one of the best port available for python.

A: Disclaimer: I am the author of Wand.
You can easily do that using Wand, a simple binding of ImageMagick for Python.  For example, the following code converts a PNG image to a JPEG image:
from wand.image import Image

with Image(filename='in.png') as img:
    img.format = 'jpeg'
    img.save(filename='out.jpg')

See this tutorial as well.


text:
Q: Rails: Is there a way to associate a name with each locale? I have 2 languages at the moment: English and Greek (:en & :el).
I'm using the globalize gem.
Is there a way so I can put them in a loop and then extract the name of each language?
For example is there something like the following:
I18n.locale.Name_of_the_locale

If yes, where do I declare/change it?

A: One solution is to create a :language_name key inside your en.yml and gr.yml:
en:
  language_name: English

gr:
  language_name: Greek

Then simply call I18n.t('language_name'). If you need to have them all at once, you can still loop through all the available locales:
I18n.available_locales.map { |locale| I18n.t('language_name', locale: locale) }


text:
Q: Netty WebSocket Client Channel always gets inactive on Linux Server I built a websocket client based on netty websocket client example to integrate with 3rd party feed, the code is almost same as the official example, only changed the URI and the TextWebSocketFrame handling.
This client is part of a Spring Boot webapp, and it works fine on my MacBook or Windows 7 PC, however, once I deploy the war to Linux server (Linux version 2.6.32-504.3.3.el6.x86_64 Red Hat 4.4.7-11), the channel would go inactive directly when the application starts.
I have checked the network, JDK version(1.8.x), Tomcat version (8.5.16), Netty version(4.1.13.Final), seems no problem, really confused.
WebSocketClientHandler.java:
public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

    private final Logger logger = LoggerFactory.getLogger("feedlogger");

    private final WebSocketClientHandshaker handshaker;
    private ChannelPromise handshakeFuture;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        handshaker.handshake(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        // always reaches here immediately on Linux
        logger.error("webSocket Client disconnected!");
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            logger.info("finishHandshake and webSocket Client Connected!");
            handshakeFuture.setSuccess();
            return;
        }

        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;
            logger.error("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
            return;
        }

        WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof TextWebSocketFrame) {
            TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
            logger.info(textFrame.text());
            List<String> messages = FeedJsonUtils.deserializeAsyncMessage(textFrame.text());
            if (!CollectionUtils.isEmpty(messages)) {
                messages.stream().forEach(message -> {
                        FeedReceiver.onMessage(message);
                });
            }
        } else if (frame instanceof PongWebSocketFrame) {
            logger.error("WebSocket Client received pong");
        } else if (frame instanceof CloseWebSocketFrame) {
            logger.error("WebSocket Client received closing");
            ch.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
    {
        logger.error("exception caught: ", cause);
        cause.printStackTrace();
        if (!handshakeFuture.isDone()) {
            handshakeFuture.setFailure(cause);
        }
        ctx.close();
    }
}

WebSocketClientImpl.java:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

@Component
public class WebsocketClientImpl {
    private final Logger logger = LoggerFactory.getLogger("feedlogger");

    private static final String WSS_URL = "wss://api.xxx.com/ws/?token=";

    private Channel ch = null;

    @Async
    public void connectWebSocket(String token) throws Exception {

        URI uri = new URI(WSS_URL + token);
        String scheme = uri.getScheme() == null ? "wss" : uri.getScheme();
        final String host = uri.getHost() == null ? "api.mollybet.com" : uri.getHost();

        final int port;
        if (uri.getPort() == -1) {
            if ("ws".equalsIgnoreCase(scheme)) {
                port = 80;
            } else if ("wss".equalsIgnoreCase(scheme)) {
                port = 443;
            } else {
                port = -1;
            }
        } else {
            port = uri.getPort();
        }

        if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
            logger.error("Only WS(S) is supported.");
            return;
        }

        // SSL handling
        final boolean ssl = "wss".equalsIgnoreCase(scheme);
        final SslContext sslCtx;
        if (ssl) {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            sslCtx = null;
        }

        EventLoopGroup group = new NioEventLoopGroup();
        try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08
        // or V00.
        // If you change it to V00, ping is not supported and remember to
        // change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the
        // pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                        WebSocketClientCompressionHandler.INSTANCE, handler);
                }
            });

            ch = b.connect(uri.getHost(), port).sync().channel();
            handler.handshakeFuture().sync();

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine();
                if (msg == null) {
                    break;
                } else if ("bye".equals(msg.toLowerCase())) {
                    ch.writeAndFlush(new CloseWebSocketFrame());
                    ch.closeFuture().sync();
                    break;
                } else if ("ping".equals(msg.toLowerCase())) {
                    WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
                } else {
                    WebSocketFrame frame = new TextWebSocketFrame(msg);
                    ch.writeAndFlush(frame);
                }
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    public void send(String message) {
        if (ch == null) {
            logger.error("channel unavailable");
            return;
        }
        WebSocketFrame frame = new TextWebSocketFrame(message);
        ch.writeAndFlush(frame);
    }

}

FeedServiceImpl.java: (connect websocket automatically when application starts)
@Service
@PropertySource("classpath:api.properties")
public class FeedServiceImpl implements FeedService {
    private final static Logger logger = LoggerFactory.getLogger("feedlogger");

    @Autowired
    private Environment env;

    @Autowired
    private WebsocketClientImpl websocketClientImpl;

    @Override
    @PostConstruct
    public void connectWs() {
        String token = env.getProperty("ws.token", String.class);
        websocketClientImpl.connectWebSocket(token);
    }

}

}

A: Finally I solved this problem, my WebSocketClient class is almost same as the WebSocketClient in the netty websocket client example, after replacing the following code:
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while (true) {
    String msg = console.readLine();
    if (msg == null) {
        break;
    } else if ("bye".equals(msg.toLowerCase())) {
        ch.writeAndFlush(new CloseWebSocketFrame());
        ch.closeFuture().sync();
        break;
    } else if ("ping".equals(msg.toLowerCase())) {
        WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
        ch.writeAndFlush(frame);
    } else {
        WebSocketFrame frame = new TextWebSocketFrame(msg);
        ch.writeAndFlush(frame);
    }
}

with:
Thread.sleep(Integer.MAX_VALUE);

the websocket connection back to normal now.


text:
Q: Android : Application's state when application is out of stack due to Memory constrain Please help me to resolve this problem.
1 > I am having application which Uses Service to retrieve data from server.
2 > Now on Pressing Home key and i have opened new application..
3 > I have opened around 20 application.
4 > So my application might go out of memory stack.
5 > now i am resuming my application, application crashes as i am opening activity of my
    application which is not in the stack.

Is there anyway by which i can handle this exception and redirect my activity to Homepage or relaunch application resume and is not in stack...

A: Indeed a very good question which I try to puzzle out myself.
I even wonder What's the difference between killing an app and restarting the phone.
If a user manually kills an app or opens 20 other apps, he'd probably want the app to start from the beginning.
Why Android aren't restoring state after phone restart?
Also, I see that when an app is killed (by the system), global variables turn to null upon activity reinitiating.
This kind of breaks the concept of Java. If you have some kind of state in the application and the application erases it, I would expect the application to restart.
The solution I propose:
1. Handle the case of a state problem: Initiate a simple state (new Object()) as a global variable. For each Activity, in the methods onCreate/Start/Resume check that the state is null. If it's null launch the first activity with 'Intent.FLAG_ACTIVITY_CLEAR_TOP' - as if the application is relaunched.
 2. Try not to use global variables - Always put data in the intent.
 3. Lazy load global variables - If you do want to use global data, don't count on one time initialization. Lazy load them 'if (A.MY_DATA == null) {A.MY_DATA = new ...}' - Don't forget to do it in the background if it will take a long time (AsyncTask). Loading partial state needs to be done carefully because it may not comply to other loaded state objects.

The downside of the first point is that the state problem handling needs to be done on every Activity (AOP is not yet implemented in Android).
Hope that helped.

A: Use SharedPreferences for save Application state


text:
Q: get app download count from android market I can use android-market-api to get nearly all information about my app from  Android Market.
But with published function from android-market-api, I cannot get download count number as it is in the Publisher's page (market.android.com/publish)
Is there any way to get this number with my android market developer account?
Thank you.

A: You can try using Google Analytics in your app (you'll get a lot of useful stats) and then use Analytics API to track download counts and source.

A: Are you looking for the exact numeric download count or a range? Because downloadsCountText (which you can get) will give you the latter.

A: I'm confusing by how you asked the question. If you have no access to the Google Developer Console, you can only search for it on Google Play and get an estimated range.
If you do, select the app, then click the first tab at left called "Statistics". It will give you a more detailed sales graph.


text:
Q: How to combine $facet result into the desired structure I need to get two different sets of data from the same collection and if any data in any set has convergence with another data in other set combine them into one and if not convert them to a desired format, to make it more clear think there is a collection named collection1 and I need to get started tasks with specific condition and completed tasks with specific condition from this collection and I managed to do it like this:
db.collection1.aggregate([{
    $facet: {
        "started":[...],
        "completed":[...]
        }
    },
  ]).toArray()

and assume that started is an array of this  :
interface Starts{
  supplier: string;
  publisher: string;
  partner: string;
  buyer: string;
  started_at: string;
  starts: number;
}

And completed is an array of this:
interface Completes{
  supplier: string;
  publisher: string;
  partner: string;
  buyer: string;
  finished_at: string;
  completes: number;
  revenue: number;
}

you see some started tasks with certain supplier,partner,buyer,publisher might be actually completed and their completion info exist in completed array so the two need to merge and some might not( and I will not have finished_at,completes,revenue info for them and I would put null for these values) and also some completed tasks might not be related to any started tasks( and I will not have starts,started_at info for them and I would put null for these values)ergo the final result will look like an array of this:
interface StartsCompletes{
  supplier: string;
  publisher: string;
  partner: string;
  buyer: string;
  started_at: string;
  finished_at: string;
  starts: number;
  completes: number;
  revenue: number;
}

well I can loop through the output of facet with JavaScript for-loops and make it happen but can I some how add another stage to my aggregate pipeline and do it with MongoDB?

A: I think it could be easier to achieve this in memory, but here is a way I use to merge arrays using $reduce, essentially I iterate over the array item by item and either push it to the array if it doesn't match the condition (of supplier x partner x buyer x publisher ), and if it does exist I merge the two objects.
Overall it looks like this:
db.collection1.aggregate([
  {
    $facet: {
      "started":[...],
      "completed":[...]
    }
  },
  {
    $project: {
      merged: {
        $reduce: {
          input: {
            $concatArrays: [
              "$started",
              "$completed"
            ]
          },
          initialValue: {
            values: [],
            mapping: []
          },
          in: {
            $cond: [
              {
                $in: [
                  {
                    $concat: [
                      "$$this.supplier",
                      "$$this.partner",
                      "$$this.buyer",
                      "$$this.publisher"
                    ]
                  },
                  "$$value.mapping.key"
                ]
              },
              {
                values: {
                  $map: {
                    input: "$$value.values",
                    as: "arrValue",
                    in: {
                      $cond: [
                        {
                          $and: [
                            {
                              $eq: [
                                "$$arrValue.supplier",
                                "$$this.supplier"
                              ]
                            },
                            {
                              $eq: [
                                "$$arrValue.partner",
                                "$$this.partner"
                              ]
                            },
                            {
                              $eq: [
                                "$$arrValue.buyer",
                                "$$this.buyer"
                              ]
                            },
                            {
                              $eq: [
                                "$$arrValue.publisher",
                                "$$this.publisher"
                              ]
                            },

                          ]
                        },
                        {
                          $mergeObjects: [
                            "$$arrValue",
                            "$$this"
                          ]
                        },
                        "$$arrValue"
                      ]
                    }
                  }
                },
                mapping: "$$value.mapping"
              },
              {
                values: {
                  $concatArrays: [
                    "$$value.values",
                    [
                      "$$this"
                    ]
                  ]
                },
                mapping: {
                  $concatArrays: [
                    "$$value.mapping",
                    [
                      {
                        key: {
                          $concat: [
                            "$$this.supplier",
                            "$$this.partner",
                            "$$this.buyer",
                            "$$this.publisher"
                          ]
                        },
                        value: {
                          $size: "$$value.mapping"
                        }
                      }
                    ]
                  ]
                }
              }
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      mergedResults: "$merged.values"
    }
  }
])

Mongo Playground

A: Another option is to replace the $facet stage with a simple $group:
db.collection.aggregate([
  {$group: {
      _id: {
        supplier: "$supplier",
        publisher: "$publisher",
        partner: "$partner",
        buyer: "$buyer"
      },
      started_at: {$max: "$started_at"},
      starts: {$max: "$starts"},
      revenue: {$max: "$revenue"},
      finished_at: {$max: "$finished_at"},
      completes: {$max: "$completes"}
  }},
  {$set: {
      buyer: "$_id.buyer",
      partner: "$_id.partner",
      publisher: "$_id.publisher",
      supplier: "$_id.supplier",
      _id: "$$REMOVE"
  }}
])

Which should not worry about document size limit.
See how it works on the playground example


text:
Q: How to pass QVector to QML? I have QObject class with 2 properties:
class Foo : public QObject {
Q_OBJECT
    Q_PROPERTY(QVector<Namespace1::Namespace2::Item> items READ getItemVector)
    Q_PROPERTY(QVector<QString> tests READ getTestVector)
    ...
}

QVector<Namespace1::Namespace2::Item> Foo::getItemVector() const
{
    return _item_vector;
}

QVector<QString> Foo::getTestVector() const
{
    return _test_vector;
}

Everything is ok with QVector of QStrings in the QML, but I was not able to pass QVector of Namespace1::Namespace2::Items.
Output to QML console gives me:
QVariant(QVector<Namespace1::Namespace2:Item>) for console.log(foo.items)
and
length = undefined for console.log(foo.items.length)
What I have found out from the Qt documentation:

These sequence types are implemented directly in terms of the underlying C++ sequence. There are two ways in which such sequences can be exposed to QML: as a Q_PROPERTY of the given sequence type; or as the return type of a Q_INVOKABLE method.

...

In particular, QML currently supports: ... QList< QString >... and all registered QList, QVector, QQueue, QStack, QSet, QLinkedList, std::list, std::vector that contain a type marked with Q_DECLARE_METATYPE.

As I understand, everything boils down simply to:
Q_DECLARE_METATYPE(Namespace1::Namespace2::Item)

Besides this:

Some types are registered automatically and do not need this macro: Pointers to classes derived from QObject, QList< T >, QVector< T >, QQueue< T >, QStack< T >, QSet< T > or QLinkedList where T is a registered meta type

However, I also tried to declare metatype(without luck, obviously):
Q_DECLARE_METATYPE(QVector<Namespace1::Namespace2::Item>)

and also tried to register metatypes(without any luck as well):
qRegisterMetaType<Namespace1::Namespace2::Item>("Namespace1::Namespace2::Item");
qRegisterMetaType<QVector<Namespace1::Namespace2::Item>>("QVector<Namespace1::Namespace2::Item>");

The Item by itself is a Q_GADGET:
namespace Namespace1 { namespace Namespace2 {
    class Item
    {
    Q_GADGET
        Q_PROPERTY(QString name READ getName CONSTANT)

    public:
        Item();
        Item(const QString& name);
        Item(const Item& origin);
        Item(Item&& origin);
        ~Item();

    private:
        QString _name;

    public:
        Item& operator=(const Item& rhs);
        Item& operator=(Item&& rhs);

    friend QDataStream& operator<<(QDataStream& out, const Item& item);
    friend QDataStream& operator>>(QDataStream& in, Item& item);
    friend QDebug operator<<(QDebug debug, const Item& item);
    }
} }

What am I missing?
Thank you!

A: The "traditional" way of doing this is to convert each element to a QVariant, and pass collection as a QVariantList
QVariantList MyClass::getFooCollection(void) const
{
    QVariantList list;

    for (const auto& l: fooCollection_)
    {
        list.append(QVariant::fromValue(l));
    }

    return list;
}

The metatype system declaration and registration you have shown are required


text:
Q: Win32 API Combo-box issue I have a combo-box within my window; and I'm capable of adding elements to the combo-box flawlessly however when I attempt to remove one or all of the items, no items are removed. According to Spy++ the message WM_DELETEITEM sends however the combo-box is not receiving the message.

A: You don't send WM_DELETEITEM to delete the item, it gets sent back to you once the control has finished deleting the item. Use CB_DELETESTRING instead.


text:
Q: Stop jQuery validation and submit the form I have jquery validation in my page which has two functionalities Submit,Search. When i click on submit, the page gets validated and once the correct values are entered the form gets submitted.
Now i have another button(Search) on the same page. When i click on that button the form again gets validated since the control submits the form. But i don't need the validation for this button.
//Code
<script type="text/javascript">
        jQuery(document).ready(function () {

 // binds form submission and fields to the validation engine
            jQuery("#form1").validationEngine('attach');
        });
    </script>

The above code makes the validation enable for both the buttons.
Is there any option to make the validation disabled on click of the Search button?
(Or)
Can this validation made to work OnClick of the button instead of submitting the form.
Note: This piece of code is in the master page.
Source: http://www.position-relative.net/creation/formValidator/demos/demoValidators.html


text:
Q: Unable to upload CSV file using google analytics API in C# I'm trying to upload a CSV file using google analytics api and it gives me a status failed.
The error that I'm getting is variable is null: parameter  name base uri
I have given the permissions for google analytics api in developer console and I'm using service account to generate the key and the id's.
This is my code snippet
        const string serviceAccountEmail = "716698526626-6s61a3tbe1m5mofo9@developer.gserviceaccount.com";
        const string serviceAccountPKCSP12FilePath = @"C:\SVN\GAPforInboundandWeb-1f6bfb.p12";
        X509Certificate2 certificate = new X509Certificate2(serviceAccountPKCSP12FilePath, "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics }
            }.FromCertificate(certificate));
        var service = new AnalyticsService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = "GAPforInboundandWeb"
        });

        FileStream realCsv = new FileStream("c:\\real.csv", FileMode.Open);
        // Create the service.

        try
        {
            var upload = service.Management.DailyUploads.Upload("50288725", "UA-50288725-1", "Oy_0JTPvRGCB3Vg5OKVIMQ",
                "2014-09-22", 1, ManagementResource.DailyUploadsResource.UploadMediaUpload.TypeEnum.Cost, realCsv,
                "application/octet-stream");
            upload.Reset = true;
            var res = upload.Upload();
            res.BytesSent.ToString();
            res.Status.ToString();
        }

A: I resolved the same problem. In my case, its a wrong DataSourceId.
Try this:
 const string serviceAccountEmail = "716698526626-6s61a3tbe1m5mofo9@developer.gserviceaccount.com";
    const string serviceAccountPKCSP12FilePath = @"C:\SVN\GAPforInboundandWeb-1f6bfb.p12";
    X509Certificate2 certificate = new X509Certificate2(serviceAccountPKCSP12FilePath, "notasecret", X509KeyStorageFlags.Exportable);

    ServiceAccountCredential credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            Scopes = new[] { AnalyticsService.Scope.Analytics }
        }.FromCertificate(certificate));
    var service = new AnalyticsService(new BaseClientService.Initializer
    {
        HttpClientInitializer = credential,
        ApplicationName = "GAPforInboundandWeb"
    });

    FileStream realCsv = new FileStream("c:\\real.csv", FileMode.Open);
    // Create the service.

    try
    {
        var dataSource = srv.Management.CustomDataSources.List(AccountId, WebId).Execute();
        var strDataSourceId = "Oy_0JTPvRGCB3Vg5OKVIMQ";
        if(dataSource!=null && dataSource.Items.Length>0)
          strDataSourceId =dataSource.Items[0].Id;
        var upload = service.Management.DailyUploads.Upload("50288725", "UA-50288725-1", strDataSourceId,
            "2014-09-22", 1, ManagementResource.DailyUploadsResource.UploadMediaUpload.TypeEnum.Cost, realCsv,
            "application/octet-stream");
        upload.Reset = true;
        var res = upload.Upload();
        res.BytesSent.ToString();
        res.Status.ToString();
    }

Use List methods on service.Management.CustomDataSources and service.Management.Uploads in this order for check your config.


text:
Q: POST using Curl with user ip I'm making a script that post on a website using curl and i was wondering if i can make the post using user's IP (actually i'm posting using server ip)
Thanks in advance

A: You can't spoof the IP address as CURL isn't the one providing it to the server you are connecting to, the TCP/IP network stack is. So there is no setting or switch to override, it is just a core mechanism of the network communication.


text:
Q: Автоматическое выделение чекбокса "Все" при нажатии на все другие чекбоксы v.2 Вот весь мой код, связанный с этой проблемой.
FilterBox.jsx

import React from 'react';
import classes from './filter-box.module.scss';

const FilterBox = ( props ) => {
    const { filterData, checkAll } = props
    const elements = filterData.map((el) => {
        const { label, id, isChecked } = el
        return (

                    <input onChange={() => checkAll(id)} checked={isChecked} className={classes.filter__input} type="checkbox" />

                    {label}

        )
    })
    return (

Количество пересадок

                {elements}

    )
}

export default FilterBox;

reducer.js

const initialState =  [
    {label: "Все", id:1, isChecked: false},
    {label: "Без пересадок", id:2, isChecked: false},
    {label: "1 пересадка", id:3, isChecked: false},
    {label: "2 пересадки", id:4, isChecked: false},
    {label: "3 пересадки", id:5, isChecked: false},
]

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'CHECKED':
            if (action.id === 1) {
                if (state[0].isChecked === false) {
                    return state.map(el => ({...el, isChecked: true}))
                } else {
                    return state.map(el => ({...el, isChecked: false}))
                }
            }
            if (state[0].isChecked === false) {
                const index = state.findIndex((el) => el.id === action.id)
                const oldItem = state[index]
                const newItem = {...oldItem, isChecked: !oldItem.isChecked }
                return [...state.slice(0, index), newItem, ...state.slice(index + 1)]
            } else {
                const index = state.findIndex((el) => el.id === action.id)
                const oldItem = state[index]
                const allOldItem = state[0]
                const allNewItem = {...allOldItem, isChecked: false}
                const newItem = {...oldItem, isChecked: !oldItem.isChecked }
                return [allNewItem, ...state.slice(1, index), newItem, ...state.slice(index + 1)]
            }
        default:
            return state
    }

}

export default reducer

index.js

import React from "react"
import ReactDOM from "react-dom"
import FilterBox from "./filter-box";
import {createStore, bindActionCreators} from "redux";
import reducer from "./reducer";
import * as actions from "./actions";

const store = createStore(reducer)
const { dispatch } = store
const { checked } =
    bindActionCreators(actions, dispatch)

const update = () => {
    ReactDOM.render(<FilterBox
                    filterData={store.getState()}
                    checkAll={checked}/>, document.getElementById("root"))
}
update()
store.subscribe(update)

И вот по всей этой информации мне нужно сделать так, чтобы первый чекбокс отмечался, когда все уже отмечены. Пробовал и через state.filter, и counter +- 1

A: Ок повторный ответ: из state я удалил объект "Все", будем рендерить его отдельно. FilterBox я подключил к Редакс так как это происходит на реальных проектах.
Имеем: App.js, reducer, initial state:
import React from "react";
import FilterBox from "./FilterBox";
import { createStore } from "redux";
import { Provider } from "react-redux";

const initialState = [
  { label: "Без пересадок", id: "2", isChecked: false },
  { label: "1 пересадка", id: "3", isChecked: false },
  { label: "2 пересадки", id: "4", isChecked: false },
  { label: "3 пересадки", id: "5", isChecked: false },
];

const reducer = (state = initialState, { type, payload }) => {
  switch (type) {
    case "CHECKED":
      return state.map((item) =>
        item.id === payload.id ? { ...item, isChecked: !item.isChecked } : item
      );
    case "CHECK_ALL":
      return state.map((item) => ({ ...item, isChecked: payload.checked }));
    default:
      return state;
  }
};

const store = createStore(reducer);

const App = () => {
  return (
    <Provider store={store}>
      <FilterBox />
    </Provider>
  );
};

export default App;

FilterBox.js, actions:
import React from "react";
import { connect } from "react-redux";

const toggleCheckbox = (e) => ({
  type: "CHECKED",
  payload: {
    id: e.target.id,
  },
});

const toggleCheckAll = (e) => ({
  type: "CHECK_ALL",
  payload: {
    checked: e.target.checked,
  },
});

const FilterBox = ({ state, toggleCheckbox, toggleCheckAll }) => {
  const renderInput = (label, id, isChecked, handler) => {
    return (

          <input
            id={id}
            onChange={(e) => handler(e)}
            checked={isChecked}
            className={"classes.filter__input"}
            type="checkbox"
          />

          {label}

    );
  };

  const renderElements = () => {
    return state.map(({ label, id, isChecked }) =>
      renderInput(label, id, isChecked, toggleCheckbox)
    );
  };

  const areAllChecked = state.every((item) => item.isChecked);

  return (

Количество пересадок

        {renderInput("Все", "1", areAllChecked, toggleCheckAll)}
        {renderElements()}

  );
};

const mapStateToProps = (state) => ({ state });

export default connect(mapStateToProps, { toggleCheckbox, toggleCheckAll })(
  FilterBox
);


text:
Q: Strange clause in Javascript the Good Parts This code is from the section of recursion.
var getElementsByAttribute = function (att, value) {
    var results = [];

    walk_the_DOM(document.body, function (node) {
        var actual = node.nodeType === 1 && node.getAttribute(att);
        if (typeof actual === 'string' &&
                (actual === value || typeof value !== 'string')) {
            results.push(node);
        }
    });

    return results;
};

I don't understand the point of the clause below:
typeof actual === 'string' && (actual === value || typeof value !== 'string')

How is it different from?
typeof actual === 'string' && actual === value

A: typeof actual === 'string' && (actual === value || typeof value !== 'string')

This will return true if and only if actual is a string, and either actual === value, or value is not a string.
typeof actual === 'string' && actual === value

This will return true if and only if actual is a string and either actual === value.
In other words, the first condition returns true if value is anything other than a string, whereas the second condition will only return true if it is a string, and strictly equal to actual.


text:
Q: Delete item in mapped array in React Let's say I have an array and I'm mapping through it:
{items &&
      items.map((item) => (
        <div key={item}>
          {item} <button>Delete</button>
        </div>
      ))}

I'm keeping items in state hook - [items, setItems] = useState(itemsArray);
How do I remove the item at its specific index when I click that 'Delete' button?


text:
Q: How to get the captured / saved image from camera to another app? I have a camera app that allows the user to "Save" or "Discard" image after each photo is taken. If "Save" is clicked the app goes back to the MainActivity (camera preview) and keeps the photo. If "Discard" is clicked the photo is removed and goes back to the MainActivity (camera preview). This all works fine.
I have a standard email app (TypeApp) that allows users to attach a photo by "Take a Picture" function which when clicked shows all installed camera. I want to use my camera app to allow this but when I save the photo and click "Back" no image is attached. I've seen it worked on other camera app but I don't know how to begin to implement this feature in my app.
How do I get my camera app to send back the location of the image to the standard email app when the user clicks the "Save" button.
Any guidance would be appreciated.

A: Please try this, maybe you'll get data in the third parameter.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    //you get data in  email app (TypeApp) Activity
    }
}//onActivityResult

Useful link:-
https://developer.android.com/training/basics/intents/result
More HelpFull:-
https://medium.com/@rodrigolmti/android-get-camera-thumbnail-and-full-image-1bddfdc5347e


text:
Q: Why are random values making pattern? I tried to generate array of zeros and ones, convert to raster and plot it.
I expect to have random pattern, so why there is apparent pattern in this raster?
Have I done some mistake in script?
# creating vector containing "0" and "1" values...
x<-sample(c(0,1), 1000, replace=TRUE)

# ...converting it into array...
x_arr<-array(x, dim=c(100,100))

# ....nest into raster
x_rast<-raster(x_arr)

# ...and making plot
plot(x_rast)

A: Because 100*100 gives 10000, not 1000, and R will fill up by repeating. Try
library(raster)
x<-sample(c(0,1), 10000, replace=TRUE)

The example was nice, but please do not forget to paste it into an virgin R before posting. You had forgotten the library.


text:
Q: Execution failed for task :app:processDebugGoogleServices
Error:Execution failed for task ':app:processDebugGoogleServices'.
  Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.2.0.

apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.nadav.firebasedemo"
    minSdkVersion 23
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
//noinspection GradleCompatible
implementation 'com.google.android.gms:play-services-auth:11.4.2'
implementation 'com.google.firebase:firebase-messaging:11.4.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
compile 'com.google.firebase:firebase-core:9.2.0'
compile 'com.google.firebase:firebase-database:9.2.0'
compile 'com.google.firebase:firebase-crash:9.2.0'
compile 'com.google.firebase:firebase-messaging:11.6.0'
 }
apply plugin: 'com.google.gms.google-services'
// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'com.google.gms:google-services:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
}
}

task clean(type: Delete) {
   delete rootProject.buildDir
 }

A: Try this Update your firebase dependencies because You need to use same version of dependencies in your build.Gradle
compile 'com.google.firebase:firebase-core:11.6.0'
compile 'com.google.firebase:firebase-database:11.6.0'
compile 'com.google.firebase:firebase-crash:11.6.0'
compile 'com.google.firebase:firebase-messaging:11.6.0'

A: You are using 3 different version of firebase libraries.
implementation 'com.google.firebase:firebase-messaging:11.4.2'
compile 'com.google.firebase:firebase-core:9.2.0'
compile 'com.google.firebase:firebase-database:9.2.0'
compile 'com.google.firebase:firebase-crash:9.2.0'
compile 'com.google.firebase:firebase-messaging:11.6.0'

You have to use the same version.
Use the latest version:
    implementation 'com.google.firebase:firebase-messaging:11.6.0'
    compile 'com.google.firebase:firebase-core:11.6.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-crash:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'


text:
Q: Effect Size Calculation with metafor (using "SMD"): insert standard deviation of difference of groups rather than group-specific SDs? I am currently trying to calculate effect sizes for a meta-analysis that I am conducting. I am interested in calculating a standardized mean difference for paired data. I am using the escalc function ("SMD") of the package metafor to do this.
I have realized why extracting data that some papers only report the standard deviation of the difference scores rather than the SDs of the two groups specifically. When this is the case, how can I implement them into the escalc function, as "SMD" always seems to require the groups' SDs.
Thanks a lot!

A: Measure SMD is not for paired data. See help(escalc) or go to https://wviechtb.github.io/metafor/reference/escalc.html and search for measures SMCC and SMCR. The section that starts with "A few notes about the change score measures." is particularly relevant.


text:
Q: Play video with this audio in AVMutableCompositionTrack I have a 2 AVMutableCompositionTrack objects. 1st contains video (with his sound) and 2nd contains some audio, for example mp3. I want to play both of them simultaneously. Everything is OK with the sound of second object. Unfortunately I can't hear the sound of video. Why ?
I can play above mentioned track in the different players. In this case everything is OK. But it is needed to play both items in the same player by using AVMutableCompositionTrack mechanizm (for exporting feature).


text:
Q: Firebase Analytics - NPE in CrashReport I've just migrated to Firebase Analytics 9.0.0 and when tried to launch the app on emulator api10/x86, then the following exception is thrown by the services. Any ideas how to work around that?

05-23 15:36:44.371 1280-1280/? E/AndroidRuntime: FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.szyk.myheart/com.szyk.myheart.MyHeartActivity}: java.lang.NullPointerException
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:130)
     at android.app.ActivityThread.main(ActivityThread.java:3683)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:507)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: java.lang.NullPointerException
     at com.google.android.gms.flags.impl.FlagProviderImpl.getBooleanFlagValue(Unknown Source)
     at com.google.android.gms.internal.zzsd$zza.zzb(Unknown Source)
     at com.google.android.gms.internal.zzsd$zza.zza(Unknown Source)
     at com.google.android.gms.internal.zzsf.zzb(Unknown Source)
     at com.google.android.gms.internal.zzsd.get(Unknown Source)
     at com.google.firebase.crash.FirebaseCrash.getInstance(Unknown Source)
     at com.google.firebase.crash.FirebaseCrash.zzOW(Unknown Source)
     at com.google.firebase.crash.FirebaseCrash.log(Unknown Source)
     at com.szyk.extras.activities.UniversalActionBarActivity.onCreate(UniversalActionBarActivity.java:46)
     at com.szyk.myheart.MyHeartActivity.onCreate(MyHeartActivity.java:99)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:130)
     at android.app.ActivityThread.main(ActivityThread.java:3683)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:507)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
     at dalvik.system.NativeStart.main(Native Method)

The code is nothing more than activity with:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FirebaseCrash.log("onCreate: " + getClass().getSimpleName());
}

A: Unfortunately, using Firebase on devices or emulators without Play Services isn't a supported use case.  Crash Reporting will fail to initialize, and you will see a message to that effect in logcat when the app launches.  However, if you are also seeing a crash when calling a method after failed init, that seems like a problem we should correct.
It sounds like you are doing the best thing you can by suppressing the exception, but I'd rather not make you go through that, so I'll pass it on as feedback to the team.

A: Just small correction on what Doug mentioned. Firebase Crash Reporting is not supported on non-play devices. Firebase Analytics in particular and some of the other Firebase product do support non-play devices.


text:
Q: Add Two or more buttons on Navigationbar
Possible Duplicate:
adding more than two button on the navigationbar

How can add two more buttons on navaigationbar?. My codes are follows.if i am using rightBarButtonItem methods there is no problem with items.
UIBarButtonItem *barPrint = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"tool_print.png"]
                                                                     style:UIBarButtonItemStylePlain
                                                                    target:self
                                                                    action:@selector(printAttach:)];
        UISwitch *OnOff = [[UISwitch alloc] init];
        UIBarButtonItem *barOnOff = [[UIBarButtonItem alloc] initWithCustomView:OnOff];

        //[onoff1 addTarget: self action: @selector(flip:) forControlEvents:UIControlEventValueChanged];
        self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:barOnOff, barPrint, nil];
        [OnOff release];

A:  UIView *iv = [[UIView alloc] initWithFrame:CGRectMake(0,0,32,32)];
 [iv setBackgroundColor:[UIColor whiteColor]];
  self.navigationItem.titleView = iv;


text:
Q: How to access value of an axis in a label? ...
        matrix {
            axes {
              axis {
                name 'FOO'
                values 'foo1' 'foo2'   //
              }
...            stages {
                stage ('doIt') {
                    agent{
                      label '???'
                    }

...

I would like to build a label instruction that will accept win or mac, if also one of the values of FOO is found. How can I combine the value of the axis with the other strings to form a meaningful label?

A: You can access the axis variable by its name - FOO. The only thing you need to keep in mind is to use it inside a double-quoted string, so the value can be interpolated correctly.
pipeline {
    agent none
    stages {
        stage('Matrix example') {
            matrix {
                agent any
                axes {
                    axis {
                        name 'FOO'
                        values 'bar1', 'bar2', 'bar3'
                    }
                }
                stages {
                    stage('Test') {
                        agent {
                            label "${FOO}"
                        }
                        steps {
                            // ...
                        }
                    }
                }
            }
        }
    }
}


text:
Q: React Js setState with params when onClick I am using Reactjs to make a simple list of albums and after a click on each item I have to get all photos of this album, so I think  to change the state (album_Id) ..
the problem is I can't change the state and I dont know how to load the second page (to display all photo of one album) independently.
please I need your help.
this is my code (App.js):

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Photolist from './photolist';
// import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props){
        super(props);
        this.state = {
          currentAlbumId: null,
          CurrentPhotoId: null
        };
        this.updateCurrentAlbum = this.updateCurrentAlbum.bind(this);
    }

  updateCurrentAlbum(id) {
    this.setState({currentAlbumId : id})
  }

  render() {

    const tab_albums = [
      {
        "albumId": 1,
        "id": 1,
        "title": "accusamus beatae ad facilis cum similique qui sunt",
        "url": "http://placehold.it/600/92c952",
        "thumbnailUrl": "http://placehold.it/150/92c952"
      },
      {
        "albumId": 1,
        "id": 2,
        "title": "reprehenderit est deserunt velit ipsam",
        "url": "http://placehold.it/600/771796",
        "thumbnailUrl": "http://placehold.it/150/771796"
      },
      {
        "albumId": 2,
        "id": 66,
        "title": "provident rerum voluptatem illo asperiores qui maiores",
        "url": "http://placehold.it/600/ee0a7e",
        "thumbnailUrl": "http://placehold.it/150/ee0a7e"
      },
      {
        "albumId": 2,
        "id": 67,
        "title": "veritatis labore ipsum unde aut quam dolores",
        "url": "http://placehold.it/600/1279e9",
        "thumbnailUrl": "http://placehold.it/150/1279e9"
      }
    ];
    const albumsIds = [];

    tab_albums.map((album_model) => {
        return (
            albumsIds.indexOf(album_model.albumId) === -1 ? albumsIds.push(album_model.albumId) : null
        )
    });

    var album_style = {"background": "#cccccc", "marginBottom": "10px", "borderLeft": "5px solid red"};
    var style_div = {"width": "50%", "float": "left"};

    const liste_album = albumsIds.map((alb_id) => {
          return (
            <Router key={alb_id}>

                    <Link to={"/photolist/"+alb_id} onClick={() => this.updateCurrentAlbum(alb_id)}>
                    Album : { alb_id }
                    </Link>
                    <Route path="/photolist" component={Photolist}/>

            </Router>
          )
    });
  return (

{liste_album}

        <button>wishlist</button>

    );
  }
}
export default App;

A: It seems like you render your links together with the what you believe should be the Router information, but that is not really how it works
What you should do however is render the links independently, and to view one item of your fotolist, to add a matching route in your rendering app.
So change the rendering of your links, like so:
const liste_album = albumsIds.map((alb_id) => {
      return (

                <Link to={"/photolist/"+alb_id}>
                Album : { alb_id }
                </Link>

      )
});

Removing the onClick handler, as this is done by the Link component. When it navigates, your app would know that the browser location has changed. To show the current active route, you should change your render some like this (note that the Router is defined here, and that you should just define a template path to match the active Route, or an exact path, depending on your need)
return (
  <Router>

{liste_album}

        <button>wishlist</button>

      <Route path="/photolist/:id" render={({match}) => <Photolist alb_id={match.params.id} />

  </Router>
  );
}

This line
<Route path="/photolist/:id" render={({match}) => <Photolist alb_id={match.params.id} />

will find any path that has a parameter and will render a certain component. At the moment I am passing along the alb_id, however you could choose to search for the matching album, and pass that to the Photolist.
Alternatively, you could also create the path as:
<Route path="/photolist/:id" component={Photolist} />

And export the Photolist component (which would be a single album, I guess) with the withRouter Higher Order Function, which would enable you to get the params at least from the router props. However, that wouldn't completely work in your current setting, as your code seems to mix data with rendering and state mapping. This is well, not perfect. Your component also seems to do way to much.
You should really create 3 or four components from that one component you have just shown, as an example, check this version of your photolist:

// just some imports matching with the cdn packages
const { Route, withRouter } = ReactRouter;
const { Link } = ReactRouterDOM;
const { createStore, combineReducers } = Redux;
const { Provider, connect } = ReactRedux;
const { Component } = React;

const Router = ReactRouter.MemoryRouter;

const tab_albums = [
  {
    "albumId": 1,
    "id": 1,
    "title": "accusamus beatae ad facilis cum similique qui sunt",
    "url": "http://placehold.it/600/92c952",
    "thumbnailUrl": "http://placehold.it/150/92c952"
  },
  {
    "albumId": 1,
    "id": 2,
    "title": "reprehenderit est deserunt velit ipsam",
    "url": "http://placehold.it/600/771796",
    "thumbnailUrl": "http://placehold.it/150/771796"
  },
  {
    "albumId": 2,
    "id": 66,
    "title": "provident rerum voluptatem illo asperiores qui maiores",
    "url": "http://placehold.it/600/ee0a7e",
    "thumbnailUrl": "http://placehold.it/150/ee0a7e"
  },
  {
    "albumId": 2,
    "id": 67,
    "title": "veritatis labore ipsum unde aut quam dolores",
    "url": "http://placehold.it/600/1279e9",
    "thumbnailUrl": "http://placehold.it/150/1279e9"
  }
];

const albumsReducer = (state = tab_albums, action) => {
  // currently not doing anything specials, so just load the albums in the state
  return state;
}

// the store will trigger all changes down to any components intrested in it, thanks to the Provider component
const store = createStore( combineReducers({ albums: albumsReducer }) );

// redux helper to match state to the props, so that components can access the defined properties inside its props
const albumsStateToProps = state => ({ albums: state.albums });

// the album is a purely stateless component, it simply receives the props it should show
const Album = ({ albums, currentAlbumId }) => {
  // get the album based on the passed currentAlbumId
  let album = albums.find(a => {
    return a.id == currentAlbumId;
  });
  return

Album: {album.title}

    <Link to="/">Back to mainpage</Link>

;
};

const ConnectedAlbum = connect( albumsStateToProps )( Album );

// the location is received thanks to the withRouter higher order function
const PathViewer = ({location}) => {
  return { location.pathname };
};

// this creates a new component that extends the props of the PathViewer
const RouterPathViewer = withRouter( PathViewer );

// the overview component will receive the albums through its props, and just needs to map it
const Overview = ( {albums} ) => {
  return
{albums && albums.map( ({id, title}) =>
<Link to={`/album/${id}`}>{ title }</Link>
 ) }
;
};

// the ConnectedOverview gets its props thanks to the albumsStateToProps method defined above
// this means that the Overview component will have access to props.albumns
const ConnectedOverview = connect(albumsStateToProps)(Overview);

// this is the layout component, it enables the routing, and shows the main page
class AlbumViewer extends Component {
  render() {
    return <Router>

Album viewer

        Current path: <RouterPathViewer />
        <Route path="/" exact={true} component={ConnectedOverview} />
        <Route path="/album/:id" render={({match}) => {
          return <ConnectedAlbum currentAlbumId={match.params.id} />;
        } }/>

    </Router>;
  }
}

// this creates the rendering, where the Provider will rerender components depending on it based on changes on the store
ReactDOM.render( <Provider store={store}><AlbumViewer /></Provider>, document.querySelector('#container') );

I welcome you to finish the small demo I made, or if you might have questions towards the setup, and why so many packages are need to run this small app, so feel free to play around with it ;)