text:
Q: MySQL - restrict tinyint column In MySQL db, I have a table with users' addresses:
CREATE TABLE `user_address` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `user_id` INT(10) NOT NULL,
    `street` VARCHAR(50) NULL DEFAULT NULL,
    `number` VARCHAR(255) NULL DEFAULT NULL,
    `city` VARCHAR(255) NULL DEFAULT NULL,
    `zip` VARCHAR(255) NULL DEFAULT NULL,
    `is_main` TINYINT(1) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`),
)

The number of addresses per user is not limited, but I want the is_main to be 1 only once per user, to indicate the main user's address. All other user's addresses will have is_main = 0.
Can this be restricted anyhow on the MySQL level?
(ALTER TABLE user_address
    ADD UNIQUE INDEX is_main (is_main, user_id); didn't help as there are several records with is_main=0...)

A: i came across this looking for something similar... i think you (and likely me in my search) are mistaking TINYINT(1) for BIT(1).
See here: MySQL Boolean "tinyint(1)" holds values up to 127?
and here: Difference between "int" and "int(3)" data types in my sql
TINYINT is a byte-storage type (as are the other ints), where defining the length (TINYINT(1)) only affects the displayed value, not the actual stored value. The stored size is defined by the type itself (MySql Doc)
BIT is more like string types in that the length (BIT(1)) defines how many will be stored (like CHAR(5) will store exactly 5 characters). So BIT(1) is more akin to a real boolean.
For your purposes, a simple unsigned TINYINT in the unique key may be sufficient, unless you anticipate users having more than 255 addresses. However, it will be up to your application to identify the 0-valued row as the main address (which kinda warps the semantics of the name is_main, so perhaps "address_index"?). i think it'll be a challenge even then if the main address is allowed to change (which is logical). You may need to set some controls with triggers so that when an address record is set to "main" (0), all others for that user are updated to distinct non-0 values. Bleh. :(


text:
Q: Error Method Illuminate\\Database\\Eloquent\\Collection::save does not exist. in Laravel I want to change the status at $ result, to get the data at $ result I use query builder, but there is an error like  that
$results = ClientVendor::where('client_id','=', $request->client_id)
                                 ->where('vendor_id','=',$request->vendor_id)
        ->get();
        $results->status = $request->status;
        $results->save();
        return response()->json($results);

A: You can try this one too.
 $results = ClientVendor::where('client_id','=', $request->client_id)
                             ->where('vendor_id','=',$request->vendor_id)
                             ->update([
                                     'status' => $request->status
                               ]);

A: You cant do this because you call whole collection where is many elements. Call just single record, then you can update it.
When you use get() you call collection
When you use first() or find($id) then you get single record that you can update.
Look at example:
$results = ClientVendor::where('client_id', $request->client_id)
                        ->where('vendor_id',$request->vendor_id)
                        ->first(); // this point is the most important to change
$results->status = $request->status;
$results->save();
return response()->json($results);;

Good luck!

A: Try this:
$results = ClientVendor::where('client_id', $request->client_id)
                                 ->where('vendor_id',$request->vendor_id)
        ->first();
        $results->status = $request->status;
        $results->save();
        return response()->json($results);

A: Many have suggested using first() instead of get(). I think fistOrFail() would be a better option to handle null results.
Otherwise, in cases where the result is null, you'd get Call to a member function save() on null error.
Eg:
ClientVendor does not have a record with either client_id or vendor_id matching $request->client_id or $request->client_id respectively.
$result = ClientVendor::where('client_id', $request->client_id)
                         ->where('vendor_id',$request->vendor_id)
                         ->first();
$result->status = $request->status; //produces error Creating default object from empty value
$result->save(); //produces error "Call to a member function save() on null" because $result will be empty

The above code produces 2 exceptions: 1. "Creating default object from empty value" on lines $result->sataus = .. and 2."Call to a member function save() on null" on line $result->save because $result will be empty.
To fix that, you would call firstOrFail() like so.
$result = ClientVendor::where('client_id', $request->client_id)
                             ->where('vendor_id',$request->vendor_id)
                             ->firstOrFail();
$result->status = $request->status;
$result->save();

This fix, firstOrFail, when there are no results would produce a 404, a handled error, and the subsequent lines would not be executed.
For situations where you query using find($id), it is better to use findOrFail($id)

A: It depends on your needs, if you want to :

*

*Get and update one record, you should use first() or firstOrFail() instead of get().  Should be look like this :

$results = ClientVendor::where('client_id', $request->client_id)
                         ->where('vendor_id',$request->vendor_id)
                         ->first();
$results->status = $request->status;
$results->save();
return response()->json($results);

*Get and update multiple records, yes you can use get(), but you should do foreach and then update the single record one by one. just like this :

$results = ClientVendor::where('client_id', $request->client_id)
                         ->where('vendor_id',$request->vendor_id)
                         ->get();
foreach($results as $result){
    $result->status = $request->status;
    $result->save();
}
return response()->json($results);

A: If you need to update one item use find with it's primary key & then update.Or without primary key then use where & first.then update as like this Just Use
$results = ClientVendor::where('client_id', $request->client_id)
                        ->where('vendor_id',$request->vendor_id)
                        ->first();

$results->update([
        'status'=>$request->status
]);
return response()->json($results);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use Docker for Windows only in command line, with GUI bypassed/disabled? I work with Windows containers on Windows 10 Pro.
Is it enough just to run dockerd process in PowerShell to use Docker? Should I need some other processes/services running?
I still don't understand the purpose of com.docker.service (Docker Desktop Service). I pull images and run containers without it.
Am I missing something?
Edit: It is not possible to switch container mode with DockerCli.exe without com.docker.service running, but when it does, it creates MobyLinuxVM to run Linux containers. It may be the main purpose of having the service enabled.
Question: Do I need the Docker Desktop Service when I only work in Windows containers mode?
Question: Why running Windows container in hyperv isolation mode does not create Hyper-V VM? I've double checked it Hyper-V Manager.

A: When you run linux containers on windows, tyou don't run in on windows but on hyperv machine with linux installed.
Windows containers are ran by windows native dockerd.
This additional gui helps you manage which type of container you're using at the moment. Probably you could live without it, but is it worth it? It might in the newer version (didn't test that) provide the connectivity betwen linux and windows containers, so I'd be careful with disabling that service.
Just to note, this is only for desktop windows. For windows server you can and should use docker ee (basic version is only for windows and it's free)


text:
Q: std::vector Erase - does it de-allocate automatically? In below code mKnownRSList is of type:
  std::vector<RSAddress *>

where RSAddress is a class I wrote. The functiop removeItem removes an item from this vector.
My question here is that after calling the erase function on mKnownRSList, am I supposed to de-allocate the address pointed by the iterator returned by std::remove_if. Currently I explicitly issue a delete call on the de-referenced iterator named last. Do you think this approach is correct? Thanks.
void
ABC::removeItem(RSAddress * rsAddr)
{
   auto last =
   std::remove_if(mKnownRSList.begin(),
                  mKnownRSList.end(),
                 [rsAddr]( RSAddress * o )
                 {
                   return (*o == *rsAddr);
                 });

 mKnownRSList.erase(last, mKnownRSList.end());

 delete *last;
}

A: You should delete what is pointed to by your pointer inside the container first and then you remove/erase the actual pointer from the container.
What you're doing here is dereferencing an iterator that points to something that no longer exists.

A:
Do you think this approach is correct?

Nope. The correct way is to use smart_pointers like shared_ptr. If you will, then you should only erase it. like this
std::vector< std::shared_ptr< RSAddress  > > mKnownRSList;
...

mKnownRSList.erase( std::remove_if(mKnownRSList.begin(),
                                   mKnownRSList.end(),
                                   [rsAddr]( const std::shared_ptr< RSAddress > & o )
                                   {
                                       return (*o == *rsAddr);
                                   }),
                    mKnownRSList.end()
);


text:
Q: find out if the of the callback function is an ES6 arrow Because of the big difference in the context difference between normal and ES6 arrow functions I'd like to be able to find out which one was received on a callback fn.
typeof will return function for both. Is there any way to distinguish?

A: Arrow functions can't be used as constructors and show typeof arrowFunc.prototype as undefined, whereas a non-arrow function shows `"object".

A: You can use Function.toString() to return a string representation of the source code of the function, then look for an arrow (=>) in the string.
var arrowFunc = x => 2 * x
var regFunc = function (x) {return 2 * x}

arrowFunc.toString().indexOf("=>") // 2
regFunc.toString().indexOf("=>") // -1


text:
Q: How to pass model values from previous page to new page post method using ajax? Home.cshtml
  @model Models.MyData
    @using (Html.BeginForm("AddData", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

    {
    }

HomeController.cs
 [HttpPost]
        public async Task<ActionResult> AddData(MyData mydata)
        {

            return View("AddDetails", mydata);
}

I'm getting values here at mydata now I want to redirect to next page with same model values for that on pageload of new redirected page i write ajax call but it pass null model.
AddDetails.cshtml
@model Models.MyData

<script>

var someRootPath = "@Url.Content("~")";

        $.ajax({
            url: someRootPath + 'Home/Process',
            data: $('#AddData').serialize(),

            type: "POST",
        });
    }
  </script>

HomeController.cs
[HttpPost]
    public async Task Progess(MyData mydata)
    {

How to get mydata model here from previous page? I want to show UI thats why using return view first instead RedirectToAction

A: https://dotnetfiddle.net/c7hAFy
Controller
namespace Testy20161006.Controllers
{
    public class MyData
    {
        public string NeoData { get; set; }
    }

    public class HomeController : Controller
    {
        [HttpPost]
        //adding generic ActionResult to Task type
        public async Task<ActionResult> Progess(MyData mydata)
        {
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> AddData(MyData mydata)
        {
            return View("AddDetails", mydata);
        }

        public ActionResult Tut137()
        {
            MyData myData = new MyData { NeoData = "neoData" };
            return View(myData);
        }

First Page -Index or Tut137 in my case-
@model Testy20161006.Controllers.MyData
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Tut137</title>
</head>
<body>
    @using (Html.BeginForm("AddData", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.TextBoxFor(r=>r.NeoData);
        <input id="theButton" type="submit" value="Go"  />
    }
</body>
</html>

AddDetails.cshtml
@model Testy20161006.Controllers.MyData
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AddDetails</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var someRootPath = "@Url.Content("~")";
            $.ajax({
                //rename Process to Progess to match call to method called
                url: someRootPath + 'Home/Progess',
                data: $('#AddData').serialize(),
                type: "POST",
            });
        })
    </script>
</head>
<body>
    <div>
        @Html.TextBoxFor(r => r.NeoData, new { id = "AddData" })
    </div>
</body>
</html>


text:
Q: Notion API paginated endpoint returning lists of varying lengths I'm running into a puzzling Notion API issue. I have implemented pagination as described here in the developer docs. When I recursively hit the Search API endpoint to return all my pages, the results seem to have random slight variations. For example, I have ~ 1,250 pages in my Notion account. One time it will return 1,247 pages, and the next time it will return 1,249 pages. In both these requests, the vast majority of the pages (1,245) remain constant, but a couple are (seemingly) randomly dropped or added on. In addition, the cursor values that are returned will usually be the same, but will sometimes randomly change as well. I've exhausted pretty much all trouble-shooting I can think of off the top of my head and haven't run into anything glaringly obvious. I'm curious if anyone else has run into this or something similar?

A: Just as (seemingly) randomly as it started, it is now no longer doing this. I wonder if, since the API is in beta, there was some feature that was buggy? Idk, but this is closed anyways.


text:
Q: How to read from binary file to a string/array and an int in c? In this program i wrote into a binary file using arrays of a structure, and i'm trying to put it's data into another array of structures this way:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct rec{
    char cim[60];
    int x;
}rec;            //my structure

 int main(){
     int i;
     FILE *ptr_myfile;
     rec ujtomb[25];    //I want to have the elements here after reading the file
     rec tomb[25]={{"Spectre",3521},
         {"The Hunger Games Mockingjay Part 2",6123},
         {"Star Wars The Force awakens",9736},
         {"The Thirty Three",2342},
         {"The man From UNCLE",4312},
         {"Creed",4123},
         {"Inside out",6584},
         {"The martian",6674},
         {"Ant-man",7352},
         {"Secret in their eyes",2345},
         {"The night before",4758},
         {"Love",1586},
         {"Legend",8576},
         {"Trainwreck",4628},
         {"Love the Coopers",6372},
         {"Maze runner The scorch trials",8750},
         {"No escape",5793},
         {"Terminator genisys",8451},
         {"Krampus",452},
         {"Bridge of spies",9581},
         {"By the sea",7582},
         {"The peanuts movie",3214},
         {"Heist",1346},
         {"Spotlight",7450},
         {"Jurassic world",5438}};      //I listed the elements of the array
 ptr_myfile=fopen("nezettseg.bin","wb");
 if (!ptr_myfile)
 {
 printf("Unable to open file!");
 return 1;
 }
 for (i=0;i<25;i++){     //here i write into nezettseg.bin
        fwrite(&tomb[i].cim, sizeof(rec), 1, ptr_myfile);
        fwrite(&tomb[i].x, sizeof(rec), 1, ptr_myfile);
 }
 fclose(ptr_myfile);

     FILE* fin = fopen("nezettseg.bin", "rb");   //opening the binary file
     for(i=0;i<25;i++){    //now I'm trying to write those movies and numbers into ujtomb
         fread(&ujtomb, sizeof(rec), 1, ptr_myfile);
         printf("%s %d\n", ujtomb->cim, ujtomb->x);
     }
     fclose(fin);
     return 0;
}

My code works but the output looks like this:
Spectre 3521
\301
 0
The Hunger Games Mockingjay Part 2 6123
\353 0
Star Wars The Force awakens 9736
& 0
The Thirty Three 2342
&    0
The man From UNCLE 4312
\330 0
Creed 4123
 0
Inside out 6584
\270 0
The martian 6674
 0
Ant-man 7352
\270 0
Secret in their eyes 2345
)    0
The night before 4758
\226 0
Love 1586
2 0
Legend 8576
Program ended with exit code: 0

sooo basically it writes 25 lines, but \number comes with the variable 'cim', and the 0-s come with x.
Can you help me how to put those titles and numbers correctly to ujtomb?

A: for (i=0;i<25;i++){
    fwrite(&tomb[i].cim, sizeof(rec), 1, ptr_myfile);
    fwrite(&tomb[i].x, sizeof(rec), 1, ptr_myfile);
}

Is not right. You need to use:
for (i=0;i<25;i++){
    fwrite(&tomb[i], sizeof(rec), 1, ptr_myfile);
}

Remember that tomb[i] is a rec, not tomb[i].cim or tomb[i].x.
Also,
 for(i=0;i<25;i++){
     fread(&ujtomb, sizeof(rec), 1, ptr_myfile);
     printf("%s %d\n", ujtomb->cim, ujtomb->x);
 }

is not right. You need to use:
 for(i=0;i<25;i++){
     fread(&ujtomb[i], sizeof(rec), 1, fin);
                 ^^^^^ Missing index.  ^^^^ Use the right FILE*

     printf("%s %d\n", ujtomb[i].cim, ujtomb[i].x);
                             ^^^^           ^^^^ Use the i-th element
 }


text:
Q: NetBeans or Eclipse. Which IDE should I use first? I've been creating Java programs in a text editor for more than a year and now I want to switch to any IDE for creating Java applications. May I know which IDE should I use first? Eclipse or NetBeans? Which is more preferable for a starter?
I've also done a little work in Visual Studio for creating C# applications. Will working on any IDE gonna be helpful for me?

A: Eclipse is heavily developed by third parties (google, adobe), netBeans by oracle, so while doing some job with java i felt netBeans to be more "native" for java. Although i do most of the programming in other languages so i use eclipse, since you can bend it to any direction you want.
So, all in all, if you're planing just program in java and have done something with visual studio - use netbeans

A: I've always liked NetBeans for it's simplicity, however I use Eclipse as it has an official plugin for Android, provided by Google.  Eclipse is very good but also somewhat complicated - I've used it for years and probably don't know what 60% of the settings or features even do.
So stick to NetBeans, unless you're doing Android development.

A: Eclipse is definitely closer to the text editor environment you're used to, while NetBeans is more geared towards interface development.
A stock installation of Eclipse is extremely lightweight relative to NetBeans. NetBeans is probably closer to Visual Studio. It depends on what kind of environment you prefer to work in.
If you enjoyed and preferred text editor coding, I'd go with Eclipse. If you preferred Visual Studio-style environments, I'd go with NetBeans.
If your computer is old, I'd go with Eclipse as well.

A: When I was learning Java they had us using jGRASP, then had us using Netbeans. Netbeans and Eclipse are very similar if you are just starting.
This is the IDE I use http://www.jetbrains.com/idea/download/

A: Netbeans is more to Visual Studio, if you are working on GUI app or Jasper reports, Netbeans is also your choice. In all other cases - Eclipse. Eclipse has much more plug-ins, integrated with server-side environment and easier customizable


text:
Q: Plotting every categorical value of a list matplotlib I think that I have a really easy problem, but I can not come up with a solution...
Consider the following code:
import numpy as np
import matplotlib.pyplot as plt

# Create some mock data
t = ["A" , "B", "C", "D", "A", "B", "C"]
data1 = [1,2,3,4,5,6,7]
data2 = [6,2,8,2,6,8,2]

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

The resulting image looks like this:

I want, that on the X-Axis, every element gets displayed seperatly, something like this (without the 1)

A: You should use numbers for plotting the x-data and then re-label the x-ticks with your desired categorical values as done in the following
xvals = range(len(t)) # This is the actual x-values to be plotted on the x-axis

fig, ax1 = plt.subplots()

# Remaining code

ax1.plot(xvals, data1, color=color) # Use xvals here
ax1.tick_params(axis='y', labelcolor=color)
ax1.set_xticks(xvals) # Set the ticks at desired locations
ax1.set_xticklabels(t) # Set the categorical values as tick-labels

# Remaining code

ax2.plot(xvals, data2, color=color) # Use xvals here
ax2.tick_params(axis='y', labelcolor=color)
ax2.set_xticks(xvals) # Set the ticks at desired locations
ax2.set_xticklabels(t) # Set the categorical values as tick-labels


text:
Q: How to stop the Subscriber in RxAndroid? I create an Observable like this:
public Observable<FileObjectModel> getAllFiles() {
    return Observable.create(new Observable.OnSubscribe<FileObjectModel>() {
        @Override
        public void call(Subscriber<? super FileObjectModel> subscriber) {
            //fileList is a huge list.
            for(int i = 1 ; i < fileList.size(); i ++){
                ...
                subscriber.onNext(fileItem);
            }
        }
    });
}

then subscribe like this:
subscription = reposistory.getAllFiles()
            .compose(scanInject())
            .subscribe(...);

When user click button stop, I want to cancel the subscription, so I call
 subscription.unsubscribe();

Unfortunately, it doesn't stop as expected. The file items are continue emitted.
Please help to point out my mistake.
UPDATE:
I debug line by line and see that the observable is being stuck in for loop. In this loop, I call a recursive method and pass subscriber as parameter. The method will browse all Android File System (start at root folder) to find all files, then emit them one by one.  (I use this way because the number of file on entire system is very large, and shouldn't save in any static list. )
Since we are being stuck in for loop, the subscription object is always null. Still don't find any solution yet.

A: Firstly if you are going to use Observable.create then to honour backpressure which is required by many possible downstream operators you need to append .onBackpressureXXX. If in doubt just use .onBackpressureBuffer.
The reason you cannot unsubscribe is because your observable is synchronous so the subscription is not set till the stream has finished! I'd suggest avoiding this pattern generally and use instead:
subscriber = ...;
reposistory.getAllFiles()
    .compose(scanInject())
    .subscribe(subscriber);

A: I would suggest checking if the subscriber is still subscribed:
for(int i = 1 ; i < fileList.size(); i ++){
    if (subscriber.isUnsubscribed()) {
        return;
    }
    subscriber.onNext(fileItem);
}

This should not be too much computation overload.

A: I hate to answer my question anyway, but I already found the root cause and action to fix it.
As I mentioned in update part of my question, the for loop did a huge job, it iterated thousand of items. And, the processor was being stuck inside.
To fix this, I assign the different threads to observable and it runs  asynchronous, like this:
 subscription = getAllObjects()
            .map(this::doScan)
            .observeOn(Schedulers.newThread())
            .subscribeOn(Schedulers.newThread())
            .subscribe(subscriber);

The variable subscription now never null as before and we can use it to stop the subscriptions by calling subscription.unsubscribe()


text:
Q: Python - Send and Receive of UDP packets I've started with Python a few month ago. Now I've reached a point where I need some help concerning networking.
I've the following scenario:

*

*One PC and 3 external devices in a small local net.

*The PC wants to observe a switch state (on/off) on each device. This will be done by an initial command from the PC to each device.

*After receiving this command each device sends automatically a packet with the new state to the PC whenever the switch state has changed.

*All the packets on the network are UDP packets

On the PC I have the following Python script running (just for one device):
import socket

UDP_IP1 = "192.168.1.64"
UDP_IP2 = "192.168.1.73"
UDP_IP3 = "192.168.1.74"
UDP_PORT = 45           # used port on external device

port = 52129

message = "Message to observe..."      # not the real command string

def SendData():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.bind(("", port))
        msg = message.encode('utf-8')
        s.sendto(msg, (UDP_IP1, UDP_PORT))
    except:
        print("Sending Error!!!\n")

    return s

def ReceiveData(sock):
    print("Receiving data: \n")

    while True:
        data, addr = sock.recvfrom(4096)      # buffer size is 4096 bytes
        print ("received message:", data)

if __name__ == "__main__":
    s = SendData()
    ReceiveData(s)

My Problem: In principal this script is running, but after approximately 2 minutes without any change of the switch on the device I do not receive any more packets from the external device when the switch state changes. But I can see the incoming packets with the installed Wireshark.
It looks like a time-out when I don't receive anything but 'sock.recvfrom' is still waiting for data.
Is there anyone who has/had the same problem?


text:
Q: Game services not working for app if downloaded from play store I've been trying to get the game services working properly for so long. My problem is that game service isn't working on the version downloaded from the play store, but on the version downloaded directly from android studio the game service works perfectly. Even though both versions use the same key and have the same SHA1 code (the release SHA1 code). I checked if the SHA1 from the play store version of my app matches with the game service's SHA1 by comparing the SHA1 codes from the android-release.apk and from https://console.developers.google.com/apis/credentials/oauthclient. I doubt that the problem lies in the code of my app, because it works perfectly in the version downloaded directly from android studio.
So my question is what I could have possibly done wrong here, and how to fix it.
Thank you for reading

A: First off, I want to thank everyone who took their time to post an answer. I don't think anyone could have guessed my stupid mistake because it only applies to libGDX users. The problem was that the target sdk in the gradle .build file of BaseGameUtils was not the same as the .build file of the android module. It's amazing how such a small mistake can cost your whole weekend!

A: I had the same problem:
You need to use this:
keytool -exportcert -keystore path-to-debug-or-production-keystore -list -v

example:
keytool -exportcert -keystore D:\Hristijan\Aplikacii\Keystore\blabla.jks -list -v

This is the PATH where you created the keystore while building the APK FILE.
The problem was that we were using the SHA1 key for debug in OAuth 2.0 client IDs, and as i understood SHA1 for debug and release is different.
So after you get the SHA1 for the release, you go to google cloud platform and in Credentials change your SHA1 for your app.

A: When using Google Play Services SDK, check and make sure that your device is also compatible and runs Android version 4.0 or higher and includes Google Play Store.
See this documentation for more information. And, this article wherein it discussed about matching Google Play Services to your Android OS version might also help


text:
Q: Momentum and Mass flow, what is wrong here Consider an aeroplane of mass M which is flying horizontally ( neglect gravity) with velocity v and dust, which has velocity u in the opposite direction to the plane get stuck to the plane. We need to find the force we need to apply to let the plane move with constant velocity, v.
What I am doing is this -
Take the plane as a system ( YES just the plane not including the sand getting attached to it )
It's rate of change in momentum is dP = (M+dm) v - Mv = vdm/dt which should be equal to the external force acting on the plane. Now the external force on the plane comes from the sand getting attached to it and the force which we need to apply ( F_us)
So,
$ F_{tot} = F_{us} + F_{dust} = vdm/dt$
Now F_(dust) is the force applied by dust on plane, so it is negative of force applied by plane on dust.
So force applied by plane on dust is rate of change of dust's momentum which is (v-u) dm/dt. So force applied by dust is (u-v) dm/dt
So $F_{us} = (2v-u) dm/dt$...which is wrong because...
If dust applies force (v-u) dm/dt on plane then to allow the plane to move with a constant velocity, by newton's 2nd law we need to apply the force F_{us} = (v-u) dm/dt..
So what have I done wrong. I know if I take the system as dust + plane then I will get the correct answer but why am I not getting the answer when I take the system as ONLY THE PLANE after all I have accounted for all the external forces on the plane too.Then what is wrong.
I have found @Jan Lalinsky's answer Second law of Newton for variable mass systems  regarding some sort of the same issue. Could anyone enlighten what is wrong here.

A: In general, the way in which we analyze variable mass systems is not by directly analyzing them but treating the system whose mass is changing and the small amount of mass getting added (or going out) as a system. So, essentially we are left with analyzing a system whose mass remains constant.
Now, coming to the method that you suggested. The basic flaw in your argument is violation of conservation of mass. While applying impulse-momentum theorem over the bigger chunk of mass (the plane) you assumed the initial mass to be M and the final mass as M+dm. You simultaneously applied the impulse-momentum theorem over the smaller mass (sand particle) and considered it's mass to be constant in that interval of time. So, it's initial mass was dm and final mass was dm as well.
The way you have applied the equations suggests that finally the mass of the system(Big chunk + small chunk) is M+2dm. From where did this extra mass dm come from?
I hope I have answered your question.

A: We need to apply some greater force than the sand because mass of the plane is increased after the sand strikes and so to make both of them move with same speed we need to apply some greater force. Also the change in momentum of sand will be
= ( V + u) dm because u was in opposite direction.


text:
Q: MySQL .Net Connector Connection is Opened but Closed I have a very strange problem with the newest MySQL .Net Connector.
Following code:
MySqlCommand cmd = new MySqlCommand("UPDATE tst SET col1 = 'Test' WHERE id = 5", conn);

if (conn.State != ConnectionState.Open)
{
    conn.Open();
}

Console.WriteLine(conn.State.ToString());
try
{
    cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine(conn.State.ToString());
}

If I run my programm I will get following output / error:

Open
The connection must be valid and open
Open

How is this possible. Do you have any idea?

A: On the official documentation for MySql and at DevArt, all the MySqlCommand's are initialized with a open connection. I suggest to open the connection first and initialize the MySqlCommand afterward.
if (!conn.State.Equals(ConnectionState.Open))
    conn.Open();

Console.WriteLine(conn.State.ToString());

MySqlCommand cmd = new MySqlCommand("UPDATE tst SET col1 = 'Test' WHERE id = 5", conn);

try
{
    cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine(conn.State.ToString());
}


text:
Q: How to correctly use OpenTelemetry exporter with OpenTelemetry collector in client and server? I am trying to make OpenTelemetry exporter to work with OpenTelemetry collector.
I found this OpenTelemetry collector demo.
So I copied these four config files

*

*docker-compose.yml (In my app, I removed generators part and prometheus which I currently having issue running)

*otel-agent-config.yaml

*otel-collector-config.yaml

*.env

to my app.
Also based on these two demos in open-telemetry/opentelemetry-js repo:

*

*Traces in Web demo

*Traces in Node - GRPC demo
I came up with my version (sorry for a bit long, really hard to set up a minimum working version due to the lack of docs):
.env
OTELCOL_IMG=otel/opentelemetry-collector-dev:latest
OTELCOL_ARGS=

docker-compose.yml
version: '3.7'
services:
  # Jaeger
  jaeger-all-in-one:
    image: jaegertracing/all-in-one:latest
    ports:
      - "16686:16686"
      - "14268"
      - "14250"

  # Zipkin
  zipkin-all-in-one:
    image: openzipkin/zipkin:latest
    ports:
      - "9411:9411"

  # Collector
  otel-collector:
    image: ${OTELCOL_IMG}
    command: ["--config=/etc/otel-collector-config.yaml", "${OTELCOL_ARGS}"]
    volumes:
      - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
    ports:
      - "1888:1888"   # pprof extension
      - "8888:8888"   # Prometheus metrics exposed by the collector
      - "8889:8889"   # Prometheus exporter metrics
      - "13133:13133" # health_check extension
      - "55678"       # OpenCensus receiver
      - "55680:55679" # zpages extension
    depends_on:
      - jaeger-all-in-one
      - zipkin-all-in-one

  # Agent
  otel-agent:
    image: ${OTELCOL_IMG}
    command: ["--config=/etc/otel-agent-config.yaml", "${OTELCOL_ARGS}"]
    volumes:
      - ./otel-agent-config.yaml:/etc/otel-agent-config.yaml
    ports:
      - "1777:1777"   # pprof extension
      - "8887:8888"   # Prometheus metrics exposed by the agent
      - "14268"       # Jaeger receiver
      - "55678"       # OpenCensus receiver
      - "55679:55679" # zpages extension
      - "13133"       # health_check
    depends_on:
      - otel-collector

otel-agent-config.yaml
receivers:
  opencensus:
  zipkin:
    endpoint: :9411
  jaeger:
    protocols:
      thrift_http:

exporters:
  opencensus:
    endpoint: "otel-collector:55678"
    insecure: true
  logging:
    loglevel: debug

processors:
  batch:
  queued_retry:

extensions:
  pprof:
    endpoint: :1777
  zpages:
    endpoint: :55679
  health_check:

service:
  extensions: [health_check, pprof, zpages]
  pipelines:
    traces:
      receivers: [opencensus, jaeger, zipkin]
      processors: [batch, queued_retry]
      exporters: [opencensus, logging]
    metrics:
      receivers: [opencensus]
      processors: [batch]
      exporters: [logging,opencensus]

otel-collector-config.yaml
receivers:
  opencensus:

exporters:
  prometheus:
    endpoint: "0.0.0.0:8889"
    namespace: promexample
    const_labels:
      label1: value1
  logging:

  zipkin:
    endpoint: "http://zipkin-all-in-one:9411/api/v2/spans"
    format: proto

  jaeger:
    endpoint: jaeger-all-in-one:14250
    insecure: true

processors:
  batch:
  queued_retry:

extensions:
  health_check:
  pprof:
    endpoint: :1888
  zpages:
    endpoint: :55679

service:
  extensions: [pprof, zpages, health_check]
  pipelines:
    traces:
      receivers: [opencensus]
      processors: [batch, queued_retry]
      exporters: [logging, zipkin, jaeger]
    metrics:
      receivers: [opencensus]
      processors: [batch]
      exporters: [logging]

After running docker-compose up -d, I can open Jaeger (http://localhost:16686) and Zipkin UI (http://localhost:9411).
And my ConsoleSpanExporter works in both web client and Express.js server.
However, I tried this OpenTelemetry exporter code in both client and server, I am still having issue to connect OpenTelemetry collector.
Please see my comment about URL inside of the code
import { CollectorTraceExporter } from '@opentelemetry/exporter-collector';

// ...
tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
tracerProvider.addSpanProcessor(
  new SimpleSpanProcessor(
    new CollectorTraceExporter({
      serviceName: 'my-service',
      // url: 'http://localhost:55680/v1/trace', // Return error 404.
      // url: 'http://localhost:55681/v1/trace', // No response, not exists.
      // url: 'http://localhost:14268/v1/trace', // No response, not exists.
    })
  )
);

Any idea? Thanks

A: Thank you sooo much for @BObecny's help! This is a complement of @BObecny's answer.
Since I am more interested in integrating with Jaeger. So here is the config to set up with all Jaeger, Zipkin, Prometheus. And now it works on both front end and back end.
First both front end and back end use same exporter code:
import { CollectorTraceExporter } from '@opentelemetry/exporter-collector';

new SimpleSpanProcessor(
  new CollectorTraceExporter({
    serviceName: 'my-service',
  })
)

docker-compose.yaml
version: "3"
services:
  # Collector
  collector:
    image: otel/opentelemetry-collector:latest
    command: ["--config=/conf/collector-config.yaml", "--log-level=DEBUG"]
    volumes:
      - ./collector-config.yaml:/conf/collector-config.yaml
    ports:
      - "9464:9464"
      - "55680:55680"
      - "55681:55681"
    depends_on:
      - jaeger-all-in-one
      - zipkin-all-in-one

  # Jaeger
  jaeger-all-in-one:
    image: jaegertracing/all-in-one:latest
    ports:
      - "16686:16686"
      - "14268"
      - "14250"

  # Zipkin
  zipkin-all-in-one:
    image: openzipkin/zipkin:latest
    ports:
      - "9411:9411"

  # Prometheus
  prometheus:
    container_name: prometheus
    image: prom/prometheus:latest
    volumes:
      - ./prometheus.yaml:/etc/prometheus/prometheus.yml
    ports:
      - "9090:9090"

collector-config.yaml
receivers:
  otlp:
    protocols:
      grpc:
      http:

exporters:
  jaeger:
    endpoint: jaeger-all-in-one:14250
    insecure: true
  zipkin:
    endpoint: "http://zipkin-all-in-one:9411/api/v2/spans"
  prometheus:
    endpoint: "0.0.0.0:9464"

processors:
  batch:
  queued_retry:

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [zipkin]
      processors: [batch, queued_retry]
    metrics:
      receivers: [otlp]
      exporters: [prometheus]
      processors: [batch, queued_retry]

prometheus.yaml
global:
  scrape_interval: 15s # Default is every 1 minute.

scrape_configs:
  - job_name: 'collector'
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
    static_configs:
      - targets: ['collector:9464']

A: The demo you tried is using older configuration and opencensus which should be replaced with otlp receiver. Having said that this is a working example
https://github.com/open-telemetry/opentelemetry-js/tree/master/examples/collector-exporter-node/docker
So I'm copying the files from there:
docker-compose.yaml
version: "3"
services:
  # Collector
  collector:
    image: otel/opentelemetry-collector:latest
    command: ["--config=/conf/collector-config.yaml", "--log-level=DEBUG"]
    volumes:
      - ./collector-config.yaml:/conf/collector-config.yaml
    ports:
      - "9464:9464"
      - "55680:55680"
      - "55681:55681"
    depends_on:
      - zipkin-all-in-one

  # Zipkin
  zipkin-all-in-one:
    image: openzipkin/zipkin:latest
    ports:
      - "9411:9411"

  # Prometheus
  prometheus:
    container_name: prometheus
    image: prom/prometheus:latest
    volumes:
      - ./prometheus.yaml:/etc/prometheus/prometheus.yml
    ports:
      - "9090:9090"

collector-config.yaml
receivers:
  otlp:
    protocols:
      grpc:
      http:

exporters:
  zipkin:
    endpoint: "http://zipkin-all-in-one:9411/api/v2/spans"
  prometheus:
    endpoint: "0.0.0.0:9464"

processors:
  batch:
  queued_retry:

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [zipkin]
      processors: [batch, queued_retry]
    metrics:
      receivers: [otlp]
      exporters: [prometheus]
      processors: [batch, queued_retry]

prometheus.yaml
global:
  scrape_interval: 15s # Default is every 1 minute.

scrape_configs:
  - job_name: 'collector'
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
    static_configs:
      - targets: ['collector:9464']

This should work fine with opentelemetry-js ver. 0.10.2
Default port for traces is 55680 and for metrics 55681
The link I posted previously - you will always find there the latest up to date working example:
https://github.com/open-telemetry/opentelemetry-js/tree/master/examples/collector-exporter-node
And for web example you can use the same docker and see all working examples here:
https://github.com/open-telemetry/opentelemetry-js/tree/master/examples/tracer-web/


text:
Q: ViewPager and fragments — what's the right way to store fragment's state? Fragments seem to be very nice for separation of UI logic into some modules. But along with ViewPager its lifecycle is still misty to me. So Guru thoughts are badly needed!
Edit
See dumb solution below ;-)
Scope
Main activity has a ViewPager with fragments. Those fragments could implement a little bit different logic for other (submain) activities, so the fragments' data is filled via a callback interface inside the activity. And everything works fine on first launch, but!...
Problem
When the activity gets recreated (e.g. on orientation change) so do the ViewPager's fragments. The code (you'll find below) says that every time the activity is created I try to create a new ViewPager fragments adapter the same as fragments (maybe this is the problem) but FragmentManager already has all these fragments stored somewhere (where?) and starts the recreation mechanism for those. So the recreation mechanism calls the "old" fragment's onAttach, onCreateView, etc. with my callback interface call for initiating data via the Activity's implemented method. But this method points to the newly created fragment which is created via the Activity's onCreate method.
Issue
Maybe I'm using wrong patterns but even Android 3 Pro book doesn't have much about it. So, please, give me one-two punch and point out how to do it the right way. Many thanks!
Code
Main Activity
public class DashboardActivity extends BasePagerActivity implements OnMessageListActionListener {

private MessagesFragment mMessagesFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Logger.d("Dash onCreate");
    super.onCreate(savedInstanceState);

    setContentView(R.layout.viewpager_container);
    new DefaultToolbar(this);

    // create fragments to use
    mMessagesFragment = new MessagesFragment();
    mStreamsFragment = new StreamsFragment();

    // set titles and fragments for view pager
    Map<String, Fragment> screens = new LinkedHashMap<String, Fragment>();
    screens.put(getApplicationContext().getString(R.string.dashboard_title_dumb), new DumbFragment());
    screens.put(getApplicationContext().getString(R.string.dashboard_title_messages), mMessagesFragment);

    // instantiate view pager via adapter
    mPager = (ViewPager) findViewById(R.id.viewpager_pager);
    mPagerAdapter = new BasePagerAdapter(screens, getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);

    // set title indicator
    TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.viewpager_titles);
    indicator.setViewPager(mPager, 1);

}

/* set of fragments callback interface implementations */

@Override
public void onMessageInitialisation() {

    Logger.d("Dash onMessageInitialisation");
    if (mMessagesFragment != null)
        mMessagesFragment.loadLastMessages();
}

@Override
public void onMessageSelected(Message selectedMessage) {

    Intent intent = new Intent(this, StreamActivity.class);
    intent.putExtra(Message.class.getName(), selectedMessage);
    startActivity(intent);
}

BasePagerActivity aka helper
public class BasePagerActivity extends FragmentActivity {

BasePagerAdapter mPagerAdapter;
ViewPager mPager;
}

Adapter
public class BasePagerAdapter extends FragmentPagerAdapter implements TitleProvider {

private Map<String, Fragment> mScreens;

public BasePagerAdapter(Map<String, Fragment> screenMap, FragmentManager fm) {

    super(fm);
    this.mScreens = screenMap;
}

@Override
public Fragment getItem(int position) {

    return mScreens.values().toArray(new Fragment[mScreens.size()])[position];
}

@Override
public int getCount() {

    return mScreens.size();
}

@Override
public String getTitle(int position) {

    return mScreens.keySet().toArray(new String[mScreens.size()])[position];
}

// hack. we don't want to destroy our fragments and re-initiate them after
@Override
public void destroyItem(View container, int position, Object object) {

    // TODO Auto-generated method stub
}

}

Fragment
public class MessagesFragment extends ListFragment {

private boolean mIsLastMessages;

private List<Message> mMessagesList;
private MessageArrayAdapter mAdapter;

private LoadMessagesTask mLoadMessagesTask;
private OnMessageListActionListener mListener;

// define callback interface
public interface OnMessageListActionListener {
    public void onMessageInitialisation();
    public void onMessageSelected(Message selectedMessage);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // setting callback
    mListener = (OnMessageListActionListener) activity;
    mIsLastMessages = activity instanceof DashboardActivity;

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    inflater.inflate(R.layout.fragment_listview, container);
    mProgressView = inflater.inflate(R.layout.listrow_progress, null);
    mEmptyView = inflater.inflate(R.layout.fragment_nodata, null);
    return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // instantiate loading task
    mLoadMessagesTask = new LoadMessagesTask();

    // instantiate list of messages
    mMessagesList = new ArrayList<Message>();
    mAdapter = new MessageArrayAdapter(getActivity(), mMessagesList);
    setListAdapter(mAdapter);
}

@Override
public void onResume() {
    mListener.onMessageInitialisation();
    super.onResume();
}

public void onListItemClick(ListView l, View v, int position, long id) {
    Message selectedMessage = (Message) getListAdapter().getItem(position);
    mListener.onMessageSelected(selectedMessage);
    super.onListItemClick(l, v, position, id);
}

/* public methods to load messages from host acitivity, etc... */
}

Solution
The dumb solution is to save the fragments inside onSaveInstanceState (of host Activity) with putFragment and get them inside onCreate via getFragment. But I still have a strange feeling that things shouldn't work like that... See code below:
    @Override
protected void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);
    getSupportFragmentManager()
            .putFragment(outState, MessagesFragment.class.getName(), mMessagesFragment);
}

protected void onCreate(Bundle savedInstanceState) {
    Logger.d("Dash onCreate");
    super.onCreate(savedInstanceState);

    ...
    // create fragments to use
    if (savedInstanceState != null) {
        mMessagesFragment = (MessagesFragment) getSupportFragmentManager().getFragment(
                savedInstanceState, MessagesFragment.class.getName());
                StreamsFragment.class.getName());
    }
    if (mMessagesFragment == null)
        mMessagesFragment = new MessagesFragment();
    ...
}

A: My solution is very rude but works: being my fragments dynamically created from retained data, I simply remove all fragment from the PageAdapter before calling super.onSaveInstanceState() and then recreate them on activity creation:
@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt("viewpagerpos", mViewPager.getCurrentItem() );
    mSectionsPagerAdapter.removeAllfragments();
    super.onSaveInstanceState(outState);
}

You can't remove them in onDestroy(), otherwise you get this exception:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
Here the code in the page adapter:
public void removeAllfragments()
{
    if ( mFragmentList != null ) {
        for ( Fragment fragment : mFragmentList ) {
            mFm.beginTransaction().remove(fragment).commit();
        }
        mFragmentList.clear();
        notifyDataSetChanged();
    }
}

I only save the current page and restore it in onCreate(), after the fragments have been created.
if (savedInstanceState != null)
    mViewPager.setCurrentItem( savedInstanceState.getInt("viewpagerpos", 0 ) );

A: When the FragmentPagerAdapter adds a fragment to the FragmentManager, it uses a special tag based on the particular position that the fragment will be placed. FragmentPagerAdapter.getItem(int position) is only called when a fragment for that position does not exist. After rotating, Android will notice that it already created/saved a fragment for this particular position and so it simply tries to reconnect with it with FragmentManager.findFragmentByTag(), instead of creating a new one. All of this comes free when using the FragmentPagerAdapter and is why it is usual to have your fragment initialisation code inside the getItem(int) method.
Even if we were not using a FragmentPagerAdapter, it is not a good idea to create a new fragment every single time in Activity.onCreate(Bundle). As you have noticed, when a fragment is added to the FragmentManager, it will be recreated for you after rotating and there is no need to add it again. Doing so is a common cause of errors when working with fragments.
A usual approach when working with fragments is this:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    CustomFragment fragment;
    if (savedInstanceState != null) {
        fragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("customtag");
    } else {
        fragment = new CustomFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment, "customtag").commit();
    }

    ...

}

When using a FragmentPagerAdapter, we relinquish fragment management to the adapter, and do not have to perform the above steps. By default, it will only preload one Fragment in front and behind the current position (although it does not destroy them unless you are using FragmentStatePagerAdapter). This is controlled by ViewPager.setOffscreenPageLimit(int). Because of this, directly calling methods on the fragments outside of the adapter is not guaranteed to be valid, because they may not even be alive.
To cut a long story short, your solution to use putFragment to be able to get a reference afterwards is not so crazy, and not so unlike the normal way to use fragments anyway (above). It is difficult to obtain a reference otherwise because the fragment is added by the adapter, and not you personally. Just make sure that the offscreenPageLimit is high enough to load your desired fragments at all times, since you rely on it being present. This bypasses lazy loading capabilities of the ViewPager, but seems to be what you desire for your application.
Another approach is to override FragmentPageAdapter.instantiateItem(View, int) and save a reference to the fragment returned from the super call before returning it (it has the logic to find the fragment, if already present).
For a fuller picture, have a look at some of the source of FragmentPagerAdapter (short) and ViewPager (long).

A: What is that BasePagerAdapter?  You should use one of the standard pager adapters -- either FragmentPagerAdapter or FragmentStatePagerAdapter, depending on whether you want Fragments that are no longer needed by the ViewPager to either be kept around (the former) or have their state saved (the latter) and re-created if needed again.
Sample code for using ViewPager can be found here
It is true that the management of fragments in a view pager across activity instances is a little complicated, because the FragmentManager in the framework takes care of saving the state and restoring any active fragments that the pager has made.  All this really means is that the adapter when initializing needs to make sure it re-connects with whatever restored fragments there are.  You can look at the code for FragmentPagerAdapter or FragmentStatePagerAdapter to see how this is done.

A: I want to offer a solution that expands on antonyt's wonderful answer and mention of overriding FragmentPageAdapter.instantiateItem(View, int) to save references to created Fragments so you can do work on them later. This should also work with FragmentStatePagerAdapter; see notes for details.

Here's a simple example of how to get a reference to the Fragments returned by FragmentPagerAdapter that doesn't rely on the internal tags set on the Fragments. The key is to override instantiateItem() and save references in there instead of in getItem().
public class SomeActivity extends Activity {
    private FragmentA m1stFragment;
    private FragmentB m2ndFragment;

    // other code in your Activity...

    private class CustomPagerAdapter extends FragmentPagerAdapter {
        // other code in your custom FragmentPagerAdapter...

        public CustomPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // Do NOT try to save references to the Fragments in getItem(),
            // because getItem() is not always called. If the Fragment
            // was already created then it will be retrieved from the FragmentManger
            // and not here (i.e. getItem() won't be called again).
            switch (position) {
                case 0:
                    return new FragmentA();
                case 1:
                    return new FragmentB();
                default:
                    // This should never happen. Always account for each position above
                    return null;
            }
        }

        // Here we can finally safely save a reference to the created
        // Fragment, no matter where it came from (either getItem() or
        // FragmentManger). Simply save the returned Fragment from
        // super.instantiateItem() into an appropriate reference depending
        // on the ViewPager position.
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
            // save the appropriate reference depending on position
            switch (position) {
                case 0:
                    m1stFragment = (FragmentA) createdFragment;
                    break;
                case 1:
                    m2ndFragment = (FragmentB) createdFragment;
                    break;
            }
            return createdFragment;
        }
    }

    public void someMethod() {
        // do work on the referenced Fragments, but first check if they
        // even exist yet, otherwise you'll get an NPE.

        if (m1stFragment != null) {
            // m1stFragment.doWork();
        }

        if (m2ndFragment != null) {
            // m2ndFragment.doSomeWorkToo();
        }
    }
}

or if you prefer to work with tags instead of class member variables/references to the Fragments you can also grab the tags set by FragmentPagerAdapter in the same manner:
NOTE: this doesn't apply to FragmentStatePagerAdapter since it doesn't set tags when creating its Fragments.
@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
    // get the tags set by FragmentPagerAdapter
    switch (position) {
        case 0:
            String firstTag = createdFragment.getTag();
            break;
        case 1:
            String secondTag = createdFragment.getTag();
            break;
    }
    // ... save the tags somewhere so you can reference them later
    return createdFragment;
}

Note that this method does NOT rely on mimicking the internal tag set by FragmentPagerAdapter and instead uses proper APIs for retrieving them. This way even if the tag changes in future versions of the SupportLibrary you'll still be safe.

Don't forget that depending on the design of your Activity, the Fragments you're trying to work on may or may not exist yet, so you have to account for that by doing null checks before using your references.
Also, if instead you're working with FragmentStatePagerAdapter, then you don't want to keep hard references to your Fragments because you might have many of them and hard references would unnecessarily keep them in memory. Instead save the Fragment references in WeakReference variables instead of standard ones. Like this:
WeakReference<Fragment> m1stFragment = new WeakReference<Fragment>(createdFragment);
// ...and access them like so
Fragment firstFragment = m1stFragment.get();
if (firstFragment != null) {
    // reference hasn't been cleared yet; do work...
}

A: If anyone is having issues with their FragmentStatePagerAdapter not properly restoring the state of its fragments...ie...new Fragments are being created by the FragmentStatePagerAdapter instead of it restoring them from state...
Make sure you call ViewPager.setOffscreenPageLimit() BEFORE you call ViewPager.setAdapter(fragmentStatePagerAdapter)
Upon calling ViewPager.setOffscreenPageLimit()...the ViewPager will immediately look to its adapter and try to get its fragments.  This could happen before the ViewPager has a chance to restore the Fragments from savedInstanceState(thus creating new Fragments that can't be re-initialized from SavedInstanceState because they're new).

A: I found another relatively easy solution for your question.
As you can see from the FragmentPagerAdapter source code, the fragments managed by FragmentPagerAdapter store in the FragmentManager under the tag generated using:
String tag="android:switcher:" + viewId + ":" + index;

The viewId is the container.getId(), the container is your ViewPager instance. The index is the position of the fragment. Hence you can save the object id to the outState:
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("viewpagerid" , mViewPager.getId() );
}

@Override
    protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null)
        viewpagerid=savedInstanceState.getInt("viewpagerid", -1 );

    MyFragmentPagerAdapter titleAdapter = new MyFragmentPagerAdapter (getSupportFragmentManager() , this);
    mViewPager = (ViewPager) findViewById(R.id.pager);
    if (viewpagerid != -1 ){
        mViewPager.setId(viewpagerid);
    }else{
        viewpagerid=mViewPager.getId();
    }
    mViewPager.setAdapter(titleAdapter);

If you want to communicate with this fragment, you can get if from FragmentManager, such as:
getSupportFragmentManager().findFragmentByTag("android:switcher:" + viewpagerid + ":0")

A: I want to offer an alternate solution for perhaps a slightly different case, since many of my searches for answers kept leading me to this thread.
My case
- I'm creating/adding pages dynamically and sliding them into a ViewPager, but when rotated (onConfigurationChange) I end up with a new page because of course OnCreate is called again.  But I want to keep reference to all the pages that were created prior to the rotation.
Problem
- I don't have unique identifiers for each fragment I create, so the only way to reference was to somehow store references in an Array to be restored after the rotation/configuration change.
Workaround
- The key concept was to have the Activity (which displays the Fragments) also manage the array of references to existing Fragments, since this activity can utilize Bundles in onSaveInstanceState
public class MainActivity extends FragmentActivity

So within this Activity, I declare a private member to track the open pages
private List<Fragment> retainedPages = new ArrayList<Fragment>();

This is updated everytime onSaveInstanceState is called and restored in onCreate
@Override
protected void onSaveInstanceState(Bundle outState) {
    retainedPages = _adapter.exportList();
    outState.putSerializable("retainedPages", (Serializable) retainedPages);
    super.onSaveInstanceState(outState);
}

...so once it's stored, it can be retrieved...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState != null) {
        retainedPages = (List<Fragment>) savedInstanceState.getSerializable("retainedPages");
    }
    _mViewPager = (CustomViewPager) findViewById(R.id.viewPager);
    _adapter = new ViewPagerAdapter(getApplicationContext(), getSupportFragmentManager());
    if (retainedPages.size() > 0) {
        _adapter.importList(retainedPages);
    }
    _mViewPager.setAdapter(_adapter);
    _mViewPager.setCurrentItem(_adapter.getCount()-1);
}

These were the necessary changes to the main activity, and so I needed the members and methods within my FragmentPagerAdapter for this to work, so within
public class ViewPagerAdapter extends FragmentPagerAdapter

an identical construct (as shown above in MainActivity )
private List<Fragment> _pages = new ArrayList<Fragment>();

and this syncing (as used above in onSaveInstanceState) is supported specifically by the methods
public List<Fragment> exportList() {
    return _pages;
}

public void importList(List<Fragment> savedPages) {
    _pages = savedPages;
}

And then finally, in the fragment class
public class CustomFragment extends Fragment

in order for all this to work, there were two changes, first
public class CustomFragment extends Fragment implements Serializable

and then adding this to onCreate so Fragments aren't destroyed
setRetainInstance(true);

I'm still in the process of wrapping my head around Fragments and Android life cycle, so caveat here is there may be redundancies/inefficiencies in this method.  But it works for me and I hope might be helpful for others with cases similar to mine.

A: I came up with this simple and elegant solution. It assumes that the activity is responsible for creating the Fragments, and the Adapter just serves them.
This is the adapter's code (nothing weird here, except for the fact that mFragments is a list of fragments maintained by the Activity)
class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {

    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        TabFragment fragment = (TabFragment)mFragments.get(position);
        return fragment.getTitle();
    }
}

The whole problem of this thread is getting a reference of the "old" fragments, so I use this code in the Activity's onCreate.
    if (savedInstanceState!=null) {
        if (getSupportFragmentManager().getFragments()!=null) {
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                mFragments.add(fragment);
            }
        }
    }

Of course you can further fine tune this code if needed, for example making sure the fragments are instances of a particular class.

A: To get the fragments after orientation change you have to use the .getTag().
    getSupportFragmentManager().findFragmentByTag("android:switcher:" + viewPagerId + ":" + positionOfItemInViewPager)

For a bit more handling i wrote my own ArrayList for my PageAdapter to get the fragment by viewPagerId and the FragmentClass at any Position:
public class MyPageAdapter extends FragmentPagerAdapter implements Serializable {
private final String logTAG = MyPageAdapter.class.getName() + ".";

private ArrayList<MyPageBuilder> fragmentPages;

public MyPageAdapter(FragmentManager fm, ArrayList<MyPageBuilder> fragments) {
    super(fm);
    fragmentPages = fragments;
}

@Override
public Fragment getItem(int position) {
    return this.fragmentPages.get(position).getFragment();
}

@Override
public CharSequence getPageTitle(int position) {
    return this.fragmentPages.get(position).getPageTitle();
}

@Override
public int getCount() {
    return this.fragmentPages.size();
}

public int getItemPosition(Object object) {
    //benötigt, damit bei notifyDataSetChanged alle Fragemnts refrehsed werden

    Log.d(logTAG, object.getClass().getName());
    return POSITION_NONE;
}

public Fragment getFragment(int position) {
    return getItem(position);
}

public String getTag(int position, int viewPagerId) {
    //getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.shares_detail_activity_viewpager + ":" + myViewPager.getCurrentItem())

    return "android:switcher:" + viewPagerId + ":" + position;
}

public MyPageBuilder getPageBuilder(String pageTitle, int icon, int selectedIcon, Fragment frag) {
    return new MyPageBuilder(pageTitle, icon, selectedIcon, frag);
}

public static class MyPageBuilder {

    private Fragment fragment;

    public Fragment getFragment() {
        return fragment;
    }

    public void setFragment(Fragment fragment) {
        this.fragment = fragment;
    }

    private String pageTitle;

    public String getPageTitle() {
        return pageTitle;
    }

    public void setPageTitle(String pageTitle) {
        this.pageTitle = pageTitle;
    }

    private int icon;

    public int getIconUnselected() {
        return icon;
    }

    public void setIconUnselected(int iconUnselected) {
        this.icon = iconUnselected;
    }

    private int iconSelected;

    public int getIconSelected() {
        return iconSelected;
    }

    public void setIconSelected(int iconSelected) {
        this.iconSelected = iconSelected;
    }

    public MyPageBuilder(String pageTitle, int icon, int selectedIcon, Fragment frag) {
        this.pageTitle = pageTitle;
        this.icon = icon;
        this.iconSelected = selectedIcon;
        this.fragment = frag;
    }
}

public static class MyPageArrayList extends ArrayList<MyPageBuilder> {
    private final String logTAG = MyPageArrayList.class.getName() + ".";

    public MyPageBuilder get(Class cls) {
        // Fragment über FragmentClass holen
        for (MyPageBuilder item : this) {
            if (item.fragment.getClass().getName().equalsIgnoreCase(cls.getName())) {
                return super.get(indexOf(item));
            }
        }
        return null;
    }

    public String getTag(int viewPagerId, Class cls) {
        // Tag des Fragment unabhängig vom State z.B. nach bei Orientation change
        for (MyPageBuilder item : this) {
            if (item.fragment.getClass().getName().equalsIgnoreCase(cls.getName())) {
                return "android:switcher:" + viewPagerId + ":" + indexOf(item);
            }
        }
        return null;
    }
}

So just create a MyPageArrayList with the fragments:
    myFragPages = new MyPageAdapter.MyPageArrayList();

    myFragPages.add(new MyPageAdapter.MyPageBuilder(
            getString(R.string.widget_config_data_frag),
            R.drawable.ic_sd_storage_24dp,
            R.drawable.ic_sd_storage_selected_24dp,
            new WidgetDataFrag()));

    myFragPages.add(new MyPageAdapter.MyPageBuilder(
            getString(R.string.widget_config_color_frag),
            R.drawable.ic_color_24dp,
            R.drawable.ic_color_selected_24dp,
            new WidgetColorFrag()));

    myFragPages.add(new MyPageAdapter.MyPageBuilder(
            getString(R.string.widget_config_textsize_frag),
            R.drawable.ic_settings_widget_24dp,
            R.drawable.ic_settings_selected_24dp,
            new WidgetTextSizeFrag()));

and add them to the viewPager:
    mAdapter = new MyPageAdapter(getSupportFragmentManager(), myFragPages);
    myViewPager.setAdapter(mAdapter);

after this you can get after orientation change the correct fragment by using its class:
        WidgetDataFrag dataFragment = (WidgetDataFrag) getSupportFragmentManager()
            .findFragmentByTag(myFragPages.getTag(myViewPager.getId(), WidgetDataFrag.class));

A: A bit different opinion instead of storing the Fragments yourself just leave it to the FragmentManager and when you need to do something with the fragments look for them in the FragmentManager:
//make sure you have the right FragmentManager
//getSupportFragmentManager or getChildFragmentManager depending on what you are using to manage this stack of fragments
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null) {
   int count = fragments.size();
   for (int x = 0; x < count; x++) {
       Fragment fragment = fragments.get(x);
       //check if this is the fragment we want,
       //it may be some other inspection, tag etc.
       if (fragment instanceof MyFragment) {
           //do whatever we need to do with it
       }
   }
}

If you have a lot of Fragments and the cost of instanceof check may be not what you want, but it is good thing to have in mind that the FragmentManager already keeps account of Fragments.

A: add:
   @SuppressLint("ValidFragment")

before your class.
it it doesn´t work do something like this:
@SuppressLint({ "ValidFragment", "HandlerLeak" })


text:
Q: Замена всех пикселей изображения черным цветом Привет, народ! Опять встал, не могу сдвинуться.
Задача: взять PNG изображение, в котором есть прозрачные, полупрозрачные, и не прозрачные пикселы, и заменить все непрозрачные пикселы черным цветом, а все полупрозрачные пикселы заменить тоже черным цветом, но сохраняя при этом полупрозрачность.
Вот начало кода:

 $im = imagecreatefrompng('img/1.png');

(да да, дальше уже надо начать обесцвечивать, и с этой строкой сижу уже оочень много верени)

Прошу помощи!

Есть идеи сделать это через два цикла, и пройтись по каждому пикселу, но что то не могу собрать все мысли в кучу, а так же знания о функциях библиотеки GD
A: Все таки сам дошел. Вот ответ если кому пригодится:

$overlay = imagecreatefrompng('img/overlay/1.png');
    $color = array(255, 0, 0);
    list($width, $height) = getimagesize('img/overlay/1.png');
    for ($i = 1; $i < $height; $i++) {
        for ($u = 1; $u < $width; $u++) {
            $color_index = imagecolorat($overlay, $u, $i);
            $rgb = imagecolorsforindex($overlay, $color_index);
            if($rgb['alpha'] < 127 ){
                $color2 = imagecolorallocatealpha($overlay, $color[0], $color[1], $color[2], $rgb['alpha']);
                imagesetpixel($overlay, $u, $i, $color2);
            }
        }
    }
    imagepng($im, 'img/overlay/img.png');


text:
Q: Can't include a reference with BibTex I want to include a reference. For this purpose, I create a file called References.bib in which I put this:
 @article{ref,
   author={First author, Second Author and Third author},
   title={Title of the article},
   journal={},
   year = 2005
 }

Then in the latex file I include the refrence by:
 \cite{ref}

I also include in the beginning:
  \usepackage{natbib}
  \usepackage{cite}

And at the end before the end document:
 \bibliographystyle{te}
 \bibliography{References}

I get a question mark instead of the reference.
I don't know what's wrong with my code ?
Thank you in advance !!

A: This works (except for the fact that you probably shouldn't be citing an "article" without a journal title...).  The thing to note is that you can use both cite and natbib at the same time, so pick one or the other.  This example uses natbib, but you can switch with cite if you like.
\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@article{ref,
%      author={First author, Second Author and Third author},
   author={First author and Second Author and Third author}, % <-- note also the consistent formatting of authors names (better still is to use "Lastname1, Firstname1 and Lastname2, Firstname2 and ..."
   title={Title of the article},
   journal={},
   year = 2005
 }
\end{filecontents*}

\usepackage[T1]{fontenc}
\usepackage{natbib}%
% \usepackage{cite}% <-- or switch with natbib

\begin{document}

\cite{ref}

\bibliographystyle{te}
\bibliography{\jobname}

\end{document}

Remember to run:
latex file   # or: file.tex
bibtex file  # or: file.aux
latex file   # or: file.tex
latex file   # or: file.tex

to resolve your citations.


text:
Q: Window object in renderer script in Electron app does not contain data from preload script I am completely new to Electron so please forgive me if I am doing this completely wrong.
Apparently for security reasons I need to use a contextBridge to communicate between the preload and renderer scripts and the main script. I could not find a clear example for how to set this up so I took the provided answer to this stack overflow question: How to use preload.js properly in Electron. However, when I try to access window.api.receive I get the error Cannot read property 'receive' of undefined. So my window.api is undefined but I can not figure out why.
I also tried to simply set window.isWorking = true in my preload.js script and tried to print it in my renderer script like I have seen others do, but this also just prints undefined.
I use the following code:
main.js
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

let win;

function createWindow() {
    win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            contextIsolation: true,
            nodeIntegration: false,
            enableRemoteModule: false,
            preload: 'preload.js'
        }
    });

    win.loadFile('index.html');
}

app.whenReady().then(() => {
    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

ipcMain.on("test", (event, args) => {
    console.log("received test request");
    win.webContents.send("test", "some data");
});

preload.js
import { ipcRenderer, contextBridge } from "electron";

contextBridge.exposeInMainWorld(
    "api", {
        send: (channel, data) => {
            let validChannels = ["test"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        receive: (channel, func) => {
            let validChannels = ["test"];
            if (validChannels.includes(channel)) {
                ipcRenderer.on(channel, (event, ...args) => func(...args));
            }
        }
    }
);

window.isWorking = true;

renderer.js
console.log(window.isWorking); // prints undefined
window.api.receive("test", (data) => { // exception on trying to access window.api.receive
    console.log("data", data);
});
window.api.send("test", "some data");

index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

Hello World!

A: I think { contextIsolation: false; nodeIntegration: true } allows importing electron and allows to set window.something
So try writing:
win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        contextIsolation: false,
        nodeIntegration: true,
        preload: 'preload.js'
    }
});


text:
Q: Object value being over written by last value on the Loop I have following input data:
{
   'a': [1, 2, 3],
   'b': ['x', 'y', 'z'],
   'c': ['a', 'b', 'c'],
}

I am trying to change above input data into following data structure:
{
  '0': { a: 1, b: 'x', c: 'a' },
  '1': { a: 2, b: 'y', c: 'b' },
  '2': { a: 3, b: 'z', c: 'c' }
}

My Javascript Code is:
let parentDataset = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c'],
}

let children = {};
let parent = {};

for (let key in parentDataset) {

  let i = 0;
  for (let value of parentDataset[key]) {
    children[key] = value;
    parent[i] = children;
    i++;
  }
}

console.log('parent', parent);

But I am getting following output where last value is over writing previous two values as below:
{
  '0': { a: 3, b: 'z', c: 'c' },
  '1': { a: 3, b: 'z', c: 'c' },
  '2': { a: 3, b: 'z', c: 'c' }
}

Any solution and explanation would be much appreciated!

A: After getting the list of keys, you can Array#reduce one of the arrays to a series of objects, and populate them using Array#forEach and Object#assign:

const obj = {
   'a': [1, 2, 3],
   'b': ['x', 'y', 'z'],
   'c': ['a', 'b', 'c'],
};

const keys = Object.keys(obj);

const result = obj[keys[0]].reduce((r, _, i) => {
  const o = r[i] = {};

  keys.forEach((key) => Object.assign(o, { [key]: obj[key][i] }));

  return r;
}, {});

console.log(result);

And here is a working version of your code:

const parentDataset = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c'],
}

const parent = {};

for (const key in parentDataset) {
  let i = 0;

  for (const value of parentDataset[key]) {
    !parent[i] && (parent[i] = {}); // create a new object if one is needed
    parent[i][key] = value; // add the key and value to the object
    i++;
  }
}

console.log('parent', parent);

A: const input = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c']
};

const output = {};

Object.keys(input).forEach( key => {
  input[key].forEach((value,i) => {
    if( !output[i] ){
       output[i] = { [key] : value };
    } else {
       output[i][key] = value;
    }
 });
});

A: Another solution would be to reduce object's values. For example:
const data = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c'],
}

const result = Object.values(data).reduce((acc, subarr, idx, arr) => {
  return { ...acc, [idx]: arr.map(sub => sub[idx]) }
}, {})

A: To achieve this you will have to loop through the given objects keys and values.
Below is the small code-snippet:

var data = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c'],
};

function addKeys(keys, values, index) {
  var subObj = {}
  for (var i = 0; i < keys.length; i++) {
    subObj[keys[i]] = values[i][index]
  }
  return subObj
}

function returnFinalObject(data) {
  var keys = Object.keys(data)
  var values = Object.values(data)
  var obj = {}
  for (var i = 0; i < keys.length; i++) {
    obj[i] = addKeys(keys, values, i)
  }
  return (obj)
}

var finalObj = returnFinalObject(data)

console.log(finalObj)

Hope this helps

A: With Array.prototype.reduce twice:

var o = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c'],
};

var transposed = Object.keys(o).reduce((res, key, i, arr) => {
  res[i] = arr.reduce((row, key) => {
    row[key] = o[key][i];
    return row;
  }, {});
  return res;
}, {});

console.log(transposed);


text:
Q: Is there any simple way to convert html text to image without cutting things that are outside of viewport I've tried using some html2image or puppeteer screenshot but every time it cuts page to viewport.
I've tried also converting html to pdf but I'cant find any simple way to convert that pdf to image.
I want to convert html text from string variable or in puppeteer screenshot to image file [png,gif,jpg]
Some Text

OR maybe if you know how to embed pdf (or html) in discord message to show it like image. Not only to download (discord bot)
I'm thinking about this

A: Try This

    await page.setContent(source)
    const element = await page.$("body")
    const buffer = await element.screenshot({
        path: "./tmp.png",
        omitBackground: false,
        ...screeshotArgs
    });
    await page.close();


text:
Q: Is it possible to play Cthulhu saves the world on Mac? I recently bought Cthulhu saves the World on Steam, and was wondering if it was possible to play it by using Crossover, or other similar applications. It's also in the App store.

A: I would try wine, which is essentially the basis of crossover. Cthulu Saves the World has a Gold Rating, but only for Gentoo Linux, which you can look up on the wine app database.
Unfortunately, running games on Steam through wine is fairly hit and miss, and there are several hoops to jump through. The first step is to install a windows version of Steam. Unfortunately, you may encounter a lack of text on Steam. Follow the instructions here: http://bugs.winehq.org/show_bug.cgi?id=31374
Then, simply install as you would with any Mac game. If you have any issues, I would check the Wine appdb link above.
Good Luck!


text:
Q: MatNativeDateModule, MatMomentDateModule not found in angular 9.1.1 Old angular/material has those two modules. but angular/material 9.1.1 version has not those two module. I got below error. Anyone has any idea how to import those two module
Uncaught (in promise): Error: MatDatepicker: No provider found for DateAdapter. You must import one of the following modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a custom implementation.
Error: MatDatepicker: No provider found for DateAdapter. You must import one of the following modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a custom implementation.

A: Angullar 8,9
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';

Angular 7 and below
import { MatDatepickerModule, MatNativeDateModule } from '@angular/material';

You need to import both MatDatepickerModule and MatNativeDateModule under imports and add MatDatepickerModule under providers
imports: [
    MatDatepickerModule,
    MatNativeDateModule
  ],
  providers: [
    MatDatepickerModule,
    MatNativeDateModule
  ],

A: In case you're looking for the MatMomentDateModule, it does not come by default, you will need to install
@angular/material-moment-adapter separately
npm install --save @angular/material-moment-adapter

In case you face the issue that the peer dependency Moment.js is missing, install it with
npm install --save-dev moment

Then go ahead and import the MatMomentDateModule in the module file
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        ...
        MatDatepickerModule,
        MatMomentDateModule

    ],
    providers: [
        {provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true}}
    ]
})
export class MyModule {}

Read more at Angular Material Datepicker component


text:
Q: How to self teach math? (when you have other academic commitments) I'm an physics undergrad student. I find my math course curricula irrelevant and my teachers unable to teach us in a way to build up a minimum back ground to further study in the field of physics and mathematical sciences. In order to do well in the exams, it is enough to solve problems from previous years and that's basically a lot memorizing and all that stuff.
I want to be self educated in mathematics using textbooks. But I find it difficult to go through the whole textbook while keeping up with the academic curriculum. For instance, I have a course in Mathematical Physics. I wanted to work through the whole book of Mathematical Methods by Arfken. I felt that if I just rush through the exercises then I will be missing out on the insights that I must gather. On the other hand if I be too "slow" and think too much then I won't be able to cover the materials for my exams.
How can I figure out which problems to do and how much time should I spend on them??


text:
Q: gevent.hub.LoopExit exception on flask SSE example I'm trying to run the following example that I copied from http://flask.pocoo.org/snippets/116/:
# author: oskar.blom@gmail.com
#
# Make sure your gevent version is >= 1.0
import gevent
from gevent.wsgi import WSGIServer
from gevent.queue import Queue

from flask import Flask, Response

import time

# SSE "protocol" is described here: http://mzl.la/UPFyxY
class ServerSentEvent(object):

    def __init__(self, data):
        self.data = data
        self.event = None
        self.id = None
        self.desc_map = {
            self.data : "data",
            self.event : "event",
            self.id : "id"
        }

    def encode(self):
        if not self.data:
            return ""
        lines = ["%s: %s" % (v, k)
                 for k, v in self.desc_map.iteritems() if k]

        return "%s\n\n" % "\n".join(lines)

app = Flask(__name__)
subscriptions = []

# Client code consumes like this.
@app.route("/")
def index():
    debug_template = """

Server sent events

    """
    return(debug_template)

@app.route("/debug")
def debug():
    return "Currently %d subscriptions" % len(subscriptions)

@app.route("/publish")
def publish():
    #Dummy data - pick up from request for real data
    def notify():
        msg = str(time.time())
        for sub in subscriptions[:]:
            sub.put(msg)

    gevent.spawn(notify)

    return "OK"

@app.route("/subscribe")
def subscribe():
    def gen():
        q = Queue()
        subscriptions.append(q)
        try:
            while True:
                result = q.get()
                ev = ServerSentEvent(str(result))
                yield ev.encode()
        except GeneratorExit: # Or maybe use flask signals
            subscriptions.remove(q)

    return Response(gen(), mimetype="text/event-stream")

if __name__ == "__main__":
    app.debug = True
    server = WSGIServer(("", 5000), app)
    server.serve_forever()
    # Then visit http://localhost:5000 to subscribe
    # and send messages by visiting http://localhost:5000/publish

I ran the server with env FLASK_APP=stream.py flask run and the server starts fine. But when I try to connect to the server with a web browser as described above, I get the following error:
127.0.0.1 - - [27/May/2018 21:37:49] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/May/2018 21:37:49] "GET /subscribe HTTP/1.1" 500 -
Error on request:
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/werkzeug/serving.py", line 209, in run_wsgi
    execute(self.server.app)
  File "/usr/lib/python2.7/site-packages/werkzeug/serving.py", line 199, in execute
    for data in application_iter:
  File "/usr/lib/python2.7/site-packages/werkzeug/wsgi.py", line 704, in __next__
    return self._next()
  File "/usr/lib/python2.7/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
    for item in iterable:
  File "/home/dov/git/learning/flask/stream/stream.py", line 88, in gen
    result = q.get()
  File "/usr/lib64/python2.7/site-packages/gevent/queue.py", line 283, in get
    return self.__get_or_peek(self._get, block, timeout)
  File "/usr/lib64/python2.7/site-packages/gevent/queue.py", line 260, in __get_or_peek
    result = waiter.get()
  File "/usr/lib64/python2.7/site-packages/gevent/hub.py", line 898, in get
    return self.hub.switch()
  File "/usr/lib64/python2.7/site-packages/gevent/hub.py", line 630, in switch
    return RawGreenlet.switch(self)
LoopExit: ('This operation would block forever', <Hub at 0x7f434fb2daf0 epoll default pending=0>)

What went wrong? Does the publish routine need to be declared as a greenlet in advance? What am I (and the pocoo snippet) missing?

A: I found a solution, and it is related to the web server used for serving the above snippet. The server supplied by flask run doesn't work. So far the only server that I have found that can serve the above application is gunicorn as follows:
gunicorn sse:app --worker-class gevent --bind 127.0.0.1:5000

This works great! (Unfortunately it only solves half my problem, as I wanted to run my server on Windows, on which there gunicorn is not supported.)


text:
Q: Expand a function in a Fourier Series Expand the function
$$ f(x) = \sin^6{x} \cdot \cos^3{x} $$
in a Fourier series on the segment $[-\pi, \pi]$.
I think we should start from the fact that this function is even, but then the $ a_n $ coefficient turns out to be very big

A: Repeatedly use the identities $\sin^{2}x=1-\cos^{2}x$, $\cos^{2}x=\frac {1-\cos (2x)} 2$ and $\cos^{3}x=\frac {\cos (3x)+3\cos x} 4$ to write  the function as finite Fourier series.

A: This is not an answer to your question because I assume you want to calculate your Fourier series manually. Nevertheless it may be useful to know how you can do this using a CAS.
Using Maxima 5.40.0 http://maxima.sourceforge.net I get
(%i1) f1:sin(x)^6*cos(x)^3;
                                   3       6
(%o1)                           cos (x) sin (x)
(%i2) f2:trigreduce(f1);
               (- cos(9 x)) + 3 cos(7 x) - 8 cos(3 x) + 6 cos(x)
(%o2)          -------------------------------------------------
                                      256
(%i3) f3:multthru(f2);
                   cos(9 x)    3 cos(7 x)   cos(3 x)   3 cos(x)
(%o3)           (- --------) + ---------- - -------- + --------
                     256          256          32        128

when I use the basic commands to manipulate expressions.
But simpler si the following
(%i4) poissimp(f1);
                   cos(9 x)    3 cos(7 x)   cos(3 x)   3 cos(x)
(%o4)          (- --------) + ---------- - -------- + --------
                     256          256          32        128

The commands are described in the Maxima Reference Manual.
The following numerical test should increase your confidence in this solution:
(%i5) sum(abs(ev(float(f1)-float(f3),\
    x=-%pi+k/N*2*%pi,numer=true,tr_numer=true)),k,0,N),N=100;
(%o5)                       1.665336423076783E-15

We calculate the absolute value of the difference of $f1$ and $f3$ at 100 equidistant points between $-\pi$ and $\pi$ and sum them up. These sum is smaller than $2\cdot 10^{-15}$. The values of $\sin$ and $\cos$ in these interval vary between $-1$ and $1$.

A: If you know complex numbers:
Let
$$z:=\cos(x)+i\sin(x)$$
Then
$$\frac{1}{x}=\cos(x)-i\sin(x) \\
\cos(x)=\frac{1}{2}(z+\frac{1}{z})\\
\sin(x)=\frac{1}{2i}(z-\frac{1}{z})
$$
$$f(x) = \sin^6{x} \cdot \cos^3{x} = \frac{-1}{2^9}(z+\frac{1}{z})^3(z-\frac{1}{z})^6\\
= \frac{-1}{2^9}(z^3+3z+3\frac{1}{z}+\frac{1}{z^3})(z^6-6z^4+15z^2 -20+15\frac{1}{z^2} -6 \frac{1}{z^4}+\frac{1}{z^6})\\
$$
Now open the brackets and use
$$z^n+\frac{1}{z^n}=2 \cos(nx) \\
z^n-\frac{1}{z^n}=2i \sin(nx)$$
Note A faster computation is to observe that
$$\frac{-1}{2^9}(z+\frac{1}{z})^3(z-\frac{1}{z})^6=\frac{-1}{2^9}(z+\frac{1}{z})^3(z-\frac{1}{z})^3(z-\frac{1}{z})^3\\
=\frac{-1}{2^9}(z^2-\frac{1}{z^2})^3(z-\frac{1}{z})^3\\
=\frac{-1}{2^9}(z^6-3z^2+3\frac{1}{z^2}-\frac{1}{z^6})(z^3-3z+3\frac{1}{z}-\frac{1}{z^3})\\
$$


text:
Q: SELinux allow http requests on Fedora 14 I have a Fedora 14 instance on Amazon EC2 and I want to make an http request from that instance to another one in the same amazon security group. When I use wget to make the request it works fine. However, when I use Apache HTTP client running through JBoss 6 I get a
HttpClient ConnectException: Connection refused

JBoss does not run as root but rather as user "jboss". I suspect this is an SELinux issue. I logged in as root and I called
setsebool -P httpd_can_network_connect 1

and
setsebool -P httpd_can_network_relay 1

But still no luck. Any advice would be much appreciated.
Regards

A: First, double check that SELinux is, in fact, the culprit by checking your audit log in /var/log/audit/audit.log.  There should be message with type=AVC related to JBoss.
Then, you can use that message in conjunction with the audit2allow tool to authorize the blocked access.  To authorize everything blocked for any binary with the name jboss in it thus far, run this as root:
grep jboss /var/log/audit/audit.log | audit2allow -M jboss
semodule -i jboss.pp

However, it's better to only allow the specific permissions needed.  To do that, copy and paste the relevant lines from your audit log to a new file, and cat that to audit2allow instead.


text:
Q: How to prove that the interpreter is /bin/bash when called from cron? That has been a bit of a puzzle for me.
When I try the following cronjobs individually:
* * * * * /bin/bash -c "readlink /proc/$$/exe >> /root/printenv"
* * * * * /bin/bash -c "readlink /proc/$PPID/exe >> /root/printenv"
* * * * * /bin/bash -c "readlink /proc/self/exe >> /root/printenv"
* * * * * /bin/bash -c "ps -h -o comm -p $$ >> /root/printenv"
* * * * * /bin/bash -c "echo $SHELL" >> /root/printenv

I get the following results respectively:
/bin/dash
/usr/sbin/cron
/bin/readlink
sh
/bin/sh

I can't seem to have it report /bin/bash in any circumstances when called from cron like that.
In a direct cronjob * * * * * /bin/bash -c "command" how can I prove that "command" is being interpreted by /bin/bash (if it is) ?
Answer for future references:
Changing the double quote for a single quote returned the right shell:
* * * * * /bin/bash -c 'readlink /proc/$$/exe >> /root/printenv'
Returned:
/bin/bash
Thanks to all contributors to the answer below.

A: In this case my default shell is bash and I just ran a test:
sh -c 'echo $0'

result: sh
sh -c "echo $0"

result: -bash
 bash -c 'echo $0'

result: bash
 bash -c "echo $0"

result: -bash
it looks like you need to use single quotes ' followed by the -c switch

A: The problem with all your commands is that you're using the wrong quote. Each command in crontab is a snippet of shell code, which is processed by a shell. The crontab command processing shell is defined by the setting of the SHELL variable in the crontab file, defaulting to /bin/sh.
When /bin/sh (or any compatible shell) executes the script /bin/bash -c "readlink /proc/$$/exe >> /root/printenv", one of the steps after parsing the command line is to perform any variable or command substitutions. There is one variable substitution here: the $$ which is inside a double-quoted string. So $$ is replaced by the process ID of the /bin/sh process. Say this process ID is 1234. The shell invoked by cron executes the command /bin/bash with the arguments -c and readlink /proc/1234/exe >> /root/printenv. The output indicates that /bin/sh is a symbolic link to /bin/bash.
If you use single quotes instead of double quotes, then the shell invoked by cron does not perform any variable substitution, and executes the command /bin/bash with the arguments -c and readlink /proc/$$/exe >> /root/printenv. Bash then parses this command, performs the substitution of $$ with its own process ID, and executes readlink with the argument 1234.
Note that depending on the shell, the output of that command might not be the shell binary, it could be /bin/readlink. The reason is that there is an optimization in bash (and several other shells): when the last thing the shell has to do is to run an external command, it doesn't run that command in a child process, it replaces the shell's process image. (Executing a program under Unix always works by replacing the process image with another; programs usually duplicate themselves just before doing that but it isn't an obligation.) Since bash detects that running readlink is the last thing it has to do, it runs readlink in the same process 1234, so readlink /proc/1234/exe reports /bin/readlink. Bash performs this optimization if you just run a command
bash -c 'readlink /proc/$$/exe`

but not if there's a redirection on it. Some shells (e.g. dash) don't perform this optimization. Some shells, such as ksh, are a little cleverer and optimize ksh -c 'readlink /proc/$$/exe >>/root/printenv, but wouldn't optimize e.g. ksh -c 'readlink /proc/$$/exe; true. (Exercise: why is it impossible to optimize that one?)