问:
Access a certain array inside a method
I want to have multiple ASCII art figures which I want to store inside different arrays.

I learned about methods in Java that they are used for splitting code into smaller parts. Therefore, my idea is to put the art into individual arrays inside a method, so it's tidy.

Is there a way to do so?
I made an example code to show how I imagine this.

My Google search about how to access a certain array inside a method didn't give me anything I can use.
I apologize if there already is a thread about this topic.

```<code>public class Main {
    public static void main(String[] args) {
        System.out.println(divArr(arr2[1])); // expected output 20
    }

    public static void divArr() {
        int arr1[] {1, 2, 3};
        int arr2[] {10, 20, 30};
    }
}
</code>```

答:
This is not the idea of functions.
functions are actions, they accept parameters, calculate stuff and return a value.
for example this is a function that returns the average of 3 numbers:

```<code>public static int avarage(int a, int b, int c) {
    int sum = a + b + c;
    int result = sum / 3;
    return result;
}
</code>```

You probably found information about javascript's dictionary, which have different syntax from java's function, although both of them have { and }

You can use the following approach:

```<code>public static class Main {
    public static int[] arr1 = {1,2,3};
    public static int[] arr2 = {10,20,30};

    public static void main(String[] args) {
        System.out.println(arr2[1]);
    }
}
</code>```

in this code, arr1 and arr2 are static variables.

You can also use a Map or a Class instead

EDIT:

another approach will be to use 2 dimensional array:

```<code>public static class Main {
    public static int[][] frame1 = {
                                     {1,2,3},
                                     {10,20,30}
                                   };
    public static int[][] frame2 = {
                                     {4,5,6},
                                     {40,50,60}
                                   };

    public static void main(String[] args) {
        System.out.println(frame1[1][1]);
    }
}
</code>```

Title: Access a certain array inside a method

Body:
I want to have multiple ASCII art figures which I want to store inside different arrays.

I learned about methods in Java that they are used for splitting code into smaller parts. Therefore, my idea is to put the art into individual arrays inside a method, so it's tidy.

Is there a way to do so?
I made an example code to show how I imagine this.

My Google search about how to access a certain array inside a method didn't give me anything I can use.
I apologize if there already is a thread about this topic.

public class Main {
    public static void main(String[] args) {
        System.out.println(divArr(arr2[1])); // expected output 20
    }

    public static void divArr() {
        int arr1[] {1, 2, 3};
        int arr2[] {10, 20, 30};
    }
}

Body:
This is not the idea of functions.
functions are actions, they accept parameters, calculate stuff and return a value.
for example this is a function that returns the average of 3 numbers:

public static int avarage(int a, int b, int c) {
    int sum = a + b + c;
    int result = sum / 3;
    return result;
}

You probably found information about javascript's dictionary, which have different syntax from java's function, although both of them have { and }

You can use the following approach:

public static class Main {
    public static int[] arr1 = {1,2,3};
    public static int[] arr2 = {10,20,30};

    public static void main(String[] args) {
        System.out.println(arr2[1]);
    }
}

in this code, arr1 and arr2 are static variables.

You can also use a Map or a Class instead

EDIT:

another approach will be to use 2 dimensional array:

public static class Main {
    public static int[][] frame1 = {
                                     {1,2,3},
                                     {10,20,30}
                                   };
    public static int[][] frame2 = {
                                     {4,5,6},
                                     {40,50,60}
                                   };

    public static void main(String[] args) {
        System.out.println(frame1[1][1]);
    }
}


来源: stackexchange

问:
Change font size in WPF compatible with Ease of Access functions
I am working on a simple WPF app that needs to be accessible for people with impaired vision.

I am testing my app with the Windows 10 -> Settings -> Ease of Access -> Display -> Make text Bigger slider setting.

I have some section titles (TextBlock) that I want to have a bigger font than the rest of the labels and text in the window. However, if I use the FontSize attribute to make it bigger it is no longer affected by changes to the system text size. Thus, while all other text that hasn't FontSize set gets bigger, the ones that do remain at their fixed size.

Is there a simple way to make some text relatively bigger than the rest while not setting a specific font size value?

答:
This achieved exactly what I wanted. It is not the prettiest, but it works well.
https://github.com/dotnet/wpf/issues/3701</p>

ContentLicense: CC BY-SA 4.0


问:
jquery picture selector
Does anyone have an example of a jquery based photo selector?  This is something you see in small photo albums.

I have the following code:

```<code><div><img class="bigpicture" src="1.jpg"></img></div>
<div>
    <img class="smallpicture" src="1.jpg"></img>
    <img class="smallpicture" src="2.jpg"></img>
    <img class="smallpicture" src="3.jpg"></img>
    <img class="smallpicture" src="4.jpg"></img>
    <img class="smallpicture" src="5.jpg"></img>
    <img class="smallpicture" src="6.jpg"></img>
</div>
</code>```

The behavior I'm looking for is when the users hovers over any of the smaller pictures, it updates the bigger picture with the one that was just hovered.

Any thoughts?

Thanks

答:
```<code>$('.smallpicture').hover(function(){
    var theSrc = $(this).attr('src');
    $('.bigpicture').attr('src', theSrc);
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: jquery picture selector

Body:
Does anyone have an example of a jquery based photo selector?  This is something you see in small photo albums.

I have the following code:

The behavior I'm looking for is when the users hovers over any of the smaller pictures, it updates the bigger picture with the one that was just hovered.

Any thoughts?

Thanks


问:
How do I merge 2 properties of 1 JSON file if the key name is the same?
I have the following JSON:

```<code>[
    {
        "computers": {
            "available": [
                6,
                2
            ],
            "held": [],
            "upgrades": [],
            "installed": [
                "PC-1"
            ]
        },
        "version": "0.6.55-0ubuntu12~20.04.4",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    },
    {
        "computers": {
            "available": [
                209,
                211,
                210
            ],
            "held": [],
            "upgrades": [],
            "installed": [
                "PC-3"
            ]
        },
        "version": "0.6.45-1ubuntu1.3",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    }
]
</code>```

I want to make a check against the data to check to see if the name property has any duplicate values. As such above, there are 2 accountservices but they have different version values.

How would I combine the 2 so that I only have 1 accountservices but 2 version in it using ReactJS? The other data is not relevant so can either be removed or merged also, I am only interested in listing different version for each name.

Expected output:

```<code>[
    {
        "version": "0.6.55-0ubuntu12~20.04.4, 0.6.45-1ubuntu1.3",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    }
]
</code>```

I have tried using the following function that I found online but can't get it working:

```<code>const sanitize = (source_array) => {
      let output = [];

      source_array.forEach( e => {
        if (output.filter( e1 => e1.name === e.name ).length === 0) {
         let unique_e = source_array.filter(j => j.name === e.name );
         let model = {};
        if (unique_e.length === 1)
          model = e;
        else {
          model.name = e.name;
          model.computers.installed = e.computers.installed;
          model.version = [];
          for ( const el of unique_e ) {
              const { version } = el;
              model.version.push({version});
        }
      }
     output.push(model)
     }
    });
      return output
    }
</code>```

答:
This is a perfect use case for the reduce function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Your sanitize function could look like something like this:

```<code>const sanitize = (source_array) => {
  const output = source_array.reduce((acc, { name, version, summary }) => {
    // try to find an entry with same name
    const entry = acc.find(e => e.name === name)
    if (entry) {
      // There was already an entry with this name !
      entry.version += `,${version}`
    } else {
      acc.push({ name, version, summary })
    }
    return acc
  }, []);
  return output
}
</code>```

Body:
I have the following JSON:

[
    {
        "computers": {
            "available": [
                6,
                2
            ],
            "held": [],
            "upgrades": [],
            "installed": [
                "PC-1"
            ]
        },
        "version": "0.6.55-0ubuntu12~20.04.4",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    },
    {
        "computers": {
            "available": [
                209,
                211,
                210
            ],
            "held": [],
            "upgrades": [],
            "installed": [
                "PC-3"
            ]
        },
        "version": "0.6.45-1ubuntu1.3",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    }
]

I want to make a check against the data to check to see if the name property has any duplicate values. As such above, there are 2 accountservices but they have different version values.

How would I combine the 2 so that I only have 1 accountservices but 2 version in it using ReactJS? The other data is not relevant so can either be removed or merged also, I am only interested in listing different version for each name.

Expected output:

[
    {
        "version": "0.6.55-0ubuntu12~20.04.4, 0.6.45-1ubuntu1.3",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    }
]

I have tried using the following function that I found online but can't get it working:

const sanitize = (source_array) => {
      let output = [];

      source_array.forEach( e => {
        if (output.filter( e1 => e1.name === e.name ).length === 0) {
         let unique_e = source_array.filter(j => j.name === e.name );
         let model = {};
        if (unique_e.length === 1)
          model = e;
        else {
          model.name = e.name;
          model.computers.installed = e.computers.installed;
          model.version = [];
          for ( const el of unique_e ) {
              const { version } = el;
              model.version.push({version});
        }
      }
     output.push(model)
     }
    });
      return output
    }

Body:
This is a perfect use case for the reduce function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Your sanitize function could look like something like this:

const sanitize = (source_array) => {
  const output = source_array.reduce((acc, { name, version, summary }) => {
    // try to find an entry with same name
    const entry = acc.find(e => e.name === name)
    if (entry) {
      // There was already an entry with this name !
      entry.version += `,${version}`
    } else {
      acc.push({ name, version, summary })
    }
    return acc
  }, []);
  return output
}


问:
aws Presigned Url doesn't support videos that are more than 1 minute long
enter image description hereWhen I tried creating Presigned URLs for my videos in s3 some of the video's presigned urls don't work. and It turned out that only URl of videos that are more then 1 minute long. Is there a problem  on my side while creating the url or is it a restriction in AWS presigned URLs</p>

答:
For S3 all files are object there is no any specific rule for image and video maybe your MIME type are property set because if there is signed url issue AWS provide the error access denied. you can confirm this with make this video pubic and try to run it I am sure after public access its not play so check below check points

Check the video MIME type

Check Video size its property uploaded or not

If you upload video from local machine try to play is it correct formatted means play as expected or not.

Thanks


问:
How to create a DS to store the accumulated result of another DS with rrdtool
I want to create a rrd file with two data souces incouded. One stores the original value the data, name it 'dc'. The other stores the accumulated result of 'dc', name it 'total'. The expected formula is current(total) = previous(total) + current(dc). For example, If I update the data sequence (2, 3, 5, 4, 9) to the rrd file, I want 'dc' is (2, 3, 5, 4, 9) and 'total' is (2, 5, 15, 19, 28).

I tried to create the rrd file with the command line below. The command fails and says that the PREV are not supported with DS COMPUTE.

```<code>rrdtool create test.rrd --start 920804700 --step 300 \
  DS:dc:GAUGE:600:0:U \
  DS:total:COMPUTE:PREV,dc,ADDNAN \
  RRA:AVERAGE:0.5:1:1200 \
  RRA:MIN:0.5:12:2400 \
  RRA:MAX:0.5:12:2400 \
  RRA:AVERAGE:0.5:12:2400
</code>```

Is there an alternative manner to define the DS 'total' (DS:total:COMPUTE:PREV,dc,ADDNAN) ?

答:
Sorry a bit late but may be helpful for someone else.

Better to use RRDtool's ' mrtg-traffic-sum ' package which when I'm using an rrd with GAUGE DS & LAST a the RRA's so it's allowing me to collect monthly traffic volumes & quota limits.

eg:  Here is a basic Traffic chart with no traffic quota.

```<code>root@server:~# /usr/bin/mrtg-traffic-sum --range=current --units=MB /etc/mrtg/R4.cfg
Subject: Traffic total for '/etc/mrtg/R4.cfg' (1.9) 2022/02

Start: Tue Feb  1 01:00:00 2022
End:   Tue Mar  1 00:59:59 2022
Interface                                    In+Out in MB
------------------------------------------------------------------------------
eth0                                                    0
eth1                                                14026
eth2                                                 5441
eth3                                                    0
eth4                                                15374
switch0.5                                           12024
switch0.19                                            151
switch0.49                                              1
switch0.51                                              0
switch0.92                                           2116
root@server:~#
</code>```

From this you can then write up a script that will generate a new rrd which stores these values & presto you have a traffic volume / quota graph.

Example fixed traffic volume chart using GAUGE

This thread reminded me to fix this collector that had stopped & just got around to posting ;)

Body:
I want to create a rrd file with two data souces incouded. One stores the original value the data, name it 'dc'. The other stores the accumulated result of 'dc', name it 'total'. The expected formula is current(total) = previous(total) + current(dc). For example, If I update the data sequence (2, 3, 5, 4, 9) to the rrd file, I want 'dc' is (2, 3, 5, 4, 9) and 'total' is (2, 5, 15, 19, 28).

I tried to create the rrd file with the command line below. The command fails and says that the PREV are not supported with DS COMPUTE.

rrdtool create test.rrd --start 920804700 --step 300 \
  DS:dc:GAUGE:600:0:U \
  DS:total:COMPUTE:PREV,dc,ADDNAN \
  RRA:AVERAGE:0.5:1:1200 \
  RRA:MIN:0.5:12:2400 \
  RRA:MAX:0.5:12:2400 \
  RRA:AVERAGE:0.5:12:2400

Is there an alternative manner to define the DS 'total' (DS:total:COMPUTE:PREV,dc,ADDNAN) ?

Body:
Sorry a bit late but may be helpful for someone else.

Better to use RRDtool's ' mrtg-traffic-sum ' package which when I'm using an rrd with GAUGE DS & LAST a the RRA's so it's allowing me to collect monthly traffic volumes & quota limits.

eg:  Here is a basic Traffic chart with no traffic quota.

root@server:~# /usr/bin/mrtg-traffic-sum --range=current --units=MB /etc/mrtg/R4.cfg
Subject: Traffic total for '/etc/mrtg/R4.cfg' (1.9) 2022/02

Start: Tue Feb  1 01:00:00 2022
End:   Tue Mar  1 00:59:59 2022
Interface                                    In+Out in MB
------------------------------------------------------------------------------
eth0                                                    0
eth1                                                14026
eth2                                                 5441
eth3                                                    0
eth4                                                15374
switch0.5                                           12024
switch0.19                                            151
switch0.49                                              1
switch0.51                                              0
switch0.92                                           2116
root@server:~#

From this you can then write up a script that will generate a new rrd which stores these values & presto you have a traffic volume / quota graph.

Example fixed traffic volume chart using GAUGE

This thread reminded me to fix this collector that had stopped & just got around to posting ;)


问:
How can I create a self update codepipeline?
I am using codepipeline as CI/CD pipeline by using CDK.

I'd like to make the pipeline update by itself so I tried to create one stage in the pipeline to update the pipeline itself by running cdk deploy  command.

In order to make the self update work, I need to specify a parameter selfMutation in codepipeline construct: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.CodePipeline.html#selfmutation

but this property only exists in cdk v2 not v1 ( I am using cdk 1.84.0 ). What is the equivalent property in v1?

答:
The CDK pipelines package also exists in v1.

CDK Pipelines are different from aws-codepipeline.Pipeline. It's build on top of it and allows you to deploy CDK apps with CodePipeline.

More information about CDK pipelines and what they are: https://aws.amazon.com/blogs/developer/cdk-pipelines-continuous-delivery-for-aws-cdk-applications/

Documentation for CDK pipelines in CDKv1: https://docs.aws.amazon.com/cdk/api/v1/docs/pipelines-readme.html


问:
Exposing a Postegres / Patroni db on Openshift to outside world
I am planning to run an SSIS ETL job , which has a sql server as SOURCE db , this is on a physical on-premise machine and the DESTINATION db (postegres/patroni) is running on Openshift platform as pod/containers. The issue I am facing now is like, DB hosted on openshift cannot be exposed via tcp port. As per few articles online, openshift only allows HTTP traffic via “routes”. Is this assumption right? If yes, how in real world people run ETL or bulk data transfer or migration to a db on openshift from outside. I am worried to use HTTP since I feel , it’s not efficient for ETL. Few folks mentioned like, use OC PORT FORWARDING. But for a production app, how an open shift port forwarding be stable? Please throw your comments</p>

答:
In a production environment it is a little questionable if you want to expose your database to the public internet. Normally you probably rather want to go with a site-to-site VPN.

That left aside it is correct that OCP is using routes for most use cases, which are then exposing an http(s) endpoint. If you need plain TCP however, you can create a service of type loadbalancer.

The regular setup with a route is stacked like

route --> service --> pods where the service is commonly of type clusterIP.

with a service of type loadbalancer, you eliminate the route and directly expose a TCP service.

If you run on a public cloud, OCP takes care of the leftover requirements for you. Namely that is to create a Loadbalancer with your cloudprovider. In the case of AWS for example, OCP would create an ELB (Elastic Loadbalancer) for you.

You can find more information in the documentation


问:
We can't install yum update on centOS
Hi everyone am new to linux when am running alma linux. In my whm terminal when i run yum update i get this error below.

CentOS-8 - Base                                                                      24 kB/s | 282  B     00:00

Error: Failed to download metadata for repo 'BaseOS': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

I tried this solution listed but didnt work out .

Step 1: Go to the /etc/yum.repos.d/ directory.

Step 2: Run the below commands

```<code>sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
</code>```

Step 3: To clean all cached information, use the following command

```<code>yum clean all
</code>```

Step 4: Now run the yum update

```<code>yum update -y
</code>```

CentOS-8 - Base                                                                      24 kB/s | 282  B     00:00

Error: Failed to download metadata for repo 'BaseOS': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

答:
It might be because of the BaseOS broken repository.

```<code># vim /etc/yum.repos.d/CentOS-Linux-BaseOS.repo
</code>```

change enabled=1 to enabled=0

or

remove the file /etc/yum.repos.d/CentOS-Linux-BaseOS.repo

Now update

```<code>#yum update -y
</code>```

Title: We can't install yum update on centOS

Body:
Hi everyone am new to linux when am running alma linux. In my whm terminal when i run yum update i get this error below.

CentOS-8 - Base                                                                      24 kB/s | 282  B     00:00

Error: Failed to download metadata for repo 'BaseOS': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

I tried this solution listed but didnt work out .

Step 1: Go to the /etc/yum.repos.d/ directory.

Step 2: Run the below commands

sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*

Step 3: To clean all cached information, use the following command

yum clean all

Step 4: Now run the yum update

yum update -y

CentOS-8 - Base                                                                      24 kB/s | 282  B     00:00

Error: Failed to download metadata for repo 'BaseOS': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

Body:
It might be because of the BaseOS broken repository.

# vim /etc/yum.repos.d/CentOS-Linux-BaseOS.repo

change enabled=1 to enabled=0

or

remove the file /etc/yum.repos.d/CentOS-Linux-BaseOS.repo

Now update

#yum update -y


问:
Solana JSON RPC API parameters encoding
Is there any documentation or paper about how exactly are rust parameters types encoded via JSON RPC API interaction?
Like for ethereum: https://docs.soliditylang.org/en/v0.8.11/abi-spec.html

There are some good abstraction tools like web3js to encode simple types like integers, but i have not found any paper about how to encode arrays or structs.

It is insanely hard for me to get into solana intricacies after building ethereum dApps, so it would be great if you share any other good specifications.

TY!

答:
So each program is unique in this regard although many follow a similar model. This is something that you must find the source code or documentation for the specific program you want to call.

If you only have the source code there is commonly, following good practices, an
instruction.rs file that identifies each of the instructions and what data they expect. It may also specify what convention of serialization is used so that would clue you in to what you need to do on the client side that submits the instruction.

In addition, for data serialization/deserialization, following good practices there may be a
state.rs or account_state.rs that shows you how the program serializes/deserializes account data.

The latter giving you the understanding of how you would need to deserialize an AccountInfo data array to see results in the client.

Title: Solana JSON RPC API parameters encoding


问:
Using spacy to redact names from a column in a data frame
I have a data frame named "df1". This data frame has 12 columns. The last column in this data frame is called notes. I need to replace common names like "john, sally and richard" from this column and replace the values with xxxx or something similar. I have a working script that is creating this data frame from MS SQL. I have spent several hours and used various resources to try and get some code that works to do this but I have not been successful. I do not have to use Spacy, but I was told this is a good package to work with. Any help would be appreciated.</p>

答:
You need to use a solution like

import spacy
import pandas as pd

# Test dataframe
df = pd.DataFrame({'notes':["Peter A. Smith came to see Bart in Washington on Tuesday."]})

print(df['notes'])
# => 0    Peter A. Smith came to see   Bart     in   Washington on  Tuesday.
##        <<PERSON>>     came to see <<PERSON>> in     <<GPE>>  on <<DATE>>.

nlp = spacy.load('en_core_web_trf')

def redact_with_spacy(text: str) -> str:
    doc = nlp(text)
    newString = text
    for e in reversed(doc.ents):
        if e.label_ == "PERSON": # Only redact PERSON entities
            start = e.start_char
            end = start + len(e.text)
            newString = newString[:start] + "xxxx" + newString[end:]
    return newString

df['notes'] = df['notes'].apply(redact_with_spacy)
print(df['notes'])
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>0    xxxx came to see xxxx in Washington on Tuesday.
</code>```

Note you may adjust the "xxxx" in the redact_with_spacy function. E.g., you may replace the found entity with the same amount of xs if you use newString = newString[:start] + ("x" * len(e.text)) + newString[end:]. Or, to keep spaces, newString = newString[:start] + "".join(["x" if not x.isspace() else " " for x in e.text]) + newString[end:].

Body:
You need to use a solution like

import spacy
import pandas as pd

# Test dataframe
df = pd.DataFrame({'notes':["Peter A. Smith came to see Bart in Washington on Tuesday."]})

print(df['notes'])
# => 0    Peter A. Smith came to see   Bart     in   Washington on  Tuesday.
##        <<PERSON>>     came to see <<PERSON>> in     <<GPE>>  on <<DATE>>.

nlp = spacy.load('en_core_web_trf')

def redact_with_spacy(text: str) -> str:
    doc = nlp(text)
    newString = text
    for e in reversed(doc.ents):
        if e.label_ == "PERSON": # Only redact PERSON entities
            start = e.start_char
            end = start + len(e.text)
            newString = newString[:start] + "xxxx" + newString[end:]
    return newString

df['notes'] = df['notes'].apply(redact_with_spacy)
print(df['notes'])

Output:

0    xxxx came to see xxxx in Washington on Tuesday.

Note you may adjust the "xxxx" in the redact_with_spacy function. E.g., you may replace the found entity with the same amount of xs if you use newString = newString[:start] + ("x" * len(e.text)) + newString[end:]. Or, to keep spaces, newString = newString[:start] + "".join(["x" if not x.isspace() else " " for x in e.text]) + newString[end:].


问:
Do not normalize docker container names in traefik rules
I want to use Traefik v2.5 as a local reverse proxy to access all docker containers of my local daemon using a domain of pattern http://container_name.localhost in my browser.

This is my docker-compose.yml file:

```<code>version: "3.7"
services:
  traefik:
    image: traefik:v2.5
    restart: always
    network_mode: "host"
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    command:
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=true"
      - "--providers.docker.defaultrule=Host(`{{ .Name }}.localhost `)"
      - "--entrypoints.web.address=:80"
</code>```

Then I started the container and a simple web server to see if it worked:

```<code>docker-compose up -d
docker run -d --name my_nginx nginx
</code>```

Then, I was able to access the web server at http://my-nginx.docker.localhost/. However, the name of the docker container uses underscores and not hyphens. This makes it very confusing if you just want to access one of your containers in the browser. Therefore, I want to access the container using http://my_nginx.localhost/. Is there a way to disable the normalization of the traefik rule?

I am aware that one normally uses hyphens in URLs, but docker just wants to have it's underscores, and this is just my local dev environment. I also do not want to add a traefik label manually, e.g.

```<code>traefik.http.routers.my_nginx.rule==Host(`my_nginx.localhost`)
</code>```

whenever I start a simple dev container.

答:
I just checked the docs, and it's written that you have sprig functions available in the go template snippets.

Therefore, you can leverage go template + sprigs string functions to replace the hyphen with underscores.

```<code>Host(`{{ .Name | replace "-" "_" }}.localhost `)
</code>```

Body:
I want to use Traefik v2.5 as a local reverse proxy to access all docker containers of my local daemon using a domain of pattern http://container_name.localhost in my browser.

This is my docker-compose.yml file:

version: "3.7"
services:
  traefik:
    image: traefik:v2.5
    restart: always
    network_mode: "host"
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    command:
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=true"
      - "--providers.docker.defaultrule=Host(`{{ .Name }}.localhost `)"
      - "--entrypoints.web.address=:80"

Then I started the container and a simple web server to see if it worked:

docker-compose up -d
docker run -d --name my_nginx nginx

Then, I was able to access the web server at http://my-nginx.docker.localhost/. However, the name of the docker container uses underscores and not hyphens. This makes it very confusing if you just want to access one of your containers in the browser. Therefore, I want to access the container using http://my_nginx.localhost/. Is there a way to disable the normalization of the traefik rule?

I am aware that one normally uses hyphens in URLs, but docker just wants to have it's underscores, and this is just my local dev environment. I also do not want to add a traefik label manually, e.g.

traefik.http.routers.my_nginx.rule==Host(`my_nginx.localhost`)

whenever I start a simple dev container.

Body:
I just checked the docs, and it's written that you have sprig functions available in the go template snippets.

Therefore, you can leverage go template + sprigs string functions to replace the hyphen with underscores.

Host(`{{ .Name | replace "-" "_" }}.localhost `)


问:
Using https for minio server
I am trying to get a minio server to run on https but everytime i try to run it i get the following error:

```<code>{"level":"FATAL","time":"2018-06-15T15:12:19.2189519Z","error":{"message":"The
parameter is incorrect.","source":["cmd\\server-main.go:225:cmd.serverMain()"]}}
</code>```

I have followed the following guide:
https://docs.minio.io/docs/how-to-secure-access-to-minio-server-with-tls

And tried to generate my own certificate but nothing seems to work... I placed the certificates inside the .minio/certs folder and named them public.crt and private.key. I have tried to re-generate the certs over and over again but I am still getting that error message... If anyone can point me in the right direction, i would greatly appropriate it

答: if you using sudo you must have private.key and public.crt in /root/.minio/certs/. In my case, I must rename my minio.key and minio.crt because minio doesn't want to use them.

Title: Using https for minio server

Body:
I am trying to get a minio server to run on https but everytime i try to run it i get the following error:

{"level":"FATAL","time":"2018-06-15T15:12:19.2189519Z","error":{"message":"The
parameter is incorrect.","source":["cmd\\server-main.go:225:cmd.serverMain()"]}}

I have followed the following guide:
https://docs.minio.io/docs/how-to-secure-access-to-minio-server-with-tls

And tried to generate my own certificate but nothing seems to work... I placed the certificates inside the .minio/certs folder and named them public.crt and private.key. I have tried to re-generate the certs over and over again but I am still getting that error message... If anyone can point me in the right direction, i would greatly appropriate it


问:
How to get an iterator from an akka streams Source?
I'm trying to create a flow that I can consume via something like an Iterator.
I'm implementing a library that exposes an iterator-like interface, so that would be the simplest thing for me to consume.

My graph designed so far is essentially a Source<Iterator<DataRow>>. One thing I see so far is to flatten it to Source<DataRow> and then use http://doc.akka.io/japi/akka/current/akka/stream/javadsl/StreamConverters.html#asJavaStream-- followed by https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#iterator--

But given that there will be lots potentially many rows, I'm wondering whether it would make sense to avoid the flattening step (at least within the akka streams context, I'm assuming there's some minor per-element overhead when passed via stages), or if there's a more direct way.

Also, I'm curious how backpressure works in the created stream, especially the child Iterator; does it only buffer one element?

答: Alternatively, you may implement an Iterator using prefixAndTail(1) under the hood for implementing hasNext and next.


问:
Does Displaytag's ExcelView even work? Getting Non-Excel output of plain strings
According to the Displaytag 1.2 documentation, ExportView is provided to output Excel files.

But actually, the source code shows that the entire Excel Model structure is just a plain data  bean of strings. The result of using ExcelView to output an XLS is the following plain-text output (not a valid XLS),

```<code>"Agreement Category"    "Approving Official"    "Second Level Approving Official"
"Regular"   "John Smith"    "Test"
</code>```

Indeed, the ExcelView Model package is just a String-based set of classes, like a POJO bean,

```<code>org.displaytag.model.Column
org.displaytag.model.HeaderCell
...
</code>```

I understand that Displaytag also has a completely different renderer, org.displaytag.export.excel.DefaultHssfExportView , which uses HSSF to write XLS files. That renderer does produce a valid Excel file. (It's in the JAR displaytag-export-poi-1.2.jar.)

So what's the purpose of ExcelView, then? Is it a final renderer, or just an interface renderer of some kind? Does it assume more implementation? Why call it ExcelView if it doesn't actually output Excel, just a String list? Are we supposed to use DefaultHssfExportView for all Excel exports?

答:
I was able to get the full binary Excel export with:

displaytag 1.2 and displaytag-export-poi 1.2

e.g. in build.gradle:

```<code>    implementation 'displaytag:displaytag:1.2'
    implementation 'displaytag:displaytag-export-poi:1.2'
</code>```

and adding the following to displaytag.properties:

```<code>export.excel.class=org.displaytag.export.excel.ExcelHssfView

</code>```

Body:
According to the Displaytag 1.2 documentation, ExportView is provided to output Excel files.

But actually, the source code shows that the entire Excel Model structure is just a plain data  bean of strings. The result of using ExcelView to output an XLS is the following plain-text output (not a valid XLS),

"Agreement Category"    "Approving Official"    "Second Level Approving Official"
"Regular"   "John Smith"    "Test"

Indeed, the ExcelView Model package is just a String-based set of classes, like a POJO bean,

org.displaytag.model.Column
org.displaytag.model.HeaderCell
...

I understand that Displaytag also has a completely different renderer, org.displaytag.export.excel.DefaultHssfExportView , which uses HSSF to write XLS files. That renderer does produce a valid Excel file. (It's in the JAR displaytag-export-poi-1.2.jar.)

So what's the purpose of ExcelView, then? Is it a final renderer, or just an interface renderer of some kind? Does it assume more implementation? Why call it ExcelView if it doesn't actually output Excel, just a String list? Are we supposed to use DefaultHssfExportView for all Excel exports?

Body:
I was able to get the full binary Excel export with:

displaytag 1.2 and displaytag-export-poi 1.2

e.g. in build.gradle:

    implementation 'displaytag:displaytag:1.2'
    implementation 'displaytag:displaytag-export-poi:1.2'

and adding the following to displaytag.properties:

export.excel.class=org.displaytag.export.excel.ExcelHssfView


问:
ROBOT framework: using environment variables in argument file
Here's a basic rundown of what I want to do:

I want to call my scripts using an argument file. But the argument file needs to work on an environment variable for the path.  So, for example, the argument file may be:

args.robot

```<code>[ROBOT_HOME variable]/test1.robot
[ROBOT_HOME variable]/test2.robot
[ROBOT_HOME variable]/test3.robot
</code>```

And I would define the ROBOT_HOME variable at the environment level:

```<code>$ export ROBOT_HOME=/path/to/tests/
$ pybot -A args.robot
</code>```

None of the following substitutions for [ROBOT_HOME variable] in the args.robot file have worked:

$ROBOT_HOME

${ROBOT_HOME}

%{ROBOT_HOME}

And neither of the following pybot commands have worked:

pybot -A args.robot

pybot -v ROBOT_HOME:$ROBOT_HOME -A args.robot

Is what I'm trying to do possible?

答:
@xNok Solution would work, but it is not very accurate. You can not rewrite a file with envsubst command. Take a look into this thread.

rewriting a file with "envsubst file" leaves it empty

So, basically if you want to get it working in this way, the argument file would look like this:

```<code>export HOME='your/path'
envsubst '${HOME}' < argumentfile.txt > argumentfile_tmp.txt && mv argumentfile_tmp.txt argumentfile.txt
</code>```

And for instance the "argumentfile.txt" would look like this:

```<code>--variable PATH:${HOME}/some/sub/path
</code>```

Then as suggested by @xNok, you can run the script this way:

```<code>generate_arguments.sh && robot --argumentfile "argumentfile.txt"
</code>```

Please note that this method would overwrite the "argumentfile.txt". So, every time you need to clone the source code or the other option is to use envsubst to write to a temporary file.

Body:
Here's a basic rundown of what I want to do:

I want to call my scripts using an argument file. But the argument file needs to work on an environment variable for the path.  So, for example, the argument file may be:

args.robot

[ROBOT_HOME variable]/test1.robot
[ROBOT_HOME variable]/test2.robot
[ROBOT_HOME variable]/test3.robot

And I would define the ROBOT_HOME variable at the environment level:

$ export ROBOT_HOME=/path/to/tests/
$ pybot -A args.robot

None of the following substitutions for [ROBOT_HOME variable] in the args.robot file have worked:

$ROBOT_HOME

${ROBOT_HOME}

%{ROBOT_HOME}

And neither of the following pybot commands have worked:

pybot -A args.robot

pybot -v ROBOT_HOME:$ROBOT_HOME -A args.robot

Is what I'm trying to do possible?

Body:
@xNok Solution would work, but it is not very accurate. You can not rewrite a file with envsubst command. Take a look into this thread.

rewriting a file with "envsubst file" leaves it empty

So, basically if you want to get it working in this way, the argument file would look like this:

export HOME='your/path'
envsubst '${HOME}' < argumentfile.txt > argumentfile_tmp.txt && mv argumentfile_tmp.txt argumentfile.txt

And for instance the "argumentfile.txt" would look like this:

--variable PATH:${HOME}/some/sub/path

Then as suggested by @xNok, you can run the script this way:

generate_arguments.sh && robot --argumentfile "argumentfile.txt"

Please note that this method would overwrite the "argumentfile.txt". So, every time you need to clone the source code or the other option is to use envsubst to write to a temporary file.


问:
Laravel Error: Details blade displays wrong data, displays previous column data
name!!}" />
I have a Details page that displays "short description", "Duration", and "description of tour" from a database.

Problem:
Some Data displayed on the blade is from the previous entry in the table

Question:
Why would a details blade display data that's from a previous entry?

code snippet for the
details.blade.php

page

```<code>    @extends('client.layout.app2')
    @section('title')

   Flamingo WIld Life Vacation | {{$itenary->name}}

    @endsection
    @section('content')

    <div id="page_caption" class="hasbg parallax  " style="background-image:url('/header_image/{{$itenary->header_image}}');">
    <div class="single_tour_header_content">
    <div class="standard_wrapper">
    <a href="/header_image/{{$itenary->header_image}}" id="single_tour_gallery_open" class="button fancy-gallery"><span class="ti-camera"></span>View Photos</a>
    <div style="display:none;">

    @foreach($images as $image)

    <a id="single_tour_gallery_image1" href="/itenary_images/{{$image->body_image}}" title="The road to success and the road to failure are almost exactly the same" class="fancy-gallery"></a>

    @endforeach

    </div>

    <div class="single_tour_header_price">
    <div class="single_tour_price">

    {{ $itenary->name }}
    </div>

    </div>
    </div>
    </div>
    </div>

    <!-- Begin content -->
    <div id="page_content_wrapper" class="hasbg ">
    <div class="inner">

    <!-- Begin main content -->
    <div class="inner_wrapper">

    <div class="sidebar_wrapper">

    <div class="sidebar_top"></div>

    <div class="sidebar">

    <div class="content">

    <div class="single_tour_header_price">

    <div class="single_tour_per_person">
     {{$itenary->name}} </div>
    </div>

    <div class="single_tour_booking_wrapper themeborder contact_form7">
    <div role="form" class="wpcf7" id="wpcf7-f142-o1" lang="en-US" dir="ltr">
        <div class="screen-reader-response"></div>
        <form action="#" method="post" class="wpcf7-form" novalidate="novalidate">

            <p>
                <label> Full Name
                    <br />
                    <span class="wpcf7-form-control-wrap your-name"><input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="John Doe" /></span> </label>
                </p>
                <p>
                    <label> Email Address
                        <br />
                        <span class="wpcf7-form-control-wrap your-email"><input type="email" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="sample@yourcompany.com" /></span> </label>
                    </p>
                    <p>
                        <label> Phone Number
                            <br />
                            <span class="wpcf7-form-control-wrap tel-729"><input type="tel" name="tel-729" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-tel wpcf7-validates-as-required wpcf7-validates-as-tel" aria-required="true" aria-invalid="false" /></span> </label>
                        </p>
                        <p>
                            <label> Tour Date
                                <br />
                                <span class="wpcf7-form-control-wrap menu-419">
                                    <select name="menu-419" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required" aria-required="true" aria-invalid="false">
                                        <option value="10-18 January 2017">10-18 January 2017</option>
                                        <option value="23-31 January 2017">23-31 January 2017</option>
                                        <option value="7-15 February 2017">7-15 February 2017</option>
                                        <option value="18-26 February 2017">18-26 February 2017</option>
                                    </select>
                                </span>
                            </label>
                        </p>
                        <p>
                            <label> Number of Person
                                <br />
                                <span class="wpcf7-form-control-wrap text-237">
                                    <input type="text" name="text-237" value="" size="40" class="wpcf7-form-control wpcf7-text" aria-invalid="false" placeholder="1 person" />
                                </span>
                            </label>
                            <span class="wpcf7-form-control-wrap dynamictourtitle">
                                <input type="hidden" name="dynamictourtitle" value="Grand Switzerland" size="40" class="wpcf7-form-control wpcf7dtx-dynamictext wpcf7-dynamichidden" aria-invalid="false" />
                            </span>
                            <span class="wpcf7-form-control-wrap dynamictoururl">
                                <input type="hidden" name="dynamictoururl" value="#" size="40" class="wpcf7-form-control wpcf7dtx-dynamictext wpcf7-dynamichidden" aria-invalid="false" />
                            </span>
                        </p>
                        <p>
                            <input type="submit" value="Book This Tour" class="wpcf7-form-control wpcf7-submit" />
                        </p>
                        <div class="wpcf7-response-output wpcf7-display-none"></div>
                    </form>
                </div>
                <div class="single_tour_view_wrapper themeborder">
                    <div class="single_tour_view_desc">
                    This tour's been viewed 544 times in the past week </div>

                    <div class="single_tour_view_icon ti-alarm-clock"></div>
                </div>
                <br class="clear" />
            </div>

            <!--  <a id="single_tour_share_button" href="javascript:;" class="button ghost themeborder"><span class="ti-email"></span>Share this tour</a> -->
            <div class="one withsmallpadding ppb_text" style="text-align:left;padding:30px 0 30px 0;">
                <div class="standard_wrapper">
                    <div class="page_content_wrapper">
                        <div class="inner">
                            <div style="margin:auto;width:100%">
                            </p>
                            <h5 class="space">Share "{{$itenary->name}}" Itenary on:</h5>
                            <div class="social_wrapper shortcode light small">
                                <ul>
                                    <li class="facebook"><a target="_blank" title="Facebook" href="#"><i class="fa fa-facebook"></i></a></li>
                                    <li class="twitter"><a target="_blank" title="Twitter" href="https://twitter.com/#"><i class="fa fa-twitter"></i></a></li>
                                    <li class="Whatsapp"><a target="_blank" title="Whatsapp" href="#"><i class="fa fa-whatsapp"></i></a></li>

                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <ul class="sidebar_widget">
            <li id="text-3" class="widget widget_text">
                <h2 class="widgettitle">For More Informations</h2>
                <div class="textwidget"><span class="ti-mobile" style="margin-right:10px;"></span>+254722230053
                    <br/>
                    <span class="ti-alarm-clock" style="margin-right:10px;"></span>Mon - Sat 8.00 - 18.00</div>
                </li>
                <li id="grandtour_tour_posts-11" class="widget Grandtour_Tour_Posts">
                    <h2 class="widgettitle"></h2>

                    @foreach($itenaries->take(3) as $itenary)
                    <div class="one gallery1 grid static filterable portfolio_type themeborder" style="background-image:url('/header_image/{{$itenary->header_image}}');">
                        <a class="tour_image" href="#"></a>
                        <div class="portfolio_info_wrapper">
               <!--  <div class="tour_price ">
               $6,000 </div> -->
               <h5>{{$itenary->name}}</h5>
               <div class="tour_attribute_wrapper">
                <div class="tour_attribute_rating">
                    <div class="br-theme-fontawesome-stars-o">
                        <div class="br-widget">
                            <a href="javascript:;" class="br-selected"></a>
                            <a href="javascript:;" class="br-selected"></a>
                            <a href="javascript:;" class="br-selected"></a>
                            <a href="javascript:;" class="br-selected"></a>
                            <a href="javascript:;"></a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <br class="clear" />
    @endforeach

    </li>
    </ul>

    <div class="single_tour_users_online_wrapper themeborder">
    <div class="single_tour_users_online_icon">
    <span class="ti-info-alt"></span>
    </div>
    <div class="single_tour_users_online_content">
    <strong>131</strong> traveler(s) are considering our tours right now! </div>
    </div>

    </div>

    </div>
    <br class="clear" />

    <div class="sidebar_bottom"></div>
    </div>
    <div class="sidebar_content ">

    <h1>{{$itenary->name}}</h1>
    <div class="single_tour_attribute_wrapper themeborder ">
    <div class="one_fourth">
    <div class="tour_attribute_icon ti-time"></div>
    <div class="tour_attribute_content">
    {{$itenary->duration}} </div>
    </div>

    <div class="one_fourth">
    <div class="tour_attribute_icon ti-id-badge"></div>
    <div class="tour_attribute_content">
    Age 12+ </div>
    </div>

    <div class="one_fourth">
    <div class="tour_attribute_icon ti-calendar"></div>
    <div class="tour_attribute_content">
    Sep, Oct, Nov, Dec </div>
    </div>

    <div class="one_fourth last">
    <div class="tour_attribute_icon ti-user"></div>
    <div class="tour_attribute_content">
    Availability 50 </div>
    </div>

    </div>
    <br class="clear" />
    <p>{!! $itenary->short_description !!}.</p>
    <div class="single_tour_content">
    <p class="p1"> {!! $itenary->description_of_tour !!}.</p>

    </div>
    <div class="fullwidth_comment_wrapper sidebar">

    <div>

    <div class="comment" id="comment-20">

    <div class="right ">

    <a rel='nofollow' class='comment-reply-link' href='#' aria-label='Reply to Jack Dawson'>Reply</a>
    <div class="comment_text" />

    </div>
    </div>
    <br class="clear" />
    </li>
    <!-- #comment-## -->

    <br class="clear" />
    </li>
    <!-- #comment-## -->

    <br class="clear" />
    </li>
    <!-- #comment-## -->

    </div>
    <br class="clear" />
    </li>
    <!-- #comment-## -->
    </div>

    </div>

    </div>
    </div>
    </div>
    <!-- End main content -->

    <br class="clear"/>
    <div class="tour_related">
    <h3 class="sub_title">Similar Tours</h3>
    <div id="portfolio_filter_wrapper" class="gallery classic three_cols portfolio-content section content clearfix" data-columns="3">

    @foreach($itenaries->take(3)  as $itenary)
    <div class="element grid classic3_cols">
    <div class="one_third gallery3 classic static filterable portfolio_type themeborder" data-id="post-171">

    <a class="tour_image" href="#">
    <img src="{{asset('header_image/'.$itenary->header_image)}}" alt="{{$itenary->name}}l" />

    <!--  <div class="tour_price has_discount">
    <span class="normal_price">
    $6,000
    </span> $5,900
    </div> -->
    </a>

    <div class="portfolio_info_wrapper">
    <a class="tour_link" href="{{ route('itenaries.show',$itenary->slug) }}"><h4>{{$itenary->name}}</h4></a>
    <div class="tour_excerpt">
    <p>{{$itenary->itenary_category}}</p>
    </div>
    <div class="tour_attribute_wrapper">
    <div class="tour_attribute_rating">
    <div class="br-theme-fontawesome-stars-o">
    <div class="br-widget">
    <a href="javascript:;" class="br-selected"></a>
    <a href="javascript:;" class="br-selected"></a>
    <a href="javascript:;" class="br-selected"></a>
    <a href="javascript:;" class="br-selected"></a>
    <a href="javascript:;"></a>
    </div>
    </div>
    <div class="tour_attribute_rating_count">
    4  reviews </div>
    </div>

    <div class="tour_attribute_days">
    <span class="ti-time"></span> {{$itenary->duration}} </div>
    </div>
    <br class="clear" />
    </div>
    </div>
    </div>

    @endforeach

    </div>
    </div>

    </div>
    <br class="clear" />
    </div>

    @endsection

</code>```

Itenary Controller

```<code>
    public function show($slug){

            $itenary=Itenary::where('slug', $slug)->firstOrFail();
            $images=$itenary->itenary_images;
             $itenaries=Itenary::get();

    // dd($images);
            return view('client.itenary.details')->with('itenary', $itenary)->with('images', $images)->with('itenaries', $itenaries);
        }

</code>```

I have done php artisan optimize,
I have cleared the cache.
but no changes

答: There is a @foreach($itenaries->take(3) as $itenary) in the view where you overwrite the $itenary variable that you fill in the controller.

Body:
name!!}" />
I have a Details page that displays "short description", "Duration", and "description of tour" from a database.

Problem:
Some Data displayed on the blade is from the previous entry in the table

Question:
Why would a details blade display data that's from a previous entry?

code snippet for the
details.blade.php

page

    @extends('client.layout.app2')
    @section('title')

   Flamingo WIld Life Vacation | {{$itenary->name}}

    @endsection
    @section('content')

header_image}}');">

    header_image}}" id="single_tour_gallery_open" class="button fancy-gallery">View Photos

    @foreach($images as $image)

    body_image}}" title="The road to success and the road to failure are almost exactly the same" class="fancy-gallery">

    @endforeach

    {{ $itenary->name }}

     {{$itenary->name}}

        <form action="#" method="post" class="wpcf7-form" novalidate="novalidate">

                 Full Name

                    <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="John Doe" />

                     Email Address

                        <input type="email" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="sample@yourcompany.com" />

                         Phone Number

                            <input type="tel" name="tel-729" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-tel wpcf7-validates-as-required wpcf7-validates-as-tel" aria-required="true" aria-invalid="false" />

                             Tour Date

                                    <select name="menu-419" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required" aria-required="true" aria-invalid="false">
                                        <option value="10-18 January 2017">10-18 January 2017</option>
                                        <option value="23-31 January 2017">23-31 January 2017</option>
                                        <option value="7-15 February 2017">7-15 February 2017</option>
                                        <option value="18-26 February 2017">18-26 February 2017</option>
                                    </select>

                             Number of Person

                                    <input type="text" name="text-237" value="" size="40" class="wpcf7-form-control wpcf7-text" aria-invalid="false" placeholder="1 person" />

                                <input type="hidden" name="dynamictourtitle" value="Grand Switzerland" size="40" class="wpcf7-form-control wpcf7dtx-dynamictext wpcf7-dynamichidden" aria-invalid="false" />

                                <input type="hidden" name="dynamictoururl" value="#" size="40" class="wpcf7-form-control wpcf7dtx-dynamictext wpcf7-dynamichidden" aria-invalid="false" />

                            <input type="submit" value="Book This Tour" class="wpcf7-form-control wpcf7-submit" />

                    </form>

                    This tour's been viewed 544 times in the past week

Share "{{$itenary->name}}" Itenary on:

For More Informations

+254722230053

                    Mon - Sat 8.00 - 18.00

                    @foreach($itenaries->take(3) as $itenary)

header_image}}');">

{{$itenary->name}}

    @endforeach

    131 traveler(s) are considering our tours right now!

{{$itenary->name}}

    {{$itenary->duration}}

    Age 12+

    Sep, Oct, Nov, Dec

    Availability 50

{!! $itenary->short_description !!}.

 {!! $itenary->description_of_tour !!}.

    Reply

Similar Tours

    @foreach($itenaries->take(3)  as $itenary)

    header_image)}}" alt="{{$itenary->name}}l" />

    slug) }}">
{{$itenary->name}}

{{$itenary->itenary_category}}

    4  reviews

     {{$itenary->duration}}

    @endforeach

    @endsection

Itenary Controller

    public function show($slug){

            $itenary=Itenary::where('slug', $slug)->firstOrFail();
            $images=$itenary->itenary_images;
             $itenaries=Itenary::get();

    // dd($images);
            return view('client.itenary.details')->with('itenary', $itenary)->with('images', $images)->with('itenaries', $itenaries);
        }

I have done php artisan optimize,
I have cleared the cache.
but no changes


问:
git clone only README and git files, not actual project work
Goal: clone repo and all of it's project contents and branches

I cloned using URL and had to setup both an SSH Key and PAT.

Bash Terminal:

me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/project$ git clone https://github.com/project/synthetic-data-gen.git
Cloning into 'synthetic-data-gen'...
remote: Enumerating objects: 178, done.
remote: Counting objects: 100% (178/178), done.
remote: Compressing objects: 100% (125/125), done.
remote: Total 178 (delta 67), reused 152 (delta 44), pack-reused 0
Receiving objects: 100% (178/178), 1.40 MiB | 1.04 MiB/s, done.
Resolving deltas: 100% (67/67), done.
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/project$ ls
synthetic-data-gen
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/project$ ls synthetic-data-gen/
README.md
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/project$ git branch
fatal: not a git repository (or any parent up to mount point /mnt)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/project$ git pull
fatal: not a git repository (or any parent up to mount point /mnt)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/project$ git checkout --track -b development origin/development
fatal: not a git repository (or any parent up to mount point /mnt)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
```

答:
You need to be into the cloned directory before doing git command</p>
```<code>cd synthetic-data-gen
</code>```

Body:
You need to be into the cloned directory before doing git command

cd synthetic-data-gen


问:
Two-way binding and event delegation in React
Is there a way to implement it? When I try to do, react throws warning that I should only use onChange + value attributes, but I would not like to spam event handlers on each element if I already have it on common parent...</p>

答:
Just pass your onChange and value to child component using props

https://codesandbox.io/s/upbeat-shadow-wxd0e?file=/src/App.js


答:
This would get the job done

let source_array = [
  {
    computers: {
      available: [6, 2],
      held: [],
      upgrades: [],
      installed: ["PC-1"]
    },
    version: "0.6.55-0ubuntu12~20.04.4",
    name: "accountsservice",
    summary: "query and manipulate user account information"
  },
  {
    computers: {
      available: [209, 211, 210],
      held: [],
      upgrades: [],
      installed: ["PC-3"]
    },
    version: "0.6.45-1ubuntu1.3",
    name: "accountsservice",
    summary: "query and manipulate user account information"
  }
];

let output = [];

source_array.map((item) => {
  let filter = output.filter((i) => i.name === item.name);
  if (filter.length) {
    filter[0].version += `, ${item.version}`;
  } else {
    output.push({
      version: item.version,
      name: item.name,
      summary: item.summary
    });
  }
});

console.log(output);```

Title: How do I merge 2 properties of 1 JSON file if the key name is the same?


问:
Why doesn't Safe Haskell support Template Haskell?
The documentation for Safe Haskell states:

[...] Unfortunately Template Haskell can be used to subvert module boundaries and so could be used gain access to this constructor. [...] The use of the -XSafe flag to compile the Danger module restricts the features of Haskell that can be used to a safe subset. This includes disallowing unsafePerfromIO, Template Haskell,[...]

Used as a macro system that translates an AST to another AST, should it not be possible to simply restrict TH to the safe subset of Haskell, and also restrict the resulting AST to this subset?

答:
A bit further down on the page you linked:

TemplateHaskell — Is particularly dangerous, as it can cause side effects even at compilation time and can be used to access abstract data types. It is very easy to break module boundaries with TH.

The concern about side effects comes from the fact that TH allows you to run arbitrary IO computations at compile time using runIO. This would throw any hope of safety right out the window.

Breaking module boundaries means that using TH you can for example access data constructors even though a module did not export them.

See this repository for many examples of things that would be unsafe to allow in Safe Haskell, including an example of breaking module boundaries.

It might be possible that Template Haskell could be made safe if these features were disabled, however it would require significant changes to TH.


问:
How do I merge 2 properties of 1 JSON file if the key name is the same?
I have the following JSON:

```<code>[
    {
        "computers": {
            "available": [
                6,
                2
            ],
            "held": [],
            "upgrades": [],
            "installed": [
                "PC-1"
            ]
        },
        "version": "0.6.55-0ubuntu12~20.04.4",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    },
    {
        "computers": {
            "available": [
                209,
                211,
                210
            ],
            "held": [],
            "upgrades": [],
            "installed": [
                "PC-3"
            ]
        },
        "version": "0.6.45-1ubuntu1.3",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    }
]
</code>```

I want to make a check against the data to check to see if the name property has any duplicate values. As such above, there are 2 accountservices but they have different version values.

How would I combine the 2 so that I only have 1 accountservices but 2 version in it using ReactJS? The other data is not relevant so can either be removed or merged also, I am only interested in listing different version for each name.

Expected output:

```<code>[
    {
        "version": "0.6.55-0ubuntu12~20.04.4, 0.6.45-1ubuntu1.3",
        "name": "accountsservice",
        "summary": "query and manipulate user account information"
    }
]
</code>```

I have tried using the following function that I found online but can't get it working:

```<code>const sanitize = (source_array) => {
      let output = [];

      source_array.forEach( e => {
        if (output.filter( e1 => e1.name === e.name ).length === 0) {
         let unique_e = source_array.filter(j => j.name === e.name );
         let model = {};
        if (unique_e.length === 1)
          model = e;
        else {
          model.name = e.name;
          model.computers.installed = e.computers.installed;
          model.version = [];
          for ( const el of unique_e ) {
              const { version } = el;
              model.version.push({version});
        }
      }
     output.push(model)
     }
    });
      return output
    }
</code>```

答:
This would also work. This solution uses the name for grouping and lists the versions for each name and groups computers under different versions.

const input = [ { computers: { available: [6, 2], held: [], upgrades: [], installed: ["PC-1"], }, version: "0.6.55-0ubuntu12~20.04.4", name: "accountsservice", summary: "query and manipulate user account information", }, { computers: { available: [209, 211, 210], held: [], upgrades: [], installed: ["PC-3"], }, version: "0.6.45-1ubuntu1.3", name: "accountsservice", summary: "query and manipulate user account information", }, ];

const output = Object.entries(
  input.reduce((prev, { name, version, computers }) => {
    // check for the same name
    if (prev[name]) {
      prev[name].version.push(version);
      // check for the same version of computers in under same name
      if (prev[name].computers[version]) {
        prev[name].computers[version].push(computers);
      } else {
        prev[name].computers[version] = [computers];
      }
    } else {
      // name is identified for the first time
      // create a new entry for that
      prev[name] = {
        version: [version],
        computers: { [version]: [computers] },
      };
    }
    return prev;
  }, {})
).map(([key, { version, computers }]) => ({
  name: key,
  versions: version,
  computers,
}));

console.log(output);```


问:
Python iterating through data and returning deltas
Python newbie here with a challenge I'm working to solve...

My goal is to iterate through a data frame and return what changed line by line. Here's what I have so far:

pseudo code (may not be correct method)
step 1: set row 0 to an initial value
step 2: compare row 1 to row 0, add changes to a list and record row number
step 3: set current row to new initial
step 4: compare row 2 to row 1, add changes to a list and record row number
step 5: iterate through all rows
step 6: return a table with changes and row index where change occurred

```<code>d = {
'col1' : [1, 1, 2, 2, 3],
'col2' : [1, 2, 2, 2, 2],
'col3' : [1, 1, 2, 2, 2]
}

df = pd.DataFrame(data=d)

def delta():
    changes = []
    initial = df.loc[0]
    for row in df:
         if row[i] != initial:
              changes.append[i]
delta()
</code>```

changes I expect to see:
index 1: col2 changed from 1 to 2, 2 should be added to changes list
index 2: col 1 and col3 changed from 1 to 2, both 2s should be added to changes list
index 4: col 1 changed from 2 to 3, 3 should be added to changes list

答:
You can check where each of the columns have changed using the shift method and then use a mask to only get the ones that have changed

```<code>df.loc[:, 'col1_changed'] = df['col1'].mask(df['col1'].eq(df['col1'].shift()))
df.loc[:, 'col2_changed'] = df['col2'].mask(df['col2'].eq(df['col2'].shift()))
df.loc[:, 'col3_changed'] = df['col3'].mask(df['col3'].eq(df['col3'].shift()))
</code>```

Once you have identified the changes, you can agg them together

```<code># We don't consider the first row
df.loc[0, ['col1_changed', 'col2_changed', 'col3_changed']] = [np.nan] * 3
df[['col1_changed', 'col2_changed', 'col3_changed']].astype('str').agg(','.join, axis=1).str.replace('nan', 'no change')
#0    no change,no change,no change
#1          no change,2.0,no change
#2                2.0,no change,2.0
#3    no change,no change,no change
#4          3.0,no change,no change
</code>```

Body:
Python newbie here with a challenge I'm working to solve...

My goal is to iterate through a data frame and return what changed line by line. Here's what I have so far:

pseudo code (may not be correct method)
step 1: set row 0 to an initial value
step 2: compare row 1 to row 0, add changes to a list and record row number
step 3: set current row to new initial
step 4: compare row 2 to row 1, add changes to a list and record row number
step 5: iterate through all rows
step 6: return a table with changes and row index where change occurred

d = {
'col1' : [1, 1, 2, 2, 3],
'col2' : [1, 2, 2, 2, 2],
'col3' : [1, 1, 2, 2, 2]
}

df = pd.DataFrame(data=d)

def delta():
    changes = []
    initial = df.loc[0]
    for row in df:
         if row[i] != initial:
              changes.append[i]
delta()

changes I expect to see:
index 1: col2 changed from 1 to 2, 2 should be added to changes list
index 2: col 1 and col3 changed from 1 to 2, both 2s should be added to changes list
index 4: col 1 changed from 2 to 3, 3 should be added to changes list

Body:
You can check where each of the columns have changed using the shift method and then use a mask to only get the ones that have changed

df.loc[:, 'col1_changed'] = df['col1'].mask(df['col1'].eq(df['col1'].shift()))
df.loc[:, 'col2_changed'] = df['col2'].mask(df['col2'].eq(df['col2'].shift()))
df.loc[:, 'col3_changed'] = df['col3'].mask(df['col3'].eq(df['col3'].shift()))

Once you have identified the changes, you can agg them together

# We don't consider the first row
df.loc[0, ['col1_changed', 'col2_changed', 'col3_changed']] = [np.nan] * 3
df[['col1_changed', 'col2_changed', 'col3_changed']].astype('str').agg(','.join, axis=1).str.replace('nan', 'no change')
#0    no change,no change,no change
#1          no change,2.0,no change
#2                2.0,no change,2.0
#3    no change,no change,no change
#4          3.0,no change,no change


问:
How to emulate Windows CE 5.0 on ARMV4i architecture
I am developing Qt application for Windows CE 5.0 device.

My setup is:
Qt 4.7.3 compiled with Visual Studio 2005 using Windows CE 5.0 Standard SDK.

Everything works OK on real device, though I would like to test software "locally" in an emulator.

Visual Studio 2005 provides Pocket PC 2003, Windows Mobile 6 emulator images but no Windows CE 5.0.

Windows Microsoft CE 5.0 Emulator does that, but its sample device is based on i486, so this doesn't work for me...

I found some kind "Plaftorm Builder" and "ARMV4i BSP for Windows CE 5.0", but I am not building device or it's SDK, and I am not interested in specific device at all. All i need is "generic" AMRv4 WinCE 5 image for basic testing...

So what is possible outcomes for me?

答:
Microssoft stopped providing Windows CE OS images for the emulator after the x86 emulator was abandoned, and for good reason.  Windows CE is a modular OS so it's not possible to create an Emulator OS image that matches what all devices are and my guess is that there were too many support calls and complaints about how the emulator either contained something unwanted or didn't contain something that was wanted.  The point being that there is no "generic Windows CE device" so there's no way to create an emulator of one.

The response from Microsoft was to provide the ARM-based Device Emulator 3.0 (available as a Standalone Release) and a BSP for the emulator so developers can create their own OS images that match their actual target hardware OSes.

So your options are to either create an OS yourself or find an OEM that provides an emulator image for their device (I'm not aware of one offhand, but I very, very rarely use the emulators so I've never bothered to look).


问:
How can I filter specific emails from an array?
I'm trying to get from an array of multiple emails string this effect
if there is more than one email that ends with the same domain name of the email do not show me that filter for example:

const db = ['example@example.com', 'example2@example.com'];

const check = ['example3@example.com', 'another@anotherdomain.com'];

function findNotSimilar(check, db) {

```<code>const arr = check.filter((item) => db.indexOf(item) === -1);
return arr;
</code>```

}

this returns ['example3@example.com', 'another@anotherdomain.com'], but I would like to return just  ['another@anotherdomain.com'] array because the email ending with the same domain name

答:
Working Demo :

const db = ['example@example.com', 'example2@example.com'];
const check = ['example3@example.com', 'another@anotherdomain.com'];

// Split the array elements with domain name and creating a new array.
const formatDb = db.map((item) => item.split('@')[1]);

// Filtered out the element with different domain name.
const arr = check.filter((item) => formatDb.indexOf(item.split('@')[1]) === -1);

console.log(arr);```

Body:
I'm trying to get from an array of multiple emails string this effect
if there is more than one email that ends with the same domain name of the email do not show me that filter for example:

const db = ['example@example.com', 'example2@example.com'];

const check = ['example3@example.com', 'another@anotherdomain.com'];

function findNotSimilar(check, db) {

const arr = check.filter((item) => db.indexOf(item) === -1);
return arr;

}

this returns ['example3@example.com', 'another@anotherdomain.com'], but I would like to return just  ['another@anotherdomain.com'] array because the email ending with the same domain name


问:
Android studio Gradle Tab
I've started to work on an android project that has many Gradle tasks. After cloning the project from git, there is no Gradle tab in Android Studio!</p>

答:
I ran into this too. All the other answers assume you have Gradle installed and it's just a matter of finding it. This is what worked for me.

Open the build.gradle file in android/app/src/

There should be a small bar at the top of the code-editor. Click Open for Editing in Android Studio

That then will download and install Gradle into Android Studio, so you'll see the Gradle tab on the right.

Title: Android studio Gradle Tab


问:
Docker run bash node: command not found
I've the following Dockerfile

```<code>FROM ubuntu:latest

WORKDIR /

# Without interactive dialogue
ARG DEBIAN_FRONTEND=noninteractive

# Install required packages
RUN apt-get update
RUN apt-get install -y wget gnupg2 software-properties-common git apt-utils vim dirmngr apt-transport-https ca-certificates zip

ENV NODE_VERSION=14

RUN wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash \
    && . .$HOME/.nvm/nvm.sh \
    && nvm install $NODE_VERSION \
    && nvm alias default $NODE_VERSION \
    && nvm use default

# Install Wine from WineHQ Repository
RUN dpkg --add-architecture i386
RUN wget -qO- https://dl.winehq.org/wine-builds/Release.key | apt-key add -
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv F987672F
RUN apt-add-repository 'deb https://dl.winehq.org/wine-builds/ubuntu/ bionic main'
RUN apt-get update
RUN apt-get install -y --install-recommends winehq-stable

# Installing mono
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
RUN sh -c 'echo "deb https://download.mono-project.com/repo/ubuntu stable-bionic main" > /etc/apt/sources.list.d/mono-official-stable.list'
RUN apt-get update
RUN apt-get install -y mono-complete

RUN PROJECT_DIR=/root/project

WORKDIR /project
</code>```

Which allows me to build electron Apps in no matter what platform I'm on. Everything works well. Image building and also running it as a container works with no issues.

I then can go ahead and manually do the following:

#build the dockerfile
docker build -t debian-wine-electron-builder:0.1 .

#run the docker image as detached container
docker run -dt --name electron-build -v ${PWD}:/project debian-wine-electron-builder:0.1

#open a bash session in the container
docker exec -it electron-build bash

#and in there execute my commands which will build me the electron application
npm install ... #and so on
```
<p>I now want to created a bash file to run all the commands making it easier to use. So one just has to run the bash file and it executes all the commands one by one.
When I want to use the <code>docker run</code> command followed by a `bash -c "command1 ; command2" <strong>I run into the following issue</strong>:</p>
<pre class="lang-sh prettyprint-override"><code>#building the image
docker build -t debian-wine-electron-builder:0.1 .

#docker run following commands
docker run --name electron-build -v ${PWD}:/project debian-wine-electron-builder:0.1 bash -c "npm install... ; command2 ..."
</code>```

Gives me this error when trying to npm install:

bash: npm: command not found
```

答:
When you run bash interactively, your .bashrc file will be run. When you run the command directly on the docker run command, bash is run non-interactively and .bashrc isn't run.

NVM uses .bashrc to set things up, so it needs to run.

You can force bash into interactive mode with the -i option. Then it'll work, but you'll get some warnings because it tries to do some terminal stuff that fails.

```<code>docker run --name electron-build -v ${PWD}:/project debian-wine-electron-builder:0.1 bash -i -c "npm install... ; command2 ..."
</code>```

If you don't use nvm to switch node versions on the fly, it might be better to install the node version you want without using nvm.

Title: Docker run bash node: command not found

Body:
I've the following Dockerfile

FROM ubuntu:latest

WORKDIR /

# Without interactive dialogue
ARG DEBIAN_FRONTEND=noninteractive

# Install required packages
RUN apt-get update
RUN apt-get install -y wget gnupg2 software-properties-common git apt-utils vim dirmngr apt-transport-https ca-certificates zip

ENV NODE_VERSION=14

RUN wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash \
    && . .$HOME/.nvm/nvm.sh \
    && nvm install $NODE_VERSION \
    && nvm alias default $NODE_VERSION \
    && nvm use default

# Install Wine from WineHQ Repository
RUN dpkg --add-architecture i386
RUN wget -qO- https://dl.winehq.org/wine-builds/Release.key | apt-key add -
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv F987672F
RUN apt-add-repository 'deb https://dl.winehq.org/wine-builds/ubuntu/ bionic main'
RUN apt-get update
RUN apt-get install -y --install-recommends winehq-stable

# Installing mono
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
RUN sh -c 'echo "deb https://download.mono-project.com/repo/ubuntu stable-bionic main" > /etc/apt/sources.list.d/mono-official-stable.list'
RUN apt-get update
RUN apt-get install -y mono-complete

RUN PROJECT_DIR=/root/project

WORKDIR /project

Which allows me to build electron Apps in no matter what platform I'm on. Everything works well. Image building and also running it as a container works with no issues.

I then can go ahead and manually do the following:

#build the dockerfile
docker build -t debian-wine-electron-builder:0.1 .

#run the docker image as detached container
docker run -dt --name electron-build -v ${PWD}:/project debian-wine-electron-builder:0.1

#open a bash session in the container
docker exec -it electron-build bash

#and in there execute my commands which will build me the electron application
npm install ... #and so on

I now want to created a bash file to run all the commands making it easier to use. So one just has to run the bash file and it executes all the commands one by one.
When I want to use the docker run command followed by a `bash -c "command1 ; command2" I run into the following issue:

#building the image
docker build -t debian-wine-electron-builder:0.1 .

#docker run following commands
docker run --name electron-build -v ${PWD}:/project debian-wine-electron-builder:0.1 bash -c "npm install... ; command2 ..."

Gives me this error when trying to npm install:

bash: npm: command not found

Body:
When you run bash interactively, your .bashrc file will be run. When you run the command directly on the docker run command, bash is run non-interactively and .bashrc isn't run.

NVM uses .bashrc to set things up, so it needs to run.

You can force bash into interactive mode with the -i option. Then it'll work, but you'll get some warnings because it tries to do some terminal stuff that fails.

docker run --name electron-build -v ${PWD}:/project debian-wine-electron-builder:0.1 bash -i -c "npm install... ; command2 ..."

If you don't use nvm to switch node versions on the fly, it might be better to install the node version you want without using nvm.


问:
How to remove a file from GIT if it doen't exist any more
I was trying to use git and git-hub for my first time;

and there was a file that I wanted to change it's name so I just changed it and committed then when I pushed it but it says :

[rejected]        main -> main (fetch first) error: failed to push some refs to 'https://github.com/MyUserName/MyProjectName.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.

so I just added -f to force but it made another directory holding the old name of the file so I delete it but every time I do push command it just makes the same thing

how can I get rid of this old file once and for ever
thanks.

答:
You need to pull the latest version of the GitHub repository before pushing local changes.

```<code>git pull
</code>```

After this make the changes you wish to make on the local repository (Changing the file name in this case)

Then :-

```<code>git commit -am "Message"
git push
</code>```

Body:
You need to pull the latest version of the GitHub repository before pushing local changes.

git pull

After this make the changes you wish to make on the local repository (Changing the file name in this case)

Then :-

git commit -am "Message"
git push


问:
Tool for exporting html as pdf
I have a html document which marks up a report. I have a button on this page "Export as pdf". However I am not sure how to export html into a pdf..Are there any tools out there that anyone recommends for such a task..

EDIT: In more detail:

I have the following php:

```<code><?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src = "jQuery.js"></script>
   <script>
   $(document).ready(function(){

   });
  </script>
  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
  </head>
  <body>
  <h1>Entry Report - <?php echo($date); ?></h1>
  <div id = "buttons">
  <a href = "http://dev.speechlink.co.uk">Export as PDF</a>
  </div>
  <h3>Biological Information</h3>
  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("<br/>");
      echo($value['question']." <br/> "."<img src = \"$image\"/>");
      echo("<br/>");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("<br/>");
    $i++;
      }
  ?>
  <h3>Fatigue and Recovery</h3>
  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Illness and Injury</h3>
  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Training Sessions</h3>
  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>General Feedback</h3>
  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       echo("User didn't leave any feedback");
     }
     echo("<br/>");
  ?>
  </body>
</html>
<?php
}
?>
</code>```

This displays the following:

So if I'm using fpdf, what is the best way to export the following as a pdf? Should I write a fpdf function in the same php file or is it best to write a separate php file which creates and displays the pdf (which means I would have to post all relevant data to this file)...

答:
Use FPDF library for php
check here

The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.

```<code><?php
require('fpdf.php');

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
</code>```

To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:

```<code>$pdf=new FPDF('P','mm','A4');
</code>```

It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).

Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().

To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:

```<code>$pdf->SetFont('Arial','B',16);
</code>```

We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:

```<code>$pdf->Cell(40,10,'Hello World !',1);
</code>```

Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.

Title: Tool for exporting html as pdf

Body:
I have a html document which marks up a report. I have a button on this page "Export as pdf". However I am not sure how to export html into a pdf..Are there any tools out there that anyone recommends for such a task..

EDIT: In more detail:

I have the following php:

<?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>

   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>

Entry Report - <?php echo($date); ?>

  Export as PDF

Biological Information

  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("
");
      echo($value['question']."
 "."");
      echo("
");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("
");
    $i++;
      }
  ?>

Fatigue and Recovery

  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Illness and Injury

  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Training Sessions

  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

General Feedback

  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       echo("User didn't leave any feedback");
     }
     echo("
");
  ?>

<?php
}
?>

This displays the following:

So if I'm using fpdf, what is the best way to export the following as a pdf? Should I write a fpdf function in the same php file or is it best to write a separate php file which creates and displays the pdf (which means I would have to post all relevant data to this file)...

Body:
Use FPDF library for php
check here

The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.

<?php
require('fpdf.php');

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:

$pdf=new FPDF('P','mm','A4');

It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).

Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().

To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:

$pdf->SetFont('Arial','B',16);

We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:

$pdf->Cell(40,10,'Hello World !',1);

Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.


问:
ionic cap add android npm ERR
After running ionic cap add android from https://ionicframework.com/docs/angular/your-first-app/deploying-mobile had npm ERR!

```<code> Found: @capacitor/core@3.3.4
npm ERR! node_modules/@capacitor/core
npm ERR!   @capacitor/core@"3.3.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @capacitor/core@"^3.4.0" from @capacitor/android@3.4.1
npm ERR! node_modules/@capacitor/android
npm ERR!   @capacitor/android@"3.4.1" from the root project

</code>```

答:
Problem figure out with next solution
manually change verions in package.json.

Change version "@capacitor/core": "VERSION",
VERSION should be the same as @capacitor/android VERSION

In my case set up "@capacitor/core": "3.4.1", because  @capacitor/android@"3.4.1"

Title: ionic cap add android npm ERR

Body:
After running ionic cap add android from https://ionicframework.com/docs/angular/your-first-app/deploying-mobile had npm ERR!

 Found: @capacitor/core@3.3.4
npm ERR! node_modules/@capacitor/core
npm ERR!   @capacitor/core@"3.3.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @capacitor/core@"^3.4.0" from @capacitor/android@3.4.1
npm ERR! node_modules/@capacitor/android
npm ERR!   @capacitor/android@"3.4.1" from the root project