text:
Q: Unit testing a List Being new to unit testing and test driven development, I'm having difficulty with unit testing a new function I just wrote for the project I'm working on.  I need to parse data from a webpage and store key pieces of data for storage later in the database.  I created a struct to hold the individual records I will need and I created a list of the struct to hold all of the collected data and then pass back the said List when the data is parsed.  Everything works as expected but the unit test fails??  I can't figure out why...Please help!!
Here is the struct and function:
//===================================================================================================================
    /// lsBuildInstalData
    ///
    ///                    This function will parse out the required data from the input list and store it in a private struct.
    ///                    Year (allowing up to 10) : Instalment Amount (pick up the first 4 and skip the rest) : Values (3 values; Year/InstalAmt/Due)
    ///
    ///
    /// Parameters
    /// <param name="sTaxDataLine">   Data to parse the values out of.</param>
    ///
    /// <returns>          Struct List<> of the parsed values.</returns>
    ///
    /// DataBase Use       N/A
    ///
    /// Change Log         04/23/14   MS   Initial development.
    ///
    //===================================================================================================================
    public struct InstalData
    {
        // -- Set the properties...
        private string sDueAmt, sInstalAmt, sYear;
        public string DueAmt
        {
            get
            {
                return sDueAmt;
            }
            set
            {
                if (value.IsNotNullOrEmpty())
                    sDueAmt = value;
            }
        }
        public string InstalAmt
        {
            get
            {
                return sInstalAmt;
            }
            set
            {
                if (value.IsNotNullOrEmpty())
                    sInstalAmt = value;
            }
        }
        public string Year
        {
            get
            {
                return sYear;
            }
            set
            {
                if (value.IsNotNullOrEmpty())
                    sYear = value;
            }
        }
    }
    private List<InstalData> lsBuildInstalDataArray(List<string> lsTaxDataLine)
    {
        // -- Create the struct and list to pick up all the install data so we can store it correctly later...
        InstalData sID                = new InstalData();
        List<InstalData> lsInstalData = new List<InstalData>();

        // -- Loop through the data, pull what we need, and build the array...
        foreach (string sLine in lsTaxDataLine)
        {
            sID.Year      = sGetParsedValue("Year", sLine);
            sID.InstalAmt = sGetParsedValue("Instal", sLine);
            sID.DueAmt    = sGetParsedValue("Due", sLine);

            // -- ONLY pick up data when there is 'Prinicipal' or 'Surchareg'...
            if ((FSH.Pos("Principal", sLine) > 0 || FSH.Pos("Surcharge", sLine) > 0) && sID.DueAmt != "0.00")
                lsInstalData.Add(sID);
        }

        // -- Return the final array...
        return lsInstalData;
    }

Here is the unit test with the commented out code of writing the list to a file for my own debugging purposes to show that the data is the same.
[TestClass]
public class OR_CK_WTax_Tests
{
    // -- Create the instance of the Scrape for the public function(s)...
    OR_CK_WTax _Scrape;

    // -- Create the instance of the main class to create a link to the targeted private function(s)...
    PrivateObject poScrape = new PrivateObject(typeof(OR_CK_WTax));

    [TestInitialize]
    public void InitializeScript()
    {
        _Scrape = new OR_CK_WTax();
    }

    [TestMethod]
    public void OR_CK_WTax_lsBuildInstalDataArray_Success()
    {
        // -- Arrange...
        List<string> lsRecordList              = new List<string>();
        lsRecordList.Add("
1993	Property Tax Interest	086-002	2,502.00	0.00	0.00	11/15/1993

1994	Property Tax Principal	086-002	3,148.75	0.00	200.00	11/15/1994

1995	Property Tax Principal	086-002	2,753.00	0.00	200.00	11/15/1995

1996	Property Tax Principal	086-002	2,925.70	0.00	200.00	11/15/1996

1997	Property Tax Principal	086-002	2,691.46	0.00	200.00	11/15/1997

1998	Property Tax Principal	086-002	2,745.44	0.00	200.00	11/15/1998

1999	Property Tax Principal	086-002	2,773.58	0.00	200.00	11/15/1999

2000	Property Tax Interest	086-042	3,125.79	0.00	0.00	11/15/2000

2001	Property Tax Interest	086-042	3,243.49	0.00	0.00	11/15/2001

2002	Property Tax Interest	086-042	3,349.15	0.00	0.00	11/15/2002

2003	Property Tax Interest	086-042	3,471.05	0.00	0.00	11/15/2003

2004	Property Tax Interest	086-042	3,556.47	0.00	0.00	11/15/2004

2005	Property Tax Interest	086-042	3,609.72	0.00	0.00	11/15/2005

2006	Property Tax Interest	086-042	3,591.16	0.00	0.00	11/15/2006

2007	Property Tax Interest	086-042	3,737.88	0.00	0.00	11/15/2007

2008	Property Tax Interest	086-042	3,827.12	0.00	0.00	11/15/2008

2009	Property Tax Interest	086-042	4,124.05	0.00	0.00	11/15/2009

2010	Property Tax Principal	086-042	4,233.20	0.00	0.00	11/15/2010

2010	Fire Patrol District Surcharge	086-042	4,333.20	0.00	0.00	11/15/2010

2011	Fire Patrol District Surcharge	086-042	4,352.73	0.00	0.00	11/15/2011

2011	Property Tax Interest	086-042	2,534.73	0.00	0.00	11/15/2011

2012	Property Tax Principal	086-042	4,483.61	0.00	0.00	11/15/2012

2013	Fire Patrol District Principal	086-042	4,630.42	0.00	0.00	11/15/2013

2013	Fire Patrol District Surcharge	086-042	4,666.42	0.00	666.00	11/15/2013

2013	Income Tax Principal	086-042	5,643.42	0.00	0.00	11/15/2013

2013	Property Tax Principal	086-042	3,639.42	0.00	0.00	11/15/2013
<TR");
        List<OR_CK_WTax.InstalData> lsExpected = new List<OR_CK_WTax.InstalData>();
        OR_CK_WTax.InstalData sID              = new OR_CK_WTax.InstalData();
        sID.Year                               = "1994";
        sID.InstalAmt                          = "3,148.75";
        sID.DueAmt                             = "200.00";
        lsExpected.Add(sID);
        sID.Year                               = "1995";
        sID.InstalAmt                          = "2,753.00";
        sID.DueAmt                             = "200.00";
        lsExpected.Add(sID);
        sID.Year                               = "1996";
        sID.InstalAmt                          = "2,925.70";
        sID.DueAmt                             = "200.00";
        lsExpected.Add(sID);
        sID.Year                               = "1997";
        sID.InstalAmt                          = "2,691.46";
        sID.DueAmt                             = "200.00";
        lsExpected.Add(sID);
        sID.Year                               = "1998";
        sID.InstalAmt                          = "2,745.44";
        sID.DueAmt                             = "200.00";
        lsExpected.Add(sID);
        sID.Year                               = "1999";
        sID.InstalAmt                          = "2,773.58";
        sID.DueAmt                             = "200.00";
        lsExpected.Add(sID);
        sID.Year                               = "2013";
        sID.InstalAmt                          = "4,666.42";
        sID.DueAmt                             = "666.00";
        lsExpected.Add(sID);

        // -- Act...
        List<OR_CK_WTax.InstalData> lsActual = (List<OR_CK_WTax.InstalData>)poScrape.Invoke("lsBuildInstalDataArray", lsRecordList);   // -- Private

        // -- Assert...
        Assert.AreEqual(lsExpected, lsActual);
    }

}

Thanks for any help you can provide!!

A: You're asking MSTest to assert whether two lists are reference equal, which they are not, by using Assert.AreEqual(object, object).
Considering using the CollectionAssert class' methods, but you may need to individually test each item in your list as well as compare the sizes etc.
There's no magic "test that these two collections and their elements are exactly the same using the logical comparison a human would use" functionality, as it were.


text:
Q: PHP json_encode issue with array 0 key I am having a problem using json_encode to generate a json encoded string from an array.
The section of the array in question looks like this
RatingDistribution (Array, 11 elements)
    0 (Array, 1 element)
        0 (String, 3 characters ) 4.5
    1 (Array, 1 element)
        1 (String, 4 characters ) 11.9
    2 (Array, 1 element)

But produces this in the string:
"RatingDistribution":[["4.5"],{"1":"11.9"},

I would expect this:
"RatingDistribution":[{"0":"4.5"},{"1":"11.9"},

All I'm doing is this:
$result = json_encode($array);

Have I done something wrong or do I need more code to ensure the 0 key is present?
Cheers
Andy

A: If you want to use arrays in your json then instead of JSON_FORCE_OBJECT parameter you can simply cast array to object.
Problem:
json_encode([0 => [1,2,3]]); // Return: [[1,2,3]]
json_encode(["0" => [1,2,3]]); // Return: [[1,2,3]]
json_encode([1 => [1,2,3]]); // Return: {"1":[1,2,3]}

Not what we expect :
json_encode([0 => [1,2,3]], JSON_FORCE_OBJECT); // Return: {"0":{"0":1,"1":2,"2":3}}

Solution:
json_encode((object)[0 => [1,2,3]]); // Return: {"0":[1,2,3]}
json_encode(new \ArrayObject([0 => [1,2,3]])); // Return: {"0":[1,2,3]}

A: The result you are getting should be expected; json_encode detects that you are only using numeric keys in the array, so it translates that to an array instead of an object in JSON. Most of the time, that's exactly what you want to do.
If for some reason you don't (why?), in PHP >= 5.3 you can use the JSON_FORCE_OBJECT flag to get your desired output:
$result = json_encode($array, JSON_FORCE_OBJECT);

A: Cou can try to cast the array key to a string for example with strval or (string).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failure to Re-open File after Closing I have been working with some code that is meant to print a poem. The goal of the code is to make borders that will fit the poem's size. But that does not pertain to my issue. I have been trying to get the code to reprint a file, line for line, but ValueError: I/O operation on closed file. is all that is returned.
I've attempted to get around this by reopening the file after it's closed, and reopening it after the def poemprint(poem): function has completed. But both methods have failed. I don't know where to go from here.
import os
os.system("clear")

quitw=["no","n","ney","ne","nope","nuh-uh","nuh","noh","neigh","nye","negative","please no","no               please","quit","stop","q","s"]
harlem=open("harlem.txt","r")
hhop=open("hhop.txt","r")
poems={"1":harlem,"2":hhop}
poemname={"1":"harlem.txt","2":"hhop.txt"}

#10 lines of def quit() code

def poemprint(poem):
    print("╭"+"-"*60+"╮")
    print("|  Poem Printer [v0.5]"+" "*39+"|")
    print("⊢"+"-"*60+"⊣")
    print("|"+" "*60+"|")
    for a in poem: #line where error occurs
        b=57-len(a)
        print("|    "+a[0:len(a)-1]+(" "*b)+"|")
    print("|"+" "*60+"|")
    print("╰"+"-"*60+"╯")
    poem.close()
    if f=="harlem.txt": #doesn't work
        harlem=open("harlem.txt","r")
    elif f=="hhop.txt":
        hhop=open("hhop.txt","r")

c=(input("Enter a Poem: "))
if c not in quitw:
    while c not in quitw:
        while c.lower() in poems:
            os.system("clear")
            f=poemname[c]
            poemprint(poems[c])
            c=(input("Enter a Poem: "))
            if c in quitw:
                quit()
            else:
                continue
        os.system("clear")
        print("Invalid input.")
        c=(input("Enter a Poem: "))
else:
    quit()

Note: quit() is a defined function to stop the code entirely.
This is what I should be seeing after asking for the Harlem poem for the second time:
    ╭------------------------------------------------------------╮
    |  Poem Printer [v0.5]                                       |
    ⊢------------------------------------------------------------⊣
    |                                                            |
    |    Harlem by Langston Hughes                               |
    |                                                            |
    |      What happens to a dream deferred?                     |
    |                                                            |
    |        Does it dry up                                      |
    |        like a raisin in the sun?                           |
    |        Or fester like a sore—                              |
    |        And then run?                                       |
    |        Does it stink like rotten meat?                     |
    |        Or crust and sugar over—                            |
    |        like a syrupy sweet?                                |
    |                                                            |
    |        Maybe it just sags                                  |
    |        like a heavy load.                                  |
    |                                                            |
    |        Or does it explode?                                 |
    |                                                            |
    ╰------------------------------------------------------------╯

Instead, I'm getting:
    ╭------------------------------------------------------------╮
    |  Poem Printer [v0.5]                                       |
    ⊢------------------------------------------------------------⊣
    |                                                            |
    Traceback (most recent call last):
      File "main.py",line 44, in <module>
        poemsprint(poems[c])
      File "main.py",line 27, in poemprint
        for a in poem:
    ValueError: I/O operation of closed file.

A: Your steps are:

*

*You open a file in harlem variable

*You call poemprint function with harlem argument. This harlem is referenced as poem inside of the function.

*You close the file that poem references to (it is harlem outside of the function)

*You create a new variable harlem that exists only inside of the function

*After the function is done, you have harlem as a closed file

This happens because harlem in the poemprint and the one outside are different objects.
Short example:
def a():
    var = 2

var = 1
a()

print(var) #prints 1

You can read more about this in mgilson's answer on a question that covers similar problem and in the Python documentation.
How to fix:
Instead of opening the files, keep their names.
poems={"1":"harlem.txt","2":"hhop.txt"}

Then modify the function to get the filename as the argument and to open the file inside of the function.
def poemprint(poem):
    print("╭"+"-"*60+"╮")
    print("|  Poem Printer [v0.5]"+" "*39+"|")
    print("⊢"+"-"*60+"⊣")
    print("|"+" "*60+"|")

    poem = open(poem, "r") #This
    for a in poem:
        b=57-len(a)
        print("|    "+a[0:len(a)-1]+(" "*b)+"|")
    print("|"+" "*60+"|")
    print("╰"+"-"*60+"╯")
    poem.close()
    #End of the function

Now it should work.
Enter a Poem: 1
╭------------------------------------------------------------╮
|  Poem Printer [v0.5]                                       |
⊢------------------------------------------------------------⊣
|                                                            |
|    Roses are red                                           |
|    Violets are blue                                        |
|                                                            |
╰------------------------------------------------------------╯
Enter a Poem: 1
╭------------------------------------------------------------╮
|  Poem Printer [v0.5]                                       |
⊢------------------------------------------------------------⊣
|                                                            |
|    Roses are red                                           |
|    Violets are blue                                        |
|                                                            |
╰------------------------------------------------------------╯
Enter a Poem:

Here's the full code:
import os
os.system("clear")

quitw=["no","n","ney","ne","nope","nuh-uh","nuh","noh","neigh","nye","negative","please no","no               please","quit","stop","q","s"]
poems={"1":"harlem.txt","2":"hhop.txt"}

#10 lines of def quit() code

def poemprint(poem):
    print("╭"+"-"*60+"╮")
    print("|  Poem Printer [v0.5]"+" "*39+"|")
    print("⊢"+"-"*60+"⊣")
    print("|"+" "*60+"|")

    poem = open(poem, "r") #This
    for a in poem:
        b=57-len(a)
        print("|    "+a[0:len(a)-1]+(" "*b)+"|")
    print("|"+" "*60+"|")
    print("╰"+"-"*60+"╯")
    poem.close()

c=(input("Enter a Poem: "))
if c not in quitw:
    while c not in quitw:
        while c.lower() in poems:
            os.system("clear")
            f=poems[c]
            poemprint(poems[c])
            c=(input("Enter a Poem: "))
            if c in quitw:
                quit()
            else:
                continue
        os.system("clear")
        print("Invalid input.")
        c=(input("Enter a Poem: "))
else:
    quit()


text:
Q: How to strip GPS location data from an MP4 video file? I have a video file captured with a smartphone.
I want to remove the GPS location data written into it, leaving all other information intact. I tried some sed commands, but nothing seems to work.

A: You need to remux the video, removing the GPS location metadata.
You can use ffmpeg:
ffmpeg -i input.mp4 -metadata location="" -metadata location-eng="" -acodec copy -vcodec copy output.mp4

Then you can verify with ffprobe:
ffprobe output.mp4


text:
Q: How to find optimal value of a certain variable using neural networks? In a data science task I have some physical data from the instrument and need to predict continous time value. The data is divided into signal samples with some peaks occuring before that target time. In order to create new features I will have to use some statistical information about the signal - but not necessarily for the whole signal sample.
I was thinking about dividing the sample into chunks and use statistical data derived from these chunks as separate features.
I could divide the sample into say 1000 chunks. But it can be that such division doesn't make much sense. Maybe it would be better to get statistical info from the first 10% of the sample, then, say, last 20% and so on. Or at least use some other value for division based on the specific sample. Maybe for some samples dividing into 1000 chunks is good but for some others it should 500 or 2000 etc.
My idea was to use Neural Network to derive that division value (or maybe a few values, like the number of chunks and their sizes)
Does it makes sense at all and if yes, any ideas how to do that? It sounds like something like parameter optimisation using neural network but googling such thing didn't give me the required result.
Maybe someone stumbled upon similar problem?


text:
Q: What is VBA code error 1004 and how to solve it? It is showing error 1004  on ** --- ** line in this code. PLease help
Sub test()

Workbooks("OI ANALYSIS.xlsm").Activate
Sheet3.Select
Range("A16:C16").Copy

Sheet4.Select

**Range("B2").End(xlDown).Offset(1, 0).Select**

Selection.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False

Application.OnTime Now + TimeValue("00:00:01"), "test"
End Sub

A: Try this-
Sub test()

Workbooks("OI ANALYSIS.xlsm").Activate
Worksheets("Sheet3").Select
Range("A16:C16").Copy

Worksheets("Sheet4").Select

Range("B2").End(xlDown).Offset(1, 0).Select

Selection.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False

Application.OnTime Now + TimeValue("00:00:01"), "test"
End Sub

The Sheet3.Select syntax isn't correct in VBA. Run-time error 1004 is common when you don't specify the range correctly or when an invalid name is used.


text:
Q: Print out cycle of directed graph from adjacency matrix using DFS in C #include<stdio.h>
#include<stdlib.h>

int visited[100];

    int A[8][8] = {
        {0, 0, 0, 0, 0, 0, 0, 1},
        {0, 0, 1, 0, 0, 0, 0, 1},
        {0, 1, 0, 0, 1, 1, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 1, 0, 1},
        {0, 0, 0, 1, 0, 0, 0, 1},
        {0, 1, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 1, 0, 0, 0}
    };

void DFS(int i){
    printf("%d ", i);

  int back = 0;

    visited[i] = 1;

     for (int j = 0; j < 8; j++) {
        if (visited[j]) {
                if (back == 1 )  {
                        printf("\nrevisited: %d\n", j);
                }
        back = 1;
        }
        if(A[i][j]==1 && !visited[j]){
            DFS(j);
        }
    }
}

void DFSLinker() {
    for (int k = 0; k < 100; k++) {
        visited[k] = 0;
    }
    for (int k = 0; k < 8; k++) {
        if (visited[k] == 0) {
            DFS(k);
        }
    }
}

int main(){
    DFSLinker();
    return 0;
}

I have an adjacency matrix of an directed graph and I am trying to print out any one cycle in this directed graph.
So far, this code prints out the DFS traversal as well as any of the nodes that I have already visited while doing the DFS traversal.
I know that the cycles in this particular directed graph are as follows:
1 2
4 7
4 5 7

When I try to get the very last revisited nodes in order to print out a cycle, I get 7 5 7, which is not a valid cycle.
What am I missing?


text:
Q: In codeigniter api I am getting 400 bad request always in android but getting 200 in postman this is my code for registration I am getting 400 bad request in response always when I hit api in android but in postman i am getting 200 response whats wrong with me. Please Help. Here is my controller code.
its validating registration data and saving it.
public function register_user_get()
{

    $user_data = $_GET['user_details'];

    $user_details_arr = array();

    $user_details_arr = json_decode($user_data);

    $username_exist = $this->apilogin_model->check_username_exists($user_details_arr->username);
    if(!empty($username_exist))
    {
        $response = array(
            'message'=>'Username is already exist',
            'status'=>false
        );

        $this->response($response,200);
    }

    $referred_by = $user_details_arr->referred_by;  //'company';

    if($referred_by == 'company')
    {
        $referral_code = ROOT_REFERRAL_CODE;
        $user = $this->apilogin_model->get_user_details_by_referral_code($referral_code);

        if(empty($user))
        {
            // if referral code in invalid
            $response = array(
                'message'=>'Invalid Referral code',
                'status'=>false
            );
            $this->response($response,200);
        }
    }
    else if($referred_by == "manual")
    {
        $referral_code = $user_details_arr->referral_code;
        $user = $this->apilogin_model->get_user_details_by_referral_code($referral_code);

        if(empty($user))
        {

            $response = array(
                'message'=>'Invalid Referral code',
                'status'=>false
            );
            $this->response($response,200);
        }
    }
    else
    {

    }

    $parent_id = $user[0]->id;

    $data = array(
        'name' => $user_details_arr->name,
        'username' => $user_details_arr->username,
        'password' => md5($user_details_arr->password),
        'paytm_no' => $user_details_arr->paytm_no,
        'mobile_no' => $user_details_arr->mobile_no,
        'email_id' => $user_details_arr->email_id,
        'parent_id' => $parent_id,
        'referral_code' => $this->generate_code(), // for generate 10 digit unique referral code
        'is_deleted' => 'N',
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
    );

    $res = $this->apilogin_model->save_affiliate_data($data);
    $transaction_data = $this->parent_get($res,$parent_id,LEVEL_FOR_HELP);
    $child_arr = array(
                'sender_id' =>$res,
                'receiver_id' =>COMPANY_ID,
                'status'=>0,
                'created_at' =>date('Y-m_d H:i:s')
            );

    array_push($transaction_data,$child_arr);
    //$this->db->set($transaction_data);

    $this->db->insert_batch(DB_PREFIX.'_transaction', $transaction_data);

    if($res > 0)
    {
        // if data saved successfully
        $response = array(
            'message'=>'Registered Successfully',
            'status'=>true
        );

        $this->response($response,200);
    }
    else
    {
        // if data doesn't saved successfully
        $response = array(
            'message'=>'Registration Failed',
            'status'=>false
        );

        $this->response($response,200);
    }
}

while I am calling same function in postman it working fine but while trying with android I am getting 400 bad request even I am not responding 400 anywhere in my code.

A: The reason why you are getting 400 is that you are trying to pass not allowed character such as(@) to CodeIgniter without encoding it.
In order to fix this try to encode the inputs from your android side
Or enable some special character such as (@) which been used in your registration email,... from Code Igniter configuration.
$config['permitted_uri_chars']


text:
Q: Loop through multiple TD, grab multiple values, fill array I have two tables on the page.
Inside of my second table I am dynamically adding html from JS.
I am checking to see if the
 inside of the tbody are empty using:
var rowCount = $('#dynatable >tbody >tr').length;

If the row count is 0 I continue on with my javascript, if 1 or more
 exists I need to go through each
 and grab the two input values inside the ; for every
 available. Then need to collect the data into an array for server-side processing.

        Time
        Description

<input type="text" name="ts_value[]" class="timestamp_input"/>	<TEXTAREA NAME="ts_description[]" class="ts_desc" rows="3" cols="30"  style="resize:none;" ></TEXTAREA>

<input type="text" name="ts_value[]" class="timestamp_input"/>	<TEXTAREA NAME="ts_description[]" class="ts_desc" rows="3" cols="30"  style="resize:none;" ></TEXTAREA>

I have browsed similar questions but I cannot figure out a solution for my situation. I had a previous solution using simpleHTMLDOM + PHP but it's way too slow performance wise.
I was told to use JS or jquery and I am quite unfamiliar with both, any help is greatly appreciated.
How do I grab the values of multiple inputs from multiple
's inside a specific table and store the values in an array?

A: If your classes will be the same, you could do something like this with jQuery.
It put the values into arrays.
var values = $("input[class='timestamp_input']").map(function(){return $(this).val();}).get();

var textAreaValues = $("textarea[class='ts_desc']").map(function(){return $(this).val();}).get();

console.log(values);

console.log(textAreaValues);

JSFiddle demo here.


text:
Q: Static cell with TextField - connect class property to viewcontroller I want to be able to have a TextField in my static cells so I'm using the StringInputTableViewCell class from this demo: https://github.com/wannabegeek/PickerTableViewCell/tree/master/PickerCellDemo
I'm using storyboards and in my storyboard I got 2 cells that use the StringInputTableViewCell class. As you can see there is a UITextField property
@property (nonatomic, strong) UITextField *textField;

in StringInputTableViewCell.h. On storyboards in MyViewController I can connect the label, etc with a property but I cannot connect the TextField since its added in code and the TextField isn't on my storyboard. So my question is how do I get that property in MyViewController class?

A: You can make your "StringInputTableViewCell" a property within your "MyViewController", or if you're trying to populate it during "cellForRowAtIndexPath", you can get get access to it through an identifier or a tag.
Once you have a pointer to the "StringInputTableViewCell" object that's being displayed in your table, you can then access the "textField" property of it in your code directly.
Something like:
StringInputTableViewCell * stringInputCell = (StringInputTableViewCell *) cell;
if(stringInputCell)
{
    stringInputCell.textField.text = @"Surprise, I can put text in here!";
}


text:
Q: Redirecting users to different pages according to their id I need to Redirecting users to different pages according to their id
mysql db user table like below
"username=admin", "id=1" & "username=user", "id=2"
I had two pages index1.php & index2.php. I need, when I login admin open index1.php & login user open index2.php page i try to below code, but always open one page.
<?php
// connect to the database
$db = mysqli_connect('localhost:3308', 'root', '', 'inventory');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['submit'])) {
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);
    if (empty($username)) {
        array_push($errors, "Username is required");
    }
    if (empty($password)) {
        array_push($errors, "Password is required");
    }
    if (count($errors) == 0) {
        $password = md5($password);
        if (md5($_POST['password']) !== $password) {
            echo "Password is invalid";
        }
        $query = "SELECT * FROM register WHERE username='$username' AND password_1 ='$password'";
        $sql = "SELECT first_name,last_name FROM register WHERE username='$username' AND password_1 ='$password'";
        $result = mysqli_query($db, $sql);
        $row = mysqli_fetch_assoc($result);
        $results = mysqli_query($db, $query);
        $res = mysqli_num_rows($results);
        if ($res) {
            $_SESSION['username'] = $username;
            $_SESSION['first_name'] = $row["first_name"];
            $_SESSION['last_name'] = $row["last_name"];
            header('location: index.php');
        } else {
            array_push($errors, "Wrong username/password combination");
        }
    }
}

A: if($row["id"]==1)
{
  header('location: index1.php');
}
elseif($row["id"]==2)
{
  header('location: index2.php');
}
else
{
  header('location: index.php');
}


text:
Q: divides each element of the matrix by 2 if the element is an even number i need to write a function in python that takes a matrix as an argument and divides each element of the matrix by 2 if the element is an even number (otherwise, does nothing).
i also need to use list comprehension for this.
as an example, if i have a matrix like m = [[5, 4], [2, 3], [6, 7]] output: [[5, 2], [1, 3], [3, 7]]
Thanks.

A: def f(matrix):
    return [ [x//2 if x%2==0 else x for x in m ] for m in matrix]
print(f([[5, 4], [2, 3], [6, 7]]))


text:
Q: Union all select query with a dynamic table name in SQL Server I have an account table with column ID,
from all the @ID, and save it as a query to run for later use
(I have thousand of accounts)
ID
------------------------------------
8C76EF27-3080-4DAA-881B-08CD2A1A558F
62FFCB40-AAB4-47A5-953A-08CD2A1A6A43
CFFD7C3C-FEFC-4E97-9970-08CD2A1A3A60
0F5ADAF3-32EF-4D43-BFBD-08CD2A1A5D88
4130153C-24C1-4914-A6F1-08CD2A16DF59

I have found something like this to generate a flex query to retrieve column ID
 in the sql to be executed like
with getAllAccount as(
select B.ID,B.DisplayName from (
select ID,DisplayName from u3_system.[dbo].[Account] with (nolock)
where ID = '8c76ef27-3080-4daa-881b-08cd2a1a555f' or ParentID = '8c76ef27-3080-4daa-881b-08cd2a1a555f') A
join u3_system.[dbo].[Account] B with (nolock)
on A.ID = B.ParentID
union
select ID,DisplayName from u3_system.[dbo].[Account] with (nolock)
where ID = '8c76ef27-3080-4daa-881b-08cd2a1a555f'
)

--create pre script
Select 'if exists (select * from sys.tables where name = ''Maillog_' + replace(getAllAccount.ID,'-','') + ') begin Select CampaignID,mailoutID,deliveryDate from  u3_data.data.Maillog_' + replace(getAllAccount.ID,'-','') + ' with(nolock) end union '
from getAllAccount

I want to select all the account if its exists then union together,
and there will be thousands of account, some of them exists, some not,
Now the union in this case doesnt work.
Is there another way to do it? thanks very much

A: Not sure what do you mean by "query for later use". You can generate select queries for all tables with a simple query like below -
Select CONCAT('select * from  u5_data.data.Mailtable_', ID)  from Account

It will generate the output as below, which you can save it in file for later use.
select * from  u5_data.data.Mailtable_8C76EF27-3080-4DAA-881B-08CD2A1A558F
select * from  u5_data.data.Mailtable_62FFCB40-AAB4-47A5-953A-08CD2A1A6A43
select * from  u5_data.data.Mailtable_CFFD7C3C-FEFC-4E97-9970-08CD2A1A3A60
select * from  u5_data.data.Mailtable_0F5ADAF3-32EF-4D43-BFBD-08CD2A1A5D88
select * from  u5_data.data.Mailtable_4130153C-24C1-4914-A6F1-08CD2A16DF59

A: It's funny; I just tweeted today about the worst database design I've ever encountered in my 20+ years as a SQL developer, and this question sounds eerily similar.  It sounds like you have a bunch of tables that are identical except for the name, and the name represents an entity that you want to retrieve data for.  You're now trying to do it as a batch, so for every entity stored in accounts, you want to pull back a (I assume) single data-set for those accounts.
This can be done in a couple of different ways, all of them hackish.  If you have any influence over the design of this database, try to figure out a way to refactor it.  I chose the CURSOR route for this sample, but it might also be done using a view or a single dynamic SQL statement.  Those two options, however, will only work if the number of tables are small (I've done it with 90 tables or less in the past).  Since I don't know that, here's the CURSOR.
 USE tempdb;

/*set up demo up here*/
CREATE TABLE Account (ID uniqueidentifier)

INSERT INTO Account (ID)
VALUES ('8C76EF27-3080-4DAA-881B-08CD2A1A558F'),
('62FFCB40-AAB4-47A5-953A-08CD2A1A6A43'),
('CFFD7C3C-FEFC-4E97-9970-08CD2A1A3A60'),
('0F5ADAF3-32EF-4D43-BFBD-08CD2A1A5D88'),
('4130153C-24C1-4914-A6F1-08CD2A16DF59')

--these are not temp tables; be sure to clean up.  naming has hyphens
CREATE TABLE [MT_4130153C-24C1-4914-A6F1-08CD2A16DF59] (val varchar(20))
CREATE TABLE [MT_CFFD7C3C-FEFC-4E97-9970-08CD2A1A3A60] (val varchar(20))
CREATE TABLE [MT_8C76EF27-3080-4DAA-881B-08CD2A1A558F] (val varchar(20))
CREATE TABLE [MT_0F5ADAF3-32EF-4D43-BFBD-08CD2A1A5D88] (val varchar(20))
CREATE TABLE [MT_62FFCB40-AAB4-47A5-953A-08CD2A1A6A43] (val varchar(20))

INSERT INTO [MT_4130153C-24C1-4914-A6F1-08CD2A16DF59] VALUES ('This')
INSERT INTO [MT_CFFD7C3C-FEFC-4E97-9970-08CD2A1A3A60] VALUES ('is')
INSERT INTO [MT_8C76EF27-3080-4DAA-881B-08CD2A1A558F] VALUES ('a')
INSERT INTO [MT_0F5ADAF3-32EF-4D43-BFBD-08CD2A1A5D88] VALUES ('bad')
INSERT INTO [MT_62FFCB40-AAB4-47A5-953A-08CD2A1A6A43] VALUES ('design')

/*magic starts here*/
CREATE TABLE #output (val varchar(20), id uniqueidentifier)

DECLARE @sql nvarchar(200), @Id varchar(50)

DECLARE c CURSOR FOR
SELECT CONVERT(VARCHAR(50), ID) FROM account

OPEN C

FETCH NEXT FROM C INTO @ID
WHILE @@FETCH_STATUS = 0
BEGIN

SET @SQL = 'SELECT val, ''' + @ID + ''' FROM [MT_' + @ID + ']'

INSERT INTO #output (val, id)
exec sp_executesql @SQL

FETCH NEXT FROM C INTO @ID
END

CLOSE C
DEALLOCATE C

/*output comes next*/
SELECT *
FROM #output
ORDER BY ID

DROP TABLE #output

/*clean up demo*/
DROP TABLE Account

DROP TABLE [MT_4130153C-24C1-4914-A6F1-08CD2A16DF59]
DROP TABLE [MT_CFFD7C3C-FEFC-4E97-9970-08CD2A1A3A60]
DROP TABLE [MT_8C76EF27-3080-4DAA-881B-08CD2A1A558F]
DROP TABLE [MT_0F5ADAF3-32EF-4D43-BFBD-08CD2A1A5D88]
DROP TABLE [MT_62FFCB40-AAB4-47A5-953A-08CD2A1A6A43]

Long story short, you iterate through each value in the accounts table and write a dynamic SQL statement.  You execute it per ID, and insert the output of that SQL statement into a temporary table, and then select the results from that temp table.

A: Below Script using Cursor
create table tbl(ID varchar(max))
insert into tbl values('8C76EF27-3080-4DAA-881B-08CD2A1A558F')
insert into tbl values('62FFCB40-AAB4-47A5-953A-08CD2A1A6A43')
insert into tbl values('CFFD7C3C-FEFC-4E97-9970-08CD2A1A3A60')
insert into tbl values('0F5ADAF3-32EF-4D43-BFBD-08CD2A1A5D88')
insert into tbl values('4130153C-24C1-4914-A6F1-08CD2A16DF59')

DECLARE @sql varchar(max)
SELECT  CONCAT('SELECT * FROM ',[ID], CHAR(13) + CHAR(10)  ) as execRecord
into #tmp
from tbl
select * from #tmp

    DECLARE ID_Cursor CURSOR FOR
        SELECT execRecord from #tmp
    DECLARE @tmpID varchar(max)
    OPEN ID_Cursor
        FETCH NEXT FROM ID_Cursor INTO @tmpID
        WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @sql = @tmpID
            EXECUTE SP_EXECUTESQL @sql
            SET @sql = ''
            FETCH NEXT FROM ID_Cursor INTO @tmpID
        END

    CLOSE ID_Cursor
    DEALLOCATE ID_Cursor

DROP TABLE #tmp
DROP TABLE tbl

A: You cannot parameterise object identifiers in SQL (i.e. you cannot use SqlParameter for this), you must use "Dynamic SQL" - which means you have to be careful to avoid SQL Injection.
Assuming you have to do this entirely in T-SQL, then I strongly recommend using SQL Server 2017 because it introduces the very useful STRING_AGG function (equivalent to MySQL's GROUP_CONCAT function).
Like so:
DECLARE @sql varchar(max)

SELECT
    @sql = STRING_AGG( CONCAT( 'SELECT * FROM ', [ID] ), CHAR(13) + CHAR(10) )
FROM
    Accounts

EXECUTE sp_executesql @sql

A: Found the answer
Select * from
(   Select case when exists (select * from sys.tables where name = 'Maillog_' + replace(getAllAccount.ID,'-',''))
        Then 'Select CampaignID,mailoutID,deliveryDate from  u3_data.data.Maillog_' + replace(getAllAccount.ID,'-','') + ' with(nolock) union ' End execQuery
    from getAllAccount
) A
where execQuery is not null


text:
Q: Changes list_display when choosing different filter options I need to change the displayed columns of django model
For example, I have the following model id - user - type1 - type2 - type3 - type4
And a filter with the following fields - filter1 - filter2 - filter3
How can I display only id - user - type1 fields when filter1 is selected, when filter2 is selected, display only id - user - type2 fields, when filter3 is selected, display only id - user - type3 - type4 fields, is there such a possibility in django?


text:
Q: removeItemAtPath - error: couldn't be removed because you don't have permission to access it My code:
NSFileManager.defaultManager().removeItemAtPath(path, error: nil)

My log error:
NSUnderlyingError=0x618000255900 "The operation couldn't be completed. Permission denied"})
"SecureDelete Lite" couldn't be removed because you don't have permission to access it

I have read two topics but they don't resolve my bug.
osx - How to programmatically delete a file with elevated privileges?
Obtaining admin privileges to delete files using rm from a Cocoa app
Answers with Objective-C or Swift are OK.


text:
Q: NavigationViewMenu not considering its MenuItemsSource Sample : link
I'm developing an application that allows people to save notes, and create categories in which you can store your notes.
Categories are listed in a List, and an ObservableCollection, because I had a problem, trying to serialize a List of NavigationViewItems.
So I made the following class:
[DataContract]
class Category
{
    [DataMember]
    public String Title { get; set; }

    [DataMember]
    public int IconIndex { get; set; }

    [DataMember]
    public String Id { get; set; }
}

And in my App.xaml.cs I have:
internal static ObservableCollection<NavigationViewItem> Categories = new ObservableCollection<NavigationViewItem>();
internal static List<Category> CategoriesItems = new List<Category>();

Categories (the ObservableCollection) is used as my NavigationView's MenuItemsSource :
nav.MenuItemsSource = App.Categories;

In an other file, I have a function called OpenCategories, called at the opening of the application:
public async static void OpenCategories(StorageFile file)
{
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(await FileIO.ReadTextAsync(file)));
    DataContractJsonSerializer ser = new DataContractJsonSerializer(App.CategoriesItems.GetType());
    App.CategoriesItems = ser.ReadObject(ms) as List<Category>;
    ms.Close();

    UIServices.RefreshCategoriesUI();
}

And here's UIServices.RefreshCategoriesUI() :
public static void RefreshCategoriesUI()
{
    App.Categories = new System.Collections.ObjectModel.ObservableCollection<NavigationViewItem>();
    foreach(Category cat in App.CategoriesItems)
    {
        App.Categories.Add(new NavigationViewItem
        {
            Content = cat.Title,
            Icon = new SymbolIcon((Symbol)Enum.GetValues(typeof(Symbol)).GetValue(cat.IconIndex))
        });
    }
}

=> My issue is that even though App.Categories contains NavigationViewItems, my NavigationViewMenu is always empty. Why isn't it updating ?
Edit :
Here are the changes I made.
Categories has been moved from App.xaml.cs to MainPage.xaml and has been transformed into a DependencyProperty
internal DependencyProperty CategoriesProperty = DependencyProperty.Register("CategoriesProperty", typeof(ObservableCollection<NavigationViewItem>), typeof(App), new PropertyMetadata(default(ObservableCollection<NavigationViewItem>)));

RefreshCategoriesUI is not used anymore. Instead, I turned CategoriesItems into a ObservableCollection property and subscribed to the CollectionChanged event:
private void CategoriesItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    var page = (MainPage)((Frame)Window.Current.Content).Content;
    page.Categories = new ObservableCollection<NavigationViewItem>();
    foreach (Category cat in CategoriesItems)
        page.Categories.Add(new NavigationViewItem
        {
            Content = cat.Title,
            Icon = new SymbolIcon((Symbol)Enum.GetValues(typeof(Symbol)).GetValue(cat.IconIndex))
        });
}

And finally OpenCategories is now working this way:
public async static void OpenCategories(StorageFile file)
{
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(await FileIO.ReadTextAsync(file)));
    DataContractJsonSerializer ser = new DataContractJsonSerializer(App.CategoriesItems.GetType());
    ObservableCollection<Category> categories = ser.ReadObject(ms) as ObservableCollection<Category>;
    foreach (Category cat in categories)
        App.CategoriesItems.Add(cat);
    ms.Close();
}

Oh and it seems obvious but I changed the MenuItemSource of my NavigationView from App.Categories to Categories, as Categories moved.
It's still not working. And when I check during runtime, Categories contains all the categories I created through my app.
Moreover, it's really weird because when I first checked if Categories contained something (to write this post), after my breakpoint, all the categories popped up in the NavigationView as it's supposed to do everytime, but when I tried again it didn't work.

A: For your sample, in the App.xaml.cs file CategoriesItems_CollectionChanged method, every time there is a CollectionChanged event triggers, you create a new ObservableCollection<NavigationViewItem> object then add the items into it, but you should also set the NavigationView.MenuItemsSource to the ObservableCollection again.
You can try to change your CategoriesItems_CollectionChanged method as the following.
private void CategoriesItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    // Gets the MainPage
    var page = (MainPage)((Frame)Window.Current.Content).Content;
    page.Categories = new ObservableCollection<NavigationViewItem>();

    // Creates all the NavigationViewItems, based on CategoriesItems
    foreach (Category cat in CategoriesItems)
        page.Categories.Add(new NavigationViewItem
        {
            Content = cat.Title,
            Icon = new SymbolIcon((Symbol)Enum.GetValues(typeof(Symbol)).GetValue(cat.IconIndex))
        });

    //Here is the code to set the NavigationView's MenuItemsSource.

    NavigationView nav= (NavigationView)page.FindName("nav");
    nav.MenuItemsSource = page.Categories;
}


text:
Q: PPPD over serial, good iperf results, poor real (scp/streaming) bitrate My goal is to have TCP/IP capable connection between two devices which are connected with each other using radio transceivers connected to each device using serial port. Their maximum bitrate is in theory 500kbps. I have managed to establish such connection using pppd:
pppd crtscts noauth lock 172.100.0.1:172.100.0.2 /dev/ttyUSB0 460800
It works fine, I can ssh from one to another. I have run iperf3 (server: iperf3 -s, client: iperf3 -c 172.100.0.1). The result was:
Connecting to host 172.100.0.1, port 5201
[  4] local 172.100.0.2 port 33740 connected to 172.100.0.1 port 5201
[ ID] Interval           Transfer     Bandwidth       Retr  Cwnd
[  4]   0.00-1.00   sec  56.2 KBytes   460 Kbits/sec    0   12.4 KBytes
[  4]   1.00-2.00   sec  70.4 KBytes   577 Kbits/sec    0   15.8 KBytes
[  4]   2.00-3.00   sec   129 KBytes  1.05 Mbits/sec    0   21.5 KBytes
[  4]   3.00-4.00   sec  78.8 KBytes   645 Kbits/sec    0   25.0 KBytes
[  4]   4.00-5.00   sec  90.3 KBytes   739 Kbits/sec    0   29.2 KBytes
[  4]   5.00-6.00   sec   113 KBytes   931 Kbits/sec    0   34.3 KBytes
[  4]   6.00-7.00   sec  21.2 KBytes   174 Kbits/sec    0   34.5 KBytes
[  4]   7.00-8.00   sec  39.2 KBytes   321 Kbits/sec    0   34.5 KBytes
[  4]   8.00-9.00   sec  54.9 KBytes   450 Kbits/sec    0   34.5 KBytes
[  4]   9.00-10.00  sec  29.6 KBytes   243 Kbits/sec    0   34.5 KBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth       Retr
[  4]   0.00-10.00  sec   683 KBytes   559 Kbits/sec    0             sender
[  4]   0.00-10.00  sec   621 KBytes   509 Kbits/sec                  receiver

iperf Done.

bidirectional tests with -d gave similar results.
However, when I try to scp a file (generated using dd if=/dev/urandom of=~/randfile bs=1M count=1 I get very repeatable results of ~20-25 KB/s (lower the mpu, lower the transfer), over 2 times worse then iperf3:
scp ~/randfile user@ip:/path
100% 1024KB  20.3KB/s   00:50

Do you have any idea what can be causing such difference? I tried video streaming and results were roughly the same, I achieved 150kbps with UDP, I could not get 200kbps working. I will give SLIP a try which should have lower overhead then pppd.
EDIT
result of pppstats
device1:
pppstats -r -v
      IN   PACK VJCOMP VJTOSS NON-VJ  RATIO  UBYTE  |      OUT   PACK VJCOMP VJSRCH VJMISS  RATIO  UBYTE
 1980812  17773   9606      0    968   1.15 1595821  |  6156633  34099  18485    480     13   3.69 5387948

device2:
pppstats -r -v
      IN   PACK VJCOMP VJTOSS NON-VJ  RATIO  UBYTE  |      OUT   PACK VJCOMP VJSRCH VJMISS  RATIO  UBYTE
 6155869  34092  18485      0   7687   3.69 5387156  |  1979984  17762   9606    422     14   1.15 1594949


text:
Q: Cost of 3 million Invocations per month on google cloud functions, with 1 minimum instance and 2 as maximum I am trying to understand cost of google cloud. Suppose I allocate 256 MB for the function and there is 1 minimum instance running all times and maximum instance is set to 2, then what will be monthly cost? I am wondering also if setting minimum instances to 0 will reduce bill significantly or ok to set it as 1 without affecting cost too much. I Could not understand the idle pricing, so If someone has real life example on cost and can share.

A: per note ,

Note: A minimum number of instances kept running incur billing costs
at idle rates. Typically, to keep one idle function instance warm
costs less than $6.00 a month

Also for Google Function Idle, but I could not find any direct google document on this.

Instances are recycled after 15 minutes of inactivity.

but another answer says it is 30 minutes

A: Your question lacks important details such as the execution time of your code or the amount of data moving out from your function but you can use the price calculator to get an estimate.
Keep in mind that since the charge for each million of invocations is 0.40 usd the price for the amount of invocations might not be as important as the price for your connectivity.
For example I did an emulation for a function with minimum 1 instance, 3 million of executions a month, 256mb, 100 ms of execution time and 1 mb of bandwidth per execution and for Uscentral1 you will be charged 354.10
In any case it would be better if you discuss this kind of questions with [Google Cloud Billing Support](Contact Cloud Billing Support) as they will be able to give you the most accurate response to this kind of questions.
Keep in mind that Stack Overflow is more focused towards code and development support


text:
Q: File truncated to 0 bytes during power failure Power went down while editing a file with Geany and the file got truncated to 0 bytes ...  Is it possible to recover the file ?

A: Normally editors rename the file to a backup, usually with a '#' or '~' in the name, and then save the new file.  In your case, the power failed before the new file was written, so just look for the backup.


text:
Q: Selenium: Go URL's "up" is there a way to go urls endings up? For an example :
driver.get("Example.com/1") then driver.get("Example.com/2") then driver.get("Example.com/3") and again and again.
Until it is at 69.
I tried googling, but I didn't found anything.

A: Just use range for that:
for i in range(1, 70):
    driver.get(f'example/{i}')
    # Do what you want
    driver.quit()


text:
Q: Setting up IPv6 on Apache2 Currently I have the "ports.conf" with the following content:
NameVirtualHost *:80
Listen 80

<IfModule mod_ssl.c>
    Listen 443
    NameVirtualHost *:443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>

So to add IPv6 I have to change it to:
NameVirtualHost 91.64.99.215:80
Listen 91.64.99.215:80

NameVirtualHost [2a01:4f8:140:54e4::3]:80
Listen [2a01:4f8:140:54e4::3]:80

<IfModule mod_ssl.c>
    Listen 443
    NameVirtualHost 91.64.99.215:443
    NameVirtualHost [2a01:4f8:140:54e4::3]:443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 91.64.99.215:443
    Listen [2a01:4f8:140:54e4::3]:443
</IfModule>

Is this correct?
My fear is that if I do this all vhosts set up like
<VirtualHost *:80>
     ServerName www.domain.tld
     ServerAlias domain.tld
     DocumentRoot /www/domain
</VirtualHost>

will go berserk. If this is not the case, doing
<VirtualHost *:80 [*]:80>
     ServerName www.domain.tld
     ServerAlias domain.tld
     DocumentRoot /www/domain
</VirtualHost>

should also make the domain available via IPv6?
I am a bit confused here and cannot make much out of the existing "examples" Any help will be appreciated.

A: You just need to change your Listen directives to:
Listen [::]:80
Listen [::]:443

while your
NameVirtualHost *:80
<VirtualHost *:80>

remain the same.
Note: netstat -tln will show apache listening only on tcp6 / :::80; that is normal (it will also respond to IPv4 as before)


text:
Q: Is it true that OPENGL ES 3.1 is slower than OPENGL ES 2.0? Found an article here OpenGL ES versus Vulkan, who is the performance king? mentioned that:

"The problem with OpenGL ES 3.1 is that while the graphics look immensely better than OpenGL ES 2.0, the performance hit is so great that games are basically not playable, looking at the image above comparing OpenGL ES 2.0 and 3.1 on my Nexus 6P shows that the exact same scene runs at a third of the frames per second compared to OpenGL ES 2.0. This is where Vulkan comes in, offering at least the same in graphics quality, but with improved performance. So how does Vulkan do?"
I can't imagine that 3.1 slower than 2.0 with the same scene. Had the author mistaken the image? Seems the right image have GI.

A:
Had the author mistaken the image?

To me it seems that the author of that article is just dumb.
Just a quote from that article:

Vulkan still will not perform as well as the lower graphics capable OpenGL ES 2.0, as Vulkan displays a lot more on screen and the scenes it can render are a lot more complex

It's like saying that a Ferrari will not perform as well as a bicycle because you can ride 10 meters in a bicycle in 10 seconds, but can't drive 100 kilometers in a Ferrari in the same amount of time.
Now, about the image from that article:
It's not the same in OpenGL ES 3.1 and 2.0. I can at least see a more realistic lighting with reflections, as well as smoother looking walls, in the ES 3.1 screenshot.
To compare things like that you need at least to make sure that the resulting images are the same for both cases. If you are rendering a scene without postprocessing effects in one case, and with postprocessing effects on the other, then it's not the right comparison. Also, If you are rendering the scene with, say, a deferred renderer in one case, and a forward renderer in the other, then it's again not the right comparison, even if you got the same image.

A: I took a look at this article also while searching the same question myself, and please note that in it the author used unreal to do the comparisons. Enabling different options in unreal such as gl es 3 doesnt only change the gl version but also adds more realism that the engine assumes that gl es 3 can handle.


text:
Q: Why does `find` in Linux skip expected results when `-o` is used? Why in Linux (Debian 8)
touch 1.cpp 1.h
find . -name "*.cpp" -o -name "*.h" -exec echo {} \;

outputs only 1.h while
find . -name "*.cpp" -o -name "*.h"

outputs both? Is it a bug or feature?

A: I think once you used -or operator, then you've to keep it consistent in order to avoid ambiguous order of logical operations when you have multiple conditions connected using logical OR.
It seems the -exec part is grouped together with the second -name "*.h".
So in order to make it work correctly, you've to add the brackets as below:
find . '(' -name '*.cpp' -o -name '*.h' ')' -exec echo {} ';'

Remember: The parentheses must be quoted or escaped with a backslash to prevent them from being interpreted as special shell characters.

Alternatively combine few extensions into one by using -regex:
find . ! -regex ".*\.\(cpp\|h\)" -exec echo {} \;

A: Neither. It's the syntax of the options that is "wrong". find evalutates sequencially. Hence, it evaluates the first expression (-name "*.cpp") then encounters a -o flag. If the first expression is true, find will not continue evaluating the second one (-name "*.h" -exec echo {} \;), instead does nothing. You see, the whole part after -o is one expression. Therefore, this is only executed for files that match the second expression. That's why you see only the 1.h file, which passes only the second expression. See the find manpage:
   expr1 -o expr2
          Or; expr2 is not evaluated if expr1 is true.

Why is this useful? Consider the following:
find /path -exec test_file_for_something {} -print \; -o -name "xyz" -exec ls -l {} \;

In this find statement the file is given to test_file_for_something as a parameter. Now, depending on that commands return code the first expression is true (then -print is executed and it ends there) or false (then the second expression after the -o flag is evaluated). And if that one is true (the name is xyz), then -exec is executed.
For your problem you can instead use this to group the elements together as one expression:
find . \( -name "*.cpp" -o -name "*.h" \) -exec echo {} \;

A: Try to surround your search criteria with brackets as such:
find . \( -name "*.cpp" -o -name "*.h" \) -exec echo {} \;

A: That is the way find works with it's operators.
See http://linux.die.net/man/1/find section OPERATORS

OPERATORS
Listed in order of decreasing precedence: ( expr ) Force precedence.
  Since parentheses are special to the shell, you will normally need to
  quote them. Many of the examples in this manual page use backslashes
  for this purpose: '(...)' instead of '(...)'. ! expr True if expr is
  false. This character will also usually need protection from
  interpretation by the shell.
-not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied "and";
  expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1
  expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant.
  expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or
  expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2
  List; both expr1 and expr2 are always evaluated. The value of expr1 is
  discarded; the value of the list is the value of expr2. The comma
  operator can be useful for searching for several different types of
  thing, but traversing the filesystem hierarchy only once. The -fprintf
  action can be used to list the various matched items into several
  different output files.

This should give you the result you want:

find . \( -name '*.cpp' -o -name '*.h' \) -exec echo {} \;

Your command is doing this (command won't work, just to show you the logic):

find . -name '*.cpp' (-o -name '*.h' -exec echo {} \;)


text:
Q: Whats wrong with this simple NodeJS crypto function? I'm trying to perform AES CBC encryption with zero padding of a url query string. I'm using NodeJS's core crypto module. It's for use with http://www.blackoutrugby.com/game/help.documentation.php#category=35
I have a key and IV. When testing the following function I'm not getting the string returned in full. I believe this has to do with padding but am unsure how to apply it correct.
If it is the padding, can anyone show me how I should apply it? If not where am I going wrong? Also is cipher.final() of significance in this usercase?
Update:
I've now included cipher.final() and things work fine with binary format but base64 gives me the truncated result. https://github.com/denishoctor/BlackoutRugbyNode/blob/master/crypto2.js is my full example code. Below is the crypto function:
function cryptoTest(data, key, iv, format) {
   var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
   var cipherChunks = [];
   cipherChunks.push(cipher.update(data, 'utf8', format));
   cipherChunks.push(cipher.final());

   var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
   var plainChunks = [];
   for (var i = 0;i < cipherChunks.length;i++) {
        plainChunks.push(decipher.update(cipherChunks[i], format, 'utf8'));
   }
   plainChunks.push(decipher.final());

   return {
       "encrypted": cipherChunks.join(''),
       "decrypted": plainChunks.join('')
   };
}

Thanks,
Denis

A: You are not putting the ciphertext returned by cipher.final into the decipher.  Here's a simplified example.  You need to collect the return values from every call to cipher.update as well as cipher.final and make sure each of those objects gets put into decipher.update.
UPDATE: here's a version that works fine with binary or hex as the encoding for the cipher text, but fails with base64.  I have no idea why this is, but if you are OK with hex that should work fine.
UPDATE 2: Looks like base64 is a bug in node itself.  See this answer to a similar question.
    var crypto = require('crypto');

    var data = "I am the clear text data";
    console.log('Original cleartext: ' + data);
    var algorithm = 'aes-128-cbc';
    var key = 'mysecretkey';
    var clearEncoding = 'utf8';
    var cipherEncoding = 'hex';
    //If the next line is uncommented, the final cleartext is wrong.
    //cipherEncoding = 'base64';
    var cipher = crypto.createCipher(algorithm, key);
    var cipherChunks = [];
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));
    var decipher = crypto.createDecipher(algorithm, key);
    var plainChunks = [];
    for (var i = 0;i < cipherChunks.length;i++) {
      plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));

    }
    plainChunks.push(decipher.final(clearEncoding));
    console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));

A: Standard crypto package only supports PKCS#7 padding. You have to disable automatic padding of standard crypto package of Node.js then you can write code to pad.
You can use padding algorithm from following package
https://github.com/tugrul/cryptian


text:
Q: Polynomial : holonomic :: rational function :? A sequence $(a_n)$ is called holonomic if it can be specified with initial terms and a recurrence
$$
a_n=P_1(n)a_{n-1}+P_2(n)a_{n-2}+\cdots+P_k(n)a_{n-k}
$$
where $k$ is an integer and $P_1,\ldots,P_k$ are polynomials. Is there a term for the generalization in which the $P_i$ are allowed to be rational functions rather than polynomials? If so, does anyone have a pointer to a reference describing their properties?


text:
Q: GRE Quantitative Comparison: Determining range of values satisfying equation involving absolute values Consider the equation
\begin{equation}
|2a-1|+|3b+2|=0
\end{equation}
Which of the following is true:

*

*$a>b$

*$a<b$

*$a=b$

*The relationship cannot be determined.

How can one solve for the range of possible values of $a$ and $b$? Thank you very much!

A: solve 2a-1 =0 and 3b+2 = 0 since we need to solve RHS=0; you will get a=1/2 and b=-2/3. Therefore, a>b.

A: Use:

$$|x|\ge0$$

$$|x|+|y|=0\iff |x|=0 \text{ and } |y|=0$$
$$|2a-1|=0\implies a=\frac12$$
$$|3b+2|=0\implies b=-\frac23
$$

$$a\gt b$$


text:
Q: Communication between laptop & Android mobile in LAN I am developing an Android app which is having sent the data collected from mobile have to sent to the laptop/desktop. But I have no idea how to send in LAN?
Avoiding web service, is there any way to sent the data to system in LAN?

A: yes, we can send data over TCP/IP sockets.
This application might have two applications:(1) Desktop Application, (2) Mobile Application

*

*Create Desktop application, create a ServerSocket in the app, listening on some port.

*Create mobile application. Create a Socket in this app, to the ip of desktop and socket, ServerSocket is listening.

*By Mobile app send data to the socket, by writing in output stream, from socket.

*In Desktop application, read the input stream, parse the stream, and save data.


text:
Q: How to download artifacts from Artifactory Server We have a bunch of jars in the artifactory server (the free version).
How can we download all the jars in a single http request from it ?
Do we need to tar all the jars into a single tar file in order to efficiently download the jars ?
Thanks
Sincerely

A: Since you are the one who generates the files, you have two options:

*

*As you said, generate the tar before uploading it. You'll still be able to search and browse the files inside it.

*Write a afterDownloadError user plugin. Each time the user tries to access a url with .tar in the end, create the tar from the needed files and serve it.


text:
Q: How to set permissions for RabbitMQ directory to create new files? I would like to move the RABBITMQ_BASE files to "/opt/rabbitmq"
I've attempted the following, but it appears that I'm making a mistake somewhere:
(while logged in as root)
mkdir -p /opt/rabbitmq
sudo chown -R rabbitmq:rabbitmq /opt/rabbitmq
sudo chmod 766 -R /opt/rabbitmq

here is the contents of my rabbitmq-env.conf
RABBITMQ_BASE=/opt/rabbitmq
export RABBITMQ_NODENAME=rabbit@localhost
export RABBITMQ_NODE_IP_ADDRESS=127.0.0.1
export ERL_EPMD_ADDRESS=127.0.0.1
export RABBITMQ_MNESIA_BASE=/opt/rabbitmq/MNESIA

I've checked the logs in /var/log/rabbitmq/startup_log:
BOOT FAILED
===========

Error description:
   {error,{cannot_create_mnesia_dir,"/opt/rabbitmq/MNESIA/rabbit@localhost/",
                                    eacces}}

Log files (may contain more information):
   /var/log/rabbitmq/rabbit@localhost.log
   /var/log/rabbitmq/rabbit@localhost-sasl.log

Stack trace:
   [{rabbit_mnesia,ensure_mnesia_dir,0,
                   [{file,"src/rabbit_mnesia.erl"},{line,505}]},
    {rabbit_node_monitor,prepare_cluster_status_files,0,
                         [{file,"src/rabbit_node_monitor.erl"},{line,101}]},
    {rabbit,'-boot/0-fun-0-',0,[{file,"src/rabbit.erl"},{line,270}]},
    {rabbit,start_it,1,[{file,"src/rabbit.erl"},{line,403}]},
    {init,start_it,1,[]},
    {init,start_em,1,[]}]

{"init terminating in do_boot",{error,{cannot_create_mnesia_dir,"/opt/rabbitmq/MNESIA/rabbit@localhost/",eacces}}}

The "/opt" directory is owned by root, but the permissions for the other directories are as follows:
ubuntu root@/opt $ ls -lah
total 48K
drwx------ 10      700 root     4.0K Jul 14 12:42 .
drwx------  5      700 root     4.0K Jul 14 10:39 ..
drwx------ 13      700 root     4.0K Jul 12 10:16 anaconda
drwx------  4      700 root     4.0K Jul 12 09:28 data
drwx------  3      700 root     4.0K Jul 12 10:38 legacy
drwx------  2      700 root      12K Jul 14 12:45 logs
drwx------  3      700 root     4.0K Jul 12 09:47 mongodb
drwxrw-rw-  4 rabbitmq rabbitmq 4.0K Jul 14 13:05 rabbitmq

A: The solution which works for me is to disable SELINUX


text:
Q: wait_timeout kills session in SLEEP MODE or all connection ?` Do wait_timeout session clear all running session or only sessions which are in SLEEP mode for specified seconds ?

A: Wait Timeout is a variable which represent the time in seconds that MySQL will wait and kill the session if it is in idle/sleep state.
Default value is 28000 secs. If you want to change the wait time value, you also need to change the interactive_timeout variable.
There will be no active sessions with this time interval. If your session is showing as active and some activity is happening so long, then there is issue with the session.


text:
Q: Updated CSV Values across Multiple CSV Files This is my code below and whenever I run my program, I receive and error stating "attribute error: 'generator' object has no attribute 'loc'"
I'm currently trying to change specified values in a specified column in all csv files to different specified values for the specified column
I'm not sure why this is happening
# Get CSV files list from a folder
csv_files = glob.glob(dest_dir + "/*.csv")

# Read each CSV file into DataFrame
# This creates a list of dataframes
df = (pd.read_csv(file) for file in csv_files)
df.loc[df['Plan_Code'].str.contains('NABVCI'), 'Plan_Code'] = 'CLEAR_BV'
df.loc[df['Plan_Code'].str.contains('NAMVCI'), 'Plan_Code'] = 'CLEAR_MV'
df.loc[df['Plan_Code'].str.contains('NA_NRF'), 'Plan_Code'] = 'FA_GUAR'

df.to_csv(csv_files, index=False)

Thanks!

A: Because you use round brackets and not square brackets when creating df, df becomes a generator object and not a list of dataframes. But even if you switch to square brackets you will still have a problem: df will now be a list, but lists don't have a loc attribute either, only dataframes -- individual elements of that list -- have it. So df.loc still wouldn't work.
If I understand your intent correctly, you want something like this instead:
csv_files = glob.glob(dest_dir + "/*.csv")
for file in csv_files:
    df = pd.read_csv(file) #now df is a dataframe, so df.loc makes sense
    #do your df.loc manipulations, then save each df to its own file
    df.to_csv(file, index=False)

A: You wrote this:
df = (pd.read_csv(file) for file in csv_files)

Rather than that generator expression,
you probably intended to write a list comprehension:
df = [pd.read_csv(file) for file in csv_files]

Additionally you likely want to call pd.concat(),
so that multiple .CSVs get incorporated into
a single dataframe.

Alternatively, you might prefer to build up a list of
dicts pulled from csv.DictReader,
and then call pd.DataFrame() on that list.
Multiple .csv files could contribute rows to the list.
One dict per row, without regard to which file
the row appears in.


text:
Q: Ionic 4 - AuthGuard page routing permission delayed I have an ionic 4 app that is storing information about the user natively. When the user opens the app then if his information is there then I want him to be sent to the Home Page. If he is not then I want him to be routed to the Login Page, pretty normal.
The problem that I am running into is that for about 500ms you will see the Login Page and then upon reading the information then it will redirect you to the home page.
What I would like is for the application to WAIT On the response from the storage before it directs you to the Login Page or the Home Page.
App.component.ts
  public initializeApp(): void {
    this.platform.ready().then((): void => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.authService.authState.subscribe((state: boolean): void => {
        if (state) {
          this.router.navigate(['home']);
        } else {
          this.router.navigate(['login-register']);
        }
      });
      this.permissionService.requestCameraPermission();
    });
  }

AuthService.service.ts
public readonly authState: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false)

  private _ifLoggedIn(): void {
    // just sees if his info is saved, if so then he has been logged in
    this.userService.getUserInfo().then((response: UserData): void => {
      if (response) {
        this.authState.next(true);
      }
    });
  }

  public isAuthenticated(): boolean {
    return this.authState.value;
  }

AuthGuard
export class AuthGuardService {
  private authService: AuthService;

  public constructor(authService: AuthService) {
    this.authService = authService;
  }
  public canActivate(): boolean {
    return this.authService.isAuthenticated();
  }
}

app-routing.module.ts
const routes: Routes = [
  {
    path: '',
    redirectTo: 'login-register',
    pathMatch: 'full',
  },
  {
    path: 'login-register',
    loadChildren: () => import('../pages/login-register/login-register.module').then(m => m.LoginRegisterPageModule),
  },
  {
    path: 'home',
    loadChildren: () => import('../pages/home/home.module').then(m => m.HomePageModule),
    canActivate: [AuthGuardService],
  },
];

if there is anything other information you need let me know. Thanks guys!

A: The first problem that you have is BehaviorSubject got initialized so it will return a result directly when you ask for a result.
The second problem is that isAuthenticated() will return the value because it is sync method, but you need anybody who calls it to wait.
The solution is to use ReplySubject and make isAuthenticated() async.
AuthService.service.ts
public readonly authState: ReplaySubject<boolean> = new ReplaySubject<boolean>(1)

  private _ifLoggedIn(): void {
    // just sees if his info is saved, if so then he has been logged in
    this.userService.getUserInfo().then((response: UserData): void => {
        this.authState.next(!!response);
    }, (reason) => this.authState.next(false));
  }

  public async isAuthenticated(): Promise<boolean> {
    return this.authState.asObservable().pipe(take(1)).toPromise();
  }

Note that this.authState.next(false) is to return a result and not stuck forever waiting, so if error returned like error 401, it will consider it not logged in.
And this.authState.next(!!response) is just shorten format for your previous condition, and will handle the case if response returned with null or undefined if you implemented your .getUserInfo() like that the user is not logged in.
AuthGuard
export class AuthGuardService implements CanActivate {
  private authService: AuthService;

  public constructor(authService: AuthService) {
    this.authService = authService;
  }
  public async canActivate(): Promise<boolean> {
    return this.authService.isAuthenticated();
  }
}

Note that canActivate() support async implementation already, also, I added implements CanActivate so it does make more sense.
You can learn more about the types of Subject here: Understanding rxjs BehaviorSubject, ReplaySubject and AsyncSubject


text:
Q: Reload Fragment, Fragment dont call onCreateView i have a Fragment(C) with a ViewPager(Adapter) with 2 Fragments(A/B).
When i call the Fragment once time, they load fine.
But when i call the Fragment(C) the secend time, the Fragment A and B dont call the View onCreateView methode and the isn´t loaded.
The Fragment C is called with Fragmetnmanger:
FragmentC fragment = new FragmentC();
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.adressenmdf_detail_container, fragment).addToBackStack(null).commit();

Fragment C
 public BelegeDetails(){

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_belege_details, container, false);
    //TODO Actionbar noch anpassen
    //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

The Setups from Fragment C
    private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());

    adapter.addFragment(new BelegeDetails1(),"Details" );
    adapter.addFragment(new BelegeDetailsPos(), "Positionen");
    viewPager.setAdapter(adapter);
}
private void setupTabIcons() {
    tabLayout.getTabAt(1).setIcon(R.drawable.ic_belege);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

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

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

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);

    }

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

The Fragment A BelegDetails1 und the Fragment B BelegDetailsPos are normal Fragment Classes like:
  public BelegeDetails1() {
    // Required empty public constructor

}

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState.......

A: try changing this:
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());

with:
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());

As you are nesting fragments, you need to use getChildFragmentManager() instead of getFragmentManager()


text:
Q: Default value V/s passing value in INSERT statement I am using MSSQL SERVER. The questions I am asking might be silly but I want some valid answers. So here is my question:
I have a table with some columns. I have taken default in some column like 0 (for INT column), GETDATE() (for DATE column). Now one of my colleague said that taking Getdate() as default will increase overhead so better to pass datetime by INSERT statement. Is it true?
Is it not applicable to 0 or 1 (for INT column)?
How does it create overhead?

A: int default 0 or 1 is a value like hardcode.
but, getdate () like function to know the date on the computer server of SQL Server.
so, when the insert statement, the column with the default getdate () will look for the value prior to the server computer before the command insert is run.


text:
Q: Passing string to JavaScript function from the server side I'm trying to pass a string parameter to a javascript function from the server side which will be posted to an AJAX method. The html is dynamically generated at the server side and I'm calling the javascript function using onclick property. The problem is that it works for a numeric value but I get an internal server error when I pass in a string value.
here's my server side code:
str.Append("");

Here's my javascript method:
function Request(param) {
        $.ajax({
            type: "POST",
            url: '<%= ResolveUrl("~/myaccount/notifications/Default.aspx/Accept") %>',
            data: "{'param' : "+param+"}",
            contentType: "application/json",
            success: function (msg) {
                msg = msg.hasOwnProperty("d") ? msg.d : msg;
                alert(msg);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }

and here's the method that will be called by AJAX:
        [WebMethod]
    public static string Accept(string param)
    {
        return param;
    }

What's the right way to do this?

A: The JSON you are passing to the web method is implying that it is an numeric value, add quotes surrounding the param value:
Old
data: "{'param' : "+param+"}",

New
data: "{'param' : '"+param+"'}",

Alternatively ...
If a string is always passed to your Request method, it will be correctly handled using JSON.stringify
data: JSON.stringify({ 'param' : param }),


text:
Q: How to align button in the header to the right side of header in ionic 4 Button is aligned right in the toolbar but the icon is not shown.
Only white box appear.
.html
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>

    <ion-title style="text-align: center;">RE-MED+</ion-title>

    <ion-buttons slot="primary">
      <ion-button>
        <ion-icon slot="icon-only" name="exit"></ion-icon>
      </ion-button>
    </ion-buttons>

  </ion-toolbar>
</ion-header>

It looks like this.

I want Like this

A: Try this in your .html
<ion-header>
  <ion-toolbar color="dark">
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>

    <ion-title class="ion-text-center">RE-MED+</ion-title>

    <ion-buttons slot="end">
      <ion-button fill="clear">
        <ion-icon slot="icon-only" name="exit"></ion-icon>
      </ion-button>
    </ion-buttons>

  </ion-toolbar>
</ion-header>

A: This will work in Ionic5. Maybe Ionic4...?
<ion-header>
  <ion-toolbar>
    <ion-title>Hello World</ion-title>
      <ion-button slot="end" (click)="actionbutton()">Close</ion-button>
  </ion-toolbar>
</ion-header>

A: It is solved.
I have created CSS for another component.
I don't know how but it applies to ion-button so I change the name of that CSS.
Its name was .button I changed to .button_border
.css
.button_border{
    border-radius: 10px !important;
    border: 2px solid #ffffff;
    background-color: white;
    color: #0032fe;
    box-shadow: none !important;
    padding-left: 24px;
    padding-right: 34px;
    padding-top: 5px;
    padding-bottom: 5px;
    font-size: 18px;
    margin-left: 20px;
    margin-right: 20px;
}


text:
Q: Faction with Neriak in EverQuest 1 What is the easiest way to get my faction up with all(...or most) of Neriak?
I need to be able to...

*

*Buy hate stones

*Bank

*Turn in 50g Mizr N`Mar for the rune for the Incandecent Mask Quest

I really don't mind if the occasional NPC aggro's, i can just gate.

A: You can hand in Red Wine in stacks of four to Lokar T'Biath in the library to increase your Dark Bargainers and Inner/Outer Guards faction.


text:
Q: allowing timeouts for commands that have no timeout option, where `IFS=$'\n'` In the lines below, which I added to my copy of Apple's sysdiagnose script:

*

*wherever a timeout is already scripted, it is effective

*I must add timeouts in two areas, but I don't know how to do so.

In the two areas, IFS=$'\n' …
# If there exists a zfs binary, get some ZFS information
if [ -f "${ZFS}" ]
then
    #
    # The pool part
    #
    "${ECHO}" "Recording ZFS pool version information ..."
    "${ZPOOL}" upgrade &> ${data_directory_path}/"ZFS pools and properties.txt" &
    add_timeout_pid $! 30
    "${ECHO}" "    listing all ZFS pools ..."
    "${ECHO}" "" >> ${data_directory_path}/"ZFS pools and properties.txt"
    "${ECHO}" "ZFS pools:" >> ${data_directory_path}/"ZFS pools and properties.txt"
    "${ECHO}" "" >> ${data_directory_path}/"ZFS pools and properties.txt"
    "${ZPOOL}" list >> ${data_directory_path}/"ZFS pools and properties.txt" &
    add_timeout_pid $! 30
    "${ECHO}" "    all properties of each pool ..."
    OLD_IFS=$IFS
    IFS=$'\n'
    # If cut or zpool can not progress, then at this point: sysdiagnose will not progress
    # <https://superuser.com/q/540939/84988>
    for zfspool in `"${ZPOOL}" list -H | cut -f 1`
    do
        { echo "\n*********************\n" ; "${ZPOOL}" get all "$zfspool" ; } >> ${data_directory_path}/"ZFS pools and properties.txt"
    done
    IFS=$OLD_IFS
    "${ECHO}" "    detailed health status and verbose data error information ..."
    "${ZPOOL}" status -v &> ${data_directory_path}/"ZFS pool detailed health status and verbose data error information.txt" &
    add_timeout_pid $! 30
    "${ECHO}" "    pools that are available but not currently imported"
    "${ZPOOL}" import &> ${data_directory_path}/"ZFS pools not imported.txt" &
    add_timeout_pid $! 30
    #
    # The file system part
    #
    "${ECHO}" "Recording ZFS file system version information ..."
    { "${ZFS}" upgrade ; "${ECHO}" "\n" ; } &> ${data_directory_path}/"ZFS file systems and properties.txt" &
    add_timeout_pid $! 30
    "${ECHO}" "    listing all ZFS file systems ..."
    #"${ECHO}" "ZFS file systems:" >> ${data_directory_path}/"ZFS file systems and properties.txt"
    "${ZFS}" list >> ${data_directory_path}/"ZFS file systems and properties.txt" &
    add_timeout_pid $! 30
    "${ECHO}" "    all properties of each file system"
    OLD_IFS=$IFS
    IFS=$'\n'
    # If cut or zfs can not progress, then at this point: sysdiagnose will not progress
    # <https://superuser.com/q/540939/84988>
    for zfsfilesystem in `zfs list -H | cut -f 1`
    do
        { echo "\n*********************\n" ; "${ZFS}" get all "$zfsfilesystem" ; } >> ${data_directory_path}/"ZFS file systems and properties.txt"
    done
    IFS=$OLD_IFS
    #
    # Directory listings
    #
    "${ECHO}" "Listing the contents of /dev/dsk"
    { "${ECHO}" "Directory listing for /dev/dsk" ; echo "\n"; } >> ${data_directory_path}/"ZEVO-oriented directory listings.txt"
    { "${LS}" -@ael /dev/dsk ; echo "\n*********************\n" ; } >> ${data_directory_path}/"ZEVO-oriented directory listings.txt" &
    add_timeout_pid $! 30
    "${ECHO}" "Listing the contents of /var/zfs/dsk"
    { "${ECHO}" "Directory listing for /var/zfs/dsk" ; echo "\n" ; } >> ${data_directory_path}/"ZEVO-oriented directory listings.txt"
    "${LS}" -@ael /var/zfs/dsk >> ${data_directory_path}/"ZEVO-oriented directory listings.txt" &
    add_timeout_pid $! 30
fi

Note the comment:
# If cut or zpool can not progress, then at this point: sysdiagnose will not progress
Question
How can I write add_timeout_pid $! 30 into those two areas?
Background
Whilst I can't reproduce the script in its entirety (it's not open source), users of Lion and greater may find Apple's script human-readable:
/usr/bin/sysdiagnose
Links
sysdiagnose(1) OS X Manual Page
cut(1) OS X Manual Page
The accepted answer to Handling whitespaces in the name of a ZFS dataset in a shell script
Also in Super User, Force a bash script to run to completion where some items may stick
– but the answer there is no good for commands (such as cut, zfs and zpool) that have no timeout option.


text:
Q: Contructive Proof of 2nd Quantization form of Operators Is there a constructive proof for these forms of operators in second quantization
$$R= \sum \limits_a \sum \limits_b \langle a | R_1 | b \rangle  C_a^\dagger C_b $$
using the general form $R = \sum \limits_i^N R_i$ where we sum over all  $n$ single particle state operators?

*

*a more precise definition of these opertors on an $N$ particle Hilbert space  would be $R|\Psi\rangle=\sum \limits_i^N |\Psi_1\rangle\otimes..\otimes R_i |\Psi_i\rangle\otimes...\otimes|\Psi_N\rangle$

All this is done with fermionic operators and states. $C_a^\dagger$ is the creation operator, where $a$ refers to a  quantum number uniquely identifying a one particle state. The sums over the quantum numbers are just over all the possible states i suppose, as that would be sensible. I can not find a definition of the single particle operators in this book, which is of course not helping.
I was trying to understand Ballentines proof for a general pair operator when this question occured to me. It looks as if going directly should be a lot easyer to just apply to that case aswell.
I tried many things but i don't seem to have a firm enough grasp on the formalism to realize this on my own. I am not shure if that is total nonsense or if i just don't know enaugh to do the last step here. I just put this example in so you know  as a rough direction what I mean by contructive proof. Somehow of course the vacuum states should vanish here and i would need to somehow discover a $ \delta_{i,1}$ in that equation but who knows...
$$R= \sum \limits_i R_i =\sum \limits_i \sum \limits_{a,b} |a\rangle\ \langle a|R_i|b\rangle\langle b|=\sum \limits_i \sum \limits_{a,b} C_a^\dagger |0\rangle\ \langle a|R_i|b\rangle\langle 0|C_b $$
$$
=\sum \limits_i \sum \limits_{a,b} \langle a|R_i|b\rangle\; C_a^\dagger |0\rangle\ \langle 0|C_b$$
I would really appriciate any Help on this and on the possibility of a construction of the general additive pair operator in a similar way.

A: It is posslible to do this proof in a direct way using a slightly different and in my opinion a lot more sensible approach to the creation/annihilation operators. I will write it up here for the benefit of any interested.
The inner product of $N$ particle states can be written as:
$$ \langle\chi_1,...,\chi_N|\Psi_1,...,\Psi_N\rangle= \det {\begin{pmatrix}\langle\chi_1|\Psi_1\rangle &...& \langle\chi_1|\Psi_N\rangle \\.\\.\\\langle\chi_N|\Psi_1\rangle& ...& \langle\chi_N|\Psi_N\rangle\end{pmatrix}}$$
Using th Slater determinant for fermion- and the permanent for Boson-states.
With this we get a new representation of the annihilation operator $C_a$. We are now looking at $N-1$ particle states:
$$ \langle\chi_1,...,\chi_{N-1}|C_a |\Psi_1,...,\Psi_N\rangle = \langle\Psi_1,...,\Psi_N|C_a^\dagger |\chi_1,...,\chi_{N-1}\rangle^* \\
\langle\Psi_1,...,\Psi_N| a,\chi_1,...,\chi_{N-1}\rangle^*=\det {\begin{pmatrix}\langle \Psi_1 |a \rangle &\langle\Psi_1|\chi_1\rangle &...& \langle\Psi_1|\chi_{N-1}\rangle \\.\\.\\ \langle \Psi_1|a \rangle & \langle\Psi_N|\chi_1\rangle& ...& \langle\ \Psi_N|\chi_{N-1}\rangle\end{pmatrix}}^*$$
from the definition of the determinant we know we can write this equally as:
$$=\sum \limits_{k=1}^N \xi^{k-1}\langle a|\Psi_k \rangle \langle\chi_1,...,\chi_{N-1}|\Psi_1,...,\sim\Psi_k,...,\Psi_N\rangle$$
whre $\xi=-1$ for fermions and $+1$ for bosons and $\sim\Psi_k$ means $\Psi_k$ is not part of that state. This gives a new representation of the annihilatinon operator $$C_a|\Psi_1,...,\Psi_N\rangle=\sum \limits_{k=1}^N \xi^{k-1}\langle a|\Psi_k \rangle  |\Psi_1,...,\sim\Psi_k,...,\Psi_N\rangle$$
We now need to look at a one particle Operator $R_{ab}=|a\rangle \langle b|$ definied as in the question above:
$$R_{ab}|\Psi_1,...,\Psi_N\rangle=\sum \limits_i^N |\Psi_1\rangle\otimes..\otimes  \underbrace{| a \rangle}_{\text{i-th ket}} \otimes...\otimes|\Psi_N\rangle \langle b | \Psi_i\rangle $$
with this and the newfound representation of the operators we see that the operator $R_{ab}$ can be writtten as $R_{ab}=C_a^\dagger C_b$. How can we see this?
First $$C_a^\dagger C_b |\Psi_1,...,\Psi_N\rangle= \sum \limits_{k=1}^N \xi^{k-1}\langle b|\Psi_k \rangle |a,\Psi_1,...,\sim\Psi_k,...,\Psi_N\rangle$$
second using the symmetry of the states we get:
$$|a,\Psi_1,...,\Psi_{k-1},\Psi_{k+1},...,\Psi_N\rangle=\xi^{k-1}|\Psi_1,...,\Psi_{k-1},a,\Psi_{k+1},...,\Psi_N\rangle$$
This results in the desired equality: $R_{ab}=C_a^\dagger C_b$. With this we now have finished the proof since i allows us to write any one particle operator A as:
$$A=\sum \limits_{k=1}^N \sum_{a,b} |a\rangle \langle a| A |b\rangle \langle b|= \sum_{a,b}  C_a^\dagger C_b \langle a| A |b\rangle $$ the sum over $k$ went into the operator $C_b$, as it should according to the introduced representation. This is what we wanted. Have a nice day. Please feel free to critique.
EDIT: this method can be used for the two particle interaction as well.


text:
Q: python discord bot wikipedia one command hindering all the others I've found a code to make the bot look for important words on wikipedia but the problem is that if I put in in the code all the other commands stops working so i wanted to know what to do
@bot.event
async def on_message(message):
    words = message.content.split()
    if words[0].lower() == ".define":
       important_words = words[1:]
       try:
           await bot.send_message(message.channel, wiki_summary(important_words))
       except wikipedia.exceptions.DisambiguationError as e:
           await bot.send_message(message.channel, e)

I've thought of putting it to a @bot.command but don't really know how to modify it to get it to work and another problem was that in only takes up one word so if I want to look for 'city block' it would only take block and make it a disambiguation error
Thanks in advance for the help !


text:
Q: javascript button that fills the current input instead of the first one I made a button that can fill forms with javascript, but it only fills the first input on the page. I want it to fill whichever input cursor is blinking on.
I need help.
Heres my code:

<script>
  function autoFill() {
    var input = document.getElementsByTagName("INPUT")[0]

    input.value += "only works with the first input";
  }
</script>

<input type="input">
<button type="button" onclick="autoFill()">fill it!</button>
<input type="input">

A: One solution would be to track the previously focused input[type="input"] element using document.querySelectorAll via an additional state variable (ie lastFocus as shown below). Then, when autoFill() is called, populate the value of the lastFocus element if it exists:

let lastFocus = ''

function autoFill() {

  /* If a last focused input exists, populate it */
  if (lastFocus) {

    var input = document.querySelector('input:focus')
    lastFocus.value += "only works with the first input";
  }
}

/* Iterate each input element in document */
document.querySelectorAll('input[type="input"]').forEach(element => {

  /* Add an "on focus" listener, which sets last focused input*/
  element.addEventListener('focus', event => {
    lastFocus = element;
  });
});
<input type="input">
<button type="button" onclick="autoFill()">fill it!</button>
<input type="input">

Hope that helps!

A: You can use the event focus and through the attribute Event.target get the currently focused element.
Embrace the function addEventListener for binding events.

let focused;
Array.from(document.querySelectorAll("input")).forEach((input) => {
  input.addEventListener('focus', function(e) {
    focused = e.target;
  });
});

document.querySelector('button').addEventListener('click', () => {
  if (focused) focused.value += "only works with the first input";
});
<input type="input">
<button type="button">fill it!</button>
<input type="input">

A: you are always setting value of the first input control in your script. You need a way to identify which input was last in focus before clicking auto fill button. Maybe you can add an onfocus handler to each required input and record the last input in focus.

A: You need a way to find out which input box the user is currently typing in. We can do this by attaching click event listeners to the individual text boxes. As soon as someone clicks on it to actually type something we update a global variable which holds a reference to just clicked - thus active - object.
First give your text boxes an id so we can distinguish them:
<input type="input" id="input1">
<input type="input" id="input2">

Afterwards add these lines:
var activeInput;
document.getElementById("input1").addEventListener("click", toggleActive);
document.getElementById("input2").addEventListener("click", toggleActive);

function autoFill() {
  activeInput.value += "only works with the first input";
}

function toggleActive(e) {
  activeInput = e.target;

}

A: This will track input focus and when button clicked it will fill correct control.

// track current focus
let currFocus;
document.addEventListener('focusin', (e) => {
  if (e.target.nodeName.toLowerCase() === 'input') currFocus = e.target;
});

function autoFill() {
  if (currFocus) currFocus.value += "only works with the first input";
}
<input type="input">
<button type="button" onclick="autoFill()">fill it!</button>
<input type="input">

A: I added listener for focus event and use one focused object for input.

var focused, inputs=document.getElementsByTagName('INPUT');
for(i = 0; i < inputs.length; i++) {

        inputs[i].addEventListener("focus", function(){
            focused = this;
        });

}

  function autoFill() {
    var input = document.getElementsByTagName("INPUT");
    for(i = 0; i < input.length; i++) {
      if(input[i] === focused){
           input[i].value += "auto filled";
      }
    }

  }
<input type="input">
<button type="button" onclick="autoFill()">fill it!</button>
<input type="input">


text:
Q: Jenkins makefile error I am setting up CI for my project, the build works fine on linux but on windows it shows Makefile:84: *** missing separator.  Stop.. What's interesting to see here is the same Makefile works fine on the local machine but not through Jenkins.
i have checked the character set and converted the file to UTF8-Without BOM but that doesn't seem to work.
Any direction to this ? If the makefiles for windows and linux is different than whats the difference there which could cause the problem.

A: Make sure your line endings are set correctly. Also make sure you use tabs and spaces as appropriate.
Check the versions of make with make --version - it might give you some hints.
Apart from that, we can only guess what is on line 84 :)


text:
Q: Show $\frac{1}{x}\leq \ln(2x+1)-\ln(2x-1)$ for $x\geq 1$. Prove that for $x\geq 1$ the following inequality is true: $$\dfrac{1}{x}\leq \ln(2x+1)-\ln(2x-1).$$
Can anyone help with this problem? I thought about some hours but any ideas

A: Let $f(x)=\ln(2x+1)-\ln(2x-1)-\frac 1x$. Then, we have
$$f'(x)=\frac{2}{2x+1}-\frac{2}{2x-1}+\frac 1{x^2}=\frac{-1}{x^2(2x+1)(2x-1)}\lt 0$$
for $x\ge 1$ with $\lim_{x\to +\infty}f(x)=0$.

A: More generally, show that if $f(t)$ is a convex differentiable function on $[a,b]$ then $$(b-a)f\left(\frac{a+b}{2}\right) \leq \int_{a}^b f(t)\,dt$$
In the above case, $a=2x-1,b=2x+1, f(t)=\frac{1}{t}$.


text:
Q: SQL Server calculating working hours with multiple IN OUT I have a table with employees attendance logs from sensor machines, employees can have multiple IN & OUT entries in a single day, I want to calculate the number of hours an employess remained IN (total worked hours) by ignoring the Time OUT
I've been looking for this solution for two days, but can't get the required result.
Logs Table is as under (checkin_out_log)
╔════════╦═══════╦═════════════════════════╦════════════╗
║ emp_id ║ shift ║       check_time        ║ check_type ║
╠════════╬═══════╬═════════════════════════╬════════════╣
║      2 ║     1 ║ 2018-02-22 07:00:44.000 ║ C-IN       ║
║      2 ║     1 ║ 2018-02-22 13:00:35.000 ║ B-OUT      ║
║      2 ║     1 ║ 2018-02-22 13:30:46.000 ║ B-IN       ║
║      2 ║     5 ║ 2018-02-22 16:00:55.000 ║ C-OUT      ║
╚════════╩═══════╩═════════════════════════╩════════════╝

Desired OUTPUT is :
╔════════╦══════════╦═════════════════════════╦════════════╗
║ emp_id ║  IN Hrs  ║       Date              ║ OUT HRS    ║
╠════════╬══════════╬═════════════════════════╬════════════╣
║      2 ║ 08:30    ║ 2018-01-22              ║ 00:30      ║
╚════════╩══════════╩═════════════════════════╩════════════╝

Here is the data in query
Here is what I get in results with data shown in screenshot with your query, please guide whats wrong

A: Assuming the IN and OUT are always in pair.
You can make use of LEAD() window function to get next check_time. And use CASE WHEN condition to determine it is IN or OUT time
select  emp_id,
        in_hrs = sum(in_mins) / 60.0,
        check_date = convert(date, check_time),
        out_hrs = sum(out_mins) / 60.0
from
(
    select  *,
            in_mins = CASE  WHEN    check_type in ('C-IN', 'B-IN')
                            AND     LEAD(check_type) OVER (PARTITION BY emp_id ORDER BY check_time) in ('C-OUT', 'B-OUT')
                            THEN    DATEDIFF(MINUTE,
                                             check_time,
                                             LEAD(check_time) OVER (PARTITION BY emp_id ORDER BY check_time))
                            ELSE    0
                            END,
            out_mins= CASE  WHEN    check_type in ('C-OUT', 'B-OUT')
                            AND     LEAD(check_type) OVER (PARTITION BY emp_id ORDER BY check_time) in ('B-IN')
                            THEN    DATEDIFF(MINUTE,
                                             check_time,
                                             LEAD(check_time) OVER (PARTITION BY emp_id ORDER BY check_time))
                            ELSE    0
                            END
    from    checkin_out_log
) d
group by emp_id, convert(date, check_time)

Edit : added condition to validate cases where IN without OUT or vice-versa. The in/out will be ignore and no calculation.
The added condition are
LEAD(check_type) OVER (PARTITION BY emp_id ORDER BY check_time) in ('C-OUT', 'B-OUT')


text:
Q: How prive this number theory $\sum_{k=1}^{p-1}kn_{k}\equiv \dfrac{1}{2}(p-1)(\mod p)$ let $p>3 $ is prime number,and $S=\{1,2,\cdots,p-1\}$,for every $k\in S$ there exist uniquely $x_{k}\in S$,such that $kx_{k}\equiv 1 (\mod p)$,that is $kx_{k}=1+n_{k}p,k=1,2,3,\cdots,p-1$
show that
$$\sum_{k=1}^{p-1}kn_{k}\equiv \dfrac{1}{2}(p-1)(\mod p)$$

A: Note that in $\Bbb{Q}_{p}$, we have
$$ \frac{1}{x_k} = \frac{k}{1 + n_k p} = k (1 - n_k p + O(p^2) ) = k - k n_k p + O(p^2). $$
Thus we have
$$ \sum_{k=1}^{p-1} \frac{1}{x_k} = \sum_{k=1}^{p-1} (k - k n_k p + O(p^2)) = \frac{p(p-1)}{2} - p \sum_{k=1}^{p-1} k n_k + O(p^2). $$
But since the map $ k \mapsto x_k$ permutes $S$, it follows that
$$ \sum_{k=1}^{p-1} \frac{1}{x_k} = \sum_{k=1}^{p-1} \frac{1}{k} = O(p^2), $$
where the last equality follows from the Wolstenholme's Theorem. Therefore rearranging,
$$ \sum_{k=1}^{p-1} k n_k = \frac{p-1}{2} + O(p) $$
and the conclusion follows.