问:
Check what Program creates a file
Is there any way to see what program creates or deletes a file in Python? I know that you can write a program that prints out when a File was created/deleted/modified using watchdog but I want to know what program creates/deletes/modifies this file. Is this possible in Python?</p>

答:
This is a great question and can done using the os module. The os module is used for many things, one of those being directory management and is perfect for what you are asking. The code in the following examples is mine and is referenced from the official documentation as mentioned previously.

Creating a file

One must take precautions when creating a file to ensure you do not corrupt or delete already existing files. Please read the following code carefully.

"""
First open the file with os.open(). This is used when ever you want to create or modify a
file and is the bread and butter of the following operations.
"""
with open("Desired_file.txt", 'w') as file:
    # Actions
    file.close()
```

<p>Now at this point you may be asking: what is 'w'? This is the flag that we are opening the file with. w is the flag that is used in two primary scenarios:<br>
 1. When you want to <strong>create</strong> a file that does not already exist.<br>
2. When you want to <strong>overwrite</strong> a file. </p>

<p>You may also be asking, <strong><em>What is file.close()?</em></strong> the close function is essentially like hitting ctrl+s on your keyboard. <strong>It is saving the file to make sure that any changes that we have saved are recorded.</strong> </p>

<h1>Adding text to a file</h1>

<p>Like in the first example, adding text to a file is a simple matter of changing the flag variable from <code>w</code> to <code>a</code>. An example of this can be found below. </p>

<pre class="lang-py prettyprint-override"><code>with open("file.txt", "a") as file:
    file.append("Note: Add fish to shopping list.")
    file.close()
</code>```

Note that file.close is used because we want to save our changes.

Reading a file

This is again, simply a matter of changing the flag to "a". See practical usage in the following example.

with open("Desired_file.txt", "r") as file:
    # Get the file data with file.read()
    file_data = file.read()
    file.close()
```

<p>It is important to note that this is not a good way to read files because if you have lines in your file it will print <code>'\n'</code> as a variable because it prints information in list format. To avoid this I like to use the .split() function after the .read() function. Another practical-usage example can be seen below.</p>

<pre class="lang-py prettyprint-override"><code>with open("Desired_file.txt", "r") as file:
    file_data = file.read().split()

    file.close()
</code>```

Now the final step is to read each line in the file. See below.

with open("Desired_file.txt", "r") as file:
    file_data = file.read().split()

    for line in file_data:
        print(line)

    # Note that at this point the file has finished reading the file. Now all that we have to do is save the file
    file.close()

```

I really hoped this helped. If you have any questions I would be more than happy to assist. I apologise that I don't have the best way of explaining things and this could be way more simplified but I hope it's readable enough.

Title: Check what Program creates a file

Body:
This is a great question and can done using the os module. The os module is used for many things, one of those being directory management and is perfect for what you are asking. The code in the following examples is mine and is referenced from the official documentation as mentioned previously.

Creating a file

One must take precautions when creating a file to ensure you do not corrupt or delete already existing files. Please read the following code carefully.

"""
First open the file with os.open(). This is used when ever you want to create or modify a
file and is the bread and butter of the following operations.
"""
with open("Desired_file.txt", 'w') as file:
    # Actions
    file.close()

Now at this point you may be asking: what is 'w'? This is the flag that we are opening the file with. w is the flag that is used in two primary scenarios:

 1. When you want to create a file that does not already exist.

2. When you want to overwrite a file.

You may also be asking, What is file.close()? the close function is essentially like hitting ctrl+s on your keyboard. It is saving the file to make sure that any changes that we have saved are recorded.

Adding text to a file

Like in the first example, adding text to a file is a simple matter of changing the flag variable from w to a. An example of this can be found below.

with open("file.txt", "a") as file:
    file.append("Note: Add fish to shopping list.")
    file.close()

Note that file.close is used because we want to save our changes.

Reading a file

This is again, simply a matter of changing the flag to "a". See practical usage in the following example.

with open("Desired_file.txt", "r") as file:
    # Get the file data with file.read()
    file_data = file.read()
    file.close()

It is important to note that this is not a good way to read files because if you have lines in your file it will print '\n' as a variable because it prints information in list format. To avoid this I like to use the .split() function after the .read() function. Another practical-usage example can be seen below.

with open("Desired_file.txt", "r") as file:
    file_data = file.read().split()

    file.close()

Now the final step is to read each line in the file. See below.

with open("Desired_file.txt", "r") as file:
    file_data = file.read().split()

    for line in file_data:
        print(line)

    # Note that at this point the file has finished reading the file. Now all that we have to do is save the file
    file.close()

I really hoped this helped. If you have any questions I would be more than happy to assist. I apologise that I don't have the best way of explaining things and this could be way more simplified but I hope it's readable enough.


来源: stackexchange

问:
Show full line of a CSV file C++
I am making a program that reads a .CSV file and loads it into binary search trees to sort its content, since I managed to load the .CSV and implement the tree however the content of the file is:

1, Peter, 230151515

5, Merrick, 25551561

7, Lucky, 4301616199

2, luis, 2589191919

16, Alfredo, 25891919

8, Linda, 129616919

I am using the first data of each row as a key and with the code that I carry, it orders it correctly, however I want it to show the rest of the row, not just the key, someone could tell me how I could do that, to show all the data of each key ordered.

output:

1

2

5

7

8

16

What I want to print would be something like:

1 Peter 230151515

2 Luis 2589191919

5 Merrick 25551561

7 Lucky 4301616199

8 Linda 129616919

16 Alfredo 25891919

Someone to help me correct my mistake please.

```<code>#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

struct node {
    int key;
    string name;
    int num;
    struct node *left, *right;
};

vector<node> persons;

struct node *newNode(int item)
{
    struct node *temp =  (struct node *)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}

void inorder(struct node *root)
{
    if (root != NULL)
    {
        //cout<<"\t";

        inorder(root->left);
        printf("\t%d\n", root->key);
        inorder(root->right);
    }
}

struct node* insert(struct node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL) return newNode(key);

    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);

    /* return the (unchanged) node pointer */
    return node;
}

struct node * minValueNode(struct node* node)
{
    struct node* current = node;

    /* loop down to find the leftmost leaf */
    while (current && current->left != NULL)
        current = current->left;

    return current;
}

int main()
{
    struct node *root = NULL;
    ifstream fin("data.txt");
    if (!fin)
    {
        cout << "File not open\n";
        return 1;
    }

    string line;
    const char delim = ',';

    while (getline(fin, line))
    {
        istringstream ss(line);
        node person;
        ss >> person.key; ss.ignore(10, delim);
        getline(ss, person.name,delim);
        ss >> person.num;
        if (ss)
            persons.push_back(person);
    }

   for (unsigned int i=0; i< persons.size(); i++)
   {
         cout << setw(5)  << persons[i].key<< setw(20) << persons[i].name<< setw(15)  << persons[i].num << '\n';

             root = insert(root, persons[i].key);
            insert(root, persons[i].key);

   }

    cout << "\n\nInorder:\n";
//    cout<<node.name;

    inorder(root);

    /*/cout<<"\nDelete 50\n";
    root = deleteNode(root, 50);
    cout<<"Inorder traversal of the modified tree \n";
    inorder(root);/*/

    /*
    insert(root, 80);*/

    return 0;
}
</code>```

答:
There were some main problems and some other problems. The main problems were that you didn't store and print all data. I did the following:

Clean up includes

Remove using namespace std;

Rename struct node to Node

Add a struct for Person next to the struct for Node

Add a constructor for Person to Node

Make insert a method

Use smart pointers. One problem of dynamic memory allocation is that you have to clean up but you didn't

```<code>#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>

struct Person {
  int key;
  std::string name;
  int num;
};

struct Node : Person {
  Node(const Person &person) : Person(person) {}
  std::unique_ptr<Node> left, right;
  void insert(const Person &person);
};

void Node::insert(const Person &person) {
  /* recur down the tree */
  if (key > person.key) {
    if (left)
        left->insert(person);
    else
        left = std::make_unique<Node>(person);
  } else if (key < person.key) {
    if (right)
        right->insert(person);
    else
        right = std::make_unique<Node>(person);
  }
}

std::vector<Person> persons;

void inorder(Node *root) {
  if (root) {
    // cout<<"\t";

    inorder(root->left.get());
    std::cout << '\t' << root->key << ' ' << root->name << ' ' << root->num << '\n';
    inorder(root->right.get());
  }
}

Node *minValueNode(Node *node) {
  Node *current = node;

  /* loop down to find the leftmost leaf */
  while (current && current->left) current = current->left.get();

  return current;
}

int main() {
  std::unique_ptr<Node> root;
  std::ifstream fin("data.txt");
  if (!fin) {
    std::cout << "File not open\n";
    return 1;
  }

  std::string line;
  const char delim = ',';

  while (std::getline(fin, line)) {
    std::istringstream ss(line);
    Person person;
    ss >> person.key;
    ss.ignore(10, delim);
    std::getline(ss, person.name, delim);
    ss >> person.num;
    if (ss) persons.push_back(person);
  }

  for (unsigned int i = 0; i < persons.size(); i++) {
    std::cout << std::setw(5) << persons[i].key << std::setw(20)
              << persons[i].name << std::setw(15) << persons[i].num << '\n';
    if (!root) root = std::make_unique<Node>(persons[i]);
    else root->insert(persons[i]);
  }

  std::cout << "\n\nInorder:\n";
  //    cout<<node.name;

  inorder(root.get());

  /*/cout<<"\nDelete 50\n";
  root = deleteNode(root, 50);
  cout<<"Inorder traversal of the modified tree \n";
  inorder(root);/*/

  /*
  insert(root, 80);*/

  return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Show full line of a CSV file C++

Body:
I am making a program that reads a .CSV file and loads it into binary search trees to sort its content, since I managed to load the .CSV and implement the tree however the content of the file is:

1, Peter, 230151515

5, Merrick, 25551561

7, Lucky, 4301616199

2, luis, 2589191919

16, Alfredo, 25891919

8, Linda, 129616919

I am using the first data of each row as a key and with the code that I carry, it orders it correctly, however I want it to show the rest of the row, not just the key, someone could tell me how I could do that, to show all the data of each key ordered.

output:

1

2

5

7

8

16

What I want to print would be something like:

1 Peter 230151515

2 Luis 2589191919

5 Merrick 25551561

7 Lucky 4301616199

8 Linda 129616919

16 Alfredo 25891919

Someone to help me correct my mistake please.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

struct node {
    int key;
    string name;
    int num;
    struct node *left, *right;
};

vector<node> persons;

struct node *newNode(int item)
{
    struct node *temp =  (struct node *)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}

void inorder(struct node *root)
{
    if (root != NULL)
    {
        //cout<<"\t";

        inorder(root->left);
        printf("\t%d\n", root->key);
        inorder(root->right);
    }
}

struct node* insert(struct node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL) return newNode(key);

    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);

    /* return the (unchanged) node pointer */
    return node;
}

struct node * minValueNode(struct node* node)
{
    struct node* current = node;

    /* loop down to find the leftmost leaf */
    while (current && current->left != NULL)
        current = current->left;

    return current;
}

int main()
{
    struct node *root = NULL;
    ifstream fin("data.txt");
    if (!fin)
    {
        cout << "File not open\n";
        return 1;
    }

    string line;
    const char delim = ',';

    while (getline(fin, line))
    {
        istringstream ss(line);
        node person;
        ss >> person.key; ss.ignore(10, delim);
        getline(ss, person.name,delim);
        ss >> person.num;
        if (ss)
            persons.push_back(person);
    }

   for (unsigned int i=0; i< persons.size(); i++)
   {
         cout << setw(5)  << persons[i].key<< setw(20) << persons[i].name<< setw(15)  << persons[i].num << '\n';

             root = insert(root, persons[i].key);
            insert(root, persons[i].key);

   }

    cout << "\n\nInorder:\n";
//    cout<<node.name;

    inorder(root);

    /*/cout<<"\nDelete 50\n";
    root = deleteNode(root, 50);
    cout<<"Inorder traversal of the modified tree \n";
    inorder(root);/*/

    /*
    insert(root, 80);*/

    return 0;
}

Body:
There were some main problems and some other problems. The main problems were that you didn't store and print all data. I did the following:

Clean up includes

Remove using namespace std;

Rename struct node to Node

Add a struct for Person next to the struct for Node

Add a constructor for Person to Node

Make insert a method

Use smart pointers. One problem of dynamic memory allocation is that you have to clean up but you didn't

#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>

struct Person {
  int key;
  std::string name;
  int num;
};

struct Node : Person {
  Node(const Person &person) : Person(person) {}
  std::unique_ptr<Node> left, right;
  void insert(const Person &person);
};

void Node::insert(const Person &person) {
  /* recur down the tree */
  if (key > person.key) {
    if (left)
        left->insert(person);
    else
        left = std::make_unique<Node>(person);
  } else if (key < person.key) {
    if (right)
        right->insert(person);
    else
        right = std::make_unique<Node>(person);
  }
}

std::vector<Person> persons;

void inorder(Node *root) {
  if (root) {
    // cout<<"\t";

    inorder(root->left.get());
    std::cout << '\t' << root->key << ' ' << root->name << ' ' << root->num << '\n';
    inorder(root->right.get());
  }
}

Node *minValueNode(Node *node) {
  Node *current = node;

  /* loop down to find the leftmost leaf */
  while (current && current->left) current = current->left.get();

  return current;
}

int main() {
  std::unique_ptr<Node> root;
  std::ifstream fin("data.txt");
  if (!fin) {
    std::cout << "File not open\n";
    return 1;
  }

  std::string line;
  const char delim = ',';

  while (std::getline(fin, line)) {
    std::istringstream ss(line);
    Person person;
    ss >> person.key;
    ss.ignore(10, delim);
    std::getline(ss, person.name, delim);
    ss >> person.num;
    if (ss) persons.push_back(person);
  }

  for (unsigned int i = 0; i < persons.size(); i++) {
    std::cout << std::setw(5) << persons[i].key << std::setw(20)
              << persons[i].name << std::setw(15) << persons[i].num << '\n';
    if (!root) root = std::make_unique<Node>(persons[i]);
    else root->insert(persons[i]);
  }

  std::cout << "\n\nInorder:\n";
  //    cout<<node.name;

  inorder(root.get());

  /*/cout<<"\nDelete 50\n";
  root = deleteNode(root, 50);
  cout<<"Inorder traversal of the modified tree \n";
  inorder(root);/*/

  /*
  insert(root, 80);*/

  return 0;
}


问:
ASP.NET Web Service Application in .net 4
I was going through the MSDN walkthrough on using client application services.
http://msdn.microsoft.com/en-us/library/bb546195.aspx

This is for .net 3.5..but i need to do it in .net 4. The thing is that it doesn't have any ASP.NET Web Service Applications listed. Has it introduced any replacement for that? Or is there any workaround?

Regards.

答:
One of the way is to select target platform as .NET 3.5 in the drop-down at the top of New Project dialog - this will allow you to select "ASP.NET Web Service Application" project template. Once you select the template, you may change the target platform to .NET 4 using project properties.

I believe that the main reason for this template not being available in .NET 4 view is that this project uses ASP.NET web services (asmx files). Microsoft has declared this to be an obsolete technology and recommends to use WCF services instead.

You can expose ASP.NET application services (authentication, role etc used the sample sited by you) as WCF services. See section titled "Using application services as WCF services" in this link. So I will recommend you to choose ASP.NET Web Application project and then expose ASP.NET services as WCF services.

ContentLicense: CC BY-SA 3.0


问:
Django on Google app engine cannot serve media files
I deployed a Django web app on Google app engine flex env, and I could upload files to this app, but the MEDIA_URL and MEDIA_ROOT are not set to Google cloud storage for now, so uploaded files should be stored on local disk.

The problem is, when I open the app website, some uploaded images cannot load successfully, with error saying

```<code>GET https://app-name.ew.r.appspot.com/media/images/icon_TPUrf8a.jpg 404
</code>```

and strangely, even the same image could some time load and then sometime cannot load, very random.

Could anyone please tell why it sometimes ok and sometime not, and what's the best way to fix it?

答:
You have to tell the app where to look for your static files.  This is best done in app.yaml:

```<code>handlers:
- url: /static
  static_dir: static/

- url: .*
  script: auto
</code>```

Body:
I deployed a Django web app on Google app engine flex env, and I could upload files to this app, but the MEDIA_URL and MEDIA_ROOT are not set to Google cloud storage for now, so uploaded files should be stored on local disk.

The problem is, when I open the app website, some uploaded images cannot load successfully, with error saying

GET https://app-name.ew.r.appspot.com/media/images/icon_TPUrf8a.jpg 404

and strangely, even the same image could some time load and then sometime cannot load, very random.

Could anyone please tell why it sometimes ok and sometime not, and what's the best way to fix it?

Body:
You have to tell the app where to look for your static files.  This is best done in app.yaml:

handlers:
- url: /static
  static_dir: static/

- url: .*
  script: auto


问:
C/C++: Easily unzip to memory
I need to find a library that allows me to easily get a directory listing of all the files inside a ZIP archive and allows me to extract any given file inside the archive to memory (a buffer). Preferably, it should be a high-level library since my requirements aren't very complex (what I mentioned above is pretty much all I need).

Previously I tried PhysFS which has the behavior I need (easily access files inside an archive), but it's unsuitable because of other reasons (there are many archives and PhysFS would require me to mount all of them individually, which is not an option). Another library that kinda has the functionality I need is Chilkat, but it's shareware so I can't use it either.

Any other suggestions?

答: How about zlib?  http://zlib.net/  "A Massively Spiffy Yet Delicately Unobtrusive Compression Library (Also Free, Not to Mention Unencumbered by Patents)"</p>

Title: C/C++: Easily unzip to memory


问:
Change image alpha from listview position and save
I'm making a music listview. I have a base adapter and music class music class have 3 property; name:String
point:String
image:Int
how can i change image alpha which item selected?

```<code>        listMusics.setOnItemClickListener { parent, view, position, id ->
        val preference = getSharedPreferences("PREFS",0)
        val editor = preference.edit()
        best1 = preference.getInt("best1", 0)
        if(best1>=position*100) {
            music = position
            view.imgMusic.alpha=1F
            editor.putInt("music", music)
            editor.apply()
        }

    }
</code>```

i'm changing image alpha with   view.imgMusic.alpha=1F it's change alpha to image but i can't save item alpha. i want to change alpha to 1F which item selected and save also change the other items to 0.5F how can i do this ?

答:
I think if you use ImageView to show image than you can use this property:

```<code><ImageView
    android:layout_width="30dp"
    android:layout_height="35dp"
    android:id="@+id/imageView"
    android:alpha="0.4" // <-----------------  this
    android:background="@drawable/imagename"
/>
</code>```

I hope this helps you

Body:
I'm making a music listview. I have a base adapter and music class music class have 3 property; name:String
point:String
image:Int
how can i change image alpha which item selected?

        listMusics.setOnItemClickListener { parent, view, position, id ->
        val preference = getSharedPreferences("PREFS",0)
        val editor = preference.edit()
        best1 = preference.getInt("best1", 0)
        if(best1>=position*100) {
            music = position
            view.imgMusic.alpha=1F
            editor.putInt("music", music)
            editor.apply()
        }

    }

i'm changing image alpha with   view.imgMusic.alpha=1F it's change alpha to image but i can't save item alpha. i want to change alpha to 1F which item selected and save also change the other items to 0.5F how can i do this ?

Body:
I think if you use ImageView to show image than you can use this property:

<ImageView
    android:layout_width="30dp"
    android:layout_height="35dp"
    android:id="@+id/imageView"
    android:alpha="0.4" // <-----------------  this
    android:background="@drawable/imagename"
/>

I hope this helps you


问:
How would I go about finding a specific link in a website with python3
I'm trying to build a python program that scrapes this website: (https://fitgirl-repacks.site/dungeon-defenders-awakened/), and then return just the 1337x download link: (https://1337x.to/torrent/4474599/Dungeon-Defenders-Awakened-v1-0-0-17001-MULTi8-FitGirl-Repack/). I succeeded in scraping the website, but how would I go about coding up the program that finds the 1337x download link: (https://1337x.to/torrent/4474599/Dungeon-Defenders-Awakened-v1-0-0-17001-MULTi8-FitGirl-Repack/), and return it in the python console?.</p>

答:
Using BeautifulSoup you can extract the url:    </p>

```<code>from requests import get
from bs4 import BeautifulSoup

response = get('https://fitgirl-repacks.site/dungeon-defenders-awakened/')
html_text = response.text
html = BeautifulSoup(html_text)

tags = html.find_all("a", string="1337x")
first_tag = tags[0]
print(first_tag['href'])
</code>```

Body:
Using BeautifulSoup you can extract the url:

from requests import get
from bs4 import BeautifulSoup

response = get('https://fitgirl-repacks.site/dungeon-defenders-awakened/')
html_text = response.text
html = BeautifulSoup(html_text)

tags = html.find_all("a", string="1337x")
first_tag = tags[0]
print(first_tag['href'])


问:
Difficulties creating a SSL web service on GKE
I am trying to create an API that serves HTTPS traffic publicly and is reachable by an IP address (not the domain), using a GKE cluster. Docker images have been tested locally. They were capable of serving HTTPS on their own, but as far as I've come to realize, this is not necessary for the setup that I am imagining.

So what I've come up with so far is to have a Kubernetes Service exposing it's 8443 port and having an Ingress load balancer mapping to that port and using self-signed certificates created using this tutorial - basic-ingress-secret referred in the template. The only thing I have skipped is the domain binding given I am not in the possession of a domain. I hoped it would bind the certificate to the external IP, but this is unfortunately not the case (have tried to attach an IP to a CN of the certificate, as some users have noted here).

This is my yaml for service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: some-node
spec:
  selector:
    app: some
  ports:
  - protocol: "TCP"
    port: 8443
    targetPort: 8443
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-node-deploy
spec:
  selector:
    matchLabels:
      app: some
  replicas: 3
  template:
    metadata:
      labels:
        app: some
    spec:
      containers:
      - name: some-container
        image: "gcr.io/some-27417/some:latest"
</code>```

This is my yaml for Ingress:

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.allow-http: "false"
spec:
  tls:
  - secretName: basic-ingress-secret
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: some-node
          servicePort: 8443
</code>```

答:
It is way simpler than these documentations explain.

1.- Create the self-signed certs

```<code>openssl req -newkey rsa:2048 -nodes -keyout tls.key -out tls.csr
openssl x509 -in tls.csr -out tls.crt -req -signkey tls.key
</code>```

2.- Create the secret

```<code>kubectl create secret tls basic-ingress-secret --cert tls.crt --key tls.key
</code>```

3.- Create the Ingress object

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.allow-http: "false"
spec:
  tls:
  - secretName: basic-ingress-secret
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: some-node
          servicePort: 8443
</code>```

Note: To make is work on GKE, your service must be of type NodePort

```<code>$ kubectl describe svc some-node
Name:                     some-node
Namespace:                default
Labels:                   run=nginx
Annotations:              <none>
Selector:                 run=nginx
Type:                     NodePort
IP:                       10.60.6.214
Port:                     <unset>  8443/TCP
TargetPort:               80/TCP
NodePort:                 <unset>  30250/TCP
Endpoints:                10.56.0.17:80
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>
</code>```

Body:
I am trying to create an API that serves HTTPS traffic publicly and is reachable by an IP address (not the domain), using a GKE cluster. Docker images have been tested locally. They were capable of serving HTTPS on their own, but as far as I've come to realize, this is not necessary for the setup that I am imagining.

So what I've come up with so far is to have a Kubernetes Service exposing it's 8443 port and having an Ingress load balancer mapping to that port and using self-signed certificates created using this tutorial - basic-ingress-secret referred in the template. The only thing I have skipped is the domain binding given I am not in the possession of a domain. I hoped it would bind the certificate to the external IP, but this is unfortunately not the case (have tried to attach an IP to a CN of the certificate, as some users have noted here).

This is my yaml for service:

apiVersion: v1
kind: Service
metadata:
  name: some-node
spec:
  selector:
    app: some
  ports:
  - protocol: "TCP"
    port: 8443
    targetPort: 8443
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-node-deploy
spec:
  selector:
    matchLabels:
      app: some
  replicas: 3
  template:
    metadata:
      labels:
        app: some
    spec:
      containers:
      - name: some-container
        image: "gcr.io/some-27417/some:latest"

This is my yaml for Ingress:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.allow-http: "false"
spec:
  tls:
  - secretName: basic-ingress-secret
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: some-node
          servicePort: 8443

Body:
It is way simpler than these documentations explain.

1.- Create the self-signed certs

openssl req -newkey rsa:2048 -nodes -keyout tls.key -out tls.csr
openssl x509 -in tls.csr -out tls.crt -req -signkey tls.key

2.- Create the secret

kubectl create secret tls basic-ingress-secret --cert tls.crt --key tls.key

3.- Create the Ingress object

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.allow-http: "false"
spec:
  tls:
  - secretName: basic-ingress-secret
  rules:
  - http:
      paths:
      - path: /
        backend:
          serviceName: some-node
          servicePort: 8443

Note: To make is work on GKE, your service must be of type NodePort

$ kubectl describe svc some-node
Name:                     some-node
Namespace:                default
Labels:                   run=nginx
Annotations:              <none>
Selector:                 run=nginx
Type:                     NodePort
IP:                       10.60.6.214
Port:                     <unset>  8443/TCP
TargetPort:               80/TCP
NodePort:                 <unset>  30250/TCP
Endpoints:                10.56.0.17:80
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>


问:
getchar() adding extra characters
I'm writing a program where I input some words into stdin and there are several different functions that do different things. I'm going to focus on the third functionality here. The user inputs multiple words in one line and I am supposed to get the last word. The issue I'm having is very weird, basically, whenever I input a word that consists of 8 characters, the program prints out the last word correctly but also adds an additional letter 'Genu' to the end of the word. For a 9 letter word it adds 'enu' and so on. Words with 12 letters or more do not have this issue. Also, this is only happening on Linux. On Winows I'm getting this message: `@.

Here's the code:

```<code>int main(void)
{
     char* commands[2] = {"search", "exit"};

     char str[100];
     int ch, n = 0;

     while(1)
     {
          while ((ch = getchar()) != '\n')
         {
             str[n] = ch;

             n++;
         }

         char *lastword = str;

         for(int i = 0; i < n; i++)
         {
              if(str[i] == ' ')
              {
                  lastword = strrchr(str, ' ') + 1;
                  break;
              }
         }

        memset(str, 0, 100);
        n = 0;
    }

   return 0;
 }
</code>```

Does anyone know what the issue may be?

答: To me it looks like you're missing a null-byte. str is not initialized properly, that means that its contents are undefined initially. You can see that your program works for all further input, that is because you memset the buffer back to all zeroes. What you need is a zero right behind the last letter of the last word (i.e. memset the buffer before going into the while loop or initialize it like char str[100] = {0};)

Title: getchar() adding extra characters

Body:
I'm writing a program where I input some words into stdin and there are several different functions that do different things. I'm going to focus on the third functionality here. The user inputs multiple words in one line and I am supposed to get the last word. The issue I'm having is very weird, basically, whenever I input a word that consists of 8 characters, the program prints out the last word correctly but also adds an additional letter 'Genu' to the end of the word. For a 9 letter word it adds 'enu' and so on. Words with 12 letters or more do not have this issue. Also, this is only happening on Linux. On Winows I'm getting this message: `@.

Here's the code:

int main(void)
{
     char* commands[2] = {"search", "exit"};

     char str[100];
     int ch, n = 0;

     while(1)
     {
          while ((ch = getchar()) != '\n')
         {
             str[n] = ch;

             n++;
         }

         char *lastword = str;

         for(int i = 0; i < n; i++)
         {
              if(str[i] == ' ')
              {
                  lastword = strrchr(str, ' ') + 1;
                  break;
              }
         }

        memset(str, 0, 100);
        n = 0;
    }

   return 0;
 }

Does anyone know what the issue may be?


问:
How to change datepicker date format like dd/mm/yyyy in ngbdatepicker
I am using ng-boostrap for datepicker:https://ng-bootstrap.github.io/#/components/datepicker/api
But i do not know how to change date format like dd/mm/yyyy. Now it is displaying yyyy/mm/dd but i want like dd/mm/yyyy.Please help anyone.

Demo:https://stackblitz.com/edit/angular-6wpn3h-ahcq4x?file=src/app/datepicker-popup.html

```<code>  <div class="input-group">
  <input class="form-control" placeholder="dd/mm/yyyy"
         name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker">
  <div class="input-group-append">
    <button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
  </div>
  </div>
</code>```

答:
Using ng-bootstrap's NgbDateISOParserFormatter as a guide, create a custom formatter in datepicker-popup.ts. The code below is (IMO) a little more straightforward than the original and doesn't rely on importing util.ts:

```<code>import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';

function padNumber(value: number | null) {
  if (!isNaN(value) && value !== null) {
    return `0${value}`.slice(-2);
  } else {
    return '';
  }
}

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
  parse(value: string): NgbDateStruct | null {
    if (value) {
      const dateParts = value.trim().split('/');

      let dateObj: NgbDateStruct = { day: <any>null, month: <any>null, year: <any>null }
      const dateLabels = Object.keys(dateObj);

      dateParts.forEach((datePart, idx) => {
        dateObj[dateLabels[idx]] = parseInt(datePart, 10) || <any>null;
      });
      return dateObj;
    }
    return null;
  }

  format(date: NgbDateStruct | null): string {
    return date ?
        `${padNumber(date.day)}/${padNumber(date.month)}/${date.year || ''}` :
        '';
  }
}
</code>```

Then import NgbDateCustomParserFormatter and set the provider in @NgModule in datepicker-popup.module.ts:

```<code>providers: [
    {provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}
   ]
</code>```

I've forked your StackBlitz and added this functionality here.

Body:
I am using ng-boostrap for datepicker:https://ng-bootstrap.github.io/#/components/datepicker/api
But i do not know how to change date format like dd/mm/yyyy. Now it is displaying yyyy/mm/dd but i want like dd/mm/yyyy.Please help anyone.

Demo:https://stackblitz.com/edit/angular-6wpn3h-ahcq4x?file=src/app/datepicker-popup.html

  <input class="form-control" placeholder="dd/mm/yyyy"
         name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker">

    <button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>

Body:
Using ng-bootstrap's NgbDateISOParserFormatter as a guide, create a custom formatter in datepicker-popup.ts. The code below is (IMO) a little more straightforward than the original and doesn't rely on importing util.ts:

import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';

function padNumber(value: number | null) {
  if (!isNaN(value) && value !== null) {
    return `0${value}`.slice(-2);
  } else {
    return '';
  }
}

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
  parse(value: string): NgbDateStruct | null {
    if (value) {
      const dateParts = value.trim().split('/');

      let dateObj: NgbDateStruct = { day: <any>null, month: <any>null, year: <any>null }
      const dateLabels = Object.keys(dateObj);

      dateParts.forEach((datePart, idx) => {
        dateObj[dateLabels[idx]] = parseInt(datePart, 10) || <any>null;
      });
      return dateObj;
    }
    return null;
  }

  format(date: NgbDateStruct | null): string {
    return date ?
        `${padNumber(date.day)}/${padNumber(date.month)}/${date.year || ''}` :
        '';
  }
}

Then import NgbDateCustomParserFormatter and set the provider in @NgModule in datepicker-popup.module.ts:

providers: [
    {provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}
   ]

I've forked your StackBlitz and added this functionality here.


问:
Instagram basic display API - Getting Invalid platform app Error
I am getting Invalid platform app error while hitting oauth/access_token API on postman.

Note - for app_id i am using Instagram App Id.

Any solution for this?

```<code>{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Invalid platform app"
}
</code>```

https://api.instagram.com/oauth/access_token?app_id=54219xxxxx359344&app_secret=190fac2eaacxxxxxxxxxd83e1cc0c382ec7&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fankush2016.github.io%2F&code=AQBSckcUcZ6edpLQlnt2NBCFgfhyJYfEBNW_cFlseJ0R7P2fisA3OWAMU8-BJXbFh0RrKdX0Z7ccrpK7rbZOyQID8epfqcpIGGbUn4oAcdC-sCBYEn2nvuPpjlXoSg5Quv-lq1uiucbqIGKoxH0mDkKDp_QKxxxxxxxxxxxxxxxxxxxxelPn1FoVJqSWqaKbVDtt9rdDlP4n0-aRg__exYWGJ8vqKnp_8dGNxg

答:
In pseudo code format you may wish to use following configuration for your request: </p>

```<code>baseURL = "https://api.instagram.com/oauth/access_token"

append = "client_id=\(API.INSTAGRAM_CLIENT_ID)&client_secret=\(API.INSTAGRAM_CLIENTSERCRET)&grant_type=authorization_code&redirect_uri=\(API.INSTAGRAM_REDIRECT_URI)&code=\(code)"

request.httpMethod = "Post"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
</code>```

Body:
I am getting Invalid platform app error while hitting oauth/access_token API on postman.

Note - for app_id i am using Instagram App Id.

Any solution for this?

{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Invalid platform app"
}

https://api.instagram.com/oauth/access_token?app_id=54219xxxxx359344&app_secret=190fac2eaacxxxxxxxxxd83e1cc0c382ec7&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fankush2016.github.io%2F&code=AQBSckcUcZ6edpLQlnt2NBCFgfhyJYfEBNW_cFlseJ0R7P2fisA3OWAMU8-BJXbFh0RrKdX0Z7ccrpK7rbZOyQID8epfqcpIGGbUn4oAcdC-sCBYEn2nvuPpjlXoSg5Quv-lq1uiucbqIGKoxH0mDkKDp_QKxxxxxxxxxxxxxxxxxxxxelPn1FoVJqSWqaKbVDtt9rdDlP4n0-aRg__exYWGJ8vqKnp_8dGNxg

Body:
In pseudo code format you may wish to use following configuration for your request:

baseURL = "https://api.instagram.com/oauth/access_token"

append = "client_id=\(API.INSTAGRAM_CLIENT_ID)&client_secret=\(API.INSTAGRAM_CLIENTSERCRET)&grant_type=authorization_code&redirect_uri=\(API.INSTAGRAM_REDIRECT_URI)&code=\(code)"

request.httpMethod = "Post"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");


问:
Can't change nav-link color in bootstrap 4
```<code><nav id="section_navbar" class="navbar navbar-expand-lg fixed-top">
        <div class="mx-auto my-2 order-0 order-md-1 position-relative">
            <div id="top_logo" class="container-fluid">
                <span>VirtualQR</span>
            </div>
        </div>
        <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-1">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#section_navbar">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_howdoesitwork">How does it work?</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_pricing">Pricings</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_contact">Contacts</a>
                </li>
            </ul>
</code>```

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

答:
Welcome to Stack Overflow. Here's what you can do.

/* Select bootstrap link */

.link{
  color: gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<!-- Standart-->
helllooo

<!-- use bootstrap color labels -->
helllooo

<!-- Use Inline Css-->
helllooo

<!-- Use External Css-->
helllooo</code>```

Body:
                VirtualQR

                    Home

                    How does it work?

                    Pricings

                    Contacts

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

Body:
Welcome to Stack Overflow. Here's what you can do.

/* Select bootstrap link */

.link{
  color: gray;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<!-- Standart-->
<a href="#" class="nav-link">helllooo</a>

<!-- use bootstrap color labels -->
<a href="#" class="nav-link text-dark">helllooo</a>

<!-- Use Inline Css-->
<a href="#" class="nav-link" style="color: red;">helllooo</a>

<!-- Use External Css-->
<a href="#" class="nav-link link">helllooo</a>


问:
Increasing clickable area of ImageView
I have created a RelativeLayout shown below as part of a toolbar. The layout consists of two images and a thin line below the images. For the two images I have increased the width because then the clickable area is wider. A screenshot (Android Studio) how it looks like is shown at the bottom.

The problem now is that I can't control the size of the image (the image is just placed in the center). How can I fix the actual size of the image to 25 x 25 dp and still extend the clickable area to the left and right of the image by let's say 70 dp and at the bottom and top of the image by 10 dp?

```<code><RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="horizontal">

    <View
        android:id="@+id/keyboard_toolbar_line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/privacyButton"
        android:layout_marginBottom="5dp"
        android:background="#c0c0c0"/>

    <ImageView
        android:id="@+id/privacyButton"
        android:layout_width="100dp"
        android:layout_alignParentStart="true"
        android:layout_height="35dp"
        android:scaleType="center"
        android:layout_marginStart="30dp"
        android:src="@drawable/research_ic_lock_open_dark" />

    <ImageView
        android:id="@+id/ratingButton"
        android:layout_width="100dp"
        android:layout_alignParentEnd="true"
        android:layout_height="35dp"
        android:scaleType="center"
        android:layout_marginEnd="30dp"
        android:src="@drawable/ic_star" />

</RelativeLayout >
</code>```

答:
You may think of wrapping it in a LinearLayout that has the exact extra width & height you want, and keep your image in 25x25dp; then add the click listener to the LinearLayout instead of the ImageView

sample for one image:

```<code><LinearLayout
    android:layout_width="140dp"
    android:gravity="center"
    android:layout_height="35dp">

    <ImageView
        android:id="@+id/privacyButton"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="30dp"
        android:scaleType="center"
        android:src="@drawable/quarter_circle" />

</LinearLayout>
</code>```

I just added arbitrary values for the LinearLayout, for the width, as you need 70dp to the right and left so the total is 140.

Title: Increasing clickable area of ImageView

Body:
I have created a RelativeLayout shown below as part of a toolbar. The layout consists of two images and a thin line below the images. For the two images I have increased the width because then the clickable area is wider. A screenshot (Android Studio) how it looks like is shown at the bottom.

The problem now is that I can't control the size of the image (the image is just placed in the center). How can I fix the actual size of the image to 25 x 25 dp and still extend the clickable area to the left and right of the image by let's say 70 dp and at the bottom and top of the image by 10 dp?

<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="horizontal">

    <View
        android:id="@+id/keyboard_toolbar_line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/privacyButton"
        android:layout_marginBottom="5dp"
        android:background="#c0c0c0"/>

    <ImageView
        android:id="@+id/privacyButton"
        android:layout_width="100dp"
        android:layout_alignParentStart="true"
        android:layout_height="35dp"
        android:scaleType="center"
        android:layout_marginStart="30dp"
        android:src="@drawable/research_ic_lock_open_dark" />

    <ImageView
        android:id="@+id/ratingButton"
        android:layout_width="100dp"
        android:layout_alignParentEnd="true"
        android:layout_height="35dp"
        android:scaleType="center"
        android:layout_marginEnd="30dp"
        android:src="@drawable/ic_star" />

</RelativeLayout >

Body:
You may think of wrapping it in a LinearLayout that has the exact extra width & height you want, and keep your image in 25x25dp; then add the click listener to the LinearLayout instead of the ImageView

sample for one image:

<LinearLayout
    android:layout_width="140dp"
    android:gravity="center"
    android:layout_height="35dp">

    <ImageView
        android:id="@+id/privacyButton"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="30dp"
        android:scaleType="center"
        android:src="@drawable/quarter_circle" />

</LinearLayout>

I just added arbitrary values for the LinearLayout, for the width, as you need 70dp to the right and left so the total is 140.


问:
How to add a header in the margin?
I need to include a header in a page like this simple Google page:

I am trying to put the text "Google" inside the top margin of the page but it's 2.5 cm under, when the top margin ends). I want this:

My HTML file:

```<code><html lang="es-AR">
<body>
    <header>Google</header>
    <h1 class="title">Hello, world</h1>
    Trying to put a header.
</body>
</html>
</code>```

My CSS file:

```<code>@page {
    size: 21cm 29.7cm;
    margin-top: 2.5cm;
    margin-right: 2.5cm;
    margin-bottom: 2.5cm;
    margin-left: 2.5cm;
}
</code>```

The page is a report so it will be printed.

答:
I solved it in this way:</p>

```<code>@page {
    size: 21cm 29.7cm;
    margin-top: 0.5cm;
    margin-right: 2.5cm;
    margin-bottom: 2.5cm;
    margin-left: 2.5cm;
}

header {
    height: 2cm;
}
</code>```

Title: How to add a header in the margin?

Body:
I need to include a header in a page like this simple Google page:

I am trying to put the text "Google" inside the top margin of the page but it's 2.5 cm under, when the top margin ends). I want this:

My HTML file:

    Google

Hello, world

    Trying to put a header.

My CSS file:

@page {
    size: 21cm 29.7cm;
    margin-top: 2.5cm;
    margin-right: 2.5cm;
    margin-bottom: 2.5cm;
    margin-left: 2.5cm;
}

The page is a report so it will be printed.

Body:
I solved it in this way:

@page {
    size: 21cm 29.7cm;
    margin-top: 0.5cm;
    margin-right: 2.5cm;
    margin-bottom: 2.5cm;
    margin-left: 2.5cm;
}

header {
    height: 2cm;
}


问:
Using XOR on char array to find if a character is unique in a string
Originally how i solved this CodeWars problem was to use:
StringUtils.countMatches();

However, I am wondering if it can be done using XOR on chars?

Here is what i have so far, but it doesn't pass the test and i am quite stumped.

```<code>static String encode(String word) {
    String test = word.toLowerCase();
    char[] temp = test.toCharArray();
    String sol = "";
    for (char y : temp) {
        if (duplicate(temp, y) == true)
            sol += "(";
        else
            sol += ")";
    }
    return sol;
}

public static boolean duplicate(char[] values, char check) {
    for (char x : values) {
        check ^= x;
        if (check == 0)
            return false;
    }
    return true;
}
</code>```

答:
The method below encodes duplicate characters (starting from the current position!) in a string with '(' and non-duplicate characters with ')':

```<code>static String encode(String word) {
    String test = word.toLowerCase();
    char[] cc = test.toCharArray();
    StringBuilder sol = new StringBuilder();
    for (int i = 0; i < cc.length; i++) {
        char c = cc[i];
        boolean duplicateFound = false;
        for (int j = i+1; j < cc.length; j++) {
            char x = cc[j];
            if ((x ^ c) == 0) {
                duplicateFound = true;
                break;
            }
        }
        sol.append(duplicateFound ? '(' : ')');
    }
    return sol.toString();
}

// test
System.out.println(encode("abcabc")); // prints: ((()))
System.out.println(encode("abcdad")); // prints: ())())
System.out.println(encode("abcdfg")); // prints: ))))))
</code>```

The following method passes CodeWars test of detecting all unique characters:

```<code>public static boolean hasUniqueChars(String str) {
    String test = str.toLowerCase();
    char[] cc = test.toCharArray();

    for (int i = 0; i < cc.length; i++) {
        char c = cc[i];
        for (int j = i+1; j < cc.length; j++) {
            char x = cc[j];
            if ((x ^ c) == 0) {
                return false;
            }
        }
    }
    return true;
}
</code>```

Body:
Originally how i solved this CodeWars problem was to use:
StringUtils.countMatches();

However, I am wondering if it can be done using XOR on chars?

Here is what i have so far, but it doesn't pass the test and i am quite stumped.

static String encode(String word) {
    String test = word.toLowerCase();
    char[] temp = test.toCharArray();
    String sol = "";
    for (char y : temp) {
        if (duplicate(temp, y) == true)
            sol += "(";
        else
            sol += ")";
    }
    return sol;
}

public static boolean duplicate(char[] values, char check) {
    for (char x : values) {
        check ^= x;
        if (check == 0)
            return false;
    }
    return true;
}

Body:
The method below encodes duplicate characters (starting from the current position!) in a string with '(' and non-duplicate characters with ')':

static String encode(String word) {
    String test = word.toLowerCase();
    char[] cc = test.toCharArray();
    StringBuilder sol = new StringBuilder();
    for (int i = 0; i < cc.length; i++) {
        char c = cc[i];
        boolean duplicateFound = false;
        for (int j = i+1; j < cc.length; j++) {
            char x = cc[j];
            if ((x ^ c) == 0) {
                duplicateFound = true;
                break;
            }
        }
        sol.append(duplicateFound ? '(' : ')');
    }
    return sol.toString();
}

// test
System.out.println(encode("abcabc")); // prints: ((()))
System.out.println(encode("abcdad")); // prints: ())())
System.out.println(encode("abcdfg")); // prints: ))))))

The following method passes CodeWars test of detecting all unique characters:

public static boolean hasUniqueChars(String str) {
    String test = str.toLowerCase();
    char[] cc = test.toCharArray();

    for (int i = 0; i < cc.length; i++) {
        char c = cc[i];
        for (int j = i+1; j < cc.length; j++) {
            char x = cc[j];
            if ((x ^ c) == 0) {
                return false;
            }
        }
    }
    return true;
}


问:
Setting up Segment.io
I have recently finished building a website on Webflow and I am looking to integrate Segment.io onto my website to connect with different destinations. I haven't been able to figure out how I could go onto collecting event and identity data into segment.io.

I have gone on their website and have seen example scripts (as shown below) but, I can seem to figure out anywhere how I could replace the dummy from the hard-coded strings to be functional on my HTML coded website.

```<code>analytics.identify('f4ca124298', {
  name: 'Michael Bolton',
  email: 'mbolton@initech.com'
});

analytics.track('Article Bookmarked', {
  title: 'Snow Fall',
  subtitle: 'The Avalanche at Tunnel Creek',
  author: 'John Branch'
});
</code>```

Is there anyone that has been successful in setting up Segment.io on their projects?

答:
this code snippet goes on your web page, usually in a javascript import. Depending on how you are setting up your page, but simple javascript would be populating using the DOM values..

The first example, using an identify call, typically happens on a form submit.

```<code>var name = document.getElementById('name_field').value;
var email = document.getElementById('email_field').value;
var user_id = document.getElementById('user_id_field').value;

analytics.identify(user_id, {name: name, email: email});

</code>```

Similar thinking when using the track calls..

Title: Setting up Segment.io

Body:
I have recently finished building a website on Webflow and I am looking to integrate Segment.io onto my website to connect with different destinations. I haven't been able to figure out how I could go onto collecting event and identity data into segment.io.

I have gone on their website and have seen example scripts (as shown below) but, I can seem to figure out anywhere how I could replace the dummy from the hard-coded strings to be functional on my HTML coded website.

analytics.identify('f4ca124298', {
  name: 'Michael Bolton',
  email: 'mbolton@initech.com'
});

analytics.track('Article Bookmarked', {
  title: 'Snow Fall',
  subtitle: 'The Avalanche at Tunnel Creek',
  author: 'John Branch'
});

Is there anyone that has been successful in setting up Segment.io on their projects?

Body:
this code snippet goes on your web page, usually in a javascript import. Depending on how you are setting up your page, but simple javascript would be populating using the DOM values..

The first example, using an identify call, typically happens on a form submit.

var name = document.getElementById('name_field').value;
var email = document.getElementById('email_field').value;
var user_id = document.getElementById('user_id_field').value;

analytics.identify(user_id, {name: name, email: email});

Similar thinking when using the track calls..


问:
Flutter: keyboard disappears immediately when editing my text fields

I'm trying to build an app front end with flutter and it's my first time so I faced some bugs like this one: there is no way to edit my textformfield because I putted my form elements in a listview ! when keyboard appears to enter some text to the field it disappears in a second ! I need an immediat solution please :(

```<code>import 'package:flutter/material.dart';
import'package:dubai274_app/mobile_verif.dart';
import 'EnsureVisible.dart';
class SignUp extends StatefulWidget{
  static String tag = 'Sign_up-page';
  SignUp_Page createState() => SignUp_Page();

}
class SignUp_Page extends State<SignUp>{

  List<DropdownMenuItem<String>> _Dropdownmenuitems;
  String _statusSel;
  List<DropdownMenuItem<String>> _getDropdownmenuitem(){

    List<DropdownMenuItem<String>> items=new List();
    items.add(new DropdownMenuItem(value:'Emirates',child: new Text('United Arab Emirates')));
    items.add(new DropdownMenuItem(value:'Tun',child: new Text('Tunisia')));
    return items;
  }
  void changeddropdowselecteditem(String selecteditem){
    setState(() {
_statusSel=selecteditem;
    });
  }
   @override
  void initState() {
    // TODO: implement initState
    //listViewController=new ScrollController().addListener(_scrollListener);
    _Dropdownmenuitems=_getDropdownmenuitem();
    _statusSel=_Dropdownmenuitems[0].value;
  }
@override
  Widget build(BuildContext context) {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final formKey = GlobalKey<FormState>();
  final TextEditingController _controller = new TextEditingController();

final first_value=TextFormField(autofocus: false,
  validator: (val) =>
  val.length < 6 ? 'First name required' : null,
  decoration: InputDecoration(
    labelText: 'First Name',
    hintText: 'First Name',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),

  ),);

final family_value=TextFormField(autofocus: false,
  decoration: InputDecoration(
    labelText: 'Last Name',
    hintText: 'Last Name',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),

  ),);

final Nationality=new DropdownButton(items: _Dropdownmenuitems, value:_statusSel,onChanged: changeddropdowselecteditem);

final email_value=TextFormField(keyboardType: TextInputType.emailAddress,
  autofocus: false,
  decoration: InputDecoration(
    labelText: 'Email',
    hintText: 'Email',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),

  ),);

final password=Column(children: <Widget>[ TextFormField(autofocus: false,

  obscureText: true,
  decoration: InputDecoration(
    labelText: 'Password',
    hintText: 'Password',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),)), Text('Min 8 characters with at least one special character')]);
  void _performsignup() {

    final snackbar = SnackBar(
      content: Text('Email: $email, password: $password'),
    );

    scaffoldKey.currentState.showSnackBar(snackbar);
  }
  void _submit() {
    final form = formKey.currentState;

    if (form.validate()) {
      form.save();
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => MobileVerif()),
      );

      _performsignup();
    }
  }
final forward_signedin=FloatingActionButton(tooltip: 'Go forward',
  child: Icon(Icons.arrow_forward,color: Colors.white,size: 38.4,),

  onPressed: (){_submit();},);

return MaterialApp(
      title: 'Sign_Up_Page',
      home: Scaffold(
        appBar: AppBar(
          elevation: 0.0,
      backgroundColor: Colors.transparent,
      title: const Text('Sign Up',style: TextStyle(color: Colors.blueAccent, fontSize: 25.0,fontWeight: FontWeight.bold),textAlign: TextAlign.center,),
  centerTitle: true,
  leading: IconButton(
  tooltip: 'Previous choice',
  icon: const Icon(Icons.arrow_back_ios),
    onPressed: () { Navigator.pop(context);},
    color: Colors.black,
    iconSize: 20.0,
  ),
  ),
        body: new Container(
          decoration: new BoxDecoration(
          image: new DecorationImage(
            image: new AssetImage("assets/background.png"),
            fit: BoxFit.cover,
          ),
        ),
        child: new Form( key: formKey,
            child: new Padding( padding: new EdgeInsets.all(40.0), child: ListView(
      children: <Widget>[

       first_value,
       family_value,
       Nationality,
       email_value,
       password,
       new ListTile( title:forward_signedin,)],
)) )

        ),

        ),

      );

  }
}
</code>```

答: If you are using StatelessWidget, transform it into StatefulWidget. Make sure the key is state's property, not widget's. This happens because your form key is getting recreated over and over again with each rebuild. To keep the key, it should be a part of state.

Body:
I'm trying to build an app front end with flutter and it's my first time so I faced some bugs like this one: there is no way to edit my textformfield because I putted my form elements in a listview ! when keyboard appears to enter some text to the field it disappears in a second ! I need an immediat solution please :(

import 'package:flutter/material.dart';
import'package:dubai274_app/mobile_verif.dart';
import 'EnsureVisible.dart';
class SignUp extends StatefulWidget{
  static String tag = 'Sign_up-page';
  SignUp_Page createState() => SignUp_Page();

}
class SignUp_Page extends State<SignUp>{

  List<DropdownMenuItem<String>> _Dropdownmenuitems;
  String _statusSel;
  List<DropdownMenuItem<String>> _getDropdownmenuitem(){

    List<DropdownMenuItem<String>> items=new List();
    items.add(new DropdownMenuItem(value:'Emirates',child: new Text('United Arab Emirates')));
    items.add(new DropdownMenuItem(value:'Tun',child: new Text('Tunisia')));
    return items;
  }
  void changeddropdowselecteditem(String selecteditem){
    setState(() {
_statusSel=selecteditem;
    });
  }
   @override
  void initState() {
    // TODO: implement initState
    //listViewController=new ScrollController().addListener(_scrollListener);
    _Dropdownmenuitems=_getDropdownmenuitem();
    _statusSel=_Dropdownmenuitems[0].value;
  }
@override
  Widget build(BuildContext context) {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final formKey = GlobalKey<FormState>();
  final TextEditingController _controller = new TextEditingController();

final first_value=TextFormField(autofocus: false,
  validator: (val) =>
  val.length < 6 ? 'First name required' : null,
  decoration: InputDecoration(
    labelText: 'First Name',
    hintText: 'First Name',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),

  ),);

final family_value=TextFormField(autofocus: false,
  decoration: InputDecoration(
    labelText: 'Last Name',
    hintText: 'Last Name',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),

  ),);

final Nationality=new DropdownButton(items: _Dropdownmenuitems, value:_statusSel,onChanged: changeddropdowselecteditem);

final email_value=TextFormField(keyboardType: TextInputType.emailAddress,
  autofocus: false,
  decoration: InputDecoration(
    labelText: 'Email',
    hintText: 'Email',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),

  ),);

final password=Column(children: <Widget>[ TextFormField(autofocus: false,

  obscureText: true,
  decoration: InputDecoration(
    labelText: 'Password',
    hintText: 'Password',
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),)), Text('Min 8 characters with at least one special character')]);
  void _performsignup() {

    final snackbar = SnackBar(
      content: Text('Email: $email, password: $password'),
    );

    scaffoldKey.currentState.showSnackBar(snackbar);
  }
  void _submit() {
    final form = formKey.currentState;

    if (form.validate()) {
      form.save();
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => MobileVerif()),
      );

      _performsignup();
    }
  }
final forward_signedin=FloatingActionButton(tooltip: 'Go forward',
  child: Icon(Icons.arrow_forward,color: Colors.white,size: 38.4,),

  onPressed: (){_submit();},);

return MaterialApp(
      title: 'Sign_Up_Page',
      home: Scaffold(
        appBar: AppBar(
          elevation: 0.0,
      backgroundColor: Colors.transparent,
      title: const Text('Sign Up',style: TextStyle(color: Colors.blueAccent, fontSize: 25.0,fontWeight: FontWeight.bold),textAlign: TextAlign.center,),
  centerTitle: true,
  leading: IconButton(
  tooltip: 'Previous choice',
  icon: const Icon(Icons.arrow_back_ios),
    onPressed: () { Navigator.pop(context);},
    color: Colors.black,
    iconSize: 20.0,
  ),
  ),
        body: new Container(
          decoration: new BoxDecoration(
          image: new DecorationImage(
            image: new AssetImage("assets/background.png"),
            fit: BoxFit.cover,
          ),
        ),
        child: new Form( key: formKey,
            child: new Padding( padding: new EdgeInsets.all(40.0), child: ListView(
      children: <Widget>[

       first_value,
       family_value,
       Nationality,
       email_value,
       password,
       new ListTile( title:forward_signedin,)],
)) )

        ),

        ),

      );

  }
}


问:
datagrip Cannot apply changes This table is read only. Cell editor changes cannot be applied
So simply the problem occurs when I want to edit selected rows and then apply it. I'm sure it worked some time ago. Tried redownload postgres driver in preferences(yeah, I use postgres) Anyone faced same issue? Anyone succeed?

PS. Running on 142.4861.1.

I found read only checkbox in connection preferences, it was not set, toggling didn't help, upgrading, reseting also didn't help.

答:
I thought I had the same problem but just realized I needed to submit changes (with a button or command + enter) for them to be applied.

This answer is 4 years late though. Maybe the bug was already fixed haha, but this may help someone else.