I can't remember a fallacious proof involving integrals and trigonometric identities.

Question: My calc professor once taught us a fallacious proof.  I'm hoping someone here can help me remember it.
Here's what I know about it:

The end result was some variation of 0=1 or 1=2.
It involved (indefinite?) integrals.
It was simple enough for Calc II students to grasp.
The (primary?) fallacy was that the arbitrary constants (+ C) were omitted after integration.

I'm not certain, but I have a strong hunch it involved a basic trigonometric identity.
Comment: "I can't remember a fallacious proof".  Don't I wish.
Comment: See http://math.stackexchange.com/questions/806254/using-integration-by-parts-results-in-0-1
Comment: [Relevant](http://math.stackexchange.com/questions/424854/1-0-by-integration-by-parts-of-tanx/).
Answer: It's probably the classic
$$\int \sin 2x \;dx = \int 2\sin x\cos x \;dx$$

Doing a $u=\sin x$ substitution "gives" $$\int 2u \;du = u^2 = \sin^2 x$$
Alternatively, using $v = \cos x$ "gives" $$\int -2v \;dv = -v^2 = -\cos^2 x$$

Since the solutions must be equal, we have
$$\sin^2 x = -\cos^2 x \quad\to\quad \sin^2 x + \cos^2 x = 0 \quad\to\quad 1 = 0$$
As you note, the fallacy here is the failure to include "+ constant" to the indefinite integrals.

Note that there's also the substitution $w = 2x$, which "gives"
$$\begin{align}
\int \frac12 \; \sin w \; dw = -\frac12 \; \cos w = -\frac12\;\cos 2x &= -\frac12\;(2 \cos^2 x - 1 ) = -\cos^2 x + \frac12 \\[6pt]
&= -\frac12\;(1 - 2 \sin^2 x) = \phantom{-}\sin^2 x - \frac12
\end{align}$$
that leads to the same kind of apparent contradiction when compared to the other integrals.
Answer: Here is my favourite: integrating by parts with $u=1/x$ and $v=x$, we get
$$\int\frac{dx}{x}=\frac1xx-\int x\Bigl(\frac{-1}{x^2}\Bigr)\,dx
  =1+\int\frac{dx}{x}$$
and "therefore" $0=1$.
Admittedly there is no trigonometry and so it's probably not the one you were looking for, but still...
Comment: One I learned in calculus class was basically exactly this, except on $\cot x\,\mathrm{d}x = (\sin x)^{-1}\,\mathrm{d}(\sin x)$, so it technically used trigonometry, but was otherwise exactly your answer.
Comment: I used to know a similar one, which I'm pretty sure involved natural logs and proved that $0=1$ using integration by parts, but I can't seem to find it...
Answer: Here is one that fits your description, but there are many possibilities. We integrate $4\sin x\cos x$ in two ways, incorrectly leaving out the constant of integration.
Way 1: Let $u=\cos x$. Then our integral is $-2u^2$, that is, $-2\cos^2 x$.
Way 2: We have $4\sin x\cos x=2\sin 2x$. Integrate. We get $-\cos 2x$. But $\cos 2x=2\cos^2 x-1$, so the integral is $-2\cos^2 x+1$.
"Thus"  $0=1$.
Comment: You beat me by 8 seconds! I'm leaving my answer up, anyway. :)
Comment: We organized things differently.
Answer: The simplest one I have is not actually 0=1 but $\pi=0$. This is one of my favourites,the most shortest and has confused a lot of people.
$\int \frac{dx}{\sqrt{1-x^2}} = sin^{-1}x$
But we also know that $\int - \frac{dx}{\sqrt{1-x^2}} = cos^{-1}x$
So therefore $sin^{-1}x=-cos^{-1}x$
But also, $sin^{-1}x+cos^{-1}x=\pi/2$
$\implies \pi/2=0$ $\implies \pi=0$.
I'm so evil. :)


Dataweave syntax for SOAP XML format

Question: I'm trying to write a DataWeave that would represent this XML:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xsi:xsd="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
    <AuthenticateResult xmlns="urn:authentication.soap.sforce.com">
        <Authenticated>true</Authenticated>
    </AuthenticateResult>
</soapenv:Body>
</soapenv:Envelope>

And I'm having a really hard time seeing if there are ns and other XML native syntax values supported via DW, or declare custom variables in DataWeave.
%dw 2.0
output application/xml
ns soapenv http://schemas.xmlsoap.org/soap/envelope/
ns xsi http://www.w3.org/2001/XMLSchema-instance
---
{
    soapenv#Envelope
    @(xsi#xsd:"http://schemas.xmlsoap.org/soap/envelope/"): {
        soapenv#Body: {
            AuthenticateResult @(xmlns: "urn:authentication.soap.sforce.com"): {
                Authenticated: payload.login
            }
        }
    }
}

my payload is just this, I want it to get updated from either true or false:
{
    "login": "true"
}

Answer: You can use @ the same way to define more ns as you have done with AuthenticateResult
%dw 2.0
output application/xml
ns soapenv http://schemas.xmlsoap.org/soap/envelope
---
{
    soapenv#Envelope @("xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "xsi:xsd":"http://schemas.xmlsoap.org/soap/envelope/"): {
        soapenv#Body: {
            AuthenticateResult @(xmlns: "urn:authentication.soap.sforce.com"): {
                Authenticated: payload.login
            }
        }
    }
}

Comment: Thanks Salim ! I updated the source with my progress, and I think it's basically the same as what you had mentioned (using a new 'ns' value or adding another variable.

Dataweave syntax for SOAP XML format


How to search for subarrays with a specific ids and generate a new array from their elements?

Question: I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.
This is what I coded:
$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data1[] = $ids['product_id'];
                $data2[] = $ids['product_file'];
                $data3[] = $ids['product_image'];
            }
        }
    }
    return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);

And the output for the following is:
Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 20
        )

    [1] => Array
        (
            [0] => file10
            [1] => file20
        )

    [2] => Array
        (
            [0] => https://i.imgur.com/dXb6.png
            [1] => https://i.imgur.com/MuP8.png
        )

)

Although what I'm trying to accomplish is:
Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

I tried the following:
function getFiles($productIDs, $urlIDs)
{
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
            }
        }
    }
    return array($data);
}

Which returns the following without looping through all id's, it should return both arrays since both id's are matching.
Array
(
    [0] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.
In case it's useful: https://eval.in/764083
Comment: The reason that your last method is not storing the `id=10` subarray is because you are overwriting `$data` on each qualifying iteration.  In other words, `id=10` is being stored, then `id=20` is replacing it.
Answer: PHP code demo
<?php
$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);

$urlIDs  = array(10,20);

function getFiles($productIDs, $urlIDs)
{
    $result=array();
    foreach($productIDs as $key => $productData)
    {
        if(!in_array($productData['product_id'],$urlIDs))
        {
            unset($productIDs[$key]);
        }
        else
        {
            $result[]=array("id"=>$productData['product_id'],"file"=>$productData['product_file'],"image"=>$productData['product_image']);
        }
    }

    return $result;
}
$getFiles = getFiles($productIDs, $urlIDs);
print_r($getFiles);

Output:
Array
(
    [0] => Array
        (
            [id] => 10
            [file] => file10
            [image] => https://i.imgur.com/dXb6.png
        )

    [1] => Array
        (
            [id] => 20
            [file] => file20
            [image] => https://i.imgur.com/MuP8.png
        )

)

Answer: Try this one.
function getFiles($productIDs, $urlIDs)
{
$newDara = [];
    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data['id'] = $ids['product_id'];
                $data['file'] = $ids['product_file'];
                $data['image'] = $ids['product_image'];
                $newData[] = $data;
            }
        }
    }
    return array($newData);
}

Answer: Leveraging your tried out solution, change your tried solution to this.
function getFiles($productIDs, $urlIDs)
{

    foreach($productIDs as $ids)
    {
        foreach($urlIDs as $products)
        {
            if(in_array($products, $ids)){
                $data[] = [ "id" => $ids['product_id'],
                            "file" => $ids['product_file'],
                            "image" => $ids['product_image']];
            }
        }
    }
    return $data;
}

Answer: Try this version
    <?php
    /**
     * Created by PhpStorm.
     * User: lenovo
     * Date: 3/30/2017
     * Time: 5:53 AM
     */
    $productIDs = array(
        '0' => array(
            'product_id' => '10',
            'product_name' => 'Test',
            'product_file' => 'file10',
            'product_image' => 'https://i.imgur.com/dXb6.png',
        ),
        '1' => array(
            'product_id' => '20',
            'product_name' => 'Test1',
            'product_file' => 'file20',
            'product_image' => 'https://i.imgur.com/MuP8.png',
        ),
        '2' => array(
            'product_id' => '30',
            'product_name' => 'No product',
            'product_file' => 'file30',
            'product_image' => 'https://i.imgur.com/kWP3.png',
        )
    );

    $urlIDs  = array(10,20);

    $ouput = [];

    foreach($productIDs as $product){

        if(in_array($product['product_id'],$urlIDs)){
           $ouput[] = array("id"=>$product["product_id"], "file"=>$product["product_file"], "image"=>$product["product_image"]);
        }
    }

   echo "
";
     print_r($ouput);
    echo "
";

Check the
Good Luck
Answer: The other answers are either doing too many loops, or looping through the $productIDs array (which I assume is much longer in your actual project).
This method will only iterate on your search array, this should provide a performance boost.  You will see this approach posted as the top comment @ http://php.net/manual/en/function.array-search.php
Code: (Demo)
$productIDs = array(
    '0' => array(
        'product_id' => '10',
        'product_name' => 'Test',
        'product_file' => 'file10',
        'product_image' => 'https://i.imgur.com/dXb6.png',
    ),
    '1' => array(
        'product_id' => '20',
        'product_name' => 'Test1',
        'product_file' => 'file20',
        'product_image' => 'https://i.imgur.com/MuP8.png',
    ),
    '2' => array(
        'product_id' => '30',
        'product_name' => 'No product',
        'product_file' => 'file30',
        'product_image' => 'https://i.imgur.com/kWP3.png',
    )
);
$urlIDs=array(10,20);
foreach($urlIDs as $prd_id){
    if(($i=array_search($prd_id,array_column($productIDs,'product_id')))!==false){
        $result[]=['id'=>$productIDs[$i]['product_id'],
                   'file'=>$productIDs[$i]['product_file'],
                   'image'=>$productIDs[$i]['product_image']
                  ];
    }else{
        echo "$prd_id not found";
    }
}
var_export($result);

Output:
array (
  0 =>
  array (
    'id' => '10',
    'file' => 'file10',
    'image' => 'https://i.imgur.com/dXb6.png',
  ),
  1 =>
  array (
    'id' => '20',
    'file' => 'file20',
    'image' => 'https://i.imgur.com/MuP8.png',
  ),
)


No output in Output Panel when running code - Python on VSCode

Question: new to Python and StackOverflow. Apologies if I miss any formalities.
I just created a one-line program to print Hello World but every time I run the program (using F5 or by going to Run->Start Debugging) the program runs and the panel at the bottom automatically switches to the Terminal window and the output gets displayed there and not in the Debug window. (Picture 1)
There are a lot of other things that get printed in the Terminal window which is why I want only the output to be printed in the Debug window. Also, that is how it is shown in the video of the course that I am doing (Picture 2).
print("Hello World")

Answer: If you want to display the results in the debug console, you could open file launch.json in folder .vscode and add this setting:  "console": "internalConsole",. (or open the setting pattern next to the debug button to open launch.json file. )

This is the complete content of my launch.json file:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Current File",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "internalConsole",
    }
  ]
}

Then, through the test, the result is displayed in the debug console. like this:

Reference: Python debug configurations in VSCode.
Comment: This was exactly what I was looking for an even numerous google searches with all combinations and permutations of keywords couldn't help me find this.
Thank you so much for your time! Very much appreciated.


go 1.18 in google.cloud

Question: Description
I am trying to install a library from a go v1.18 program to access Google Cloud.
Previously, the "go get" command was used, but since version 1.18, it is no longer available.
It seems to use go install, but I get an error when executing the command.
% go install cloud.google.com/go/bigquery
go: 'go install' requires a version when current directory is not in a module
    Try 'go install cloud.google.com/go/bigquery@latest' to install the latest version

% go install cloud.google.com/go/bigquery@latest
package cloud.google.com/go/bigquery is not a main package

% go install cloud.google.com/go@latest
package cloud.google.com/go is not a main package

Environments
% go version
go version go1.18 darwin/amd64

% uname -v
Darwin Kernel Version 21.4.0: Fri Mar 18 00:45:05 PDT 2022; root:xnu-8020.101.4~15/RELEASE_X86_64

% sw_vers
ProductName:    macOS
ProductVersion: 12.3.1
BuildVersion:   21E258

Reference
bigquery package - cloud.google.com/go/bigquery - pkg.go.dev
I tried,
Thank you for your support.
% go mod init cloud.google.com/go

% go get -u cloud.google.com/go/datacatalog
go: added cloud.google.com/go/datacatalog v1.3.0

% go mod tidy
go: downloading google.golang.org/appengine v1.6.7
go: downloading golang.org/x/sys v0.0.0-20220209214540-3681064d5158

% go mod vendor

% go run catalog.go
package command-line-arguments is not a main package

What should I do next ?
Self resolved.
-> change package name "main"
Comment: Hi @redpanda, are you trying to add this module as a dependency of your project or install it globally to use outside of your project?

If the answer is the former, try running `go get cloud.google.com/go/bigquery@latest`
Answer: go install is used to install binary programs available on the package. Usually command line tools.
go get, until go1.18, was used to update packages and install programs, they change it by split in several programs
Seems there is nothing to install. Also the main package is not bigquery but cloud.google.com/go
If you want to install a dependency, if you are using vendorized modules you can do
$ go get -u cloud.google.com/go/bigquery
$ go mod tidy
$ go mod vendor
If not, you may try it by running go mod init first

go 1.18 in google.cloud


Vue: positioning logo component to have zero margin top

Question: I have a simple vue component like this:
Logo.vue:
<template>

</template>

I'm using it in the App.vue like this:
App.vue:
<template>

    <Logo/>

</template>

It gives this result:

However I would like it to be closer to the top and rightmost edge, like this:

But putting margin-top: 0; didn't do the work.
Answer: Well what about position absolute:
 img  {
        position: absolute;
        right: 0;
        top: 0;
        width: 300px;
    }

If you want your logo to stick always on the top right even if you scroll then use position: fixed


iOS MPRemoteCommandCenter when switching between audio and video stream

Question: I am working on a music/video streaming app, and I'm using AVPlayer to load up the videos and songs.
I have a singleton instance of my music player class that handles music playback. I have included a code snippet with the relevant audio session and command center setup:
let audio_Session: AVAudioSession = AVAudioSession.sharedInstance()

        do {
            try audio_Session.setCategory(AVAudioSessionCategoryPlayback)
        } catch _ {
        }
        do {
            try audio_Session.setActive(true)
        } catch _ {
        }

        UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
        if UIApplication.sharedApplication().canBecomeFirstResponder() {
            UIApplication.sharedApplication().becomeFirstResponder()
        }

let now_Playing_Command: MPRemoteCommandCenter = MPRemoteCommandCenter.sharedCommandCenter()
        now_Playing_Command.pauseCommand.addTarget(self, action: #selector(self.pause_Command))
        now_Playing_Command.playCommand.addTarget(self, action: #selector(self.play_Command))
        now_Playing_Command.nextTrackCommand.addTarget(self, action: #selector(self.next_Track_Command))
        now_Playing_Command.togglePlayPauseCommand.addTarget(self, action: #selector(self.toggle_Play_Pause))
        now_Playing_Command.previousTrackCommand.addTarget(self, action: #selector(self.previous_Track_Command))

Everything works fine UNTIL I start streaming a video. During video playback, the command center begins accepting pause/play commands for the video, which pause/resume the video. Sometimes, it causes the song to resume playing in the background.
This is the sequence:

begin streaming song
pause song
begin streaming video
end video
but when i resume the song playback (via the view controller controls), the MPCommandCenter buttons are grayed out and I cant set them. Starting a new song (which does most of the setup for audio session and such) does not work either.

Starting a video and ending it before any song is played grays out the command center buttons for all future song streams' .
I would like to be able to program the command center to seamlessly transition from receiving remote commands from music (singleton instance) to a video (regular instance) and back to the paused Singleton instance song.
Answer: I solved my problem. I'm posting here since it might help someone in the future.
My songs playback is handled by a custom sharedInstance singleton instance of AVPlayer, which I built myself.
I also created a custom AVPlayerViewController, which only handles the video playback and is stateless, so when the user dismisses the video, its gone forever.
From my parent VC, I instantiated and displayed my custom AVPlayerViewController, which is only for the video.
let mainStoryBoard:UIStoryboard = UIStoryboard(name:"Main", bundle:nil)

        //Create View Controllers
        let video_VC:VideoViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("video_View_Controller") as! VideoViewController

        video_VC.url = url
        video_VC.video_Holder = video_Holder
        video_VC.player = AVPlayer(URL: url)

        self.presentViewController(video_VC, animated: true, completion: { void in
            video_VC.player?.play()
        })`

Then, in my AVPlayerViewController's viewDidLoad, I checked to see if my singleton instance of audio player is has any songs playing/paused. If so, I set a variable in that singleton instance called is_Variable_Open to true. At that point, the music player functions will ignore all command center commands. Furthermore, I enable the command buttons again and set them to this instance of AVPlayerViewController, which only handles the video stream.
override func viewDidLoad() {
if(media().sharedInstance.playerItem != nil){
            print("there is a song playing, so lets pause it")
            media().sharedInstance.is_Video_Player_Open = true
            if(media().sharedInstance.player?.rate == 1){
                media().sharedInstance.player.pause()
            }

            let now_Playing_Command: MPRemoteCommandCenter = MPRemoteCommandCenter.sharedCommandCenter()
            now_Playing_Command.pauseCommand.enabled = true
            now_Playing_Command.pauseCommand.addTarget(self, action: #selector(self.pause_Command))
            now_Playing_Command.playCommand.enabled = true
            now_Playing_Command.playCommand.addTarget(self, action: #selector(self.play_Command))
            now_Playing_Command.togglePlayPauseCommand.enabled = true
            now_Playing_Command.togglePlayPauseCommand.addTarget(self, action:#selector(self.toggle_Play_Pause))

And then upon dismissal of the video, in viewWillDisappear, I set the variable is_Video_Player_Open back to false, and tell the music player to set its command center setup again. BAM.
override func viewWillDisappear(animated: Bool) {
        print("video player is about to disapear")

        if(media().sharedInstance.playerItem != nil){
            print("video is about to end, and there is ssog playing, so lets do stuff")
            media().sharedInstance.is_Video_Player_Open = false
            media().sharedInstance.set_MP_Command()
            media().sharedInstance.set_Now_Playing()
        }
    }


Changing color of navigation drawer item before clicking it

Question: I am changing the color of selected item of the navigation drawer and that is working fine through the following code
<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
        app:menu="@menu/activity_main_drawer"
        app:itemTextColor="@color/nav_item_color"
        android:background="#000000"/>

</android.support.v4.widget.DrawerLayout>

following is the code line doing the trick for me
app:itemTextColor="@color/nav_item_color"

code of xml from color directory
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#81DDFF" android:state_checked="true" style="@style/NavDrawerTextStyle"/>
    <item android:color="#FFFFFF" style="@style/NavDrawerTextStyle"/>
</selector>

Now the problem for me is I want to change the color of first item (before it is clicked as the screen corresponding to first item is there) of Navigation drawer when the drawer opens for the first time.
In other words how can I change the color of a single navigation drawer item from my activity class? Thank you
Here is the screenshot when drawer opens for the first time and I wanted the color of login item light blue

When login item is clicked and drawer opens again
Answer: you can set selected manually
navigationView.getMenu().getItem(0).setChecked(true);

or you can use
navigationView.setCheckedItem(menuItemid);


Getting error while trying to use mainClassName

Question: I am trying to use this SMS service but while setting the SMSBackend class I am not able to set the mainClassName due to which I am not able to get the link as given in the blog for last few hr I am stuck at this I have tried the jar method, only class name, full class name here is my gradle file
buildscript {
repositories { jcenter() }
dependencies {
    classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.3'
}
}

apply plugin: 'com.android.application'

apply plugin: 'com.github.johnrengelman.shadow'

android {
compileSdkVersion 28
defaultConfig {
    applicationId "net.iquesoft.smsapp"
    minSdkVersion 16
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
mainClassName = 'net.iquesoft.smsapp.SMSBackend'

compileOptions {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
testImplementation 'junit:junit:4.12'
implementation 'com.sparkjava:spark-core:2.6.0'
implementation group: 'com.twilio.sdk', name: 'twilio', version: '7.9.0'
implementation 'org.slf4j:slf4j-simple:1.6.1'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

and i am getting error like this
Could not set unknown property 'mainClassName' for object of type com.android.build.gradle.internal.dsl.BaseAppModuleExtension.

Answer: You are creating an Android project to generate the Backend.
You have to create a Java project with the Spark framework as he said here and when you have your Backend running you can create your Android project.
Comment: Bro i tried but not able to get any message i even set the twilio no also


Teleport players back to the center of the region when they leave

Question: I'm trying to set up my Minecraft server so I can have minigames and a survival mode and I'm having trouble setting up so when players jump from the spawn (Which is high in the air) they get teleported back into the spawn. Is this possible?
Answer: You could set up a repeating command block with:
/tp @a[x=<X>,y=<Y>,z=<Z>,rm=<R>] <X> <Y> <Z>

Replace <X>, <Y>, and <Z> with the corrosponding coordinates of spawn, and <R> with the distance people can get from spawn before they are teleported back.
Comment: @FlatPancake I don't know how Multiverse works. If it does stop the portals from working, you could also set a `r` (radius max) so that only people between `` and `` blocks are teleported. E.G: `/tp @a[x=20,y=64,z=10,r=60,rm=50] 20 64 10`
Comment: Then the next question would be: Would this stop players from using the portals created by the plugin Multiverse to move around or would it just keep teleporting the players back to the spawn?
Comment: 1.13 syntax: `/tp @a[x=,y=,z=,distance=..]   `


Run all tasks in playbook with_items

Question: I want the playbook to run once with each item in the list and not all items in the list at once.
Ansible version: 2.6.1
Tasks.yaml:
 ---

- name: Task 1
  debug:
    msg: "Message 1: {{ item }}"
  with_items: "{{ messages }}"

- name: Task 2
  debug:
    msg: "Message 2: {{ item }}"
  with_items: "{{ messages }}"

Playbook:
- hosts: localhost
  gather_facts: no
  tasks:
  - import_tasks: Tasks.yml
    vars:
      messages:
        - 1
        - 2

This is my expected result:
Task 1 with Item 1
Task 2 with Item 1
Task 3 with Item 1
Task 1 with Item 2
Task 2 with Item 2
Task 3 with Item 2
Task 1 with Item 3
Task 2 with Item 3
Task 3 with Item 3

But when I execute the playbook, then it is like this:
Task 1 with Item 1
Task 1 with Item 2
Task 2 with Item 1
Task 2 with Item 2
Task 3 with Item 1
Task 3 with Item 2
...

I tried both import and include - both have the same result.
Comment: ? I do not know, what you mean... ;)
Comment: Hmm. I thought I only added the two tags "ansible" and "playbook".
Answer: Your playbook.yml should implement a loop (notice you cannot loop with import_tasks; it will raise an error):
- hosts: localhost
  connection: local
  gather_facts: no

  vars:
    messages:
      - 1
      - 2
      - 3

  tasks:
    - include_tasks: Tasks.yml
      loop: "{{ messages }}"

And Tasks.yml should look like this (no loops inside):
---
- name: Task 1
  debug:
    msg: "Message 1: {{ item }}"

- name: Task 2
  debug:
    msg: "Message 2: {{ item }}"

Comment: Thanks for the answer! I will check that.
Comment: Note that if you have an inside "with_items" you need to save the outer var like in https://docs.ansible.com/ansible/2.3/playbooks_loops.html#loops-and-includes-in-2-0 and if you want to avoid the warning about "item" already in use you must  use loop_control:
    loop_var: item_foo
to redeclare the item var

Run all tasks in playbook with_items


How to make side arrow images non-transparent

Question: I'm using Bootstrap's Carousel but with some custom arrow images. They are still showing up transparent, how can I get them to show normally, at full opacity? Some code:
HTML:

CSS:
.carousel-control .glyphicon,
.carousel-control .icon-prev,
.carousel-control .icon-next {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 5;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-top: -10px;
  margin-left: -10px;
  font-family: serif;
  opacity: 0;
}

Answer: Try changing the opacity: 0; to opacity: 1; in the css.
Answer: The Bootstrap css have some other css class with opacity, try to use the css below:
.carousel-control {
  filter: none;
  opacity: 1;
}
.carousel-control:hover,
.carousel-control:focus {
  filter: none;
  opacity: 1;
}

This worked for you?If it doesnt, post your code at http://jsfiddle.net/ :)


JSON Get List of attributes values

Question: I have the following JSON, and I want to take a list of IDs with its values
For example in LINQ something like this: result.Select(x=>x.id)
I tried this:
 var inner = outer["pictures"].Value<JArray>().ToList();

I have a list there but with all attributes but I am not able to select just IDs since it is an anonymous list.
    outer
{{
  "id": "669654603",
  "pictures": [
    {
      "id": "659745-MLA25600661898_052017",
      "url": "http://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "size": "500x365",
      "max_size": "625x457",
      "quality": ""
    },
    {
      "id": "908422-MLA25658267858_062017",
      "url": "http://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "size": "47x47",
      "max_size": "47x47",
      "quality": ""
    },
    {
      "id": "794138-MLA25658267889_062017",
      "url": "http://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "size": "40x40",
      "max_size": "40x40",
      "quality": ""
    }
  ]

}}

Comment: This is not a valid JSON document
Comment: @SirRufo Sorry I had a big JSON and I cut it for this example, seems that I did it wrong.
Comment: you can also visit http://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm as i mentioned in my answer
Answer: When working with Newtonsoft JSON you can do it like this:
var values = JObject.Parse(jsonString)["pictures"].Select(p => p["id"].Value<string>()).ToList();

Answer: In order to be valid your json should not contain double curly brackets:
{
  "id": "669654603",
  "pictures": [ ... ]
}

You can parse it without additional classes:
var ids = JObject.Parse(json)["pictures"].Select(p => (string)p["id"]);

Output:
[
  "659745-MLA25600661898_052017",
  "908422-MLA25658267858_062017",
  "794138-MLA25658267889_062017"
]

Or you can create several classes to hold your json data:
public class Container
{
    public List<Picture> Pictures { get; set; }
}

public class Picture
{
    public string Id { get; set; }
    // you can add other properties here
}

And use strongly-typed parsing:
var ids = JsonConvert.DeserializeObject<Container>(json).Pictures.Select(p => p.Id);

JSON Get List of attributes values


How to run go vet on all code regardless of platform

Question: When I run go vet ./... to check my project it only checks source code matching the current platform and architecture. E.g. suppose I have:
example.go
example_darwin.go
example_windows.go
example_linux.go
example_linux_amd64.go
example_linux_arm64.go

If I'm on my Mac and I run go vet ./... then it will only look at example.go and example_darwin.go but it won't vet the Windows or Linux files.
If I want to vet everything I could just invoke it over and over again for every combination:
GOOS=darwin GOARCH=amd64 go vet ./...
GOOS=windows GOARCH=amd64 go vet ./...
GOOS=linux GOARCH=amd64 go vet ./...
GOOS=linux GOARCH=arm64 go vet ./...

That seems a bit excessive. Is there any straightforward way to vet all the code in one pass without re-vetting some files many times over? Is that even a meaningful thing to do, or is vetting inherently a "whole package" operation?
Comment: vet runs the type checker, so it's probably not possible to run it for all architectures at once.
Answer: Invoking it over and over again is the only way to do this.  The reason is that go vet does type and symbol resolution, so it's possible that any given file may vet cleanly for one architecture, but not for another.
The best you may be able to do is to programatically execute all of the various go vet statements for the available build tags. I have not tried this, but go list's -format flag may be able to provide this list of tags for you, to feed into such a script.


Calculate percentage of responses for each column in R?

Question: I have data that looks like this
User <-c('User_1','User_2','User_3','User_4','User_5')
Q1 <- c('Never', 'Rarely', 'Sometimes', 'Often', 'Always')
Q2<- c('Sometimes', 'Rarely', 'Sometimes', 'Often', 'Rarely')
Q3 <- c('Always', 'Rarely', 'Sometimes', 'Always', 'Rarely')
data1 <- data.frame(User, Q1, Q2, Q3)
print(data1)

Output
    User        Q1        Q2        Q3
1 User_1     Never Sometimes    Always
2 User_2    Rarely    Rarely    Rarely
3 User_3 Sometimes Sometimes Sometimes
4 User_4     Often     Often    Always
5 User_5    Always    Rarely    Rarely

My goal is to create a data frame that shows the percentage of each ordinal value for the data set. So that would look something like this:
          Q1        Q2        Q3
Never     20%        0%        0%
Rarely    20%       40%       40%
Sometimes 20%       40%       20%
Often     20%       20%        0%
Always    20%        0%       40%

I have no idea how to go about this. Could someone help me out?
Answer: library(dplyr)
library(tidyr) # pivot_*
facs <- c("Never", "Rarely", "Sometimes", "Often", "Always")
data1 %>%
  pivot_longer(cols = -User) %>%
  mutate(value = factor(value, levels = facs)) %>%
  count(name, value) %>%
  pivot_wider(
    id_cols = value, names_from = name, values_from = n,
    values_fill = 0L) %>%
  mutate(across(starts_with("Q"), ~ 100 * . / sum(.)))
# # A tibble: 5 × 4
#   value        Q1    Q2    Q3
#   <fct>     <dbl> <dbl> <dbl>
# 1 Never        20     0     0
# 2 Rarely       20    40    40
# 3 Sometimes    20    40    20
# 4 Often        20    20     0
# 5 Always       20     0    40

Walk-through:

create facs then factor(values, levels=facs) so that the premise of "order" in your ordinal scale is preserved and easily sorted
reshape from wide to long so that we easily count the name and value pairs
reshape from long to wide again, using value on the "left", and question number across the top
for each of the Q* columns, normalize to a 0-100 scale

Refs for pivoting:

pivot wide-to-long: Reshaping data.frame from wide to long format (names_pattern) Transforming wide data to long format with multiple variables (multiple value columns) pivot_longer into multiple columns, Is there way to pivot_longer to multiple values columns in R?
pivot long-to-wide: How to reshape data from long to wide format, Reshape multiple value columns to wide format

BTW, you said that there might be masking; in your case, switch to dplyr::count(..) (this should not be necessary for others).
Comment: Thank you. I got it to work, I think it was a masking issue. If I replace `count(name, value)` with `dplyr::count(name, value)` it works fine.
Comment: Thank you! I have two questions: 1: How would I do this without using the starts_with() function? In my actual data set, the column names don't have any common labelling. 2:  When I run it with the sample code above, I get 'Error in count(., name, value) : Argument 'x' is not a vector: list'
Comment: (!) You can replace `across(starts_with("Q"), ...)` with `across(c(var1, col2, field3), ...)`. (2) No idea, it works with the sample data provided. Perhaps post the output from `dput(head(yourdata,20))` into your question?
Comment: (that `(!)` was supposed to be `(1)` :-/)
Answer: Consider Percent crosstab in wps/sas uses normalization and r uses initial denormalized data?
see
github
https://github.com/rogerjdeangelis/utl-percent-crosstab-in-wps-r
This is a very common problem.
Perhaps normalization is a better initial structure for this data.
Many SAS procedures can summarize normalized data easily, ie procs: SQL, freq, tabulate, report, means, corresp and summary.
I expect the same issue with R packages.
I have examples of all of the repos below.
 1 wps proc corresp
 2 R
   https://stackoverflow.com/users/3358272/r2evans
 3 related repos


BigInteger most time optimized multiplication

Question: Hi I want to multiply 2 big integer in a most timely optimized way. I am currently using karatsuba algorithm. Can anyone suggest more optimized way or algo to do it.
Thanks
<code>public static BigInteger karatsuba(BigInteger x, BigInteger y) {

        // cutoff to brute force
        int N = Math.max(x.bitLength(), y.bitLength());
        System.out.println(N);
        if (N <= 2000) return x.multiply(y);                // optimize this parameter

        // number of bits divided by 2, rounded up
        N = (N / 2) + (N % 2);

        // x = a + 2^N b,   y = c + 2^N d
        BigInteger b = x.shiftRight(N);
        BigInteger a = x.subtract(b.shiftLeft(N));
        BigInteger d = y.shiftRight(N);
        BigInteger c = y.subtract(d.shiftLeft(N));

        // compute sub-expressions
        BigInteger ac    = karatsuba(a, c);
        BigInteger bd    = karatsuba(b, d);
        BigInteger abcd  = karatsuba(a.add(b), c.add(d));

        return ac.add(abcd.subtract(ac).subtract(bd).shiftLeft(N)).add(bd.shiftLeft(2*N));
    }
</code>
Comment: what's wrong with BigInteger.Multiply() ?
Comment: If the size isn't going to be bigger than 500 digits, then you won't need to go any higher than Karatsuba. Toom-Cook >=3 and FFT are only useful when you get into tens of thousands of digits.
Comment: It's complexity is of order O(n^2). Karatsuba is approximately O(n^1.5). I want a more optimized one.
Comment: There's probably a way to solve the problem without solving *this* problem (fast bigint multiplication) then.
Comment: If you want speed then why not Toom-Cook ?
Comment: If they are huge, FFT-based multiplication could help. Should be something like O(n*log(n)).
Comment: yes I should use that. I read somewhere that it's complexity is O(n^1.4). Is it the best possible solution? Or there is a more optimized way?
Comment: @AlexeyFrunze there can be upto 500 digits.
Comment: Yeah, more details, as usual, here: [Multiplication algorithm](http://en.wikipedia.org/wiki/Multiplication_algorithm).
Comment: @Mysticial I am solving a spoj problem using karatsuba but it is giving me time limit exceeded. That is why I wanted the best way.
Comment: Like the Java SDK, you should use different methods for different sizes. For "small" bigintegers, you use the normal "schoolbook" multiplication. For bigger sizes, you use Karatsuba, For even larger sizes, you use Toom-Cook 3 way, or one of the other Toom-Cook versions, and for extremely huge bigintegers, you use FFT-based algorithms. These algorithms are all fast, but some only for very big integers. For smaller, their overhead is far too big. Even Karatsuba has too much overhead for small bigintegers.
Answer: The version of BigInteger in jdk8 switches between the naive algorithm, The Toom-Cook algorithm, and Karatsuba depending on the size of the input to get excellent performance.
Comment: Here's the source, for the curious: https://github.com/dmlloyd/openjdk/blob/e7f494fc8/jdk/src/java.base/share/classes/java/math/BigInteger.java#L1558
Answer: Complexity and actual speed are very different things in practice, because of the constant factors involved in the O notation. There is always a point where complexity prevails, but it may very well be out of the range (of input size) you are working with. The implementation details (level of optimization) of an algorithm also directly affect those constant factors.
My suggestion is to try a few different algorithms, preferably from a library that the authors already spent some effort optimizing, and actually measure and compare their speeds on your inputs.
Regarding SPOJ, don't forget the possibility that the main problem lies elsewhere (i.e. not in the multiplication speed of large integers).
Comment: Interestingly enough, the constant is dependent also upon the machine word size.  If you were dealing with raw bits, Karatsuba becomes advantageous much sooner, than if you can assume say 32 or 64-bit multiplications are O(1) and therefore the bit size will be higher.  Its also the details of memory allocation, copying and usage that are relevant as if you are not careful, the optimized algorithms tend to make the constant larger than is necessary.


Lie subalgebras of $so(3)$ and complex Lie subalgebras of $sl(2,\mathbb{C})$.

Question: I am looking for a reference that:
describes all Lie subalgebras of $so(3)$,and describes all complex Lie subalgebras of $sl(2,\mathbb{C})$.
Does someone have appropriate references?
Comment: the complex Lie algebras (2,ℂ): https://en.wikipedia.org/wiki/Special_linear_Lie_algebra#Representation_theory_of_%7F'%22%60UNIQ--postMath-00000007-QINU%60%22'%7F
Comment: Lie algebras $su(2)$ and $so(3)$: https://en.wikipedia.org/wiki/Special_unitary_group#The_group_SU(2)
Answer: I don't know if it answers these specific questions explicitly, but you can find all you need in Helgason's book Differential Geometry, Lie Groups, and Symmetric Spaces.


Facing unexpected 'misaligned pointer dereference: address must be a multiple of 0x8 but is 0x__' error

Question: I am trying to use a library users [Docs.rs] [GitHub].
When I use try to get the details of user number 5 (i.e. 'operators') on macOS, using the following code...
use users::get_group_by_gid;

fn main() {
    let group = get_group_by_gid(5).unwrap();
    println!("{:?}", group.name());
}

...I get an unexpected error:
thread 'main' panicked at 'misaligned pointer dereference: address must be a multiple of 0x8 but is 0x14400880b', /Users/dhruvkb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/users-0.11.0/src/base.rs:297:34
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'panic in a function that cannot unwind', library/core/src/panicking.rs:126:5
stack backtrace:
   0:        0x104fe684c - std::backtrace_rs::backtrace::libunwind::trace::h0a647ce7e8dc2fab
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/../../backtrace/src/backtrace/libunwind.rs:93:5
   1:        0x104fe684c - std::backtrace_rs::backtrace::trace_unsynchronized::hea920694a2a8ac80
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/../../backtrace/src/backtrace/mod.rs:66:5
   2:        0x104fe684c - std::sys_common::backtrace::_print_fmt::h7b4e20c1da2ebb61
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/sys_common/backtrace.rs:65:5
   3:        0x104fe684c - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h819e9cbdf1a9e730
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/sys_common/backtrace.rs:44:22
   4:        0x104ff80e0 - core::fmt::write::ha5e9bf3131ecb7c0
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/fmt/mod.rs:1254:17
   5:        0x104fe46b0 - std::io::Write::write_fmt::h414ce9994bf17404
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/io/mod.rs:1698:15
   6:        0x104fe6660 - std::sys_common::backtrace::_print::h28d98f2094da6d1d
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/sys_common/backtrace.rs:47:5
   7:        0x104fe6660 - std::sys_common::backtrace::print::h8072db0bbd5bcc3d
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/sys_common/backtrace.rs:34:9
   8:        0x104fe7b80 - std::panicking::default_hook::{{closure}}::h2c85c5b0c2ede151
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:269:22
   9:        0x104fe7940 - std::panicking::default_hook::hcf2f70992d02f6fe
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:288:9
  10:        0x104fe8058 - std::panicking::rust_panic_with_hook::h023af7f90b47eb8b
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:691:13
  11:        0x104fe7f4c - std::panicking::begin_panic_handler::{{closure}}::h14283519edc1d634
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:580:13
  12:        0x104fe6c6c - std::sys_common::backtrace::__rust_end_short_backtrace::hc366c0b0cef5b747
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/sys_common/backtrace.rs:150:18
  13:        0x104fe7d20 - rust_begin_unwind
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:578:5
  14:        0x104fff6b8 - core::panicking::panic_nounwind_fmt::h48fca0782e5a5b33
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/panicking.rs:96:14
  15:        0x104fff734 - core::panicking::panic_nounwind::hc8dbc36c10163a33
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/panicking.rs:126:5
  16:        0x104fff82c - core::panicking::panic_cannot_unwind::h8bbe98643cda7e5c
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/panicking.rs:188:5
  17:        0x104fca054 - users::base::members::h897f0606a81fa18e
                               at /Users/dhruvkb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/users-0.11.0/src/base.rs:291:1
  18:        0x104fc9bb0 - users::base::os::unix::GroupExtras::from_struct::hdb1f84273e3fef19
                               at /Users/dhruvkb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/users-0.11.0/src/base.rs:1060:33
  19:        0x104fc9e44 - users::base::struct_to_group::h968dc5b5260e3ea2
                               at /Users/dhruvkb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/users-0.11.0/src/base.rs:280:19
  20:        0x104fca3bc - users::base::get_group_by_gid::hbcac997dd823548f
                               at /Users/dhruvkb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/users-0.11.0/src/base.rs:473:26
  21:        0x104fc875c - ug::main::h9b6b146ea9ce450b
                               at /Users/dhruvkb/Developer/personal/test/ug/src/main.rs:4:17
  22:        0x104fc8908 - core::ops::function::FnOnce::call_once::h7e6c46cf308f75b9
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/ops/function.rs:250:5
  23:        0x104fc8874 - std::sys_common::backtrace::__rust_begin_short_backtrace::h1d5bc4a1fd871dea
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/sys_common/backtrace.rs:134:18
  24:        0x104fc89ac - std::rt::lang_start::{{closure}}::hd278346b68dd1f23
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/rt.rs:166:18
  25:        0x104fe2408 - core::ops::function::impls::<impl core::ops::function::FnOnce for &F>::call_once::h6f7eb9f266759f90
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/ops/function.rs:287:13
  26:        0x104fe2408 - std::panicking::try::do_call::h54b2febb9ea02379
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:485:40
  27:        0x104fe2408 - std::panicking::try::h95a2f9f45aeb75ea
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:449:19
  28:        0x104fe2408 - std::panic::catch_unwind::h9686256fa0fc97a1
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panic.rs:140:14
  29:        0x104fe2408 - std::rt::lang_start_internal::{{closure}}::h227e8b10bc4e486b
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/rt.rs:148:48
  30:        0x104fe2408 - std::panicking::try::do_call::h414d500a3ee5fa44
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:485:40
  31:        0x104fe2408 - std::panicking::try::h4f025820961f1c3f
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:449:19
  32:        0x104fe2408 - std::panic::catch_unwind::h0b71dfe3538d125d
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panic.rs:140:14
  33:        0x104fe2408 - std::rt::lang_start_internal::h8ee16b8f6c950a26
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/rt.rs:148:20
  34:        0x104fc8978 - std::rt::lang_start::hb3f96d07eed31802
                               at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/rt.rs:165:17
  35:        0x104fc8854 - _main
thread caused non-unwinding panic. aborting.
[1]    12348 abort      cargo run

This error is unexpected because it works for other group IDs like 0 i.e. 'root' or 20 i.e. 'staff'.
This happened in my app so I made a greenfield project with no other dependencies except users and it happened there as well. I know that exa, a popular CLI app uses this lib, so I cloned its repo and added the same lines from my main() to exa's main() function.
It works there, which is even more confusing.
Comment: It seems `exa` is using Rust 1.63.0 (because of rust-toolchain.toml) and you're using latest stable for your project.
Comment: @ChayimFriedman you are right! This works on Rust version 1.63.0 (but unfortunately my other dependencies, like Clap, will not support it). Is there a way to get it to work on stable?
Comment: Rust 1.70, implements by default runtime debug assertions for dereferencing misaligned pointers (https://github.com/rust-lang/rust/pull/98112). I can confirm that this update has broken some code
Answer: Some pointer in the list group.gr_mem returned by getgrgid_r() from libc is underaligned. This may be a bug in the C library, or in the documentation, but likely not in the Rust library because I found nothing in the documentation about this. This causes UB, which mean the compiler can do whatever it wants. Previously, the "whatever it wants" was pretty much ignoring it (minus applying optimizations that exploit this fact). As of latest Rust version (1.70.0) the compiler started being helpful by checking for underaligned pointers in debug builds to help prevent UB. This caused your code to crash. You can silence this checks, if you want. This won't solve you the actual problem of UB, but will at least not crash your program, and you can hope the compiler won't apply any optimization that will suddenly break your code in hard-to-aniticipate ways.
Silencing this check is done by disabling debug assertions. In your Cargo.toml:
[profile.dev]
debug-assertions = false

This is not a good idea. This is not even a bad idea. This is a terrible idea. This disables all debug assertions, even unrelated ones, and just silences the UB without actually solving it. But this may be the best you can get.
A better option is to patch the dependency to avoid the UB. Patch the users dependency and replace the code at src/base.rs lines 291-306 (the whole members() function) from:
unsafe fn members(groups: *mut *mut c_char) -> Vec<OsString> {
    let mut members = Vec::new();

    for i in 0.. {
        let username = groups.offset(i);

        if username.is_null() || (*username).is_null() {
            break;
        }
        else {
            members.push(from_raw_buf(*username));
        }
    }

    members
}

To:
unsafe fn members(groups: *mut *mut c_char) -> Vec<OsString> {
    let mut members = Vec::new();

    for i in 0.. {
        let username = groups.offset(i);

        if username.is_null() || username.read_unaligned().is_null() {
            break;
        }
        else {
            members.push(from_raw_buf(username.read_unaligned()));
        }
    }

    members
}

You may want to send a PR, but I have no idea if this is a bug in the OS or in the documentation so I have no idea if this should be fixed in the Rust library.


Java Printing ArrayList of ArrayList

Question: I am trying to print my arraylist but i don't know why my printing does not print line by line of IntegerPair in each index of Adjlist:
 private ArrayList<ArrayList<IntegerPair>> AdjList; //outer arraylist
 private ArrayList<IntegerPair> storeNeighbour; //inner arraylist
 private IntegerPair pair;

This is my snippet:
for (ArrayList<IntegerPair> l1 : AdjList) {
  for (IntegerPair n : l1) {
    System.out.println( n + "# ");
  }
}

Comment: Can you add your expected output and the output you are currently getting to the question?
Comment: And what is the output? Something like `IntegerPair@...`? If so, read JavaDoc for `Object.toString()` ;-)
Comment: the code looks to work, are those lists empty???
Comment: What is `IntegerPair` class? Is it yours?
Answer: The default behavior of ArrayList.toString() is to return a single string containing a (somewhat) beautified list of calls to toString() on each element in the list.
So, long story short: you are almost there; the one thing that is missing:
@Override
public String toString() {
...

within your class IntegerPair.
Like:
public class IntegerPair {
  private final Integer first;
  private final Integer second;
  ...
  @Override
  public String toString() {
    return "(" + first + "/" + second ")";
  }

or something alike. Without overriding toString() your class will fall back on the default implementation given in java.lang.Object; and that method returns class name + hashcode number (and is thus not so human-readable).
Answer: Here :
for (ArrayList<IntegerPair> l1 : AdjList) {
    for (IntegerPair n : l1) {
        System.out.println( n + "# ");
    }
}

You don't differentiate each printed List.
As a result, you will have a series of output without knowing those associated to a same list.
A more readable print would be :
for (ArrayList<IntegerPair> l1 : AdjList) {
    System.out.println("ArrayList with :");
    for (IntegerPair n : l1) {
        System.out.println( n + "# ");
    }
}

You don't specify your output. So I don't suppose toString() is or not overridden. If it is not overridden you should either override it to render the String expected here :   System.out.println( n + "# ");, or you should specify the content to render here :
System.out.println( n.getOne() + "," + n.getOther()  + "# ");

As a side note, toString() is designed for debugging/logging, not for displaying functional messages as an object could be rendered in a way for a case and in another way for other cases.

Java Printing ArrayList of ArrayList


Where are the highlight definitions inside of my shader?

Question: I have a pretty good glow shader going now thanks to some tips from people here.
However there are a few things that bother me that could maybe be better.
#1 Definition of the particles
A lot of times if the particles are moving a lot it just looks like a single sheet of color. The image below is zoomed in so you can see a bit more definition, but zoomed out and real time it just looks like a sheet of sorts

#2 The particles don't look like they are neon
I mean I don't want the effect to be huge but when they are grouped together I would hope for them to have some white highlighting in the glow.
It looks like this:

When it should look more like this (this was just a mockup by blending in an additive copy of it with more contrast) when particles are grouped together [However singular particles shouldn't have white highlights]:

Here is my current rendering process:
I have a couple FBO's with texture attachments:

Drawing Frame: Never cleared, up-scaled for the purposes of anti-aliasing
Smaller Frame: Cleared each frame, exact resolution of screen, Draws the drawing frame on it with the darkest parts cut out
Horizontal Blur: Cleared each frame, does a horizontal blur (lower resolution than screen)
Vertical Blur: Cleared each frame, blurs the horizontal blur vertically (lower resolution then screen)
Front buffer: Draws the Smaller frame, and Vertical Buffers on top of each-other to the screen.

So A typical render might look like this (I apologize for the misalignment and cropping, the Xcode frame debugger allows you to peek at FBO's but not export the texture inside of them I had to use screenshots)

To combine the two textures I am using this
gl_FragColor = vec4(clamp(texture2D(s_texture, v_texcoord).xyz, 0.,
1.) + (clamp(texture2D(s_texture2, v_texcoord).xyz, 0., 1.) * 1.5),
1.0);

And for the two blurs I am using code like this, a lot of this is pre-computed but to make it easier to read I put how I computed it.
float Gaussian(float x, float deviation)
{
    return (1.0 / sqrt(2.0 * 3.141592 * deviation)) * exp(-((x * x) / (2.0 * deviation)));
}
vec3 blurS15()

{
    vec3 blr = vec3(0.0);

    float scalart =  (1 / screenResolution.x) * (1.0 / 7.0) * 14.0;
    float deviationScale = 1.2;
    float finalScalar = 1.1;

    blr += texture2D(s_texture, (v_texcoord + vec2(7.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(7.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(6.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(6.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(5.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(5.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(4.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(4.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(3.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(3.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(2.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(2.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(1.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(1.0, 7.0 * deviationScale) ;

    blr += texture2D(s_texture, (v_texcoord + vec2(0.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(0.0, 7.0 * deviationScale) ;

    blr += texture2D(s_texture, (v_texcoord + vec2(-1.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-1.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(-2.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-2.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(-3.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-3.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(-4.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-4.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(-5.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-5.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(-6.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-6.0, 7.0 * deviationScale) ;
    blr += texture2D(s_texture, (v_texcoord + vec2(-7.0 * scalart, 0.0))).xyz *  finalScalar * Gaussian(-7.0, 7.0 * deviationScale) ;

    return blr; //This gets put into gl_FragColor
}

Now while the issue could be in how I calculate the blur, and combine it I think it is more likely that the issue is in the way I render the particles. Basically each particle is rendered with a circle and a rectangle each frame. The dot marks where it is, and the rectangle connects it the the previous frame. Each new frame the previous frame is faded and then drawn over.
Here is a diagram of the process, each new hue group represents a new frame, sorry for the childish look of the colors.

I do this using two draw calls, one that draws the rectangles (GL_TRIANGLES with indices), and one that draws the circles (GL_POINTS with outsides alpha set to 0).
While this allows me to quickly simulate an accumulation buffer it comes with some drawbacks, if these can be dealt with without compromising speed then it would be nice to change them.

No actual depth sorting, although the particles could easily have z values it is futile because opengles 2.0 will go black if you don't clear the depth buffer each frame, so it cant really work with an accumulation buffer.
No additive drawing

Because there are two separate draw calls, even with that setting on nothing seems to draw additively inside of the same draw call
Even if I did the area where the circle and rectangle meet would be extra bright which is undesirable

The additive mode I tried was
glBlendFunc(GLenum(GL_ONE), GLenum(GL_ONE))
glEnable(GLenum(GL_BLEND));

To be specific when I said it didn't work I tried disabling it before fade, and then enabling it afterwards. It caused everything to look weird almost as if there were no trails. And there didn't seem to be highlights where particles intersect. However if I had it enabled the whole time then it did look like additive blending. Only the previous frame never faded because you can't draw black in add blend mode.
If you can think of any way I can get more highlighting especially when particles collide, or otherwise make the glow effect look better please let me know.
I am very curious if there is a way to still do depth sorting with an accumulation buffer/a way to not have to clear the depth buffer.
Answer: In order to achieve the "white" glow effect for amassed particles, you should probably switch to HDR rendering and have your tone mapping operator desaturate the "overbright" pixels. So you'll need a higher-precision, floating point render target (e.g. RGBA1010102, or RGBA16F) and a post-process step to bring  that down to the LDR system back-buffer. Then just make sure that your colliding particles add up to a sufficiently high colour value (i.e. over 1.0) and the tone mapper should do the trick.
You may easily simulate an accumulation buffer by using the ping-pong pattern for your render targets:

Render frame #0 to FBO A.
Render frame #1 to FBO B, taking FBO A as history (i.e. hitherto accumulation) input.
Render frame #2 to FBO A, taking FBO B as history input.
Repeat from point 2.

In particular, you could have a moving average in order for the particles to leave nice trails like that. Check out Brian Karis's presentation on Unreal Engine 4's temporal supersampling - slides 15-17 describe the moving average-based blend weighting.
Comment: Actually, that should be taken care of by the moving average. If new pixel's value is:

`gl_FragColor = weight * current + (1.0 - weight) * history`

Then note that the contribution to the final image of a particular frame will simply approach zero over time by principle of diminishing weight, thus fading away.

There is no need to clear the RT, then, just overwrite it with each ping-pong.
Comment: Isn't this the same as Alpha blending?
Comment: For your last comment, do you mean that moving average should be used for the simulated accumulation buffer?  Aren't you missing a step where you draw a fullscreen black quad to "erase" the buffer lest it blow out to white?
Comment: As long as you don't need to accumulate alpha, it is so indeed, since you can put weight in the alpha channel.


Can any information be gathered from the list of people who did or did not vote

Question: I have found out to my surprise that the list of who did or did not vote is publically available in Texas.
My question is, can information regarding my preference be ascertained by the fact that I decided not to vote.
If I vote: my options are (a) YES, (b) NO or possible (c) Register to vote and then not actually vote.
If I decide not to vote - apparently the list is available to registered interest groups : NOT VOTING can mean (a) Im not interested in voting, (b) Im voting with the 'majority' of the electorate.
Somehow, it seems that having a list of specific people who decided to vote or not vote mathematically allows interested groups to gather more more information about me personally than if I went to vote and chose a/b/c (if indeed c is really an option)
I am offended that the list of who voted and who did not vote, has been made available in the public domain. So, is there any basis in mathematic probability for me to be concerned?
Answer: Denote by $A$ that you support candidate $A$, and denote by $V$ that you voted.
Your question amounts to:

Given that someone did not vote, what is the probability that they support $A$: $P(A \mid \neg V)$?

Mathematically, we can use the total probability law:
$$\begin{align*}
P(A) &= P(A \mid V) P(V) + P(A\mid \neg V)P(\neg V) \\
 &= P(A \mid V) P(V) + P(A\mid \neg V)(1-P(V) )\end{align*}$$
$$P(A\mid \neg V) = \frac{P(A)-P(A\mid V)P(V)}{1-P(V)}.$$
Using the poll data, we can compute some of these quantities:
$$P(A\mid \neg V) = \frac{\overbrace{P(A)}^{\substack{\color{green}{\textrm{infer from}} \\ \color{green}{\textrm{phone polls}}}}-\overbrace{P(A\mid V)}^{\color{red}{\textrm{actual election tally}}} \overbrace{P(V)}^{\color{blue}{\substack{\textrm{% of voting} \\ \textrm{registered voters}}}}}{1-\underbrace{P(V)}_{\color{blue}{\substack{\textrm{% of voting}\\\textrm{registered voters} }}}}.$$
The big stretch is computing $P(A)$, since it's basically impossible to determine. However, pre-election phone polling does sample from both people who do and do not vote, so it may be sufficiently accurate.
Comment: Now, whether you have cause to worry... probably not. Suppose Candidate A is polling at 61%, and the final tally turns out as 55% for A, 45% for B, with a 30% voter turnout. This suggests that the likelihood of any non-voter to support Candidate A is about 63.6%, which is close enough to the phone polling that it is functionally indistinguishable. It gets more interesting the higher the turnout gets.


Azure TimerTrigger is not working in .NET 7 Isolated Worker Process

Question: I'm trying to trigger an orchestrated function TimerTrigger in .NET 7. Below is the function I created
    [Function(nameof(FunctionSampleTimer))]
    public async Task Run([TimerTrigger("*/5 * * * * *", RunOnStartup = false)] MyInfo myTimer, [DurableClient] DurableTaskClient client, FunctionContext context)
    {
        var instanceid = Guid.NewGuid().ToString();
        var logger = context.GetLogger("TimerFunction");
        logger.LogInformation($"Function Ran. Next timer schedule = {myTimer.ScheduleStatus.Next}");
    }

The above function is getting triggered once every 5 seconds only for the first time when the project is created, and is not getting triggered again and getting stuck on that "Host lock lease acquired..." line.
Console output shows this:
[2023-02-20T01:26:52.843Z] Azure Functions .NET Worker (PID: 49120) initialized in debug mode. Waiting for debugger to attach...
[2023-02-20T01:26:53.305Z] The next 5 occurrences of the 'FunctionSampleTimer' schedule (Cron: '0,5,10,15,20,25,30,35,40,45,50,55 * * * * *') will be:
[2023-02-20T01:26:53.307Z] 02/19/2023 17:26:55-08:00 (02/20/2023 01:26:55Z)
[2023-02-20T01:26:53.308Z] 02/19/2023 17:27:00-08:00 (02/20/2023 01:27:00Z)
[2023-02-20T01:26:53.309Z] 02/19/2023 17:27:05-08:00 (02/20/2023 01:27:05Z)
[2023-02-20T01:26:53.310Z] 02/19/2023 17:27:10-08:00 (02/20/2023 01:27:10Z)
[2023-02-20T01:26:53.311Z] 02/19/2023 17:27:15-08:00 (02/20/2023 01:27:15Z)
[2023-02-20T01:26:53.312Z]
[2023-02-20T01:26:53.323Z] Host started (775ms)
[2023-02-20T01:26:53.324Z] Job host started
[2023-02-20T01:26:54.472Z] {
[2023-02-20T01:26:54.473Z]   "ProcessId": 49120,
[2023-02-20T01:26:54.474Z]   "RuntimeIdentifier": "win10-x64",
[2023-02-20T01:26:54.475Z]   "WorkerVersion": "184.108.40.206",
[2023-02-20T01:26:54.476Z]   "ProductVersion": "1.8.0-local202209270007\u002B04ccbd8e45bb9017dc30ff5e1343e893a216e173",
[2023-02-20T01:26:54.477Z]   "FrameworkDescription": ".NET 7.0.0",
[2023-02-20T01:26:54.478Z]   "OSDescription": "Microsoft Windows 10.0.22621",
[2023-02-20T01:26:54.479Z]   "OSArchitecture": "X64",
[2023-02-20T01:26:54.480Z]   "CommandLine": "C:\\Users\\swkandhi\\source\\repos\\FunctionTimerTrigger\\FunctionTimerTrigger\\bin\\Debug\\net7.0\\FunctionTimerTrigger.dll --host 127.0.0.1 --port 58647 --workerId e70ddb42-819a-45b2-a17c-dca35392699d --requestId 326e359b-9d29-4105-b2f1-9ef01892ae95 --grpcMaxMessageLength 2147483647"
[2023-02-20T01:26:54.481Z] }
[2023-02-20T01:26:54.493Z] Worker process started and initialized.
[2023-02-20T01:26:55.053Z] Executing 'Functions.FunctionSampleTimer' (Reason='Timer fired at 2023-02-19T17:26:55.0194750-08:00', Id=872452e5-4d71-42ea-a16d-d4790ccf38a2)
[2023-02-20T01:26:57.821Z] Host lock lease acquired by instance ID '00000000000000000000000074E57A56'.

Answer: I have observed for every minute and couple of minutes in .NET 7 Isolated Azure Functions with generating the GUID Id, it is working successfully:
Below are my test cases:

For every
1st Run
Next Runs

2 minutes
Yes
Yes

1 minute
Yes
Yes

60 seconds
Yes
Yes

30 Seconds
Yes
No

5 Seconds
Yes
No

For every minute:

For every 2 minutes:

For every 60 Seconds:

For every 5 Seconds:

AFAIK, the shortest interval requires at least 60 seconds minimum in the CRON Expression - the same is mentioned in the articles of Hostinger - Cron Job Tutorial.
Comment: Crystal Clear Explanation..!
Answer: With what you have there for timing (5 * * * * *) I think it means it should run once at the 5 second mark. If you want it to run every 5 seconds you should do this (*/5 * * * * *)
Comment: no, it's still the same. I put a breakpoint inside the function and it's not hitting.
Comment: I think your method needs to be static, try that
Comment: yes I tried that too, but didn't work.
Comment: I don't see anything else wrong with the code then. Could be something to do with your project setup or your VS setup, make sure you are building the correct function if you have multiple ones in your solution?
Comment: Oh wait, what's that [Function….] attribute above your method? I think that's the wrong attitude name, i think it should be [FunctionName…]
Comment: no it's .NET 7. FunctionName has been changed to Function
Comment: I tried creating a new project and it did work for the first time. But when I ran again it's not triggering the function.


Outside Frost Proof Spigot sprays water

Question: I have a frost proof outside spigot. When I hook the hose to it, as much water comes out near the front of the spigot (not the top) as comes out of the end of the hose. What is wrong with it? Do I need to call a plumber and have the whole thing replaced?
Comment: Hello, and welcome to Stack Exchange. Is this only when you turn the spigot on? Could you post a picture (or a URL of a picture)?
Comment: Does the hose have a rubber washer in it?
Answer: Sounds like it has a vacuum-breaker, and the vacuum-breaker valve/disc is stuck or failed.
Or, depending on what you mean for the leak location, the packing on the valve stem is loose or needs to be replaced.

Outside Frost Proof Spigot sprays water


invisible items in Horizontal recyclerview

Question: I'm using GridLayoutManager to show some image in recyclerview with HORIZONTAL orientation.
But images are invisible in recyclerview. when i tap in the empty space it shows the image in another activity but they are invisible in the recyclerview. i have tried VERTICAL and they are prefectly fine and visible.
here is my fragment xml:
<RelativeLayout>
    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:rotation="180"
        android:scaleType="centerCrop"
        app:srcCompat="@drawable/page_start" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:visibility="visible"
        android:layout_height="match_parent" />

</RelativeLayout>

fragment.java :
RecyclerView rv;
    List<Cards> cardsList;
    Context context;

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getActivity();
        View rootView = inflater.inflate(R.layout.fragment_cards, container, false);

        readJson readJson = new readJson(context);
        cardsList = readJson.getcardsList();

        rv = rootView.findViewById(R.id.rv);

        rv.setLayoutManager(new GridLayoutManager(context, 3, GridLayoutManager.HORIZONTAL, false));
        rv.setAdapter(new CardsListAdapter(empty, context));

Answer: "rv.setLayoutManager(new GridLayoutManager(context, 3, GridLayoutManager.HORIZONTAL, false));"

use below line
rv.setLayoutManager(new GridLayoutManager(context, 3, GridLayoutManager.HORIZONTAL, true));

or
rv.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, true));

Comment: they are invisible too!


phpunit mock function inside value

Question: I am working with phpunit and trying to mock a wordpress page. I have done few steps but I count not able to achive a particulat scenario.
Following is My Parent function:
public static function getMyFavouritesList()
    {
        $userId = get_current_user_id();
        $myFavouites = get_user_meta($userId, 'wpfp_favorites', true);
        $myIncidents = get_user_meta($userId, 'favourite_incidents', true);

        $pages = array();
        $forumPosts = array();
        $userPosts = array();
        $incidents = array();

        $pageId = get_the_ID();

        if (is_array($myFavouites)) {
            foreach ($myFavouites as $favourite) {

                if ($pageId == $favourite) {
                    continue;
                }

                $favouritePost = get_post($favourite);
                if (!empty($favouritePost) && is_object($favouritePost)) {

                    // Get post last updated date from post reply
                    $args = array(
                        'orderby' => 'date',
                        'order' => 'DESC',
                        'posts_per_page' => '1',
                        'post_type' => 'reply',
                        'post_parent' => $favouritePost->ID
                    );//Facing issue while providing data to this block.
                    $lastModified = get_posts($args);
                    if (isset($lastModified{0}->post_modified)) {
                        $postModified = $lastModified{0}->post_modified;
                    } else {
                        $postModified = $favouritePost->post_modified;
                    }

                    $favouriteDetail = array(
                        'id' => $favouritePost->ID,
                        'title' => $favouritePost->post_title,
                        'url' => get_permalink($favouritePost->ID),
                        'date' => date("d F Y", strtotime($postModified)),
                    );
                    if (in_array($favouritePost->post_type, array('page'))) {

                        $pages[] = $favouriteDetail;
                    } elseif (in_array($favouritePost->post_type, array('forum', 'topic'))) {

                        $forumPosts[] = $favouriteDetail;
                    }
                }
            }
        }
}

Following is the PHPunit test code for the above block:
public function testGetMyFavouritesListForPage($post, $currentPostId, $userMeta, $expected, $userPosts)
    {
        $GLOBALS['post'] = $post;
        $GLOBALS['get_ID'] = $currentPostId;
        $GLOBALS['user_meta'] = $userMeta;
        $GLOBALS['posts'] = $userPosts;

        $result = MyFavourites::getMyFavouritesList();
        $this->assertEquals($expected, $result);
    }

public function dataProviderForMyFavourites()
    {
        $page = new \stdClass();
        $page->ID = 1;
        $page->post_title = 'page title';
        $page->post_modified = '2014-06-30 14:50:04';
        $page->post_type = 'page';
$favouriteIncidents = array( 0 => array('id' => '15', 'name' => 'Incident name'));

$incidentsExpected = '
';
        $incidentsExpected .='
Pages
';
        $incidentsExpected .='
';
        $incidentsExpected .='

Page	';
        $incidentsExpected .='Last updated	';
        $incidentsExpected .='Remove	';
        $incidentsExpected .='Print
';
        $incidentsExpected .='
page title	';
        $incidentsExpected .='26 August 2014	';
        $incidentsExpected .='	';
        $incidentsExpected .='

';
        $incidentsExpected .='

';
        $incidentsExpected .='
Forum posts
';
        $incidentsExpected .='
You have no favourite forum posts

';
        $incidentsExpected .='
';
        $incidentsExpected .='
Your posts
';
        $incidentsExpected .="
You haven't created any forum posts yet

";
        $incidentsExpected .='

Incidents
';
        $incidentsExpected .='

';
        $incidentsExpected .='Incidents	 	';
        $incidentsExpected .='Remove
';
        $incidentsExpected .='
Incident name	 	';
        $incidentsExpected .='';
        $incidentsExpected .='
';
        $incidentsExpected .='

';
return array(array($page, 1, $favouriteIncidents,  $incidentsExpected, ''));
}

My Problem is I couldnt able to provide date to this block:
$lastModified = get_posts($args);
                    if (isset($lastModified{0}->post_modified)) {
                        $postModified = $lastModified{0}->post_modified;
                    } else {
                        $postModified = $favouritePost->post_modified;
                    }

Any help.! Thanks!
Answer: The problem is that the code access the database. You should either provide the dataset, so the code loads the correct posts from the database (using either fixtures or factories), or you should stub the get_posts function (you can do this by putting the test in a namespace and defining get_posts function in that namespace)

phpunit mock function inside value


How to fix hiding for the first three turns when replaying a game of Tic Tac Toe in C++?

Question: I am creating a game of Tic Tac Toe in C using a console based interface. Two players go against each other by choosing a number from 1-9 to place their pieces on the board. I have this strange issue that when the game is completed (Such as if one player wins the game or the game ends in a draw). The user(s) is offer a prompt to play again.
If the player types in "Y" to play again, the board is cleared and then is shown up again. However for the first three turns, when the player types a number to choose a position on the board, the console will give out an "error" saying "This move is invalid because this space has been claimed", however on the fourth turn, the game carries on as normal with all the pieces the players previously selected during this round is now displayed on the board with no "errors" printed to the user. Is there anyway to fix this strange glitch? Sorry if I worded this poorly. Thank you.
//Libaries
#include <iostream>
#include <string>
#include <array>
#include <limits>

using namespace std;
//Indentifers
void gamescreen(); //Used to display the board
char gamecondition(); //This is indentifer is used to check the game is won lost/draw
void playerturn();
void playernames();
int resultsscreen();
int turn;
int playerinput(int playerchoice);
int Player1Score, Player2Score;

//Variables
//int menuchoice; //Not Neeeded for now
char PlayerPiece = 'X';
char GameWinner; //Declare for game winner
char board[3][3] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //Creates a 3 by 3 matrix, which is basically the board.
int playerchoice; //Reason why playerchoice is a int rather than a char is because
string Player1Name, Player2Name, Player;
char finalchoice;

void playernames()
{
    cout << "Player 1 please enter your name" << endl; //Asks for the first username
    cin >> Player1Name; // Gets the first user name
    cout << "Player 2 please enter your name" << endl; //Asks for the second username
    cin >> Player2Name; // Gets the second user name
    cout << "Player 1 Name is: " << Player1Name << " " << "and Player 2 name is: " << Player2Name << endl; //Displays Usernames
}

void gamescreen() //Displays the board on the screen to the players
{
    system("cls"); //CLears the screen again, to make the game clean and tidy
    cout << "SCOREBOARD: " << Player1Name << ": " << Player1Score << " " << Player2Name << ": " << Player2Score << endl;
    cout << "\n" << endl;

    cout << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
    cout << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
    cout << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
}

void playercheck()
{
    if (PlayerPiece == 'X')
    {
        cout << "It is " << Player1Name << " Turn, please put select a piece on the board" << endl;
    }
    if (PlayerPiece == 'O')
    {
        cout << "It is " << Player2Name << " Turn, please put select a piece on the board" << endl;
    }
    cin >> playerchoice;
    playerinput(playerchoice);
}

int playerinput(int playerchoice)
{
    if (playerchoice > 9 || playerchoice < 1 || cin.fail())
    {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Please enter a number from 1-9!" << endl;
        playercheck();
    }
    else
    {
        if (playerchoice == 1) //If the player chose this one then
        {
            if (board[0][0] == '1') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[0][0] = PlayerPiece; //If the condition is true, then it replaces that board space with the player piece
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else if (playerchoice == 2) //If the player chose this one then
        {
            if (board[0][1] == '2') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[0][1] = PlayerPiece;
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else if (playerchoice == 3) //If the player chose this one then
        {
            if (board[0][2] == '3') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[0][2] = PlayerPiece;
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else if (playerchoice == 4) //If the player chose this one then
        {
            if (board[1][0] == '4') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[1][0] = PlayerPiece;
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else if (playerchoice == 5) //If the player chose this one then
        {
            if (board[1][1] == '5') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[1][1] = PlayerPiece;
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else if (playerchoice == 6) //If the player chose this one then
        {
            if (board[1][2] == '6') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[1][2] = PlayerPiece;
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else if (playerchoice == 7) //If the player chose this one then
        {
            if (board[2][0] == '7') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[2][0] = PlayerPiece;
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else if (playerchoice == 8) //If the player chose this one then
        {
            if (board[2][1] == '8') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[2][1] = PlayerPiece;
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else if (playerchoice == 9) //If the player chose this one then
        {
            if (board[2][2] == '9') //This turns the number into a position on the board, it checks if the place is valid and there isn't a position on the board. If so then it places the player piece down
                board[2][2] = PlayerPiece;
            else
            {
                cout << "This move is invalid because this space has been claimed" << endl; //However if there was not a space or the player just decides to put a number other than 1-9 then this message pops up
                playercheck(); //This function is called again to elimate the need for loops.
            }
        }
        else
        {
            cout << "Please enter in a valid number!" << endl;
            playercheck();
            //Fail safe just in case the first one failed somehow.
        }
    }
    //The if statements about choices, etc. Checking if this space has not been picked yet

    //NEED TO CHANGE ALL OF THE NUMBERS
    return 1;
}

void playerturn()
{
    if (PlayerPiece == 'X')
        PlayerPiece = 'O';
    else
        PlayerPiece = 'X';
}

char gamecondition() //This is used to check the win conidtion aka who won or if not how does this game draw?
{
    //Checks for the first player
    if (board[0][0] == 'X' && board[0][1] == 'X' && board[0][2] == 'X')
        return 'X'; //Basically this checks if the there is three in a row in the board, if show it returns the value X, which will be shown in the main. (Basically if GameWinner == X, cout << "Player1 wins!" << endl;
    if (board[1][0] == 'X' && board[1][1] == 'X' && board[1][2] == 'X')
        return 'X';
    if (board[2][0] == 'X' && board[2][1] == 'X' && board[2][2] == 'X')
        return 'X';
    if (board[0][0] == 'X' && board[1][0] == 'X' && board[2][0] == 'X')
        return 'X';
    if (board[0][1] == 'X' && board[1][1] == 'X' && board[2][1] == 'X')
        return 'X';
    if (board[0][2] == 'X' && board[1][2] == 'X' && board[2][2] == 'X')
        return 'X';
    if (board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X')
        return 'X';
    if (board[2][0] == 'X' && board[1][1] == 'X' && board[0][2] == 'X')
        return 'X'; //Returns X to the gamecondition()

                    //Checks for the second player
    if (board[0][0] == 'O' && board[0][1] == 'O' && board[0][2] == 'O')
        return 'O'; //Basically this checks if the there is three in a row in the board, if show it returns the value X, which will be shown in the main. (Basically if gameconidition == X, cout << "Player1 wins!" << endl;
    if (board[1][0] == 'O' && board[1][1] == 'O' && board[1][2] == 'O')
        return 'O';
    if (board[2][0] == 'O' && board[2][1] == 'O' && board[2][2] == 'O')
        return 'O';
    if (board[0][0] == 'O' && board[1][0] == 'O' && board[2][0] == 'O')
        return 'O';
    if (board[0][1] == 'O' && board[1][1] == 'O' && board[2][1] == 'O')
        return 'O';
    if (board[0][2] == 'O' && board[1][2] == 'O' && board[2][2] == 'O')
        return 'O';
    if (board[0][0] == 'O' && board[1][1] == 'O' && board[2][2] == 'O')
        return 'O';
    if (board[2][0] == 'O' && board[1][1] == 'O' && board[0][2] == 'O')
        return 'O';

    else
        return '/'; //If it isn't either O or X then returns '/' which shows it's a draw
}

int main()
{
    playernames();
    turn = 0; //This is a turn counter, this will be used to determine the draw (Without it the game will keep on going)
    gamescreen(); //Displays the game screen again
    while (1)
    {
        turn++; //If the game hasn't been completed yet then adds 1 to the number counter
        playercheck();
        gamescreen();
        if (gamecondition() == 'X')
        {
            cout << Player1Name << " wins!" << endl;
            Player1Score++;
            resultsscreen();
        }
        else if (gamecondition() == 'O')
        {
            cout << Player2Name << " wins!" << endl;
            Player2Score++;
            resultsscreen();
        }
        else if (gamecondition() == '/' && turn == 9)
        {
            cout << "It's a draw!" << endl;
            resultsscreen();
        }
        playerturn();
    }
}

int resultsscreen()
{
    cout << "The current score is:" << endl;
    cout << Player1Name << ":" << Player1Score << endl;
    cout << Player2Name << ":" << Player2Score << endl;
    cout << "Would you like to play again, Y/N?" << endl;

    cin >> finalchoice;

    if (finalchoice == 'Y' || finalchoice == 'y')
    {
        turn = 0;
        board[0][0] = '1', board[0][1] = '2', board[0][2] = '3';
        board[1][0] = '4', board[1][1] = '5', board[1][2] = '6';
        board[2][0] = '7', board[2][1] = '8', board[2][2] = '9';
        system("cls");
        gamescreen();
        playercheck();
        playerturn();
        playerinput(playerchoice);
    }
    if (finalchoice == 'N' || finalchoice == 'n')
    {
        if (Player1Score > Player2Score)
        {
            cout << Player1Name << " wins!" << endl;
            system("pause");
            exit(0);
        }
        if (Player1Score < Player2Score)
        {
            cout << Player2Name << " wins!" << endl;
            system("pause");
            exit(0);
        }
        else if (Player1Score == Player2Score)
        {
            cout << "It's a draw!" << endl;
            system("pause");
            exit(0);
        }
    }
    return 0;
}

Comment: It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming.  Further reading: **[How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)**
Comment: Yes, there is. It is called "debugging". Using a debugger is one of a good way of debugging. Another way is to print information to check.
Comment: Why are you calling `gamescreen()`, `playercheck()`, etc. in `resultscreen()` when you already call all of those things in the main loop?
Comment: This is some seriously ugly code. Functions should perform a well defined task, and then return. They should not be used as a goto. Why are you trying to avoid loops?
Answer: you are calling
playerinput();
playercheck();
gamescreen();

Functions from
resultsscreen();

which is unnecessary and causing your problem. Remove these function from resultsscreen() as they will be called again in you main function loop if the user choose to continue the game(and hence the reason it shows the slot is already taken).