问:
Turning the Nth (input from user) number into Uppercase and the rest will be in Lowercase
I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:

string = "good morning everyone"

n = 2

Output = gOod mOrning eVeryone

```<code>    for (int x = 0; x < s.length(); x++)
        if (x == n-1){
            temp+=(""+s.charAt(x)).toUpperCase();
        }else{
            temp+=(""+s.charAt(x)).toLowerCase();
        }
    s=temp;
    System.out.println(s);
}
</code>```

Output: gOod morning everyone

答:
I know what you want to happen - but you didn't phrase your question very well. The only part your missing is iterating through every word in the sentence. If you asked "how do I apply a function on every word in a String" you likely would have gotten a better response.

This is a bit sloppy since it adds a trailing " " to the end - but you could fix that easily.

```<code>public class Test {

    static String test = "This is a test.";

    public static void main(String[] args) {
        String[] words = test.split(" ");
        String result = "";

        for (String word : words) {
            result += nthToUpperCase(word, 2);
            result += " ";
        }

        System.out.println(result);
    }

    public static String NthToUpperCase(String s, int n) {
        String temp = "";

        for (int i = 0; i < s.length(); i++) {
            if (i == (n-1)) {
                temp+=Character.toString(s.charAt(i)).toUpperCase();
            } else {
                temp+=Character.toString(s.charAt(i));
            }
        }

        return temp;
    }
}
</code>```

Body:
I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:

string = "good morning everyone"

n = 2

Output = gOod mOrning eVeryone

    for (int x = 0; x < s.length(); x++)
        if (x == n-1){
            temp+=(""+s.charAt(x)).toUpperCase();
        }else{
            temp+=(""+s.charAt(x)).toLowerCase();
        }
    s=temp;
    System.out.println(s);
}

Output: gOod morning everyone

Body:
I know what you want to happen - but you didn't phrase your question very well. The only part your missing is iterating through every word in the sentence. If you asked "how do I apply a function on every word in a String" you likely would have gotten a better response.

This is a bit sloppy since it adds a trailing " " to the end - but you could fix that easily.

public class Test {

    static String test = "This is a test.";

    public static void main(String[] args) {
        String[] words = test.split(" ");
        String result = "";

        for (String word : words) {
            result += nthToUpperCase(word, 2);
            result += " ";
        }

        System.out.println(result);
    }

    public static String NthToUpperCase(String s, int n) {
        String temp = "";

        for (int i = 0; i < s.length(); i++) {
            if (i == (n-1)) {
                temp+=Character.toString(s.charAt(i)).toUpperCase();
            } else {
                temp+=Character.toString(s.charAt(i));
            }
        }

        return temp;
    }
}


来源: stackexchange

问:
Upload file to S3 service 403 ERROR (com.amazonaws.AWSS3TransferUtilityErrorDomain error 2.) Swift iOS
I tried to upload my file to S3 service vie AWSS3 SDK swift.
My code:

```<code>    let credentialsProvider = AWSStaticCredentialsProvider(accessKey: Config.main.accessKey, secretKey: Config.main.secretKey)
    let configuration = AWSServiceConfiguration(region: .USEast1, endpoint: AWSEndpoint(url: URL(string: Config.main.AWS_ENDPOINT)!), credentialsProvider: credentialsProvider)
    AWSServiceManager.default().defaultServiceConfiguration = configuration

let image = UIImage(named: "photo")!
let data: Data = image.pngData()!
let remoteName = generateRandomStringWithLength(length: 12) + "." + data.format
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(remoteName)
try! data.write(to: fileURL, options: .atomic)
upload(fileUrl: fileURL, fileData: data, fileName: remoteName, type: .image, completionHandler: {_ in})
</code>```

```<code>func upload(fileUrl: URL, fileData: Data, fileName: String, type: FileTypes, completionHandler: @escaping (URL?) -> ()) {

    let expression = AWSS3TransferUtilityUploadExpression()
    expression.progressBlock = { task, progress in
        DispatchQueue.main.async {
            print("Progress = \(progress.completedUnitCount)/\(progress.totalUnitCount)")
        }
    }
    let util = AWSS3TransferUtility.default()
    util.uploadData(
        fileData,
        bucket: self.getBucket(type: type),
        key: "\(self.getDir(type: type))_\(fileName)",
        contentType: "image/png",
        expression: expression) { task, error in
            print("ERROR: \(error?.localizedDescription)")
            print("response: \(task.response)")
            print("response: \(task.response)")

        }.continueWith { task in
            if let error = task.error {
                print("ERROR1: \(error.localizedDescription)")
            }
            return nil
    }
}
</code>```

It returns me something like 5 times progress response and after that

ERROR: Optional("The operation couldn’t be completed.
  (com.amazonaws.AWSS3TransferUtilityErrorDomain error 2.)")

response: Optional( { URL:
  http://(bucket).(host)/image_L24i8RGCeAaj.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=59589007eea780cf27c5%2F20200131%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20200131T125453Z&X-Amz-Expires=2999&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  } { Status Code: 403, Headers {
      "Content-Length" =     (
          186
      );
      Date =     (
          "Fri, 31 Jan 2020 12:54:53 GMT"
      );
      Server =     (
          LeoFS
      ); } })

Android app with same setup works perfect.

What is the solution of the problem?

答:
There is some useful info about this at https://medium.com/@lewisjkl/signing-aws4-31dcff1bf1f0, from Jeff Lewis.

It uses the CryptoSwift library; I'm working now to convert it to use the new CryptoKit.

ContentLicense: CC BY-SA 4.0

Body:
I tried to upload my file to S3 service vie AWSS3 SDK swift.
My code:

    let credentialsProvider = AWSStaticCredentialsProvider(accessKey: Config.main.accessKey, secretKey: Config.main.secretKey)
    let configuration = AWSServiceConfiguration(region: .USEast1, endpoint: AWSEndpoint(url: URL(string: Config.main.AWS_ENDPOINT)!), credentialsProvider: credentialsProvider)
    AWSServiceManager.default().defaultServiceConfiguration = configuration

let image = UIImage(named: "photo")!
let data: Data = image.pngData()!
let remoteName = generateRandomStringWithLength(length: 12) + "." + data.format
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(remoteName)
try! data.write(to: fileURL, options: .atomic)
upload(fileUrl: fileURL, fileData: data, fileName: remoteName, type: .image, completionHandler: {_ in})

func upload(fileUrl: URL, fileData: Data, fileName: String, type: FileTypes, completionHandler: @escaping (URL?) -> ()) {

    let expression = AWSS3TransferUtilityUploadExpression()
    expression.progressBlock = { task, progress in
        DispatchQueue.main.async {
            print("Progress = \(progress.completedUnitCount)/\(progress.totalUnitCount)")
        }
    }
    let util = AWSS3TransferUtility.default()
    util.uploadData(
        fileData,
        bucket: self.getBucket(type: type),
        key: "\(self.getDir(type: type))_\(fileName)",
        contentType: "image/png",
        expression: expression) { task, error in
            print("ERROR: \(error?.localizedDescription)")
            print("response: \(task.response)")
            print("response: \(task.response)")

        }.continueWith { task in
            if let error = task.error {
                print("ERROR1: \(error.localizedDescription)")
            }
            return nil
    }
}

It returns me something like 5 times progress response and after that

ERROR: Optional("The operation couldn’t be completed.
  (com.amazonaws.AWSS3TransferUtilityErrorDomain error 2.)")

response: Optional( { URL:
  http://(bucket).(host)/image_L24i8RGCeAaj.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=59589007eea780cf27c5%2F20200131%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20200131T125453Z&X-Amz-Expires=2999&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  } { Status Code: 403, Headers {
      "Content-Length" =     (
          186
      );
      Date =     (
          "Fri, 31 Jan 2020 12:54:53 GMT"
      );
      Server =     (
          LeoFS
      ); } })

Android app with same setup works perfect.

What is the solution of the problem?


问:
Change default font color for navigation-drawer and toolbar
I would like to define the default font-color for the navigation-drawer and toolbar.

I looked at changing colors through theming: https://vuetifyjs.com/en/customization/theme

Aswell as overriding scss defaults: https://vuetifyjs.com/en/customization/sass-variables

But nowhere can i find changing the needed setting.

Playground: codepen io/timar/pen/WNvxOYB

答:
The Vuetify CSS has multiple color classes for background as well as text. The format for the text color classes are in the format of: .[color]--text. There is also various flavoring for lighten, darken and accent in the format of: .text--lighten-2, for example. The naming of colors and such can be found at the Vuetify Colors page.

What I have shown below, essentially forking the codepen in the OP, illustrates a method, customColor, to return a CSS class to set the text color based on the item.title value that is called on v-list-item-title.

Vue.config.productionTip = false;
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      items: [
        { title: 'Dashboard', icon: 'mdi-view-dashboard' },
        { title: 'Photos', icon: 'mdi-image' },
        { title: 'About', icon: 'mdi-help-box' },
      ],
      right: null,
    }
  },
  methods: {
    customColor(text) {
      return (text === 'Photos') ? 'green--text' : '';
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.1.14/dist/vuetify.min.css" rel="stylesheet"/>

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-card
      height="400"
      width="256"
      class="mx-auto"
    >
      <v-navigation-drawer permanent>
        <v-list-item>
          <v-list-item-content>
            <v-list-item-title class="title">
              Application
            </v-list-item-title>
            <v-list-item-subtitle>
              subtext
            </v-list-item-subtitle>
          </v-list-item-content>
        </v-list-item>

        <v-divider></v-divider>

        <v-list
          dense
          nav
        >
          <v-list-item
            v-for="item in items"
            :key="item.title"
            link
          >
            <v-list-item-icon>
              <v-icon>{{ item.icon }}</v-icon>
            </v-list-item-icon>

            <v-list-item-content>
              <v-list-item-title
                :class="customColor(item.title)"
              >{{ item.title }}</v-list-item-title>
            </v-list-item-content>
          </v-list-item>
        </v-list>
      </v-navigation-drawer>
    </v-card>
  </v-app>
</div></code>```

Body:
The Vuetify CSS has multiple color classes for background as well as text. The format for the text color classes are in the format of: .[color]--text. There is also various flavoring for lighten, darken and accent in the format of: .text--lighten-2, for example. The naming of colors and such can be found at the Vuetify Colors page.

What I have shown below, essentially forking the codepen in the OP, illustrates a method, customColor, to return a CSS class to set the text color based on the item.title value that is called on v-list-item-title.

Vue.config.productionTip = false;
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      items: [
        { title: 'Dashboard', icon: 'mdi-view-dashboard' },
        { title: 'Photos', icon: 'mdi-image' },
        { title: 'About', icon: 'mdi-help-box' },
      ],
      right: null,
    }
  },
  methods: {
    customColor(text) {
      return (text === 'Photos') ? 'green--text' : '';
    }
  }
})

<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.1.14/dist/vuetify.min.css" rel="stylesheet"/>

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-card
      height="400"
      width="256"
      class="mx-auto"
    >
      <v-navigation-drawer permanent>
        <v-list-item>
          <v-list-item-content>
            <v-list-item-title class="title">
              Application
            </v-list-item-title>
            <v-list-item-subtitle>
              subtext
            </v-list-item-subtitle>
          </v-list-item-content>
        </v-list-item>

        <v-divider></v-divider>

        <v-list
          dense
          nav
        >
          <v-list-item
            v-for="item in items"
            :key="item.title"
            link
          >
            <v-list-item-icon>
              <v-icon>{{ item.icon }}</v-icon>
            </v-list-item-icon>

            <v-list-item-content>
              <v-list-item-title
                :class="customColor(item.title)"
              >{{ item.title }}</v-list-item-title>
            </v-list-item-content>
          </v-list-item>
        </v-list>
      </v-navigation-drawer>
    </v-card>
  </v-app>
</div>


问:
Why toolbar = null in fragment?
Why my toolbar equals to null in fragment ?

Main theme in manifest

```<code><!-- Base application theme. -->
"Theme.MaterialComponents.Light.NoActionBar"
</code>```

fragment_home.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".home.HomeFragment">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:background="?attr/colorPrimary" />

</LinearLayout>
</code>```

HomeFragment.kt

```<code>class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        (activity as AppCompatActivity).setSupportActionBar(toolbar)
        (activity as AppCompatActivity).supportActionBar?.title = "Title"

        Log.i("HomeFragment", "$toolbar")
        return view
    }

}
</code>```

And in logs i get null on toolbar!!

答:
Obviously it is null, since you did not assign and init it.

Just add after view assigning

```<code>val toolbar: Toolbar = view.findViewById(R.id.toolbar)
</code>```

Title: Why toolbar = null in fragment?

Body:
Why my toolbar equals to null in fragment ?

Main theme in manifest

"Theme.MaterialComponents.Light.NoActionBar"

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".home.HomeFragment">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:background="?attr/colorPrimary" />

</LinearLayout>

HomeFragment.kt

class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        (activity as AppCompatActivity).setSupportActionBar(toolbar)
        (activity as AppCompatActivity).supportActionBar?.title = "Title"

        Log.i("HomeFragment", "$toolbar")
        return view
    }

}

And in logs i get null on toolbar!!

Body:
Obviously it is null, since you did not assign and init it.

Just add after view assigning

val toolbar: Toolbar = view.findViewById(R.id.toolbar)


问:
P4Python does not check out the file in Perforce
I have following piece of code. I'm trying to check out two files from Perforce and put them in a changelist. But run_add does not check the files out. The only thing I see in Perforce is a empty changelist with no files in it.

```<code>""" Checks out files from workspace using P4"""
files = ['analyse-location.cfg', 'CMakeLists.txt']
p4 = P4()

# Connect and disconnect
if (p4.connected()):
    p4.disconnect()

p4.port = portp4
p4.user = usernameP4
p4.password = passwordP4
p4.client = clientP4
try:
    p4.connect()
    if p4.connected():
        change = p4.fetch_change()
        change['Description'] = "Auto"
        change['Files'] = []
        changeList = p4.save_change(change)[0].split()[1]

        for items in files:
            abs_path = script_dir + "\\" + items
            p4.run_add("-c", changeList, items)
            print("Adding file "+ abs_path + " to "+ changeList)

    # Done! Disconnect!
    p4.disconnect()

except P4Exception:
    print("Something went wrong in P4 connection. The errors are: ")
    for e in p4.errors:
        print(e)
    p4.disconnect()
</code>```

However, when I have instead p4.run("edit", items) it puts the files in the default changelist.It really gets on my nervs. I don't know I am doing that is wrong. The changes list created as well. I use python 3.7 32 bits on Windows

答:
Your script discards the output of the run_add call.  Try changing this:

```<code>    for items in files:
        abs_path = script_dir + "\\" + items
        p4.run_add("-c", changeList, items)
        print("Adding file "+ abs_path + " to "+ changeList)
</code>```

to:

```<code>    for items in files:
        abs_path = script_dir + "\\" + items
        output = p4.run_add("-c", changeList, items)
        print("Adding file "+ abs_path + " to "+ changeList)
        if output:
            print(output)

if p4.errors:
    print(p4.errors)
if p4.warnings:
    print(p4.warnings)
</code>```

That will show you the results of the p4 add commands that you're running.  Based on the fact that a p4 edit opens the files, I expect you'll find a message like this:

```<code>C:\Perforce\test>p4 add foo
//stream/main/foo - can't add existing file
</code>```

The p4 add and p4 edit commands are not synonymous; one is for adding a new file, one is for editing an existing file.  If your script is editing existing files, it should be calling run_edit, not run_add.

Body:
I have following piece of code. I'm trying to check out two files from Perforce and put them in a changelist. But run_add does not check the files out. The only thing I see in Perforce is a empty changelist with no files in it.

""" Checks out files from workspace using P4"""
files = ['analyse-location.cfg', 'CMakeLists.txt']
p4 = P4()

# Connect and disconnect
if (p4.connected()):
    p4.disconnect()

p4.port = portp4
p4.user = usernameP4
p4.password = passwordP4
p4.client = clientP4
try:
    p4.connect()
    if p4.connected():
        change = p4.fetch_change()
        change['Description'] = "Auto"
        change['Files'] = []
        changeList = p4.save_change(change)[0].split()[1]

        for items in files:
            abs_path = script_dir + "\\" + items
            p4.run_add("-c", changeList, items)
            print("Adding file "+ abs_path + " to "+ changeList)

    # Done! Disconnect!
    p4.disconnect()

except P4Exception:
    print("Something went wrong in P4 connection. The errors are: ")
    for e in p4.errors:
        print(e)
    p4.disconnect()

However, when I have instead p4.run("edit", items) it puts the files in the default changelist.It really gets on my nervs. I don't know I am doing that is wrong. The changes list created as well. I use python 3.7 32 bits on Windows

Body:
Your script discards the output of the run_add call.  Try changing this:

    for items in files:
        abs_path = script_dir + "\\" + items
        p4.run_add("-c", changeList, items)
        print("Adding file "+ abs_path + " to "+ changeList)

to:

    for items in files:
        abs_path = script_dir + "\\" + items
        output = p4.run_add("-c", changeList, items)
        print("Adding file "+ abs_path + " to "+ changeList)
        if output:
            print(output)

if p4.errors:
    print(p4.errors)
if p4.warnings:
    print(p4.warnings)

That will show you the results of the p4 add commands that you're running.  Based on the fact that a p4 edit opens the files, I expect you'll find a message like this:

C:\Perforce\test>p4 add foo
//stream/main/foo - can't add existing file

The p4 add and p4 edit commands are not synonymous; one is for adding a new file, one is for editing an existing file.  If your script is editing existing files, it should be calling run_edit, not run_add.


问:
How to swipe panels between each other c#?
I wrote the code so that I could move the controls(panels) in the main panel. I would like the controls(panels) not to overlap. I would like the controls(panels) to move as I add a new one between.

I would like to move blue panel(panel2) to down between red and gray panel but If i set dock=TOP, I can't move the controls.

```<code>public Form1()
    {
        InitializeComponent();
        INIT();
    }
    private Point firstPoint = new Point();
    private Point firstPoint2 = new Point();
    private void button1_Click(object sender, EventArgs e)
    {
        panel2.Dock = DockStyle.Top;
        panel3.Dock = DockStyle.Top;
        panel4.Dock = DockStyle.Top;
    }

    public void INIT()
    {
        panel2.MouseDown += (ss, ee) => {
            if (ee.Button == MouseButtons.Left) firstPoint = Control.MousePosition;
        };

        panel2.MouseMove += (ss, ee) =>
        {
            if(ee.Button == MouseButtons.Left)
            {
                Point temp = Control.MousePosition;
                Point res = new Point(firstPoint.X - temp.X, firstPoint.Y - temp.Y);
                panel2.Location = new Point(panel2.Location.X - res.X, panel2.Location.Y - res.Y);
                firstPoint = temp;
            }
        };

        panel3.MouseDown += (ss, ee) => {
            if (ee.Button == MouseButtons.Left) firstPoint2 = Control.MousePosition;
        };

        panel3.MouseMove += (ss, ee) =>
        {
            if (ee.Button == MouseButtons.Left)
            {
                Point temp = Control.MousePosition;
                Point res = new Point(firstPoint2.X - temp.X, firstPoint2.Y - temp.Y);
                panel3.Location = new Point(panel3.Location.X - res.X, panel3.Location.Y - res.Y);
                firstPoint2 = temp;
            }
        };
    }
</code>```

答: Instead of adding your controls to the form, dock on of the Panel container  (maybe a FlowLayoutPanel) into your form, and add your controls to that.  Then you don't have to worry about positioning, the container will handle it.</p>

Body:
I wrote the code so that I could move the controls(panels) in the main panel. I would like the controls(panels) not to overlap. I would like the controls(panels) to move as I add a new one between.

I would like to move blue panel(panel2) to down between red and gray panel but If i set dock=TOP, I can't move the controls.

public Form1()
    {
        InitializeComponent();
        INIT();
    }
    private Point firstPoint = new Point();
    private Point firstPoint2 = new Point();
    private void button1_Click(object sender, EventArgs e)
    {
        panel2.Dock = DockStyle.Top;
        panel3.Dock = DockStyle.Top;
        panel4.Dock = DockStyle.Top;
    }

    public void INIT()
    {
        panel2.MouseDown += (ss, ee) => {
            if (ee.Button == MouseButtons.Left) firstPoint = Control.MousePosition;
        };

        panel2.MouseMove += (ss, ee) =>
        {
            if(ee.Button == MouseButtons.Left)
            {
                Point temp = Control.MousePosition;
                Point res = new Point(firstPoint.X - temp.X, firstPoint.Y - temp.Y);
                panel2.Location = new Point(panel2.Location.X - res.X, panel2.Location.Y - res.Y);
                firstPoint = temp;
            }
        };

        panel3.MouseDown += (ss, ee) => {
            if (ee.Button == MouseButtons.Left) firstPoint2 = Control.MousePosition;
        };

        panel3.MouseMove += (ss, ee) =>
        {
            if (ee.Button == MouseButtons.Left)
            {
                Point temp = Control.MousePosition;
                Point res = new Point(firstPoint2.X - temp.X, firstPoint2.Y - temp.Y);
                panel3.Location = new Point(panel3.Location.X - res.X, panel3.Location.Y - res.Y);
                firstPoint2 = temp;
            }
        };
    }


问:
Function vs. Macro in CMake
The official document of CMake 2.8.12 says about macro

When it is invoked, the commands recorded in the macro are first
modified by replacing formal parameters (${arg1}) with the arguments
passed, and then invoked as normal commands.

and about function

When it is invoked, the commands recorded in the function are first
modified by replacing formal parameters (${arg1}) with the arguments
passed, and then invoked as normal commands.

Obviously, the two quotes are almost the same but it's confusing. Does parameter replacement behave the same in functions and macros?

答:
Another notable difference between function() and macro() is the behavior of return().

From the cmake documentation of return():

Note that a macro, unlike a function, is expanded in place and therefore cannot handle return().

So because it is expanded in place, in a macro() it returns from the caller. While in a function it just exits the function()

Example:

```<code>macro(my_macro)
    return()
endmacro()

function(my_function)
    return()
endfunction()

my_function()
message(hello) # is printed
my_macro()
message(hi) # is not printed
</code>```

Title: Function vs. Macro in CMake

Body:
Another notable difference between function() and macro() is the behavior of return().

From the cmake documentation of return():

Note that a macro, unlike a function, is expanded in place and therefore cannot handle return().

So because it is expanded in place, in a macro() it returns from the caller. While in a function it just exits the function()

Example:

macro(my_macro)
    return()
endmacro()

function(my_function)
    return()
endfunction()

my_function()
message(hello) # is printed
my_macro()
message(hi) # is not printed


问:
Unable to use access properties from Properties file in IntelliJ IDEA using Singleton class
I was practicing to access properties from property file using a singleton class called PropertyLoader but however my maven project is not able to locate the file in resources and giving null pointer excepiton.

Here is the class code.

import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;

public class PropertyLoader {
    private static PropertyLoader instance = null;
    private Properties properties;
    private final static Logger LOGGER = Logger.getLogger(PropertyLoader.class.getName());

    protected PropertyLoader() throws IOException {
        //TODO: Fix problem with loading properties file below
        properties = new Properties();
        properties.load(PropertyLoader.class.getResourceAsStream("app.properties"));

    }

    public static PropertyLoader getInstance() {
        if(instance == null) {
            try {
                instance = new PropertyLoader();
            } catch (IOException ioe) {
                LOGGER.error("Error Occurred while creating Property Loader instance: " + ioe.getMessage());
            }
        }
        return instance;
    }

    public String getValue(String key) {
        LOGGER.info("Getting property value for: " + key);
        return properties.getProperty(key);
    }

}
```

Error I am getting:

Exception in thread "main" java.lang.NullPointerException: inStream
  parameter is null     at
  java.base/java.util.Objects.requireNonNull(Objects.java:247)  at
  java.base/java.util.Properties.load(Properties.java:404)  at
  in.net.sudhir.evernote.client.batchjob.PropertyLoader.(PropertyLoader.java:16)
    at
  in.net.sudhir.evernote.client.batchjob.PropertyLoader.getInstance(PropertyLoader.java:23)
    at
  in.net.sudhir.evernote.client.batchjob.EvernoteClient.(EvernoteClient.java:51)
    at
  in.net.sudhir.evernote.client.batchjob.BatchProcess.main(BatchProcess.java:33)

Here is the Screen shot of Project Structure.

Project Structure in IntelliJ IDEA

答:
```<code>properties = new Properties();

try(InputStream inputStream = PropertyLoader.class.getClassLoader().getResourceAsStream("app.properties")) {
    if(inputStream == null)
        throw new FileNotFoundException("File not found in classpath");

    properties.load(inputStream);
}
</code>```

NOTE: It's bad practice to do computations in the constructor. It's better to create some method that load a resource file.

Body:
I was practicing to access properties from property file using a singleton class called PropertyLoader but however my maven project is not able to locate the file in resources and giving null pointer excepiton.

Here is the class code.

import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;

public class PropertyLoader {
    private static PropertyLoader instance = null;
    private Properties properties;
    private final static Logger LOGGER = Logger.getLogger(PropertyLoader.class.getName());

    protected PropertyLoader() throws IOException {
        //TODO: Fix problem with loading properties file below
        properties = new Properties();
        properties.load(PropertyLoader.class.getResourceAsStream("app.properties"));

    }

    public static PropertyLoader getInstance() {
        if(instance == null) {
            try {
                instance = new PropertyLoader();
            } catch (IOException ioe) {
                LOGGER.error("Error Occurred while creating Property Loader instance: " + ioe.getMessage());
            }
        }
        return instance;
    }

    public String getValue(String key) {
        LOGGER.info("Getting property value for: " + key);
        return properties.getProperty(key);
    }

}

Error I am getting:

Exception in thread "main" java.lang.NullPointerException: inStream
  parameter is null     at
  java.base/java.util.Objects.requireNonNull(Objects.java:247)  at
  java.base/java.util.Properties.load(Properties.java:404)  at
  in.net.sudhir.evernote.client.batchjob.PropertyLoader.(PropertyLoader.java:16)
    at
  in.net.sudhir.evernote.client.batchjob.PropertyLoader.getInstance(PropertyLoader.java:23)
    at
  in.net.sudhir.evernote.client.batchjob.EvernoteClient.(EvernoteClient.java:51)
    at
  in.net.sudhir.evernote.client.batchjob.BatchProcess.main(BatchProcess.java:33)

Here is the Screen shot of Project Structure.

Project Structure in IntelliJ IDEA

Body:
properties = new Properties();

try(InputStream inputStream = PropertyLoader.class.getClassLoader().getResourceAsStream("app.properties")) {
    if(inputStream == null)
        throw new FileNotFoundException("File not found in classpath");

    properties.load(inputStream);
}

NOTE: It's bad practice to do computations in the constructor. It's better to create some method that load a resource file.


问:
Linking problem when using jsoncpp library
I have a problem related to the parsing of a JSON file. It is composed of an array of JSON objects and the program I've developed parses this by just iterate over the various { ... } elements found in the file.

The elements (in the JSON file, these are the rows of the file) are structured in such a way that inside each row there can be other inner elements, but this goes beyond the problem I have to handle now.

In short, I have a Block; inside it, I have, in addition to other fields, a vector Operations whose type is Operation, and in this vector, each element can be a subtype of Operation, so e.g., Vote, Comment, Follow, Repost, ...

To handle this, I've created a BlockStructure.hpp file header that includes both the definition of the class Operation together with the (only) virtual method print() and the definition of the classes listed before. In addition to these definitions, there is also the definition of the TransactionBlock, Transaction and BlockStructure

```<code>// BlockStructure.hpp

#include <string>
#include <list>
#include <utility>
#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

using ui = unsigned int;

class Operation{
public:
    string kind = "";
    virtual string print();
};

class Vote : public Operation {
private:
    string voter, author;
public:
    Vote(string voter, string author);
    virtual string print();
    string get_voter();
    string get_author();
};

class Comment : Operation{
private:
    string parent_author, author, title, body;
public:
    Comment(string parent_author, string author, string title, string body);
    string get_author();
    virtual string print();
};

class Follow : Operation{
private:
    string follower, following;
    vector<string> common_follows{};
public:
    CustomJsonFollow(string follower, string following, vector<string> common_follows);
    static void strip(vector<string> *w); // implements the common strip function
    static void stripLeadingAndtrailingSpaces(string *stng); // implements the strip by removing the whitespaces
    string get_follower();
    string get_following();
    vector<string> get_common_follows();
    virtual string print();
};

class Reblog : Operation{
private:
    string account, author;
public:
    CustomJsonReblog(string account, string author);
    string get_account();
    string get_author();
    virtual string print();
};

class TransactionBlock{
private:
    vector<Operation*> operations{};
    string transaction_id;
    int transaction_num = -1;

public:
    TransactionBlock(vector<Operation*> ops);
    TransactionBlock();
    vector<Operation*> get_operations();
    void set_operations(vector<Operation*> ops);
    string get_transaction_id();
    void set_transaction_id(string tid);
    int get_transaction_num();
    void set_transaction_num(int trn);
    string print();
};

class Transaction{
private:
    string transaction_id;
    TransactionBlock transactionBlock;
public:
    Transaction(string tr_id, TransactionBlock  transactionBlock);
    string get_transaction_id();
    void set_transaction_id(string tid);
    TransactionBlock get_transaction_block();
    void set_transaction_block(TransactionBlock tbl);
    void print();
};

class BlockStructure{
private:
    list<Transaction> transactions{};
    string timestamp;
    list<int> transaction_ids;
    TransactionBlock transactionBlock;
public:
    BlockStructure();
    void set_transactions(list<Transaction> transact);
    void set_transaction_block(TransactionBlock transactBlock);
    void set_timestamp(string ts);
    void set_transaction_ids(list<int> tr_ids);
    void set_transaction_block(const TransactionBlock& tb);
    TransactionBlock get_transaction_block();
    void print_block();

};
</code>```

Afterwards, in another file, called BlockStructure.cpp I have the implementation of all the methods defined in the header, so:

```<code>// BlockStructure.cpp

#include "BlockStructure.hpp"

using namespace std;

using ui = unsigned int;

// Operation

string Operation::print(){
    return "";
}

// Vote

Vote::Vote(string voter, string author) : voter(move(voter)), author(move(author)) { this->kind = "VOTE"; }

string Vote::print(){
    string toret = "V\n";
    toret += "voter: " + this->voter + "\n";
    toret += "auth: " + this->author + "\n";
    return toret;
}

string Vote::get_voter(){
    return this->voter;
}

string Vote::get_author(){
    return this->author;
}

// Comment

Comment::Comment(string parent_author, string author, string title, string body){
    this->parent_author = move(parent_author);
    this->author = move(author);
    this->title = move(title);
    this->body = move(body);
    this->kind = "COMMENT";
}

string Comment::get_author(){
    return this->author;
}

string Comment::print(){
    string toret = "C\n";
    toret += "par_auth: " + this->parent_author + "\n";
    toret += "auth: " + this->author + "\n";
    toret += "title: " + this->title + "\n";
    toret += "body: " + this->body + "\n";
    return toret;
}

// Follow

void Follow::strip(vector<string> *w) {
    auto it = w->begin();
    for (ui i = 0; i < w->size(); i++) {
        stripLeadingAndtrailingSpaces(&(*it));
        advance(it, 1);
    }
}

void Follow::stripLeadingAndtrailingSpaces(string *stng) {
    char *cur = const_cast<char *>(stng->c_str());
    /* First remove leading spaces */
    const char *firstNonSpace = cur;
    while (*firstNonSpace != '\0' && isspace(*firstNonSpace))
        ++firstNonSpace;
    size_t len = strlen(firstNonSpace) + 1;
    memmove(cur, firstNonSpace, len);
    /* Now remove trailing spaces */
    char *endOfString = cur + len;
    while (cur < endOfString && isspace(*endOfString))
        --endOfString;
    *endOfString = '\0';
}

Follow::Follow(string follower, string following, vector<string> common_follows, vector<string> required_posting_auths) {
    this->follower = move(follower);
    stripLeadingAndtrailingSpaces(&this->follower);
    this->following = move(following);
    stripLeadingAndtrailingSpaces(&this->following);
    this->common_follows = move(common_follows);
    strip(&this->common_follows);
    this->kind = "FOLLOW";
}

string Follow::get_follower() {
    return this->follower;
}

string Follow::get_following(){
    return this->following;
}

vector<string> Follow::get_common_follows(){
    return this->common_follows;
}

string Follow::print(){
    string toret = "F\n";
    toret += "follower: " + this->follower + "\n";
    toret += "following: " + this->following + "\n";
    if (!this->common_follows.empty()){
        toret += "common_follows: \n";
        for (const string& w : this->common_follows)
            toret += w + "\n";
    } else
        toret += "common_follows: []\n";
    return toret;
}

// Reblog

Reblog::Reblog(string account, string author){
    this->account = move(account);
    this->author = move(author);
    this->kind = "REBLOG";
}

string Reblog::get_account(){
    return this->account;
}

string Reblog::get_author(){
    return this->author;
}

string Reblog::print(){
    string toret = "RB\n";
    toret += "account: " + this->account + "\n";
    toret += "author: " + this->author + "\n";
    return toret;
}

</code>```

(and similarly for the TransactionBlock, Transaction and BlockStructure)

Then, I include BlockStructure.hpp inside the file ParsingBlocks.cpp defined in the following. The

```<code>"jsoncpp/dist/json/json.h"
"jsoncpp/dist/jsoncpp.cpp"
</code>```

files that I include in the beginning are the result of the python amalgamate.py script (this script generates also the jsoncpp/dist/json/json-forward.h, but I have read that it is not commonly used for the projects). I read that it is an approach to integrating JsonCpp in the project.

```<code>#include <fstream>
#include "jsoncpp/dist/json/json.h"
#include "jsoncpp/dist/jsoncpp.cpp"

#include "BlockStructure.hpp"

class ParsingBlocks {
private:
    string path;

public:
    ParsingBlocks(string path) : path(move(path)) {}

    vector<Operation*> fill_ops(const Value& trans_operations){
        vector<Operation*> op_array = {};
        for(Value op : trans_operations) {
            if (op[(UInt) 0].asString() == "vote") {
                string voter = op[1]["voter"].asString();
                Vote vt = Vote(op[1]["voter"].asString(), op[1]["author"].asString());
                op_array.push_back((Operation*)&vt);
            } else if (op[(UInt) 0].asString() == "comment") {
                Comment cmt = Comment(op[1]["parent_author"].asString(),
                                      op[1]["author"].asString(),
                                      op[1]["title"].asString(),
                                      op[1]["body"].asString());
                op_array.push_back((Operation*)&cmt);
            } else if (op[(UInt) 0].asString() == "custom_json") {
                auto custom = op[(UInt) 1];
                if (custom["id"].asString() == "follow") {
                    Value injs = custom["id"];
                    if (injs[(UInt) 0].asString() == "follow") {
                        vector<string> common_follows = {};
                        for (const auto &itr : injs[(UInt) 1]["common_follows"])
                            common_follows.push_back(itr.asString());
                        CustomJsonFollow follow = CustomJsonFollow(
                                injs[1]["follower"].asCString(),
                                injs[1]["following"].asCString(),
                                common_follows);
                        op_array.push_back((Operation*)&follow);
                    } else {
                        if (injs[(UInt) 0].asString() == "reblog") {
                            CustomJsonReblog reblog = CustomJsonReblog(
                                    injs[(UInt) 1]["account"].asCString(),
                                    injs[(UInt) 1]["author"].asCString());
                            op_array.push_back((Operation*)&reblog);
                        }
                    }
                }
            }
        }
    return op_array;

    BlockStructure evaluate_block(const string& line){
        ifstream ifs(line);
        CharReaderBuilder reader;
        Value data;
        string errs;

        Json::parseFromStream(reader, ifs, &data, &errs);
        BlockStructure bs = BlockStructure();

        for(Value::ArrayIndex i = 0; i != data.size(); i++){
            bs.set_timestamp(data[i]["timestamp"].asString());
            list<Transaction> transss{};
            for(const Value& transaction : data[i]["transactions"]){
                vector<Operation*> operations = fill_ops(transaction["operations"]);
                auto t_block = new TransactionBlock();
                t_block->set_transaction_num(transaction["transaction_num"].asInt());
                if (!operations.empty()){
                    t_block->set_operations(operations);
                }
                Transaction t = Transaction(transaction["transaction_id"].asString(), *t_block);
                transss.push_back(t);
            }
            bs.set_transactions(transss);
            bs.set_witness_name(data[i]["witness"].asString());
        }
        return bs;
    }

    list<BlockStructure> parsing_blocks(){
        string line;
        ifstream file;
        file.open(this->path);
        list<BlockStructure> blocks{};

        if(!file.is_open()){
            perror("Error open");
            exit(EXIT_FAILURE);
        }
        while (getline(file, line)){
            BlockStructure b = evaluate_block(line);
            blocks.push_back(b);
        }
        return blocks;
    }

}

</code>```

Leaving aside possible copy-and-paste errors (which I don't think I've done), now, I use the ParsingBlocks.cpp into the main.cpp defined as follows:

```<code>#include "ParsingBlocks.cpp"

using namespace std;

int main() {
    ParsingBlocks *pb = new ParsingBlocks("jsonfile.json");
    list<BlockStructure> blocks = pb->parsing_blocks();
    for(BlockStructure bl : blocks){
        bl.print_block();
    }
    return 0;
}
</code>```

I don't show another class (UserStructure.cpp) used in the compilation because it is useless for the purposes of the question.

My problem now is to understand how to compile the main.cpp file.

I'm relying on the jsoncpp external library so, at compile time I execute from command line the following:

c++ -std=c++17 -Wall -pedantic -I.  .\UserStructure.cpp .\BlockStructure.hpp .\BlockStructure.cpp .\ParsingBlocks.cpp .\main.cpp -o parsing.out

where the -I. flag is used to link in the current directory, the jsoncpp.cpp and json/json.h defined in the #includes at the beginning of the ParsingBlock.cpp file, as shown before.

The compilation gives me the following errors:

```<code>C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2b6): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x2e0): multiple definition of `Json::Features::all()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2e0): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x2fe): multiple definition of `Json::Features::strictMode()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2fe): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x32c): multiple definition of `Json::Reader::containsNewLine(char const*, char const*)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x32c): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x36e): multiple definition of `Json::Reader::Reader()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x36e): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x36e): multiple definition of `Json::Reader::Reader()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x36e): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x44a): multiple definition of `Json::Reader::Reader(Json::Features const&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x44a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x44a): multiple definition of `Json::Reader::Reader(Json::Features const&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x44a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x52a): multiple definition of `Json::Reader::parse(std::__cxx11::basic_string<char,
std::char_traits<char>, std::allocator<char> > const&, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x52a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x5de): multiple definition of `Json::Reader::parse(std::istream&, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x5de): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x698): multiple definition of `Json::Reader::parse(char const*, char const*, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x698): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x934): multiple definition of `Json::Reader::readValue()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x934): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1032): multiple definition of `Json::Reader::skipCommentTokens(Json::Reader::Token&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1032): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1086): multiple definition of `Json::Reader::readToken(Json::Reader::Token&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1086): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1246): multiple definition of `Json::Reader::skipSpaces()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1246): first defined here
</code>```

So, it should be evident that the problem is in the linking phase, but I cannot solve it!

I have tried by reading both the documentation and other questions on stackoverflow.com, but I get nowhere.

Thanks in advance for the help, and I'm sorry if this question is a little bit huge.

EDIT: The stderr output does not stop there: there are at least 1000 lines of error, but each one of these regards the same multiple definition of ..., C:...: first defined here.

答:
You keep #includeing source files ("ParsingBlocks.cpp" and "jsoncpp/dist/jsoncpp.cpp").

Don't do that.

It results in the definitions existing multiple times across your final program.

Your main.cpp should #include "ParsingBlocks.h" so that it has access to the declarations of things.

And you should compile and link jsoncpp/dist/jsoncpp.cpp into your executable in your build tool, just like your other cpp files:

```<code>c++ -std=c++17 -Wall -pedantic -I. \
  UserStructure.cpp \
  BlockStructure.cpp \
  ParsingBlocks.cpp \
  main.cpp \
  jsoncpp/dist/jsoncpp.cpp \
  -o parsing.out
</code>```

The backslashed-newlines are for clarity so we can more easily read the command.

Notice that I also removed your attempt to link in header files.

Refer to your C++ book for more information on how to build programs.

Body:
I have a problem related to the parsing of a JSON file. It is composed of an array of JSON objects and the program I've developed parses this by just iterate over the various { ... } elements found in the file.

The elements (in the JSON file, these are the rows of the file) are structured in such a way that inside each row there can be other inner elements, but this goes beyond the problem I have to handle now.

In short, I have a Block; inside it, I have, in addition to other fields, a vector Operations whose type is Operation, and in this vector, each element can be a subtype of Operation, so e.g., Vote, Comment, Follow, Repost, ...

To handle this, I've created a BlockStructure.hpp file header that includes both the definition of the class Operation together with the (only) virtual method print() and the definition of the classes listed before. In addition to these definitions, there is also the definition of the TransactionBlock, Transaction and BlockStructure

// BlockStructure.hpp

#include <string>
#include <list>
#include <utility>
#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

using ui = unsigned int;

class Operation{
public:
    string kind = "";
    virtual string print();
};

class Vote : public Operation {
private:
    string voter, author;
public:
    Vote(string voter, string author);
    virtual string print();
    string get_voter();
    string get_author();
};

class Comment : Operation{
private:
    string parent_author, author, title, body;
public:
    Comment(string parent_author, string author, string title, string body);
    string get_author();
    virtual string print();
};

class Follow : Operation{
private:
    string follower, following;
    vector<string> common_follows{};
public:
    CustomJsonFollow(string follower, string following, vector<string> common_follows);
    static void strip(vector<string> *w); // implements the common strip function
    static void stripLeadingAndtrailingSpaces(string *stng); // implements the strip by removing the whitespaces
    string get_follower();
    string get_following();
    vector<string> get_common_follows();
    virtual string print();
};

class Reblog : Operation{
private:
    string account, author;
public:
    CustomJsonReblog(string account, string author);
    string get_account();
    string get_author();
    virtual string print();
};

class TransactionBlock{
private:
    vector<Operation*> operations{};
    string transaction_id;
    int transaction_num = -1;

public:
    TransactionBlock(vector<Operation*> ops);
    TransactionBlock();
    vector<Operation*> get_operations();
    void set_operations(vector<Operation*> ops);
    string get_transaction_id();
    void set_transaction_id(string tid);
    int get_transaction_num();
    void set_transaction_num(int trn);
    string print();
};

class Transaction{
private:
    string transaction_id;
    TransactionBlock transactionBlock;
public:
    Transaction(string tr_id, TransactionBlock  transactionBlock);
    string get_transaction_id();
    void set_transaction_id(string tid);
    TransactionBlock get_transaction_block();
    void set_transaction_block(TransactionBlock tbl);
    void print();
};

class BlockStructure{
private:
    list<Transaction> transactions{};
    string timestamp;
    list<int> transaction_ids;
    TransactionBlock transactionBlock;
public:
    BlockStructure();
    void set_transactions(list<Transaction> transact);
    void set_transaction_block(TransactionBlock transactBlock);
    void set_timestamp(string ts);
    void set_transaction_ids(list<int> tr_ids);
    void set_transaction_block(const TransactionBlock& tb);
    TransactionBlock get_transaction_block();
    void print_block();

};

Afterwards, in another file, called BlockStructure.cpp I have the implementation of all the methods defined in the header, so:

// BlockStructure.cpp

#include "BlockStructure.hpp"

using namespace std;

using ui = unsigned int;

// Operation

string Operation::print(){
    return "";
}

// Vote

Vote::Vote(string voter, string author) : voter(move(voter)), author(move(author)) { this->kind = "VOTE"; }

string Vote::print(){
    string toret = "V\n";
    toret += "voter: " + this->voter + "\n";
    toret += "auth: " + this->author + "\n";
    return toret;
}

string Vote::get_voter(){
    return this->voter;
}

string Vote::get_author(){
    return this->author;
}

// Comment

Comment::Comment(string parent_author, string author, string title, string body){
    this->parent_author = move(parent_author);
    this->author = move(author);
    this->title = move(title);
    this->body = move(body);
    this->kind = "COMMENT";
}

string Comment::get_author(){
    return this->author;
}

string Comment::print(){
    string toret = "C\n";
    toret += "par_auth: " + this->parent_author + "\n";
    toret += "auth: " + this->author + "\n";
    toret += "title: " + this->title + "\n";
    toret += "body: " + this->body + "\n";
    return toret;
}

// Follow

void Follow::strip(vector<string> *w) {
    auto it = w->begin();
    for (ui i = 0; i < w->size(); i++) {
        stripLeadingAndtrailingSpaces(&(*it));
        advance(it, 1);
    }
}

void Follow::stripLeadingAndtrailingSpaces(string *stng) {
    char *cur = const_cast<char *>(stng->c_str());
    /* First remove leading spaces */
    const char *firstNonSpace = cur;
    while (*firstNonSpace != '\0' && isspace(*firstNonSpace))
        ++firstNonSpace;
    size_t len = strlen(firstNonSpace) + 1;
    memmove(cur, firstNonSpace, len);
    /* Now remove trailing spaces */
    char *endOfString = cur + len;
    while (cur < endOfString && isspace(*endOfString))
        --endOfString;
    *endOfString = '\0';
}

Follow::Follow(string follower, string following, vector<string> common_follows, vector<string> required_posting_auths) {
    this->follower = move(follower);
    stripLeadingAndtrailingSpaces(&this->follower);
    this->following = move(following);
    stripLeadingAndtrailingSpaces(&this->following);
    this->common_follows = move(common_follows);
    strip(&this->common_follows);
    this->kind = "FOLLOW";
}

string Follow::get_follower() {
    return this->follower;
}

string Follow::get_following(){
    return this->following;
}

vector<string> Follow::get_common_follows(){
    return this->common_follows;
}

string Follow::print(){
    string toret = "F\n";
    toret += "follower: " + this->follower + "\n";
    toret += "following: " + this->following + "\n";
    if (!this->common_follows.empty()){
        toret += "common_follows: \n";
        for (const string& w : this->common_follows)
            toret += w + "\n";
    } else
        toret += "common_follows: []\n";
    return toret;
}

// Reblog

Reblog::Reblog(string account, string author){
    this->account = move(account);
    this->author = move(author);
    this->kind = "REBLOG";
}

string Reblog::get_account(){
    return this->account;
}

string Reblog::get_author(){
    return this->author;
}

string Reblog::print(){
    string toret = "RB\n";
    toret += "account: " + this->account + "\n";
    toret += "author: " + this->author + "\n";
    return toret;
}

(and similarly for the TransactionBlock, Transaction and BlockStructure)

Then, I include BlockStructure.hpp inside the file ParsingBlocks.cpp defined in the following. The

"jsoncpp/dist/json/json.h"
"jsoncpp/dist/jsoncpp.cpp"

files that I include in the beginning are the result of the python amalgamate.py script (this script generates also the jsoncpp/dist/json/json-forward.h, but I have read that it is not commonly used for the projects). I read that it is an approach to integrating JsonCpp in the project.

#include <fstream>
#include "jsoncpp/dist/json/json.h"
#include "jsoncpp/dist/jsoncpp.cpp"

#include "BlockStructure.hpp"

class ParsingBlocks {
private:
    string path;

public:
    ParsingBlocks(string path) : path(move(path)) {}

    vector<Operation*> fill_ops(const Value& trans_operations){
        vector<Operation*> op_array = {};
        for(Value op : trans_operations) {
            if (op[(UInt) 0].asString() == "vote") {
                string voter = op[1]["voter"].asString();
                Vote vt = Vote(op[1]["voter"].asString(), op[1]["author"].asString());
                op_array.push_back((Operation*)&vt);
            } else if (op[(UInt) 0].asString() == "comment") {
                Comment cmt = Comment(op[1]["parent_author"].asString(),
                                      op[1]["author"].asString(),
                                      op[1]["title"].asString(),
                                      op[1]["body"].asString());
                op_array.push_back((Operation*)&cmt);
            } else if (op[(UInt) 0].asString() == "custom_json") {
                auto custom = op[(UInt) 1];
                if (custom["id"].asString() == "follow") {
                    Value injs = custom["id"];
                    if (injs[(UInt) 0].asString() == "follow") {
                        vector<string> common_follows = {};
                        for (const auto &itr : injs[(UInt) 1]["common_follows"])
                            common_follows.push_back(itr.asString());
                        CustomJsonFollow follow = CustomJsonFollow(
                                injs[1]["follower"].asCString(),
                                injs[1]["following"].asCString(),
                                common_follows);
                        op_array.push_back((Operation*)&follow);
                    } else {
                        if (injs[(UInt) 0].asString() == "reblog") {
                            CustomJsonReblog reblog = CustomJsonReblog(
                                    injs[(UInt) 1]["account"].asCString(),
                                    injs[(UInt) 1]["author"].asCString());
                            op_array.push_back((Operation*)&reblog);
                        }
                    }
                }
            }
        }
    return op_array;

    BlockStructure evaluate_block(const string& line){
        ifstream ifs(line);
        CharReaderBuilder reader;
        Value data;
        string errs;

        Json::parseFromStream(reader, ifs, &data, &errs);
        BlockStructure bs = BlockStructure();

        for(Value::ArrayIndex i = 0; i != data.size(); i++){
            bs.set_timestamp(data[i]["timestamp"].asString());
            list<Transaction> transss{};
            for(const Value& transaction : data[i]["transactions"]){
                vector<Operation*> operations = fill_ops(transaction["operations"]);
                auto t_block = new TransactionBlock();
                t_block->set_transaction_num(transaction["transaction_num"].asInt());
                if (!operations.empty()){
                    t_block->set_operations(operations);
                }
                Transaction t = Transaction(transaction["transaction_id"].asString(), *t_block);
                transss.push_back(t);
            }
            bs.set_transactions(transss);
            bs.set_witness_name(data[i]["witness"].asString());
        }
        return bs;
    }

    list<BlockStructure> parsing_blocks(){
        string line;
        ifstream file;
        file.open(this->path);
        list<BlockStructure> blocks{};

        if(!file.is_open()){
            perror("Error open");
            exit(EXIT_FAILURE);
        }
        while (getline(file, line)){
            BlockStructure b = evaluate_block(line);
            blocks.push_back(b);
        }
        return blocks;
    }

}

Leaving aside possible copy-and-paste errors (which I don't think I've done), now, I use the ParsingBlocks.cpp into the main.cpp defined as follows:

#include "ParsingBlocks.cpp"

using namespace std;

int main() {
    ParsingBlocks *pb = new ParsingBlocks("jsonfile.json");
    list<BlockStructure> blocks = pb->parsing_blocks();
    for(BlockStructure bl : blocks){
        bl.print_block();
    }
    return 0;
}

I don't show another class (UserStructure.cpp) used in the compilation because it is useless for the purposes of the question.

My problem now is to understand how to compile the main.cpp file.

I'm relying on the jsoncpp external library so, at compile time I execute from command line the following:

c++ -std=c++17 -Wall -pedantic -I.  .\UserStructure.cpp .\BlockStructure.hpp .\BlockStructure.cpp .\ParsingBlocks.cpp .\main.cpp -o parsing.out

where the -I. flag is used to link in the current directory, the jsoncpp.cpp and json/json.h defined in the #includes at the beginning of the ParsingBlock.cpp file, as shown before.

The compilation gives me the following errors:

C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2b6): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x2e0): multiple definition of `Json::Features::all()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2e0): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x2fe): multiple definition of `Json::Features::strictMode()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2fe): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x32c): multiple definition of `Json::Reader::containsNewLine(char const*, char const*)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x32c): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x36e): multiple definition of `Json::Reader::Reader()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x36e): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x36e): multiple definition of `Json::Reader::Reader()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x36e): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x44a): multiple definition of `Json::Reader::Reader(Json::Features const&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x44a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x44a): multiple definition of `Json::Reader::Reader(Json::Features const&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x44a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x52a): multiple definition of `Json::Reader::parse(std::__cxx11::basic_string<char,
std::char_traits<char>, std::allocator<char> > const&, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x52a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x5de): multiple definition of `Json::Reader::parse(std::istream&, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x5de): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x698): multiple definition of `Json::Reader::parse(char const*, char const*, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x698): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x934): multiple definition of `Json::Reader::readValue()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x934): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1032): multiple definition of `Json::Reader::skipCommentTokens(Json::Reader::Token&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1032): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1086): multiple definition of `Json::Reader::readToken(Json::Reader::Token&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1086): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1246): multiple definition of `Json::Reader::skipSpaces()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1246): first defined here

So, it should be evident that the problem is in the linking phase, but I cannot solve it!

I have tried by reading both the documentation and other questions on stackoverflow.com, but I get nowhere.

Thanks in advance for the help, and I'm sorry if this question is a little bit huge.

EDIT: The stderr output does not stop there: there are at least 1000 lines of error, but each one of these regards the same multiple definition of ..., C:...: first defined here.

Body:
You keep #includeing source files ("ParsingBlocks.cpp" and "jsoncpp/dist/jsoncpp.cpp").

Don't do that.

It results in the definitions existing multiple times across your final program.

Your main.cpp should #include "ParsingBlocks.h" so that it has access to the declarations of things.

And you should compile and link jsoncpp/dist/jsoncpp.cpp into your executable in your build tool, just like your other cpp files:

c++ -std=c++17 -Wall -pedantic -I. \
  UserStructure.cpp \
  BlockStructure.cpp \
  ParsingBlocks.cpp \
  main.cpp \
  jsoncpp/dist/jsoncpp.cpp \
  -o parsing.out

The backslashed-newlines are for clarity so we can more easily read the command.

Notice that I also removed your attempt to link in header files.

Refer to your C++ book for more information on how to build programs.


问:
How to clear a form?
For example I have a form like this:

```<code><form method='post' action='someaction.php' name='myform'>

<input type='text' name='text1'>
<input type='text' name='text2'>

<input type='checkbox' name="check1">Check Me

<textarea rows="2" cols="20" name='textarea1'></textarea>

<select name='select1'>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<input type='reset' value='Reset' name='reset'>
<input type='submit' value='Submit' name='submit'>

</form>
</code>```

When I press Reset it empties all fields. But if I populate some fields using URL params and then press Reset, it only empties fields which I enter after form reload.

How can I empty all fields whether some fields are already populated at the time of form load.

答:
You will have to clear them all through javascript (or clear it out server side).

The reset button will only reset form elements to their initial value - if this was a specific value, that's what it will be reset to.

ContentLicense: CC BY-SA 3.0

Title: How to clear a form?

Body:
For example I have a form like this:

<form method='post' action='someaction.php' name='myform'>

<input type='text' name='text1'>
<input type='text' name='text2'>

<input type='checkbox' name="check1">Check Me

<textarea rows="2" cols="20" name='textarea1'></textarea>

<select name='select1'>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<input type='reset' value='Reset' name='reset'>
<input type='submit' value='Submit' name='submit'>

</form>

When I press Reset it empties all fields. But if I populate some fields using URL params and then press Reset, it only empties fields which I enter after form reload.

How can I empty all fields whether some fields are already populated at the time of form load.


问:
Prestashop buy via email
i want to ask. Is it possible to disable all payment method's and buy product via email? I mean when user click buy in cart page, he need to enter email and confirm order without payment and then admin get notification about order?</p>

答:
Yes, this is possible with the development of a custom payment module.

Regards

Title: Prestashop buy via email


问:
How to specify click callback?
I have interface that describes a button:

```<code>export interface IButtonConfig {
  text: string,
  class: string,
  click?: any
}
</code>```

I need to set click property as callback to use it like this:

```<code>click(cb) {
  cb();
}
 click(data => {
     // get Callback result here
})
</code>```

How to to that?

答:
You have two different signatures in your second lot of code (the example usage).

One looks like:

```<code>export interface IButtonConfig {
  text: string,
  class: string,
  click?:(data: any) => void
}
</code>```

The other looks like:

```<code>export interface IButtonConfig {
  text: string,
  class: string,
  click?:() => void
}
</code>```

It looks like you want to do this?

```<code>const click = (cb: () => any) => (data: any) => {
  const callbackResult = cb()
  ... do something with data and the result of the callback
})
</code>```

This allows you to bind a function in to the click handler (I think that's what it is?), so that when the click event handler ((data: any) => void) is called, the first callback is executed and the result of that callback is available with the click event data in the handler function.

Is that what you are trying to achieve?

If so, the signature is:

```<code>export interface IButtonConfig {
  text: string,
  class: string,
  click?: (cb: () => any) => (data: any) => void
}
</code>```

Title: How to specify click callback?

Body:
I have interface that describes a button:

export interface IButtonConfig {
  text: string,
  class: string,
  click?: any
}

I need to set click property as callback to use it like this:

click(cb) {
  cb();
}
 click(data => {
     // get Callback result here
})

How to to that?

Body:
You have two different signatures in your second lot of code (the example usage).

One looks like:

export interface IButtonConfig {
  text: string,
  class: string,
  click?:(data: any) => void
}

The other looks like:

export interface IButtonConfig {
  text: string,
  class: string,
  click?:() => void
}

It looks like you want to do this?

const click = (cb: () => any) => (data: any) => {
  const callbackResult = cb()
  ... do something with data and the result of the callback
})

This allows you to bind a function in to the click handler (I think that's what it is?), so that when the click event handler ((data: any) => void) is called, the first callback is executed and the result of that callback is available with the click event data in the handler function.

Is that what you are trying to achieve?

If so, the signature is:

export interface IButtonConfig {
  text: string,
  class: string,
  click?: (cb: () => any) => (data: any) => void
}


问:
Helpers from twitter-login gem in User model
I'm using twitter-login in my Rails app. It's a Rack app that gets mounted in routes.rb.

It provides a helper method called twitter_client which is an instance of OAuth::AccessToken. With OAuth::AccessToken, I can make calls to the Twitter api:

```<code>twitter_client.post('/statuses/update.xml', {'status' => 'test test test', 'Accept' => 'application/xml'})
</code>```

I'm trying to tie this into a method in my User model, but run into an error because the session is not available inside the model class.

What's a good way to wrap OAuth::AccessToken#post into User#tweet_something?

答:
All you need to be able to interact with twitter is the access token.

The simplest way would be to add two columns to the users table: access_token_key and access_token_secret and update them when User logs in with Twitter (in a before_filter). The access token is stored by twitter-login in session: https://github.com/mislav/twitter-login/blob/master/lib/twitter/login.rb#L141

If you have the access token in the user model, then you can OAuth::Consumer and OAuth::AccessToken the same way twitter-login does it, but without the need for the session: https://github.com/mislav/twitter-login/blob/master/lib/twitter/login.rb#L49.

This way you can interact with Twitter on behalf of your user not only from withing controllers, but also withing background jobs, rake tasks and whatnot.

Body:
I'm using twitter-login in my Rails app. It's a Rack app that gets mounted in routes.rb.

It provides a helper method called twitter_client which is an instance of OAuth::AccessToken. With OAuth::AccessToken, I can make calls to the Twitter api:

twitter_client.post('/statuses/update.xml', {'status' => 'test test test', 'Accept' => 'application/xml'})

I'm trying to tie this into a method in my User model, but run into an error because the session is not available inside the model class.

What's a good way to wrap OAuth::AccessToken#post into User#tweet_something?


问:
Google maps - Query to geocode returns incorrect results
Searching for '31708' returns results with the right postal_code

https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/utils/geocoder/#q%3D31707

Searching for '31707' returns results in a different postal_code

https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/utils/geocoder/#q%3D31708

How do I fix this?

答:
add "zipcode" to the query (if you know it is going to be a zipcode).

https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/utils/geocoder/#q%3Dzipcode+31707


问:
Appending empty dataframe with for loop over CSV files
I am dealing with time series data saved in CSV files in a directory. Each CSV file is a day's worth of random data and the file is named accordingly to the month & day of the data it contains.

For SO purposes we can generate some random data:

```<code>import pandas as pd
import numpy as np
from numpy.random import randint
import os

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)
</code>```

With a folder named csv in the root directory, create some CSV files representing each day:

```<code># create csv's
for date in set(df.index.date):

    # filter dataframe
    filtered_df = df.loc[df.index.date == date].copy()

    # save it
    filename = date.strftime('%m_%d')  # filename represented as 'month_day'
    filtered_df.to_csv(f"./csv/{filename}.csv")
</code>```

Question, how do I create an empty pandas df and a program that can loop over all CSV files and append dataset min, max, median summary statistics? (Code below doesnt work)

```<code>path = './csv/'
filelist = os.listdir(path)

frame = pd.DataFrame(columns=['Date','max', 'min', 'median'])
for file in filelist:
    df2 = pd.read_csv(path+file)
    date_name = date.strftime('%m_%d')
    df2['Date'] = date_name

    frame.append({'Date': date_name, 'max': df2['Random_Number'].max(), 'min': df2['Random_Number'].min(), 'median': df2['Random_Number'].median()})
</code>```

答:
Use concat() and create an empty DataFrame object before the for loop.

```<code>path = './csv/'
filelist = os.listdir(path)

frame = pd.DataFrame() # don't supply anything
for file in filelist:
    df2 = pd.read_csv(path+file)
    date_name = date.strftime('%m_%d')
    df2['Date'] = date_name

    frame = pd.concat([frame, pd.DataFrame({'Date': [date_name], 'max': [df2['Random_Number'].max()], 'min': [df2['Random_Number'].min()], 'median': [df2['Random_Number'].median()]})])
</code>```

However this approach isn't very efficient. A better approach would be to create a dict and then a dataframe at the end

```<code>frame_dict = {'date': [], 'max': [], 'min': [], 'median': []}
for file in filelist:
    df2 = pd.read_csv(path+file)
    date_name = date.strftime('%m_%d')
    df2['Date'] = date_name

    frame_dict['date'].append(date_name)
    frame_dict['min'].append(df2['Random_Number'].min())
    frame_dict['max'].append(df2['Random_Number'].max())
    frame_dict['median'].append(df2['Random_Number'].median())

frame = pd.DataFrame(frame_dict)
</code>```

Body:
I am dealing with time series data saved in CSV files in a directory. Each CSV file is a day's worth of random data and the file is named accordingly to the month & day of the data it contains.

For SO purposes we can generate some random data:

import pandas as pd
import numpy as np
from numpy.random import randint
import os

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)

With a folder named csv in the root directory, create some CSV files representing each day:

# create csv's
for date in set(df.index.date):

    # filter dataframe
    filtered_df = df.loc[df.index.date == date].copy()

    # save it
    filename = date.strftime('%m_%d')  # filename represented as 'month_day'
    filtered_df.to_csv(f"./csv/{filename}.csv")

Question, how do I create an empty pandas df and a program that can loop over all CSV files and append dataset min, max, median summary statistics? (Code below doesnt work)

path = './csv/'
filelist = os.listdir(path)

frame = pd.DataFrame(columns=['Date','max', 'min', 'median'])
for file in filelist:
    df2 = pd.read_csv(path+file)
    date_name = date.strftime('%m_%d')
    df2['Date'] = date_name

    frame.append({'Date': date_name, 'max': df2['Random_Number'].max(), 'min': df2['Random_Number'].min(), 'median': df2['Random_Number'].median()})

Body:
Use concat() and create an empty DataFrame object before the for loop.

path = './csv/'
filelist = os.listdir(path)

frame = pd.DataFrame() # don't supply anything
for file in filelist:
    df2 = pd.read_csv(path+file)
    date_name = date.strftime('%m_%d')
    df2['Date'] = date_name

    frame = pd.concat([frame, pd.DataFrame({'Date': [date_name], 'max': [df2['Random_Number'].max()], 'min': [df2['Random_Number'].min()], 'median': [df2['Random_Number'].median()]})])

However this approach isn't very efficient. A better approach would be to create a dict and then a dataframe at the end

frame_dict = {'date': [], 'max': [], 'min': [], 'median': []}
for file in filelist:
    df2 = pd.read_csv(path+file)
    date_name = date.strftime('%m_%d')
    df2['Date'] = date_name

    frame_dict['date'].append(date_name)
    frame_dict['min'].append(df2['Random_Number'].min())
    frame_dict['max'].append(df2['Random_Number'].max())
    frame_dict['median'].append(df2['Random_Number'].median())

frame = pd.DataFrame(frame_dict)


问:
Make GitHub's README look different on smartphones and desktops using only HTML (CSS is restricted)
I have a GitHub project with README.md file. I embed an image in the following way

```<code><img src="./logo.svg" align="right" width="180px">
</code>```

Here is an example of such an image.

Note: GitHub allows using embedded HTML but not CSS, that's why I am using width property instead of css.

This way the image occupies the right side of the screen allowing to put text on the left side.

Problem: If you open such link on a smartphone there is too less space for the text and it looks bad with split words or letters that take the whole line. It would be great if I could use larger width specifically for mobile devices. But GitHub restricts usage of CSS in markdown files and I can't use @media queries.

Question: How to make GitHub's README look different on mobile and desktop without using CSS?

答:
udacity/responsive-images is:

a GitHub page project, visible at udacity.github.io/responsive-images/

with a page dedicated to responsive images, with examples.

For instance: "Two images, 50% width with margin", seen in examples/1-07/twoImages50pcWithMargin

Check in their viewport directives would be enough to implement a responsive image, combine with their inline CSS style.

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
</code>```

Body:
I have a GitHub project with README.md file. I embed an image in the following way

Here is an example of such an image.

Note: GitHub allows using embedded HTML but not CSS, that's why I am using width property instead of css.

This way the image occupies the right side of the screen allowing to put text on the left side.

Problem: If you open such link on a smartphone there is too less space for the text and it looks bad with split words or letters that take the whole line. It would be great if I could use larger width specifically for mobile devices. But GitHub restricts usage of CSS in markdown files and I can't use @media queries.

Question: How to make GitHub's README look different on mobile and desktop without using CSS?

Body:
udacity/responsive-images is:

a GitHub page project, visible at udacity.github.io/responsive-images/

with a page dedicated to responsive images, with examples.

For instance: "Two images, 50% width with margin", seen in examples/1-07/twoImages50pcWithMargin

Check in their viewport directives would be enough to implement a responsive image, combine with their inline CSS style.

<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">


问:
Excel formula, add leading 0 after the dash (-) but before the numbers
I have data that looks like: D-8, FE-09, I-18, P-1 in a range.

I would want all the numbers from 1 to 9 to have a 0 before them. The previous sequence would then be

D-08, FE-09, I-18, P-01

Is there any way to do this with formulas or as a last resort with a macro? I can do this with formulas but it's long since I'm doing it step by step; separating the letters from the numbers in 2 columns, adding the leading 0, putting them back together.

Body:
With TEXTJOIN:

=TEXTJOIN(", ",,FILTERXML("<a><b>"&SUBSTITUTE(SUBSTITUTE(A1,",","</b><b>"),"-","</b><b>")&"</b></a>","//b["&(ROW($ZZ$1:INDEX($ZZ:$ZZ,LEN(A1)-LEN(SUBSTITUTE(A1,",",""))+1))-1)*2+1&"]")&"-"&TEXT(FILTERXML("<a><b>"&SUBSTITUTE(SUBSTITUTE(A1,",","</b><b>"),"-","</b><b>")&"</b></a>","//b["&(ROW($ZZ$1:INDEX($ZZ:$ZZ,LEN(A1)-LEN(SUBSTITUTE(A1,",",""))+1))-1)*2+2&"]"),"00"))

Per your comments, having only one value in a per cell:

=LEFT(A1,FIND("-",A1))&TEXT(MID(A1,FIND("-",A1)+1,2),"00")


问:
VNC to MAC but MAC is sleeping
I assume my my MAC is sleeping if I try and connect with VNC is hangs.  If I happen to be at the MAC console I can move the mouse or keyboard and then the VNC works. Is there a way to trigger a wake up or disable sleeping from the console?</p>

答:
Sounds like you need to enable WOL (Wakeup On Lan) in OSX, see the following for a detailed explanation of what's involved and how to do it.

http://lifehacker.com/348197/access-your-computer-anytime-and-save-energy-with-wake+on+lan

Title: VNC to MAC but MAC is sleeping


问:
Visual studio 2019: Enabling "Use Managed Compatibility Mode" leads to `Access Denied` in remote debugging
I started to use remote debugging for checking my web-service behavior which developed in ASP.NET (not MVC not .net core) but during debug process value of variables what not shown and watch was not working.

Many answers such as [1],[2] suggested to enable Use Managed Compatibility Mode. I did this but after this change I cannot connect to remote process anymore due to error: Unable to attach to the process. Access is denied.
I should disable Use Managed Compatibility Mode to be able to attach to remote process again.

I don't know how to fix this although there are many suggestions such as Running as administrator and etc but they did not work.
Details:
MY IDE: VS 2019 Version 16.2.0 in windows 10x64
IIS Server runs on Windows 7x64
Both VS2019 and Remote Debugger ran as administrator.

答:
I am not sure this will help but I will give my 2 cents here.

first make sure you have passed test settings

once it is done, right click on the website in IIS -> Manage Website -> then browse this will create new instance in the processes(in case the instance was the issue).

now go ahead and attach the process for w3wp.exe, it should allow you to attach the process.

a couple threads I found may help you

https://social.technet.microsoft.com/Forums/en-US/51f55fd6-bed7-412d-b410-d0ad4113f533/cannot-attach-debugger-to-miiserverexe?forum=identitylifecyclemanager

https://learn.microsoft.com/en-us/visualstudio/debugger/unable-to-attach-to-the-process?view=vs-2019


答:
You could use a UNION  in sql  </p>

```<code>select 1 id, amount_1, amount_2, amount_3
from my_table
where user_id = 1
union
select 2  , sum(amount_1) , sum(amount_2), sum(amount_3 )
from my_table
where user_id <> 1
</code>```

Title: SQL query to return combined data of all rows that don't belong to current user

Body:
Imagine this is my table:

----------------------------------------------------
| id | user_id    | amount_1 | amount_2 | amount_3 |
----------------------------------------------------
| 1  | 1          | 2        | 3        | 4        |
----------------------------------------------------
| 2  | 2          | 2        | 1        | 1        |
----------------------------------------------------
| 3  | 2          | 1        | 2        | 2        |
----------------------------------------------------
| 4  | 3          | 2        | 1        | 4        |
----------------------------------------------------

I need a query that gives me one result set for every entry that belongs to my current user, and then returns everything else as a single combined row with the amounts summed.

So in this case if I am user 1, I should get the following rows back:

---------------------------------------
| id | amount_1 | amount_2 | amount_3 |
---------------------------------------
| 1  | 2        | 3        | 4        |   my own amounts
---------------------------------------
| 2  | 5        | 4        | 7        |   everyone else's amounts
---------------------------------------

Any tips?

I've considered it might be a better idea to just filter the data in the code (php). Please help i'm starting to hate myself

Body:
You could use a UNION  in sql

select 1 id, amount_1, amount_2, amount_3
from my_table
where user_id = 1
union
select 2  , sum(amount_1) , sum(amount_2), sum(amount_3 )
from my_table
where user_id <> 1


问:
Print option for each item in array
I have an array and for each item in the array, I'm trying to add in a new <option>.

To do so, I've tried the following:

```<code> array.forEach(function(arr) {
   console.log(array);
   $(".filterSection .department").append('<option value="'+array+'">'+array+'</option>');
 });
</code>```

However, the option is just printing with all the array values in the <option>. It creates new option tags, but their value and text is all the items in the array.

Full demo:

var array = ["Value 1", "Value 2", "Value 3"];

array.forEach(function(arr) {
  console.log(array);
  $(".department").append('<option value="' + array + '">' + array + '</option>');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="department" name="department" id="department"></select></code>```

Where am I going wrong?

答:
You can do it by using JavaScript

var array = ["Value 1", "Value 2", "Value 3"];

var select = document.getElementById("department");
array.map(function(item){
 var option = document.createElement("option");
 option.value = item;
 option.text  = item;
 select.appendChild(option)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="department" id="department"></select></code>```

Title: Print option for each item in array

Body:
I have an array and for each item in the array, I'm trying to add in a new <option>.

To do so, I've tried the following:

 array.forEach(function(arr) {
   console.log(array);
   $(".filterSection .department").append('<option value="'+array+'">'+array+'</option>');
 });

However, the option is just printing with all the array values in the <option>. It creates new option tags, but their value and text is all the items in the array.

Full demo:

var array = ["Value 1", "Value 2", "Value 3"];

array.forEach(function(arr) {
  console.log(array);
  $(".department").append('<option value="' + array + '">' + array + '</option>');
});

<select class="department" name="department" id="department"></select>

Where am I going wrong?

Body:
You can do it by using JavaScript

var array = ["Value 1", "Value 2", "Value 3"];

var select = document.getElementById("department");
array.map(function(item){
 var option = document.createElement("option");
 option.value = item;
 option.text  = item;
 select.appendChild(option)
});

<select name="department" id="department"></select>


问:
only allow children of a specific type in a react component
I have a Card component and a CardGroup component, and I'd like to throw an error when CardGroup has children that aren't Card components. Is this possible, or am I trying to solve the wrong problem?

答:
Assert the type:</p>

```<code>props.children.forEach(child =>
  console.assert(
    child.type.name == "CanvasItem",
    "CanvasScroll can only have CanvasItem component as children."
  )
)
</code>```

Body:
Assert the type:

props.children.forEach(child =>
  console.assert(
    child.type.name == "CanvasItem",
    "CanvasScroll can only have CanvasItem component as children."
  )
)


问:
Git commit opens blank text file, for what?
In all the Git tutorials I've read they say that you can do:

```<code>git init
git add .
git commit
</code>```

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

答:
The text file that is being opened is a summary of the current commit operation. The git commit drops you into this file so the you can add a commit message at the top of the file. Once you've added your message just save and exit from this file.

There is also a "-m msg" switch on this command that allows you to add the commit message on the command line.

OwnerDisplayName: Alex

LastEditorDisplayName: Baishampayan Ghose

Body:
In all the Git tutorials I've read they say that you can do:

git init
git add .
git commit

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

OwnerDisplayName: Lou

ContentLicense: CC BY-SA 2.5