问:
Convert dict of dicts to CSV in a composite-key format
I asked this question but it was closed, having the below suggested solutions:

Thread 1

Thread 2

Thread 3

Thread 4

These unfortunately do not answer my question as they are all based on a matrix-format table. I'd like a composite-key format. I was informed if the suggested threads do not answer my question, then I post another one.

I have a JSON file in the following format:

```<code>{
    "0": {
        "0": "skinless, boneless chicken breast halves",
        "1": "butter",
        "2": "condensed cream of chicken soup",
        "3": "onion, finely diced",
        "4": "refrigerated biscuit dough, torn into pieces"
    },
    "1": {
        "5": "condensed cream of mushroom soup",
        "3": "dry onion soup mix",
        "6": "water",
        "7": "pot roast"
    },
...
}
</code>```

I would like to convert it as follows:

```<code>pk1 pk2 text
0   1   skinless, boneless chicken breast halves
0   2   butter
0   3   condensed cream of chicken soup
...
1   7   pot roast
...
</code>```

I have tried using pandas, as follows:

df = pd.DataFrame.from_records(ingredient_list)

df.to_csv('outputfile.csv')
```

<p>But this resulted a csv file in a matrix-like format:</p>

```    0            1       2            ...  5            ...
0   skinless...  butter  condensed...
1                                          condensed...
...
```

This is not what I expected. How can I achieve the result I require, in a composite-key manner?

答:
Try this:

```<code>pd.DataFrame([(k,k1,v1) for k,v in dct.items() for k1,v1 in v.items()], columns=['pk1', 'pk2', 'text'])
</code>```

where dct is:

```<code>{
    "0": {
        "0": "skinless, boneless chicken breast halves",
        "1": "butter",
        "2": "condensed cream of chicken soup",
        "3": "onion, finely diced",
        "4": "refrigerated biscuit dough, torn into pieces"
    },
    "1": {
        "5": "condensed cream of mushroom soup",
        "3": "dry onion soup mix",
        "6": "water",
        "7": "pot roast"
    },
...
}
</code>```

Body:
I asked this question but it was closed, having the below suggested solutions:

Thread 1

Thread 2

Thread 3

Thread 4

These unfortunately do not answer my question as they are all based on a matrix-format table. I'd like a composite-key format. I was informed if the suggested threads do not answer my question, then I post another one.

I have a JSON file in the following format:

{
    "0": {
        "0": "skinless, boneless chicken breast halves",
        "1": "butter",
        "2": "condensed cream of chicken soup",
        "3": "onion, finely diced",
        "4": "refrigerated biscuit dough, torn into pieces"
    },
    "1": {
        "5": "condensed cream of mushroom soup",
        "3": "dry onion soup mix",
        "6": "water",
        "7": "pot roast"
    },
...
}

I would like to convert it as follows:

pk1 pk2 text
0   1   skinless, boneless chicken breast halves
0   2   butter
0   3   condensed cream of chicken soup
...
1   7   pot roast
...

I have tried using pandas, as follows:

df = pd.DataFrame.from_records(ingredient_list)

df.to_csv('outputfile.csv')

But this resulted a csv file in a matrix-like format:

    0            1       2            ...  5            ...
0   skinless...  butter  condensed...
1                                          condensed...
...

This is not what I expected. How can I achieve the result I require, in a composite-key manner?

Body:
Try this:

pd.DataFrame([(k,k1,v1) for k,v in dct.items() for k1,v1 in v.items()], columns=['pk1', 'pk2', 'text'])

where dct is:

{
    "0": {
        "0": "skinless, boneless chicken breast halves",
        "1": "butter",
        "2": "condensed cream of chicken soup",
        "3": "onion, finely diced",
        "4": "refrigerated biscuit dough, torn into pieces"
    },
    "1": {
        "5": "condensed cream of mushroom soup",
        "3": "dry onion soup mix",
        "6": "water",
        "7": "pot roast"
    },
...
}


来源: stackexchange

问:
How do you convert variable names to a string in Dart?
Very new to Flutter and Dart, so pardon me for the ill-phrased question.

This is a generic code that I have:

```<code>// Constructor class
class ctr {
  String i;
  ctr(String a){
    this.a = a;
}

// New variables based on contsructor
var ctrA = ctr('a');
var ctrB = ctr('b');
var ctrC = ctr('c');

// Storing the variables based on constructor in an array
List ctrList = [ctrA, ctrB, ctrC]

void main() {
  String match = 'ctrB';
  for (var i = 0; i<ctrList.length; i++) {
    if(match == ctrList.toString() {
      print('The string of your match is ${ctrList[i].a}');
    } else {
      print('Error!);
    }
  }
}
</code>```

The current output is Error!.
Instead, what I'm looking for is a.

As you can see, I'm trying to iterate the variable match over the array that stores the variables based on an aforementioned constructor, and if it matches, print out the value in the constructor that it has matched to. runtimeType can only get me the name of the origin Class (which will be ctr).

I tried to convert the variable name by using toString() but that didn't work either. What I need is a method to convert these variable names to a string and get a match, but I'm not sure what I can do.

Thanks in advance for the help!

答:
There is no way in Dart to get an objects name. C# for instance has the nameof() function, but Dart has nothing like it.

That being said there is probably a much easier way of doing whatever your reason for needing this is. So feel free to ask for alternative approaches.

If you just want to use the variable name as an identifier of sorts, maybe look into Maps.

```<code>Map<String,String> x = {"ctrB" : "b"};
</code>```

They let you define a key and value of whatever type you want.

EDIT: as an aside, this declaration

```<code>class ctr {
  String i;
  ctr(String a){
    this.a = a;
}
</code>```

can be simplified to this:

```<code>class ctr {
  String i;
  ctr(this.i);

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Very new to Flutter and Dart, so pardon me for the ill-phrased question.

This is a generic code that I have:

// Constructor class
class ctr {
  String i;
  ctr(String a){
    this.a = a;
}

// New variables based on contsructor
var ctrA = ctr('a');
var ctrB = ctr('b');
var ctrC = ctr('c');

// Storing the variables based on constructor in an array
List ctrList = [ctrA, ctrB, ctrC]

void main() {
  String match = 'ctrB';
  for (var i = 0; i<ctrList.length; i++) {
    if(match == ctrList.toString() {
      print('The string of your match is ${ctrList[i].a}');
    } else {
      print('Error!);
    }
  }
}

The current output is Error!.
Instead, what I'm looking for is a.

As you can see, I'm trying to iterate the variable match over the array that stores the variables based on an aforementioned constructor, and if it matches, print out the value in the constructor that it has matched to. runtimeType can only get me the name of the origin Class (which will be ctr).

I tried to convert the variable name by using toString() but that didn't work either. What I need is a method to convert these variable names to a string and get a match, but I'm not sure what I can do.

Thanks in advance for the help!

Body:
There is no way in Dart to get an objects name. C# for instance has the nameof() function, but Dart has nothing like it.

That being said there is probably a much easier way of doing whatever your reason for needing this is. So feel free to ask for alternative approaches.

If you just want to use the variable name as an identifier of sorts, maybe look into Maps.

Map<String,String> x = {"ctrB" : "b"};

They let you define a key and value of whatever type you want.

EDIT: as an aside, this declaration

class ctr {
  String i;
  ctr(String a){
    this.a = a;
}

can be simplified to this:

class ctr {
  String i;
  ctr(this.i);

}


问:
How to return the two biggest items in an OCaml int list in the most efficient way?
I am new to Caml and don't always understand everything I'm doing.
In a homework I am asked to write a function which, given l a list of n integers and max a function which returns the biggest integer of two, returns the two biggest items in l, calling the max function at most 2n-3 times. I have already made a max_in_list function which returns the biggest, if this can be useful:

```<code>let max a1 a2 = if a1>a2 then a1 else a2;;

let rec max_in_list l = match l with
    | [] -> 0
    | [a] -> a
    | a::q -> max a (max_in_list q)
;;
</code>```

How could I solve this problem?

答:
Enumerate elements of the list and keep the biggest integers in the accumulator. The following function has O(n). It returns None when the length of the list is less than two and Some result otherwise.

let double_max =
  let rec f (a, b) = function
    | h :: t when h > a -> f (h, a) t
    | h :: t when h > b -> f (a, h) t
    | _ :: t            -> f (a, b) t
    | []                ->   (a, b) in
  function
  | a :: b :: t when a > b
                -> Some (f (a, b) t)
  | a :: b :: t -> Some (f (b, a) t)
  | _           -> None
```

Body:
I am new to Caml and don't always understand everything I'm doing.
In a homework I am asked to write a function which, given l a list of n integers and max a function which returns the biggest integer of two, returns the two biggest items in l, calling the max function at most 2n-3 times. I have already made a max_in_list function which returns the biggest, if this can be useful:

let max a1 a2 = if a1>a2 then a1 else a2;;

let rec max_in_list l = match l with
    | [] -> 0
    | [a] -> a
    | a::q -> max a (max_in_list q)
;;

How could I solve this problem?


问:
Webscraping of product prices and specs
I'm new to the VBA world and i was trying to create a Excel file to get the cheapest price and name tag on a website. I've created one file that goes through the whole search list and gathers each product URL and places on a spreadsheet. My challenge now is in making this second code work. It starts out getting the information without any issues but then, after 10 or more URLs the macro gives a bug and it starts repeating the information on all the following cells.. Is there a way i can make the code run slower so it doesn't get into this problem?

I'll list here my code and a sample of the URLs im scraping..

here's the code i've been using:

```<code>Sub test()
Dim URL As String

Set ie = CreateObject("internetexplorer.application")

For i = 2 To 300

URL = Cells(i, 1).Value

ie.navigate URL
ie.Visible = False

Do While ie.busy And ie.readystate <> "readystate_complete"
DoEvents
Loop

Cells(i, 3) = ie.document.getElementsByTagName("h1")(0).innerText
Cells(i, 4) = ie.document.getElementsByTagName("strong")(0).innerText
Next i

ie.Quit

MsgBox "acabou"

End Sub
</code>```

<https://www.zoom.com.br/notebook/notebook-vaio-vjf157f11x-b0211s-intel-core-i5-8250u-15-6-8gb-ssd-256-gb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-samsung-chromebook-plus-intel-celeron-3965y-12-2-4gb-emmc-32-gb-chrome-os-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-xps-7390-intel-core-i7-10710u-13-3-16gb-ssd-512-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a5-intel-core-i7-8565u-15-6-8gb-hd-2-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-4gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-7580-a20-intel-core-i7-8550u-15-6-8gb-hd-1-tb-geforce-mx150-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i14-3480-u30-intel-core-i5-8265u-14-4gb-hd-1-tb-linux-8-geracao>
<https://www.zoom.com.br/notebook/macbook-pro-apple-muhn2bz-intel-core-i5-13-3-8gb-ssd-128-gb-tela-de-retina>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc150-amd-a4-9120-14-2gb-emmc-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-samsung-np930qaa-kw1br-intel-core-i7-8550u-13-3-8gb-ssd-256-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-acer-a515-51g-58vh-intel-core-i5-7200u-15-6-8gb-hd-1-tb-geforce-940mx>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc222-intel-celeron-dual-core-13-3-4gb-emmc-64-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-pt515-51-788a-intel-core-i7-9750h-15-6-32gb-ssd-1-tb-geforce-rtx-2070-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-53-53ak-intel-core-i5-7200u-15-6-4gb-hd-1-tb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-5584-m40-intel-core-i7-8565u-15-6-8gb-hd-2-tb-geforce-mx130-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-41g-r21b-amd-ryzen-5-2500u-15-6-8gb-hd-1-tb-radeon-535-windows-10>
<https://www.zoom.com.br/notebook/notebook-positivo-master-n2140-intel-core-i3-7020u-14-4gb-hd-500-gb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc101-intel-atom-14-1gb-ssd-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-8gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-acer-an515-51-77fh-intel-core-i7-7700hq-15-6-8gb-hd-1-tb-geforce-gtx-1050-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a2yp-intel-core-i5-8265u-15-6-4gb-optane-16-gb-hd-1-tb-windows-10>
<https://www.zoom.com.br/notebook/notebook-asus-g531gt-intel-core-i7-9750h-15-6-16gb-ssd-512-gb-geforce-gtx-1650-windows-10>
<https://www.zoom.com.br/notebook/notebook-vaio-fit-15s-intel-core-i3-7100u-15-6-4gb-hd-1-tb-windows-10-home>
<https://www.zoom.com.br/notebook/notebook-samsung-s50-intel-core-i7-7500u-13-3-8gb-ssd-256-gb-windows-10-style>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i3-7020u-15-6-4gb-ssd-120-gb-windows-10-7-geracao>```

答:
In python I will do :

You should first import library

from time import sleep

Two functions available :

this function let you sleep before execute every 3 seconds

```<code>  time.sleep(3)
</code>```

this function let you random sleep between every execute from 1 to 3 seconds

```<code>  sleep(randint(1, 3)
</code>```

Note: take aware about :

cookies because sometimes you need to post request to scrape some id before get.

the syntax of your header and set correctly origin & referrer parameters.

Title: Webscraping of product prices and specs

Body:
I'm new to the VBA world and i was trying to create a Excel file to get the cheapest price and name tag on a website. I've created one file that goes through the whole search list and gathers each product URL and places on a spreadsheet. My challenge now is in making this second code work. It starts out getting the information without any issues but then, after 10 or more URLs the macro gives a bug and it starts repeating the information on all the following cells.. Is there a way i can make the code run slower so it doesn't get into this problem?

I'll list here my code and a sample of the URLs im scraping..

here's the code i've been using:

Sub test()
Dim URL As String

Set ie = CreateObject("internetexplorer.application")

For i = 2 To 300

URL = Cells(i, 1).Value

ie.navigate URL
ie.Visible = False

Do While ie.busy And ie.readystate <> "readystate_complete"
DoEvents
Loop

Cells(i, 3) = ie.document.getElementsByTagName("h1")(0).innerText
Cells(i, 4) = ie.document.getElementsByTagName("strong")(0).innerText
Next i

ie.Quit

MsgBox "acabou"

End Sub

<https://www.zoom.com.br/notebook/notebook-vaio-vjf157f11x-b0211s-intel-core-i5-8250u-15-6-8gb-ssd-256-gb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-samsung-chromebook-plus-intel-celeron-3965y-12-2-4gb-emmc-32-gb-chrome-os-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-xps-7390-intel-core-i7-10710u-13-3-16gb-ssd-512-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a5-intel-core-i7-8565u-15-6-8gb-hd-2-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-4gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-7580-a20-intel-core-i7-8550u-15-6-8gb-hd-1-tb-geforce-mx150-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i14-3480-u30-intel-core-i5-8265u-14-4gb-hd-1-tb-linux-8-geracao>
<https://www.zoom.com.br/notebook/macbook-pro-apple-muhn2bz-intel-core-i5-13-3-8gb-ssd-128-gb-tela-de-retina>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc150-amd-a4-9120-14-2gb-emmc-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-samsung-np930qaa-kw1br-intel-core-i7-8550u-13-3-8gb-ssd-256-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-acer-a515-51g-58vh-intel-core-i5-7200u-15-6-8gb-hd-1-tb-geforce-940mx>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc222-intel-celeron-dual-core-13-3-4gb-emmc-64-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-pt515-51-788a-intel-core-i7-9750h-15-6-32gb-ssd-1-tb-geforce-rtx-2070-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-53-53ak-intel-core-i5-7200u-15-6-4gb-hd-1-tb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-5584-m40-intel-core-i7-8565u-15-6-8gb-hd-2-tb-geforce-mx130-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-41g-r21b-amd-ryzen-5-2500u-15-6-8gb-hd-1-tb-radeon-535-windows-10>
<https://www.zoom.com.br/notebook/notebook-positivo-master-n2140-intel-core-i3-7020u-14-4gb-hd-500-gb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc101-intel-atom-14-1gb-ssd-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-8gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-acer-an515-51-77fh-intel-core-i7-7700hq-15-6-8gb-hd-1-tb-geforce-gtx-1050-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a2yp-intel-core-i5-8265u-15-6-4gb-optane-16-gb-hd-1-tb-windows-10>
<https://www.zoom.com.br/notebook/notebook-asus-g531gt-intel-core-i7-9750h-15-6-16gb-ssd-512-gb-geforce-gtx-1650-windows-10>
<https://www.zoom.com.br/notebook/notebook-vaio-fit-15s-intel-core-i3-7100u-15-6-4gb-hd-1-tb-windows-10-home>
<https://www.zoom.com.br/notebook/notebook-samsung-s50-intel-core-i7-7500u-13-3-8gb-ssd-256-gb-windows-10-style>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i3-7020u-15-6-4gb-ssd-120-gb-windows-10-7-geracao>

Body:
In python I will do :

You should first import library

from time import sleep

Two functions available :

this function let you sleep before execute every 3 seconds

  time.sleep(3)

this function let you random sleep between every execute from 1 to 3 seconds

  sleep(randint(1, 3)

Note: take aware about :

cookies because sometimes you need to post request to scrape some id before get.

the syntax of your header and set correctly origin & referrer parameters.


问:
How to install Java on Arch Linux
According to https://wiki.archlinux.org/index.php/Java I can install Open JDK 7 on a clean Arch Linux installation by invoking the command

```<code>pacman -S jdk7-openjdk
</code>```

But when doing so, I get an error saying

```<code>error: target not found: jdk7-openjdk
</code>```

I already commented out my nearest Pacman repository in /etc/pacman.d/mirrorlist and ran a first update by invoking pacman -Syu hoping that this would cause the package above to be discovered.

How can I install Open JDK 7 on Arch Linux using pacman?

Edit: I'm running a Raspberry Pi with an ARM processor and I'm hoping to get a Java build that is tailored for its hardware and uses the OS hardware floating point support.

答:
Or you may completely skip pacman and take full control:

Download the tar.gz of the JDK version you need from https://adoptopenjdk.net/

Expand the archive: tar zxvf OpenJDKxxx.ta.gz

Move the JDK to /opt: sudo mv jdk-xxx /opt

Update the PATH:

```<code>export JAVA_HOME=/opt/jdk-xxx
export PATH=$PATH:$JAVA_HOME/bin
</code>```

Test: java -version

This way you can install as many different versions of the JDK you want and switch between them by changing the value of PATH

ContentLicense: CC BY-SA 3.0

Title: How to install Java on Arch Linux

Body:
According to https://wiki.archlinux.org/index.php/Java I can install Open JDK 7 on a clean Arch Linux installation by invoking the command

pacman -S jdk7-openjdk

But when doing so, I get an error saying

error: target not found: jdk7-openjdk

I already commented out my nearest Pacman repository in /etc/pacman.d/mirrorlist and ran a first update by invoking pacman -Syu hoping that this would cause the package above to be discovered.

How can I install Open JDK 7 on Arch Linux using pacman?

Edit: I'm running a Raspberry Pi with an ARM processor and I'm hoping to get a Java build that is tailored for its hardware and uses the OS hardware floating point support.

Body:
Or you may completely skip pacman and take full control:

Download the tar.gz of the JDK version you need from https://adoptopenjdk.net/

Expand the archive: tar zxvf OpenJDKxxx.ta.gz

Move the JDK to /opt: sudo mv jdk-xxx /opt

Update the PATH:

export JAVA_HOME=/opt/jdk-xxx
export PATH=$PATH:$JAVA_HOME/bin

Test: java -version

This way you can install as many different versions of the JDK you want and switch between them by changing the value of PATH


问:
How to print a pdf file in color using Adobe reader in C#
In my C# winform application, I print silently a pdf file by using Adobe Reader DC. The pdf file should be printed in color, but the printing preferences of printer's settings is on Black and White. How can I change this property and set it on color programmatically.
Here is my code to print silently:

```<code>public void StartPrinting(string fullFilePathForPrintProcess, string printerName)
        {
            string printApplicationPath = FindAdobeAcrobatPath();
            const string flagNoSplashScreen = "/s";
            const string flagOpenMinimized = "/h";

            var flagPrintFileToPrinter = string.Format("/t \"{0}\" \"{1}\"", fullFilePathForPrintProcess, printerName);

            var args = string.Format("{0} {1} {2}", flagNoSplashScreen, flagOpenMinimized, flagPrintFileToPrinter);

            var startInfo = new ProcessStartInfo
                            {
                                FileName = printApplicationPath,
                                Arguments = args,
                                CreateNoWindow = true,
                                ErrorDialog = false,
                                UseShellExecute = false,
                                WindowStyle = ProcessWindowStyle.Hidden
                            };

            var process = Process.Start(startInfo);

            // Close Acrobat regardless of version
            if (process != null)
            {
                process.WaitForInputIdle();
                process.CloseMainWindow();
                process.Dispose();
            }
        }
</code>```

Any help is appreciated.

答:
I think this is what you're looking for

```<code>private void MyButtonPrint_OnClick(object sender, System.EventArgs e)
{

    // Set the printer name and ensure it is valid. If not, provide a message to the user.
    printDoc.PrinterSettings.PrinterName = "\\mynetworkprinter";

    if (printDoc.PrinterSettings.IsValid) {

        // If the printer supports printing in color, then override the printer's default behavior.
        if (printDoc.PrinterSettings.SupportsColor) {

            // Set the page default's to print in color.
            printDoc.DefaultPageSettings.Color = true;
        }

        // Provide a friendly name, set the page number, and print the document.
        printDoc.DocumentName = "My Presentation";
        currentPageNumber = 1;
        printDoc.Print();
    }
    else {
        MessageBox.Show("Printer is not valid");
    }
}
</code>```

Full code can be found at

Microsoft's documentation

Body:
In my C# winform application, I print silently a pdf file by using Adobe Reader DC. The pdf file should be printed in color, but the printing preferences of printer's settings is on Black and White. How can I change this property and set it on color programmatically.
Here is my code to print silently:

public void StartPrinting(string fullFilePathForPrintProcess, string printerName)
        {
            string printApplicationPath = FindAdobeAcrobatPath();
            const string flagNoSplashScreen = "/s";
            const string flagOpenMinimized = "/h";

            var flagPrintFileToPrinter = string.Format("/t \"{0}\" \"{1}\"", fullFilePathForPrintProcess, printerName);

            var args = string.Format("{0} {1} {2}", flagNoSplashScreen, flagOpenMinimized, flagPrintFileToPrinter);

            var startInfo = new ProcessStartInfo
                            {
                                FileName = printApplicationPath,
                                Arguments = args,
                                CreateNoWindow = true,
                                ErrorDialog = false,
                                UseShellExecute = false,
                                WindowStyle = ProcessWindowStyle.Hidden
                            };

            var process = Process.Start(startInfo);

            // Close Acrobat regardless of version
            if (process != null)
            {
                process.WaitForInputIdle();
                process.CloseMainWindow();
                process.Dispose();
            }
        }

Any help is appreciated.

Body:
I think this is what you're looking for

private void MyButtonPrint_OnClick(object sender, System.EventArgs e)
{

    // Set the printer name and ensure it is valid. If not, provide a message to the user.
    printDoc.PrinterSettings.PrinterName = "\\mynetworkprinter";

    if (printDoc.PrinterSettings.IsValid) {

        // If the printer supports printing in color, then override the printer's default behavior.
        if (printDoc.PrinterSettings.SupportsColor) {

            // Set the page default's to print in color.
            printDoc.DefaultPageSettings.Color = true;
        }

        // Provide a friendly name, set the page number, and print the document.
        printDoc.DocumentName = "My Presentation";
        currentPageNumber = 1;
        printDoc.Print();
    }
    else {
        MessageBox.Show("Printer is not valid");
    }
}

Full code can be found at

Microsoft's documentation


问:
How do I map a non-binary Occupancy Grid with several values to a cost map in ROS?
I'm looking for a way to map a non-binary occupancy grid to a global cost map. The occupancy grid has the values -1 for undefined, 0 for non-collision and 1-100 for collision areas. There is a similar question here for which the given answer doesn't offer a concrete solution:

https://answers.ros.org/question/335530/what-range-of-costs-does-ros-navigation-support/

For a better overview:

I'm using ROS Melodic.

My occupancy grid looks like this:
Image of Occupancy grid

My global_costmap_params.yaml looks like this:

```<code>global_costmap:
plugins:
- {name: static_layer, type: "costmap_2d::StaticLayer"}
- {name: inflation_layer, type: "costmap_2d::InflationLayer"}
global_frame: base_link
map_topic: "prediction_occ_grid"
update_frequency: 10.0
publish_frequency: 10.0
rolling_window: true
always_send_full_costmap: true
height: 26.9
width: 36.4
</code>```

Note that I'm a pure beginner in costmaps, so it might be that this doesn't make sense at all!

Using the given global_costmap_params.yaml deliveres the following costmap: Image of the resulting global costmap

As you can see the costmap "ignores" the collision-areas and maps them in the same costs as the non-collision-path-area. Is there any way to modify the costmap_params in order for it to map the occupancy grid properly?

Thanks in advance!

答:
Most specifically, I'd look at the costmap params for the plugins, chiefly the static_map and obstacles plugins. Perhaps you want the staticmap parameter trinary_costmap to be true, to have the full scale of values in the costmap. The ones in obstacles are likely to change what you expect to see, with multiple layers or input data.

I would also look at Clearpath's Husky husky_navigation package for a good example, ex. move_base.launch file. All the parameters are written in the config/ dir, and loaded by rosparam within the move_base node. Some details: if you're doing a local costmap that moves with the robot, you don't want to track the empty space, you'd want a rolling window, and to use the Obstacle layer instead of the static layer; for the global, you would track all the space, but not move the window with respect to the robot, and you'd use a static map.

I think one issue you have is in data flow. How Ros (& most people, because of it) leans is to have an initial/static map loaded from the beginning (map_server) for both amcl and move_base, update both with either LaserScans &/or PointClouds, and then you're just left with the amcl output of frame tfs & local position estimation, and feeding that into the move_base node, you only need the goal. To use an occ_grid map msg to update amcl, for example, you have to change the use_map_topic param.

Edit:
In case map_server was what you really needed, here's an example usage I pulled from husky_nav's amcl_demo.launch:

<arg name="map_file" default="$(find husky_navigation)/maps/playpen_map.yaml"/>
<node name="map_server" pkg="map_server" type="map_server" args="$(arg map_file)" />
```

Body:
I'm looking for a way to map a non-binary occupancy grid to a global cost map. The occupancy grid has the values -1 for undefined, 0 for non-collision and 1-100 for collision areas. There is a similar question here for which the given answer doesn't offer a concrete solution:

https://answers.ros.org/question/335530/what-range-of-costs-does-ros-navigation-support/

For a better overview:

I'm using ROS Melodic.

My occupancy grid looks like this:
Image of Occupancy grid

My global_costmap_params.yaml looks like this:

global_costmap:
plugins:
- {name: static_layer, type: "costmap_2d::StaticLayer"}
- {name: inflation_layer, type: "costmap_2d::InflationLayer"}
global_frame: base_link
map_topic: "prediction_occ_grid"
update_frequency: 10.0
publish_frequency: 10.0
rolling_window: true
always_send_full_costmap: true
height: 26.9
width: 36.4

Note that I'm a pure beginner in costmaps, so it might be that this doesn't make sense at all!

Using the given global_costmap_params.yaml deliveres the following costmap: Image of the resulting global costmap

As you can see the costmap "ignores" the collision-areas and maps them in the same costs as the non-collision-path-area. Is there any way to modify the costmap_params in order for it to map the occupancy grid properly?

Thanks in advance!

Body:
Most specifically, I'd look at the costmap params for the plugins, chiefly the static_map and obstacles plugins. Perhaps you want the staticmap parameter trinary_costmap to be true, to have the full scale of values in the costmap. The ones in obstacles are likely to change what you expect to see, with multiple layers or input data.

I would also look at Clearpath's Husky husky_navigation package for a good example, ex. move_base.launch file. All the parameters are written in the config/ dir, and loaded by rosparam within the move_base node. Some details: if you're doing a local costmap that moves with the robot, you don't want to track the empty space, you'd want a rolling window, and to use the Obstacle layer instead of the static layer; for the global, you would track all the space, but not move the window with respect to the robot, and you'd use a static map.

I think one issue you have is in data flow. How Ros (& most people, because of it) leans is to have an initial/static map loaded from the beginning (map_server) for both amcl and move_base, update both with either LaserScans &/or PointClouds, and then you're just left with the amcl output of frame tfs & local position estimation, and feeding that into the move_base node, you only need the goal. To use an occ_grid map msg to update amcl, for example, you have to change the use_map_topic param.

Edit:
In case map_server was what you really needed, here's an example usage I pulled from husky_nav's amcl_demo.launch:

<!-- Run the map server -->
<arg name="map_file" default="$(find husky_navigation)/maps/playpen_map.yaml"/>
<node name="map_server" pkg="map_server" type="map_server" args="$(arg map_file)" />


问:
How to secure dealloc memory for objectiveC Strings in iOS?
I am pretty new in iOS development and I have the following question:
In my code I have a UIViewController with a UIText field that will hold a password when user will type in the view. The password is used for authentication in front a server:

```<code>UItextField* txtPassword;
[myClass loginWithPassword:txtPassword.text];
</code>```

After using it I want to be sure that there are no leftovers of the password in the memory, so an attacker won't be able performing a memory dump of the iPhone and extracting from it the password.

In windows for example I could use the SeucreZeroMemory function for filling a block of memory with zeros.

What is the best way doing it for iOS? Who is responsible to free the UItextField* string, and is it enough?

答:
What you want is really not needed, you don't need to write zeros over you allocated data to be sure that it is secure. The reason is that no one but you can access the memory and iOS uses address space randomization so even if it would be possible to get your memory, its hard to guess where your data is (and if one don't know where the data is, it is hard to guess what exactly the data is, luckily the RAM has no filesystem that helps in such a case).
The second thing is, if you use [foo release] and you textfield gets deallocated in this process, the OS reclaims the memory. Now the OS will always fill new memory pages with zeroes before giving it to the asking process, so you don't have to fear that there is an malicious app that just allocates memory in the hope it finds the password this way.

Body:
I am pretty new in iOS development and I have the following question:
In my code I have a UIViewController with a UIText field that will hold a password when user will type in the view. The password is used for authentication in front a server:

UItextField* txtPassword;
[myClass loginWithPassword:txtPassword.text];

After using it I want to be sure that there are no leftovers of the password in the memory, so an attacker won't be able performing a memory dump of the iPhone and extracting from it the password.

In windows for example I could use the SeucreZeroMemory function for filling a block of memory with zeros.

What is the best way doing it for iOS? Who is responsible to free the UItextField* string, and is it enough?


问:
How can i build the user profile page in instagram with swift?
i want to build the user profile page in instagram app for iOS, i used tableView with nested collectionView and it is not working correctly for me, is there any recommendation or certain approaches to consider, i am only interested in The Profile Header(profile Image and Bio) and the photos grid with horizontal scrolling section.

instagram user profile image

currently i achieved this behaviour (ignore horizontal scrolling for section):

tableView and collectionView is not scrolling togther like a single content or signle page they scrolls separately, if collectionView scrollingisEnabled = false and tableViewCell height is something large it works fine, but the collectionView will load the entire cells at once

storyboard view hierarchy :

source code:

```<code>class ViewController: UITableViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(SectionHeader.self, forHeaderFooterViewReuseIdentifier: "h")
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return tableView.frame.size.height - tableView.tableHeaderView!.frame.height
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 60
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let x = tableView.dequeueReusableHeaderFooterView(withIdentifier: "h") as! SectionHeader
    x.contentView.backgroundColor = .green
    x.addSections(sectionNames: [ "A", "B", "C", "D" ])
    x.segment.addTarget(self, action: #selector(handleSegmentSectionChange(segmentControl:)), for: .valueChanged)
    return x
}

@objc
func handleSegmentSectionChange(segmentControl: UISegmentedControl) {
    print("load section")
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 100
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "c", for: indexPath)
    let label = cell.viewWithTag(10) as! UILabel
    label.text = "\(indexPath)"
    print("getting cell at \(indexPath)")
    cell.backgroundColor = .orange
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width , height: 80)
}
</code>```

}

thanks.

答:
I think I know what you're asking so I'll take a stab at it. </p>

<p>Like you said, you can use a tableView with a nested collectionView for the photos. For the profile image. I would say that's just a UIImage and the boi is probably a UITextView. That would be my guess. </p>

Body:
i want to build the user profile page in instagram app for iOS, i used tableView with nested collectionView and it is not working correctly for me, is there any recommendation or certain approaches to consider, i am only interested in The Profile Header(profile Image and Bio) and the photos grid with horizontal scrolling section.

instagram user profile image

currently i achieved this behaviour (ignore horizontal scrolling for section):

tableView and collectionView is not scrolling togther like a single content or signle page they scrolls separately, if collectionView scrollingisEnabled = false and tableViewCell height is something large it works fine, but the collectionView will load the entire cells at once

storyboard view hierarchy :

source code:

class ViewController: UITableViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(SectionHeader.self, forHeaderFooterViewReuseIdentifier: "h")
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return tableView.frame.size.height - tableView.tableHeaderView!.frame.height
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 60
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let x = tableView.dequeueReusableHeaderFooterView(withIdentifier: "h") as! SectionHeader
    x.contentView.backgroundColor = .green
    x.addSections(sectionNames: [ "A", "B", "C", "D" ])
    x.segment.addTarget(self, action: #selector(handleSegmentSectionChange(segmentControl:)), for: .valueChanged)
    return x
}

@objc
func handleSegmentSectionChange(segmentControl: UISegmentedControl) {
    print("load section")
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 100
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "c", for: indexPath)
    let label = cell.viewWithTag(10) as! UILabel
    label.text = "\(indexPath)"
    print("getting cell at \(indexPath)")
    cell.backgroundColor = .orange
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width , height: 80)
}

}

thanks.

Body:
I think I know what you're asking so I'll take a stab at it.

Like you said, you can use a tableView with a nested collectionView for the photos. For the profile image. I would say that's just a UIImage and the boi is probably a UITextView. That would be my guess.


问:
How to print a string representation of myFirstCar using the _str_method?
I'm doing this question in a python book and I just stumbled across this question. As shown in the title I wrote above, it's asking me to use that variable with the _str_method and also, I should get the output:
Make = Honda, Model = Civic, Color = White, Price = 1500
How should I write the code? (Please help)

答:
classes will be your friend here.

```<code>class Car:
  def __init__(self, make, model, color, price):
    self.make = make
    self.model = model
    self.color = color
    self.price = price

car = Car('Honda', 'Civic', 'White', '1500')
print('Make = ' + car.make + ', Model = ' + car.model + ', Color = ' + car.color + ', Price = ' + car.price)
</code>```

On top of this, you can make other variables to store the attributes of whatever other car you want to create. Such as:

car2 = Car('Toyota', 'Camry', 'Black', '1900')

And you would call it the same way.

Body:
classes will be your friend here.

class Car:
  def __init__(self, make, model, color, price):
    self.make = make
    self.model = model
    self.color = color
    self.price = price

car = Car('Honda', 'Civic', 'White', '1500')
print('Make = ' + car.make + ', Model = ' + car.model + ', Color = ' + car.color + ', Price = ' + car.price)

On top of this, you can make other variables to store the attributes of whatever other car you want to create. Such as:

car2 = Car('Toyota', 'Camry', 'Black', '1900')

And you would call it the same way.


问:
Character-Matrix - how to operate by row?
I have a matrix of character data

```<code>charMatrix <- structure(c("Bolt", "Nut Plate", "Magnet", "", "Clevis", "welded",
     "", "Receptacle"), .Dim = c(4L, 2L))

[,1]            [,2]
[1,] "Bolt"      "Clevis"
[2,] "Nut Plate" "welded"
[3,] "Magnet"    ""
[4,] ""          "Receptacle"
</code>```

I want to paste the rows together and trim them to get the vector.

```<code>[1] "Bolt Clevis" "Nut Plate welded" "Magnet" "Receptacle"
</code>```

I solved it this way, but I think there must be something much simpler, either in Base R or Tidyverse.

```<code>vec <- charMatrix %>% t() %>%
  as_tibble(.name_repair = "universal") %>%
  summarise_all(~ str_trim(paste(., collapse = " "))) %>%
  unlist() %>%
  as.character()

vec
[1] "Bolt Clevis"      "Nut Plate welded" "Magnet"           "Receptacle"
</code>```

Can you show me a more direct way to get this answer?

答:
You can do it easily with tidyverse:</p>

```<code>library(tidyverse)

charMatrix %>%
  as_tibble() %>%
  unite("Var", sep = " ") %>%
  mutate(Var = str_trim(Var)) %>%
  pull()
</code>```

Body:
I have a matrix of character data

charMatrix <- structure(c("Bolt", "Nut Plate", "Magnet", "", "Clevis", "welded",
     "", "Receptacle"), .Dim = c(4L, 2L))

[,1]            [,2]
[1,] "Bolt"      "Clevis"
[2,] "Nut Plate" "welded"
[3,] "Magnet"    ""
[4,] ""          "Receptacle"

I want to paste the rows together and trim them to get the vector.

[1] "Bolt Clevis" "Nut Plate welded" "Magnet" "Receptacle"

I solved it this way, but I think there must be something much simpler, either in Base R or Tidyverse.

vec <- charMatrix %>% t() %>%
  as_tibble(.name_repair = "universal") %>%
  summarise_all(~ str_trim(paste(., collapse = " "))) %>%
  unlist() %>%
  as.character()

vec
[1] "Bolt Clevis"      "Nut Plate welded" "Magnet"           "Receptacle"

Can you show me a more direct way to get this answer?

Body:
You can do it easily with tidyverse:

library(tidyverse)

charMatrix %>%
  as_tibble() %>%
  unite("Var", sep = " ") %>%
  mutate(Var = str_trim(Var)) %>%
  pull()


问:
Convert a dictionary of strings to a dictionary of numpy arrays
I have a dictionary structured similar to below.

```<code>test_dict = {1: 'I run fast', 2: 'She runs', 3: 'How are you?'}
</code>```

What I'm trying to do is convert all the strings to 4x4 numpy arrays where each word is in it's own row and each letter occupies one cell of the array, populated with blanks for lines that wouldn't fill the entire row a whole row of blanks for sentences that are less than 4 words long. I also need to be able to tie it back to the ID, so the result needs to be in some format that can allow for referencing each array by it's ID later on.

I don't know of any pre built functions that can handle something like this, but I would be happy to be wrong. For now I've been trying to write a loop to handle it. Below is obviously incomplete because I'm stuck at the point of creating an array in the structure I would like.

```<code>for k in test_dict.keys():
    sentence = test_dict.getvalues(k)
    sentence_ascii = [ord(c) for c in sentence]
    sentence_array = np.array(sentence_ascii)
</code>```

答:
You can use this to call your arrays using field 'ID':

```<code>dt=[('ID', '<i4'), ('sentences', object)]
new_dict = np.empty(len(test_dict), dtype=dt)
for i, (k, v) in enumerate(test_dict.items()):
  new_dict[i] = (k, np.pad(np.array([list("{:<4}".format(w)) for w in v.split(' ')]).view(np.int32), [(0,4-len(v.split(' '))),(0,0)]))
</code>```

example output:

```<code>print(new_dict[new_dict['ID']==2]['sentences'])

[array([[ 83, 104, 101,  32],
   [114, 117, 110, 115],
   [  0,   0,   0,   0],
   [  0,   0,   0,   0]], dtype=int32)]
</code>```

Body:
I have a dictionary structured similar to below.

test_dict = {1: 'I run fast', 2: 'She runs', 3: 'How are you?'}

What I'm trying to do is convert all the strings to 4x4 numpy arrays where each word is in it's own row and each letter occupies one cell of the array, populated with blanks for lines that wouldn't fill the entire row a whole row of blanks for sentences that are less than 4 words long. I also need to be able to tie it back to the ID, so the result needs to be in some format that can allow for referencing each array by it's ID later on.

I don't know of any pre built functions that can handle something like this, but I would be happy to be wrong. For now I've been trying to write a loop to handle it. Below is obviously incomplete because I'm stuck at the point of creating an array in the structure I would like.

for k in test_dict.keys():
    sentence = test_dict.getvalues(k)
    sentence_ascii = [ord(c) for c in sentence]
    sentence_array = np.array(sentence_ascii)

Body:
You can use this to call your arrays using field 'ID':

dt=[('ID', '<i4'), ('sentences', object)]
new_dict = np.empty(len(test_dict), dtype=dt)
for i, (k, v) in enumerate(test_dict.items()):
  new_dict[i] = (k, np.pad(np.array([list("{:<4}".format(w)) for w in v.split(' ')]).view(np.int32), [(0,4-len(v.split(' '))),(0,0)]))

example output:

print(new_dict[new_dict['ID']==2]['sentences'])

[array([[ 83, 104, 101,  32],
   [114, 117, 110, 115],
   [  0,   0,   0,   0],
   [  0,   0,   0,   0]], dtype=int32)]


问:
Camel body is lost with 500 status when testing with ProducerTemplate
I have a simple camel route:

```<code>from("jetty:http://localhost:8080/path")
.setBody(simple("<zzz>zzz</zzz>"))
.setHeader(Exchange.HTTP_RESPONSE_CODE, simple("500"))
.setHeader(Exchange.CONTENT_TYPE, simple("application/xml"));
</code>```

I have a test case with code like:

```<code>Exchange ex = producerTemplate.request("http://localhost:8080/path", (e) -> {
  e.getIn().setBody(requestBody);
  e.getIn().setHeader("Content-Type", "application/xml");
});

</code>```

As soon as the response code is set to 500, then the body comes back as null. In fact ex.hasOut() is false.

When testing with curl the body is returned. So it's the test case use of producerTemplate that causes the problem.

What do I need to do to get the body I expect returned?

答:
Http component translates 5xx status codes to HttpOperationFailedException.

You can turn this behavior off with option throwExceptionOnFailure=false.

Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.

```<code>Exchange ex = template.request("http://localhost:8080/path?throwExceptionOnFailure=false", (e) -> {
    e.getIn().setBody(requestBody);
    e.getIn().setHeader("Content-Type", "application/xml");
});
log.info(ex.getMessage().getBody());
</code>```

Or obtain response body from HttpOperationFailedException object.

```<code>Exchange ex = template.request("http://localhost:8080/path", (e) -> {
    e.getIn().setBody(requestBody);
    e.getIn().setHeader("Content-Type", "application/xml");
});
log.info(ex.getException(HttpOperationFailedException.class).getResponseBody());
</code>```

Body:
I have a simple camel route:

from("jetty:http://localhost:8080/path")
.setBody(simple("<zzz>zzz</zzz>"))
.setHeader(Exchange.HTTP_RESPONSE_CODE, simple("500"))
.setHeader(Exchange.CONTENT_TYPE, simple("application/xml"));

I have a test case with code like:

Exchange ex = producerTemplate.request("http://localhost:8080/path", (e) -> {
  e.getIn().setBody(requestBody);
  e.getIn().setHeader("Content-Type", "application/xml");
});

As soon as the response code is set to 500, then the body comes back as null. In fact ex.hasOut() is false.

When testing with curl the body is returned. So it's the test case use of producerTemplate that causes the problem.

What do I need to do to get the body I expect returned?

Body:
Http component translates 5xx status codes to HttpOperationFailedException.

You can turn this behavior off with option throwExceptionOnFailure=false.

Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.

Exchange ex = template.request("http://localhost:8080/path?throwExceptionOnFailure=false", (e) -> {
    e.getIn().setBody(requestBody);
    e.getIn().setHeader("Content-Type", "application/xml");
});
log.info(ex.getMessage().getBody());

Or obtain response body from HttpOperationFailedException object.

Exchange ex = template.request("http://localhost:8080/path", (e) -> {
    e.getIn().setBody(requestBody);
    e.getIn().setHeader("Content-Type", "application/xml");
});
log.info(ex.getException(HttpOperationFailedException.class).getResponseBody());


问:
Showing post data from logged in user only swift/xcode/firebase
Hey I have been following tutorials online to try and make a social media app and it works fine where all the posts made by users populates in one scene but in another scene I would like for the users who are currently logged in to be able to see their posts only instead of having to find their posts from a bunch of posts made by other users, below are my code samples:

Posts Code:

```<code>import Foundation
import UIKit
import Firebase

class Posts{

var id: String
var author: UserProfile
var text: String
var timestamp:Double
var createdAt:Date

init(id:String, author:UserProfile,text:String,timestamp:Double) {
    self.id = id
    self.author = author
    self.text = text
    self.timestamp = timestamp
    self.createdAt = Date(timeIntervalSince1970: timestamp / 1000)
}

static func parse(_ key:String, _ data:[String:Any]) -> Posts? {

    if let author = data["author"] as? [String:Any],
        let uid = author["uid"] as? String,
        let name = author["name"] as? String,
        let photoURL = author["photoURL"] as? String,
        let url = URL(string:photoURL),
        let text = data["text"] as? String,
        let timestamp = data["timestamp"] as? Double {

        let userProfile = UserProfile(uid: uid, name: name, photoURL: url)
        return Posts(id: key, author: userProfile, text: text, timestamp:timestamp)

        func performDeepQuery() {
             guard let user = Auth.auth().currentUser else { return }
            let uid = user.uid
            let ref = Database.database().reference().child("posts")
            let query = ref.queryOrdered(byChild: "author/uid").queryEqual(toValue: uid)
            query.observeSingleEvent(of: .value, with: { snapshot in
                let allPosts = snapshot.children.allObjects as! [DataSnapshot]
                for postSnap in allPosts {

                    let text = postSnap.childSnapshot(forPath: "text").value as? String ?? "No Text"
                    print(text)
                   //same as above
                }
            })
        }

  }

  return nil }
 }

func numberOfSections(in tableView: UITableView) -> Int {
     return 2

 }

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     switch section {
            case 0:
                return theposts.count
            case 1:
                return fetchingMore ? 1 : 0
            default:
                return 0
            }    }

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 { let cell = HomeViewControllerScene.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! Posting_TableViewCell
     cell.set(theposts: theposts[indexPath.row])
     return cell}
 else {
         let cell = HomeViewControllerScene.dequeueReusableCell(withIdentifier: "loadingCell", for: indexPath) as! LoadingCell
         cell.spinner.startAnimating()
         return cell
     }
 }

 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

     cellHeights[indexPath] = cell.frame.size.height
 }

 func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeights[indexPath] ?? 72.0
    }
</code>```

Please someone help me out here I have been scratching my head for a while with this!!!

答:
I believe the question is how to get the posts for a certain user. The structure looks good but no need to have a child node 'author' in each post so instead of this:

```<code>posts
   post_id_0
      author
         author data
      text: "Hello, World"
      uid: "uid_0"
</code>```

do this

```<code>posts
   post_id_0
      text: "Hello, World"
      uid: "uid_0"
      name: "usmaan"
      photoURL:"https://firebasestorage..."
</code>```

So now just query for this users posts (this is for Firestore, scroll down fo the RTDB solution)...

```<code>func getThisUsersPosts() {
    let uid = "uid_0" //this users uid
    self.db.collection("posts]").whereField("uid", isEqualTo: uid).getDocuments { (snapshot, error) in
        if let err = error {
            print(err.localizedDescription)
            return
        }

        if let doc = snapshot?.documents {
            for d in doc {
                let text = d.get("text") as? String ?? "No Post Text"
                print(text)
            }
        } else {
            print("no posts found")
        }
    }
}
</code>```

self.db points to my Firestore.

EDIT:

OP is using the Real Time Database so here's the code for that

```<code>func getThisUsersPosts() {
    let uid = "uid_0"
    let ref = self.ref.child("posts") //self.ref points to MY firebase.
    let query = ref.queryOrdered(byChild: "uid").queryEqual(toValue: uid)
    query.observeSingleEvent(of: .value, with: { snapshot in
        let allPosts = snapshot.children.allObjects as! [DataSnapshot]
        for postSnap in allPosts {
            let text = postSnap.childSnapshot(forPath: "text").value as? String ?? "No Text"
            print(text)
        }
    })
}
</code>```

EDIT 2:

OP wants to keep their same structure.

To query for data that's two levels deep we use what's called Deep Query and will look something like this:

```<code>func performDeepQuery() {
    let uid = "uid_0"
    let ref = self.ref.child("posts")
    let query = ref.queryOrdered(byChild: "author/uid").queryEqual(toValue: uid)
    query.observeSingleEvent(of: .value, with: { snapshot in
        let allPosts = snapshot.children.allObjects as! [DataSnapshot]
        for postSnap in allPosts {
           //populate your tableView datasource here
           let post = PostClass()
           post.postId = postSnap.key
           post.name = postStap.childSnapshot("name").value as? String ?? "No Post Name"
           post.text = postStap.childSnapshot("text").value as? String ?? "No Post Text"
           self.postArray.append(post)
        }
        self.myTableView.reloadData()
    })
}
</code>```

which will perform a deep query on this structure

```<code>posts
   post_0
      author
         uid: "uid_0"
      name: "post 0 name"
      text: "post 0 text"
</code>```

The PostClass could be this

```<code>class PostClass {
   var postId = ""
   var name = ""
   var text = ""
}
</code>```

More Info:

To get the current users uid (which is covered in the getting started guide as well) and assuming you are authenticated (otherwise it will be nil)

```<code>guard let user = Auth.auth().currentUser else { return }
let uid = user.uid
</code>```

Body:
Hey I have been following tutorials online to try and make a social media app and it works fine where all the posts made by users populates in one scene but in another scene I would like for the users who are currently logged in to be able to see their posts only instead of having to find their posts from a bunch of posts made by other users, below are my code samples:

Posts Code:

import Foundation
import UIKit
import Firebase

class Posts{

var id: String
var author: UserProfile
var text: String
var timestamp:Double
var createdAt:Date

init(id:String, author:UserProfile,text:String,timestamp:Double) {
    self.id = id
    self.author = author
    self.text = text
    self.timestamp = timestamp
    self.createdAt = Date(timeIntervalSince1970: timestamp / 1000)
}

static func parse(_ key:String, _ data:[String:Any]) -> Posts? {

    if let author = data["author"] as? [String:Any],
        let uid = author["uid"] as? String,
        let name = author["name"] as? String,
        let photoURL = author["photoURL"] as? String,
        let url = URL(string:photoURL),
        let text = data["text"] as? String,
        let timestamp = data["timestamp"] as? Double {

        let userProfile = UserProfile(uid: uid, name: name, photoURL: url)
        return Posts(id: key, author: userProfile, text: text, timestamp:timestamp)

        func performDeepQuery() {
             guard let user = Auth.auth().currentUser else { return }
            let uid = user.uid
            let ref = Database.database().reference().child("posts")
            let query = ref.queryOrdered(byChild: "author/uid").queryEqual(toValue: uid)
            query.observeSingleEvent(of: .value, with: { snapshot in
                let allPosts = snapshot.children.allObjects as! [DataSnapshot]
                for postSnap in allPosts {

                    let text = postSnap.childSnapshot(forPath: "text").value as? String ?? "No Text"
                    print(text)
                   //same as above
                }
            })
        }

  }

  return nil }
 }

func numberOfSections(in tableView: UITableView) -> Int {
     return 2

 }

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     switch section {
            case 0:
                return theposts.count
            case 1:
                return fetchingMore ? 1 : 0
            default:
                return 0
            }    }

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 { let cell = HomeViewControllerScene.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! Posting_TableViewCell
     cell.set(theposts: theposts[indexPath.row])
     return cell}
 else {
         let cell = HomeViewControllerScene.dequeueReusableCell(withIdentifier: "loadingCell", for: indexPath) as! LoadingCell
         cell.spinner.startAnimating()
         return cell
     }
 }

 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

     cellHeights[indexPath] = cell.frame.size.height
 }

 func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeights[indexPath] ?? 72.0
    }

Please someone help me out here I have been scratching my head for a while with this!!!

Body:
I believe the question is how to get the posts for a certain user. The structure looks good but no need to have a child node 'author' in each post so instead of this:

posts
   post_id_0
      author
         author data
      text: "Hello, World"
      uid: "uid_0"

do this

posts
   post_id_0
      text: "Hello, World"
      uid: "uid_0"
      name: "usmaan"
      photoURL:"https://firebasestorage..."

So now just query for this users posts (this is for Firestore, scroll down fo the RTDB solution)...

func getThisUsersPosts() {
    let uid = "uid_0" //this users uid
    self.db.collection("posts]").whereField("uid", isEqualTo: uid).getDocuments { (snapshot, error) in
        if let err = error {
            print(err.localizedDescription)
            return
        }

        if let doc = snapshot?.documents {
            for d in doc {
                let text = d.get("text") as? String ?? "No Post Text"
                print(text)
            }
        } else {
            print("no posts found")
        }
    }
}

self.db points to my Firestore.

EDIT:

OP is using the Real Time Database so here's the code for that

func getThisUsersPosts() {
    let uid = "uid_0"
    let ref = self.ref.child("posts") //self.ref points to MY firebase.
    let query = ref.queryOrdered(byChild: "uid").queryEqual(toValue: uid)
    query.observeSingleEvent(of: .value, with: { snapshot in
        let allPosts = snapshot.children.allObjects as! [DataSnapshot]
        for postSnap in allPosts {
            let text = postSnap.childSnapshot(forPath: "text").value as? String ?? "No Text"
            print(text)
        }
    })
}

EDIT 2:

OP wants to keep their same structure.

To query for data that's two levels deep we use what's called Deep Query and will look something like this:

func performDeepQuery() {
    let uid = "uid_0"
    let ref = self.ref.child("posts")
    let query = ref.queryOrdered(byChild: "author/uid").queryEqual(toValue: uid)
    query.observeSingleEvent(of: .value, with: { snapshot in
        let allPosts = snapshot.children.allObjects as! [DataSnapshot]
        for postSnap in allPosts {
           //populate your tableView datasource here
           let post = PostClass()
           post.postId = postSnap.key
           post.name = postStap.childSnapshot("name").value as? String ?? "No Post Name"
           post.text = postStap.childSnapshot("text").value as? String ?? "No Post Text"
           self.postArray.append(post)
        }
        self.myTableView.reloadData()
    })
}

which will perform a deep query on this structure

posts
   post_0
      author
         uid: "uid_0"
      name: "post 0 name"
      text: "post 0 text"

The PostClass could be this

class PostClass {
   var postId = ""
   var name = ""
   var text = ""
}

More Info:

To get the current users uid (which is covered in the getting started guide as well) and assuming you are authenticated (otherwise it will be nil)

guard let user = Auth.auth().currentUser else { return }
let uid = user.uid


问:
Android MaterialDatePicker layout problems
I'm developing an app that needs to get the user's birthday,
I've already did it with DatePickerDialogFragment, but now I'm trying to do it with Material Design,
so I found a way to create a date picker dialog with this library:

```<code>private MaterialDatePicker<Long> materialDatePicker;
...
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
        builder.setTitleText(getResources().getString(R.string.birthday_it));
        builder.setTheme(R.style.ThemeOverlay_MaterialComponents_MaterialCalendar);

        materialDatePicker = builder.build();
</code>```

And then with a button I show it:

```<code>    birthdayButton.setOnClickListener(view -> {
        materialDatePicker.show(getSupportFragmentManager(), "DATE_PICKER");
    });
</code>```

There's no problem with this, indeed I can select my date etc, but on display it looks like this:

https://i.stack.imgur.com/60sD8.png

https://i.stack.imgur.com/fWEGW.png

As you can see from these two images, when i select a day the selector image is not aligned with the day number and then when I pass to dialog mode is still on the previous layout and doesn't wrap it.

What can I do? I searched but I didn't find anything for this. Thank you!

答:
Just change your app theme to a Material Components Theme.

```<code><style name="AppTheme" parent="Theme.MaterialComponents.*">
   ....
</style>
</code>```

Also builder.setTheme(R.style.ThemeOverlay_MaterialComponents_MaterialCalendar); is not needed since it is the default theme.

Body:
I'm developing an app that needs to get the user's birthday,
I've already did it with DatePickerDialogFragment, but now I'm trying to do it with Material Design,
so I found a way to create a date picker dialog with this library:

private MaterialDatePicker<Long> materialDatePicker;
...
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
        builder.setTitleText(getResources().getString(R.string.birthday_it));
        builder.setTheme(R.style.ThemeOverlay_MaterialComponents_MaterialCalendar);

        materialDatePicker = builder.build();

And then with a button I show it:

    birthdayButton.setOnClickListener(view -> {
        materialDatePicker.show(getSupportFragmentManager(), "DATE_PICKER");
    });

There's no problem with this, indeed I can select my date etc, but on display it looks like this:

https://i.stack.imgur.com/60sD8.png

https://i.stack.imgur.com/fWEGW.png

As you can see from these two images, when i select a day the selector image is not aligned with the day number and then when I pass to dialog mode is still on the previous layout and doesn't wrap it.

What can I do? I searched but I didn't find anything for this. Thank you!

Body:
Just change your app theme to a Material Components Theme.

<style name="AppTheme" parent="Theme.MaterialComponents.*">
   ....
</style>

Also builder.setTheme(R.style.ThemeOverlay_MaterialComponents_MaterialCalendar); is not needed since it is the default theme.


问:
Design question - template pattern with enum implementing an interface
My code is starting to look out of control so I thought I would ask for help.

I have an enum class that implements an interface. The first thing the method does is get a db connection from a pool using jndi.  Then based on the objects properties performs a series of calculations and returns a result.

```<code>public interace MyInterface {
     public ResultObject calculate(MyObject myObject);
</code>```

}

```<code>public enum MyEnum implements Myinterface {
    public ResultObject calculate(MyObject myObject) {
         //several steps
    }
}
</code>```

This has been working fine with only one calculation.  I now have a few more ways to calculate with just a few changes needed for each calculation.

The template method design pattern sounds perfect for this but I am confused on how I can make it work with the enum implementation I currently have?  I don't want to add a bunch of branch statements in my enum calculate method and make it hard to maintain.

I am using spring mvc and I have a controller for each calculation that extends a base class.  I call super.calculate() in each controller and I would like to keep this the same.

Does anyone have any suggestions for this scenerio?  I feel like when I started the design was good but now I am not so sure.

答:
I find it really confusing that you would have an enum that implements an interface like this, especially if the enum is responsible for interacting with a database - sounds like you may be misusing enums.

As for the actual problem, I would create a base class (potentially abstract) which contains the core logic of the calculate(MyObject) method and delegates the "additional ways" to calculate to either an abstract method or a protected method override-able by subclasses, so that you can have slightly different implementations of MyInterface which provide the different behavior.

Body:
My code is starting to look out of control so I thought I would ask for help.

I have an enum class that implements an interface. The first thing the method does is get a db connection from a pool using jndi.  Then based on the objects properties performs a series of calculations and returns a result.

public interace MyInterface {
     public ResultObject calculate(MyObject myObject);

}

public enum MyEnum implements Myinterface {
    public ResultObject calculate(MyObject myObject) {
         //several steps
    }
}

This has been working fine with only one calculation.  I now have a few more ways to calculate with just a few changes needed for each calculation.

The template method design pattern sounds perfect for this but I am confused on how I can make it work with the enum implementation I currently have?  I don't want to add a bunch of branch statements in my enum calculate method and make it hard to maintain.

I am using spring mvc and I have a controller for each calculation that extends a base class.  I call super.calculate() in each controller and I would like to keep this the same.

Does anyone have any suggestions for this scenerio?  I feel like when I started the design was good but now I am not so sure.


问:
AWS CodeDeploy redeployment from command line
Is it possible to retry/redeploy a previously successful deployment through command line? I know a list of deployments can be fetched from command line using
aws deploy list-deployments but I didn't find any option to rerun the deployment using deployment-id returned from this command.
There is an option to retry a previously run deployment from console though.

答:
Re-deployment is simply based on creating new-deployment using a previous version of your application. Unfortunately, there is no special redeploy command for that.

In the docs there is example how to redeploy sample project:

```<code>aws deploy create-deployment --application-name HelloWorld_App --deployment-config-name CodeDeployDefault.OneAtATime --deployment-group-name HelloWorld_DepGroup --s3-location bucket=codedeploydemobucket,bundleType=zip,key=HelloWorld_App.zip
</code>```

Body:
Re-deployment is simply based on creating new-deployment using a previous version of your application. Unfortunately, there is no special redeploy command for that.

In the docs there is example how to redeploy sample project:

aws deploy create-deployment --application-name HelloWorld_App --deployment-config-name CodeDeployDefault.OneAtATime --deployment-group-name HelloWorld_DepGroup --s3-location bucket=codedeploydemobucket,bundleType=zip,key=HelloWorld_App.zip


问:
ASP.NET Core Runtime deploymenet CERTIFICATES TRUST
I am deploying my API (ASP.NET Core 3.1) to a server and I am listening on https url only:

```<code>return WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseUrls("http://*:5000;https://*:5001");
</code>```

But I am getting and error:

```<code>crit: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to start Kestrel.
System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date.
</code>```

In deployement, you make your self-signed ceritifate with:

```<code>...
dotnet dev-certs https --trust
...
</code>```

But I cannot use it ofcourse because I have only runtime .Net Core and not SDK and it should be deployed app.

I have certificate file and key ssl.crt and ssl.key which I am using in my frontends apps (apache settings etc etc... you know what I mean).

Can I use it in ASP.NET or how do I do it?

Thanks

答:
So as you can see in comments above (under question), there was a tip from Lex Li to listen on http:// and use proxyreverse to redirect https calls onto http.

But to be honest, this solution is little bit shady and I did not want to do it that way, so I continued my searching and found NuGet LettuceEncrypt which is actually solving my problem. I can now listen https calls, I dont need to use some shady solution with proxyreverse and also I dont have to install whole SDK to use dotnet dev-certs commands.

On github page I sent before is sample usage with 2 sample applications, so if you have similar problem, take a look at it and maybe it will wolve the problem for you too.

Body:
I am deploying my API (ASP.NET Core 3.1) to a server and I am listening on https url only:

return WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseUrls("http://*:5000;https://*:5001");

But I am getting and error:

crit: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to start Kestrel.
System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date.

In deployement, you make your self-signed ceritifate with:

...
dotnet dev-certs https --trust
...

But I cannot use it ofcourse because I have only runtime .Net Core and not SDK and it should be deployed app.

I have certificate file and key ssl.crt and ssl.key which I am using in my frontends apps (apache settings etc etc... you know what I mean).

Can I use it in ASP.NET or how do I do it?

Thanks


问:
How to replace tabs in a string?
I need to replace tabs in a string, but only the tabs, not the spaces.

If I use the str.replace() function, what would go in the first set of quotes?

答:
This is too late for original poster, but for those that follow ...</p>

```<code>def expandTab( txt, tabWidth=8):
out=[]
for line in txt.split('\n'):
    try:
        while True:
            i = line.index( '\t')
            if ( tabWidth > 0 ):
                pad = " " * (tabWidth - (i % tabWidth))
            else :
                pad = ""
            line = line.replace("\t", pad, 1)
    except:
        out.append(line)
return "\n".join(out)
</code>```

Title: How to replace tabs in a string?

Body:
This is too late for original poster, but for those that follow ...

def expandTab( txt, tabWidth=8):
out=[]
for line in txt.split('\n'):
    try:
        while True:
            i = line.index( '\t')
            if ( tabWidth > 0 ):
                pad = " " * (tabWidth - (i % tabWidth))
            else :
                pad = ""
            line = line.replace("\t", pad, 1)
    except:
        out.append(line)
return "\n".join(out)


问:
Git Rebase Include Specific Commits
```<code>Foo:
A-O-X-Y-Z
Bar:
A-B-C-D
</code>```

I am looking to understand what is the correct strategy to achieve this. When I do a rebase of branch Foo against Bar, I get the following branch output.

```<code>I ran:
git checkout Foo
git rebase Bar
# fix merge errors and push

Resulting Foo branch:
A-B-C-D-O-X-Y-Z
</code>```

What I am trying to ask is, is it possible to rebase and include only a specific set of commits (X,Y,Z)? I want to achieve this so the "O" commit is excluded.

```<code>Desired Result:
A-B-C-D-X-Y-Z
</code>```

答:
It's easy to achieve the result you desire.
The command you need is:

```<code>git rebase --onto Bar Foo~3 Foo
</code>```

This form of rebase that takes two references as arguments (ignore --onto Bar for now) is a shortcut for the following two commands:

```<code>git checkout Foo
git rebase --onto Bar Foo~3
</code>```

How it works

Without --onto Bar, the rebase command above gets the commits from the current branch (Foo) that are not accessible from Foo~3 and saves them in a temporary area. Then it resets the current branch to Foo~3 and applies the saved commits one by one, in their original order.

With --onto Bar, the saving and restoring of the commits happens the same way but the restoring starts on top of the commit identified by Bar instead of Foo~3.

All in all, the command above takes the most recent 3 commits from the branch Foo (together with the Foo branch) and puts them on top of the commit identifies by Bar.

Warning!

If, after you run this command, the commit O cannot be accessed starting from a branch, it will disappear from the history. It is not removed immediately. You can still access it for a while if you know its hash or by inspecting the output of git reflog. Git will remove it completely after a while (usually about two weeks) if it is not accessible any more using a branch, tag or the reflog.

In fact, nothing is removed immediately; even the commits that git rebase "moved" from one branch to another were actually copied and the originals are still in the repository and they are accessible but not visible.

Read more about git rebase on the Git website or run git help rebase on your terminal.

Title: Git Rebase Include Specific Commits

Body:
Foo:
A-O-X-Y-Z
Bar:
A-B-C-D

I am looking to understand what is the correct strategy to achieve this. When I do a rebase of branch Foo against Bar, I get the following branch output.

I ran:
git checkout Foo
git rebase Bar
# fix merge errors and push

Resulting Foo branch:
A-B-C-D-O-X-Y-Z

What I am trying to ask is, is it possible to rebase and include only a specific set of commits (X,Y,Z)? I want to achieve this so the "O" commit is excluded.

Desired Result:
A-B-C-D-X-Y-Z

Body:
It's easy to achieve the result you desire.
The command you need is:

git rebase --onto Bar Foo~3 Foo

This form of rebase that takes two references as arguments (ignore --onto Bar for now) is a shortcut for the following two commands:

git checkout Foo
git rebase --onto Bar Foo~3

How it works

Without --onto Bar, the rebase command above gets the commits from the current branch (Foo) that are not accessible from Foo~3 and saves them in a temporary area. Then it resets the current branch to Foo~3 and applies the saved commits one by one, in their original order.

With --onto Bar, the saving and restoring of the commits happens the same way but the restoring starts on top of the commit identified by Bar instead of Foo~3.

All in all, the command above takes the most recent 3 commits from the branch Foo (together with the Foo branch) and puts them on top of the commit identifies by Bar.

Warning!

If, after you run this command, the commit O cannot be accessed starting from a branch, it will disappear from the history. It is not removed immediately. You can still access it for a while if you know its hash or by inspecting the output of git reflog. Git will remove it completely after a while (usually about two weeks) if it is not accessible any more using a branch, tag or the reflog.

In fact, nothing is removed immediately; even the commits that git rebase "moved" from one branch to another were actually copied and the originals are still in the repository and they are accessible but not visible.

Read more about git rebase on the Git website or run git help rebase on your terminal.


问:
Change the background color of CardView programmatically
The CardView has an attribute card_view:cardBackgroundColor to define the background color.
This attribute works fine.

At the same time there isn't a method to change the color dynamically.

I've just tried solutions like:

```<code>mCardView.setBackgroundColor(...);
</code>```

or using a Layout inside the cardView

```<code>   <android.support.v7.widget.CardView>
        <LinearLayout
            android:id="@+id/inside_layout">
    </android.support.v7.widget.CardView>

 View insideLayout = mCardView.findViewById(R.id.inside_layout);
 cardLayout.setBackgroundColor(XXXX);
</code>```

These solutions don't work because the card has a cardCornerRadius.

答:
In Kotlin, I was able to change the background color like this:

```<code>var card: CardView = itemView.findViewById(com.mullr.neurd.R.id.learn_def_card)
card.setCardBackgroundColor(ContextCompat.getColor(main,R.color.selected))
</code>```

Then if you want to remove the color, you can do this:

```<code>card.setCardBackgroundColor(Color.TRANSPARENT)
</code>```

Using this method I was able to create a selection animation.

https://gfycat.com/equalcarefreekitten

Body:
The CardView has an attribute card_view:cardBackgroundColor to define the background color.
This attribute works fine.

At the same time there isn't a method to change the color dynamically.

I've just tried solutions like:

mCardView.setBackgroundColor(...);

or using a Layout inside the cardView

   <android.support.v7.widget.CardView>
        <LinearLayout
            android:id="@+id/inside_layout">
    </android.support.v7.widget.CardView>

 View insideLayout = mCardView.findViewById(R.id.inside_layout);
 cardLayout.setBackgroundColor(XXXX);

These solutions don't work because the card has a cardCornerRadius.

Body:
In Kotlin, I was able to change the background color like this:

var card: CardView = itemView.findViewById(com.mullr.neurd.R.id.learn_def_card)
card.setCardBackgroundColor(ContextCompat.getColor(main,R.color.selected))

Then if you want to remove the color, you can do this:

card.setCardBackgroundColor(Color.TRANSPARENT)

Using this method I was able to create a selection animation.

https://gfycat.com/equalcarefreekitten


问:
CSS width/height issue
I am facing a problem with image height. I want to make that image 100% height without hard coding. But i can't do that. Every time some margin goes bottom to the image. I have changed the image width, height, font size but nothing works.

Here is an example of the image not filling the height:

* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}
html {
  font-size:16px;
}
body {
  font-family: Raleway, "Times New Roman", Times, serif;
  background-color: #f6f6f6;
  line-height: 1.5rem;
  width: 100%;
  color: #424242;
}

.flexbox {
  display: flex;
  justify-content: space-between;
}

.img-responsive {max-width:100%;max-height:100%;}
.card {
  background-color: #ffffff;
  border: 2px solid red;
  margin: 1.5rem 0rem 0rem;
  width: 75%;
}

.post-card-body {
  padding: 1.5rem;
}

.post-card-heading {
  margin: 0 0 0.75rem;
}

.btn-section {
  margin-top: 1rem;
}
.continue-btn {
  background-color: #ffb69b;
  border-color: #ffb69b;
}

.btn {
  font-size: 0.75rem;
  text-transform: uppercase;
  color: #ffffff;
  padding: 0.75rem 1.25rem;
  border: 0.0625rem solid #e9e9ea;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox card">
  <div class="post-card-img">
    <img src="http://via.placeholder.com/300x300/DDaDaa/FFFFFF" alt="" class="img-responsive" />
  </div>
  <div class="post-card-body">
    <div class="post-card-heading">
      <h3>Lorem ipsum dolor sit amet.</h3>
      <h6>By Admin Ahsan September 11, 2015</h6>
      <hr />
    </div>
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum
      atque sed in, fugiat natus laboriosam
    </p>
    <div class="btn-section">
      <button class="btn continue-btn">Continue Reading</button>
    </div>
  </div>
</div></code>```

codepen link: click here
Screenshot: click here

答:
When using images to fill areas, I like to use the object-fit css property, as it will fit no matter the dimentions of the container it is in.

.img-responsive {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
```

<p>This code will tell the image to cover the continer it is in with 100% of the containers height and width.</p>

<p>This may not work if you don't want any of the image to be cut off. For more resources you can look into the other properties you can use with <code>object-fit</code> to get your desired result. Here is a good resource: object-fit | CSS-Tricks</p>

<p>See here for example with your code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}

html {
  font-size:16px;
}

body {
  font-family: Raleway, "Times New Roman", Times, serif;
  background-color: #f6f6f6;
  line-height: 1.5rem;
  width: 100%;
  color: #424242;
}

.flexbox {
  display: flex;
  justify-content: space-between;
}

.img-responsive {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

.card {
  background-color: #ffffff;
  border: 2px solid red;
  margin: 1.5rem 0rem 0rem;
  width: 75%;
}

.post-card-body {
  padding: 1.5rem;
}

.post-card-heading {
  margin: 0 0 0.75rem;
}

.btn-section {
  margin-top: 1rem;
}
.continue-btn {
  background-color: #ffb69b;
  border-color: #ffb69b;
}

.btn {
  font-size: 0.75rem;
  text-transform: uppercase;
  color: #ffffff;
  padding: 0.75rem 1.25rem;
  border: 0.0625rem solid #e9e9ea;
}</code>```

Lorem ipsum dolor sit amet.

By Admin Ahsan September 11, 2015

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum
      atque sed in, fugiat natus laboriosam

      <button class="btn continue-btn">Continue Reading</button>

```

Title: CSS width/height issue

Body:
I am facing a problem with image height. I want to make that image 100% height without hard coding. But i can't do that. Every time some margin goes bottom to the image. I have changed the image width, height, font size but nothing works.

Here is an example of the image not filling the height:

* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}
html {
  font-size:16px;
}
body {
  font-family: Raleway, "Times New Roman", Times, serif;
  background-color: #f6f6f6;
  line-height: 1.5rem;
  width: 100%;
  color: #424242;
}

.flexbox {
  display: flex;
  justify-content: space-between;
}

.img-responsive {max-width:100%;max-height:100%;}
.card {
  background-color: #ffffff;
  border: 2px solid red;
  margin: 1.5rem 0rem 0rem;
  width: 75%;
}

.post-card-body {
  padding: 1.5rem;
}

.post-card-heading {
  margin: 0 0 0.75rem;
}

.btn-section {
  margin-top: 1rem;
}
.continue-btn {
  background-color: #ffb69b;
  border-color: #ffb69b;
}

.btn {
  font-size: 0.75rem;
  text-transform: uppercase;
  color: #ffffff;
  padding: 0.75rem 1.25rem;
  border: 0.0625rem solid #e9e9ea;
}

Lorem ipsum dolor sit amet.

By Admin Ahsan September 11, 2015

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum
      atque sed in, fugiat natus laboriosam

      <button class="btn continue-btn">Continue Reading</button>

codepen link: click here
Screenshot: click here

Body:
When using images to fill areas, I like to use the object-fit css property, as it will fit no matter the dimentions of the container it is in.

.img-responsive {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

This code will tell the image to cover the continer it is in with 100% of the containers height and width.

This may not work if you don't want any of the image to be cut off. For more resources you can look into the other properties you can use with object-fit to get your desired result. Here is a good resource: object-fit | CSS-Tricks

See here for example with your code:

* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}

html {
  font-size:16px;
}

body {
  font-family: Raleway, "Times New Roman", Times, serif;
  background-color: #f6f6f6;
  line-height: 1.5rem;
  width: 100%;
  color: #424242;
}

.flexbox {
  display: flex;
  justify-content: space-between;
}

.img-responsive {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

.card {
  background-color: #ffffff;
  border: 2px solid red;
  margin: 1.5rem 0rem 0rem;
  width: 75%;
}

.post-card-body {
  padding: 1.5rem;
}

.post-card-heading {
  margin: 0 0 0.75rem;
}

.btn-section {
  margin-top: 1rem;
}
.continue-btn {
  background-color: #ffb69b;
  border-color: #ffb69b;
}

.btn {
  font-size: 0.75rem;
  text-transform: uppercase;
  color: #ffffff;
  padding: 0.75rem 1.25rem;
  border: 0.0625rem solid #e9e9ea;
}

<div class="flexbox card">
  <div class="post-card-img">
    <img src="http://via.placeholder.com/300x300/DDaDaa/FFFFFF" alt="" class="img-responsive" />
  </div>
  <div class="post-card-body">
    <div class="post-card-heading">
      <h3>Lorem ipsum dolor sit amet.</h3>
      <h6>By <a href="#">Admin Ahsan</a> September 11, 2015</h6>
      <hr />
    </div>
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum
      atque sed in, fugiat natus laboriosam
    </p>
    <div class="btn-section">
      <button class="btn continue-btn">Continue Reading</button>
    </div>
  </div>
</div>


问:
My pip is broken on Windows, how can I fix it?
Whenever I try to use pip, using any command I get this:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qzc5n2dfsdra8p0\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qzc5n2dfsd8p0\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_q3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\__main__.py", line 23, in <module>
    from pip._internal.cli.main import main as _main  # isort:skip # noqa
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\main.py", line 10, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\autocompletion.py", line 9, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\main_parser.py", line 7, in <module>
    from pip._internal.cli import cmdoptions
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\cmdoptions.py", line 24, in <module>
    from pip._internal.cli.progress_bars import BAR_TYPES
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\progress_bars.py", line 8, in <module>
    from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar
ModuleNotFoundError: No module named 'pip._vendor.progress'
PS C:\Users\SE> No module named 'pip._vendor.progress'No module named 'pip._vendor.progress'
```

I am on Windows 10, 64 bit, Python version 3.7.7.

I cannot use pip, how can I fix it?

答:
Try doing python -m pip install pytest. This should install it, and it will make it usable by your IDE.

Hope this helps!

Body:
Whenever I try to use pip, using any command I get this:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qzc5n2dfsdra8p0\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qzc5n2dfsd8p0\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_q3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\__main__.py", line 23, in <module>
    from pip._internal.cli.main import main as _main  # isort:skip # noqa
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\main.py", line 10, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\autocompletion.py", line 9, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\main_parser.py", line 7, in <module>
    from pip._internal.cli import cmdoptions
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\cmdoptions.py", line 24, in <module>
    from pip._internal.cli.progress_bars import BAR_TYPES
  File "C:\Users\SE\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qzc5n2dfsd8p0\LocalCache\local-packages\Python38\site-packages\pip\_internal\cli\progress_bars.py", line 8, in <module>
    from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar
ModuleNotFoundError: No module named 'pip._vendor.progress'
PS C:\Users\SE> No module named 'pip._vendor.progress'No module named 'pip._vendor.progress'

I am on Windows 10, 64 bit, Python version 3.7.7.

I cannot use pip, how can I fix it?


答:
You could follow the equivalent steps mentioned here and here (Both are closed issues on pip's github page) on your windows machine.

On windows you can do this:

```<code>python -m pip uninstall pip setuptools # Sometimes setuptools might be the problem
</code>```

This will uninstall pip and setuptools.

After which you can reinstall them using

```<code>python -m ensurepip
</code>```

This will install pip and setuptools.

I have tried this on my windows 10 machine running Python 3.7.4!

Title: My pip is broken on Windows, how can I fix it?

Body:
You could follow the equivalent steps mentioned here and here (Both are closed issues on pip's github page) on your windows machine.

On windows you can do this:

python -m pip uninstall pip setuptools # Sometimes setuptools might be the problem

This will uninstall pip and setuptools.

After which you can reinstall them using

python -m ensurepip

This will install pip and setuptools.

I have tried this on my windows 10 machine running Python 3.7.4!


问:
Can functors always replace callbacks
In C++ can  functors always replace callbacks? Or there are cases when "regular" callbacks are needed?
I.e. each function that takes a function pointer , take instead a functor ,having the same arguments and return value as the function pointer?</p>

答:
Traditional C function pointers can not be substituted using just any functor.
So structs with operator() overloads or lambdas with capture variables will not work. See the following code:

#include <functional>

// this function takes a void() function pointer
void run_callback(void(*callback)()) {
    callback();
}

// this function takes a std::function
void run_function(std::function<void()> fun) {
    fun();
}

struct Callable {
    void operator()();
};

int main() {
    int x;
    run_callback([](){});     // OK
    run_callback([x](){});    // ERROR, we are not allowed to capture x
    run_callback(Callable{}); // ERROR, can't convert Callable to function pointer

    run_function([](){});     // OK
    run_function([x](){});    // ALSO OK
    run_function(Callable{}); // ALSO OK
}
```

If you want a solution that just works for anything from function pointers to lambdas/functors, then use std::function.

C function pointers are necessary when calling C APIs from C++.

C function pointers are also better in performance critical applications.
std::function can take anything because internally, it wraps function pointers and functors in a polymorphic wrapper class. This requires a virtual function call, meaning that std::function needs to dereference a pointer before it knows what to call. Also std::function can be empty. As a result, it needs to test each call whether it is empty and throws std::bad_function_call if so.

Title: Can functors always replace callbacks

Body:
Traditional C function pointers can not be substituted using just any functor.
So structs with operator() overloads or lambdas with capture variables will not work. See the following code:

#include <functional>

// this function takes a void() function pointer
void run_callback(void(*callback)()) {
    callback();
}

// this function takes a std::function
void run_function(std::function<void()> fun) {
    fun();
}

struct Callable {
    void operator()();
};

int main() {
    int x;
    run_callback([](){});     // OK
    run_callback([x](){});    // ERROR, we are not allowed to capture x
    run_callback(Callable{}); // ERROR, can't convert Callable to function pointer

    run_function([](){});     // OK
    run_function([x](){});    // ALSO OK
    run_function(Callable{}); // ALSO OK
}

If you want a solution that just works for anything from function pointers to lambdas/functors, then use std::function.

C function pointers are necessary when calling C APIs from C++.

C function pointers are also better in performance critical applications.
std::function can take anything because internally, it wraps function pointers and functors in a polymorphic wrapper class. This requires a virtual function call, meaning that std::function needs to dereference a pointer before it knows what to call. Also std::function can be empty. As a result, it needs to test each call whether it is empty and throws std::bad_function_call if so.