问:
Drools Eclipse Plugin ignores source level
I have installed the Drools Eclipse Plugin org.drools.eclipse 7.36.0.Final into my Eclipse 2020_03 running with a Oracle JDK 1.8.0_92. I have downloaded und unzipped drools-distribution-7.36.0.Final and added the binaries/ directory as Drools > Installed Drools Runtimes in the Eclipse Preferences.

As soon as I use any Java 1.5+ features (generics, foreach loops, closures, ...) I get error markers in the Rule Editor saying that there are syntax errors and those features require source level 1.5 (1.8 for closures).

My .drl files and the project itself seem to be fine, because I can compile and run via maven without errors. So it's not a blocking issue, but it's annoying that I cannot seem to get syntax checks for .drl files working properly in my IDE.

I have searched the internet and tried out all kinds of things:

I have set the JDT source levels in my project and workspace to 1.8

I have checked Installed JREs in the properties and only the one JDK 1.8.0_92 is listed

I have created a kmodule.xml file in /src/main/resources/META-INF/ with this content

```<code><?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
    <configuration>
        <property key="drools.dialect.java.compiler.lnglevel" value="1.8" />
        <property key="drools.dialect.java.compiler" value="ECLIPSE" />
        <property key="drools.compiler.lnglevel" value="1.8" />
    </configuration>
    <kbase name="rules">
        <ksession name="codegen-rules"/>
    </kbase>
</kmodule>
</code>```

I have created a kie.properties.conf file in /src/main/resources/META-INF/ with this content:

```<code>drools.dialect.java.compiler.lnglevel=1.8
drools.dialect.java.compiler=ECLIPSE
drools.compiler.lnglevel=1.8
</code>```

I have added the properties in the VM args section of my eclipse.ini file:

```<code>-Ddrools.dialect.java.compiler.lnglevel=1.8
-Ddrools.dialect.java.compiler=ECLIPSE
-Ddrools.compiler.lnglevel=1.8
</code>```

But all of these do not seem to have any effect and it keeps giving me the same error markers.

How can I tell the Rule Editor that I want to enable Java 1.8 source level when syntax checking my .drl files?

答:
I have run into this issue as well using the latest eclipse release and the latest drools release.

Using Eclipse 2019-03 and the Jboss Tools Integration Stack here does work. So either something broke in later eclipse releases or in the later drools versions. The integration stack uses 7.21.0.Final

I have not dug into what exactly broke but even if I did I don't know who I would report it to :(

Body:
I have installed the Drools Eclipse Plugin org.drools.eclipse 7.36.0.Final into my Eclipse 2020_03 running with a Oracle JDK 1.8.0_92. I have downloaded und unzipped drools-distribution-7.36.0.Final and added the binaries/ directory as Drools > Installed Drools Runtimes in the Eclipse Preferences.

As soon as I use any Java 1.5+ features (generics, foreach loops, closures, ...) I get error markers in the Rule Editor saying that there are syntax errors and those features require source level 1.5 (1.8 for closures).

My .drl files and the project itself seem to be fine, because I can compile and run via maven without errors. So it's not a blocking issue, but it's annoying that I cannot seem to get syntax checks for .drl files working properly in my IDE.

I have searched the internet and tried out all kinds of things:

I have set the JDT source levels in my project and workspace to 1.8

I have checked Installed JREs in the properties and only the one JDK 1.8.0_92 is listed

I have created a kmodule.xml file in /src/main/resources/META-INF/ with this content

<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
    <configuration>
        <property key="drools.dialect.java.compiler.lnglevel" value="1.8" />
        <property key="drools.dialect.java.compiler" value="ECLIPSE" />
        <property key="drools.compiler.lnglevel" value="1.8" />
    </configuration>
    <kbase name="rules">
        <ksession name="codegen-rules"/>
    </kbase>
</kmodule>

I have created a kie.properties.conf file in /src/main/resources/META-INF/ with this content:

drools.dialect.java.compiler.lnglevel=1.8
drools.dialect.java.compiler=ECLIPSE
drools.compiler.lnglevel=1.8

I have added the properties in the VM args section of my eclipse.ini file:

-Ddrools.dialect.java.compiler.lnglevel=1.8
-Ddrools.dialect.java.compiler=ECLIPSE
-Ddrools.compiler.lnglevel=1.8

But all of these do not seem to have any effect and it keeps giving me the same error markers.

How can I tell the Rule Editor that I want to enable Java 1.8 source level when syntax checking my .drl files?


来源: stackexchange

问:
Kubernetes: modify a secret using kubectl?
How can I modify the values in a Kubernetes secret using kubectl?

I created the secret with kubernetes create secret generic, but there does not seem to be a way to modify a secret. For example, to add a new secret-value to it, or to change a secret-value in it.

I assume i can go 'low-level', and write the yaml-file and do a kubectl edit but I hope there is a simpler way.

(I'm using kubernetes 1.2.x)

答:
The easiest way from the command line:

```<code>echo "This is my secret" | base64 | read output;kubectl patch secret my_secret_name -p="{\"data\":{\"secret_key\": \"$output\"}}" -v=1
</code>```

It will encode value This is my secret and update your my_secret_name secret by adding secret_key key and encoded values as a last key-value pair in that secret.

ContentLicense: CC BY-SA 4.0

Body:
The easiest way from the command line:

echo "This is my secret" | base64 | read output;kubectl patch secret my_secret_name -p="{\"data\":{\"secret_key\": \"$output\"}}" -v=1

It will encode value This is my secret and update your my_secret_name secret by adding secret_key key and encoded values as a last key-value pair in that secret.


问:
Split array into differently N sized chunks
I was wondering if this is possible in VueJS

I have an array of N items, and I want to split it into arrays of different lengths to ultimately output something like this (note the first row has two columns, and the second has 3)

Array = [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"}]
```

<pre class="lang-html prettyprint-override"><code><div class="row">
    <div class="col-1-of-2">
       hello
    </div>
    <div class="col-1-of-2">
        hello1
    </div>
</div>
<div class="row">
    <div class="col-1-of-3">
       hello2
    </div>
    <div class="col-1-of-3">
        hello3
    </div>
    <div class="col-1-of-3">
        hello4
    </div>
</div>
</code>```

And repeat

I would think that you need to chunk the array but the examples I've seen assume a fixed N length

答:
The most common way to deal with this is to use a computed.

Take the array, and nest as needed (not sure what your rules are for having 2 then 3)

and then use nested loops in the template to show the data

new Vue({
  el: "#app",
  data() {
    return {
      split: "2,3",
      items: [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"},{"text": "hello9"}]
    }
  },
  computed: {
    rows() {
      const { split, items } = this;
   let ret = [];
      let si = 0;
      let ci = 0;
      let splitArr = split.split(',');
      this.items.forEach(item => {
        if(!ret[si]){ret.push([])}
        ret[si][ci] = item
        ci = (ci + 1)
        if (ci >= splitArr[si % splitArr.length]) {
         ci = 0;
          si++;
        }

      })
      return ret
    }
  },
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row{
  display: block;
}
.col{
  box-sizing: border-box;
  padding: 10px;
  margin: 2px;
  border: 1px solid;
  display: inline-block;
}
.col-1-of-1{
  width: calc(100% - 4px);
}
.col-1-of-2{
  width: calc(50% - 4px);
}
.col-1-of-3{
  width: calc(33.3% - 4px);
}
.col-1-of-4{
  width: calc(25% - 4px);
}
.col-1-of-5{
  width: calc(20% - 4px);
}</code>```

    SPLIT: <input v-model="split">

    <div :class="`col col-1-of-${row.length}`" v-for="col in row">
      {{col.text}}

```

Body:
I was wondering if this is possible in VueJS

I have an array of N items, and I want to split it into arrays of different lengths to ultimately output something like this (note the first row has two columns, and the second has 3)

Array = [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"}]

       hello

        hello1

       hello2

        hello3

        hello4

And repeat

I would think that you need to chunk the array but the examples I've seen assume a fixed N length

Body:
The most common way to deal with this is to use a computed.

Take the array, and nest as needed (not sure what your rules are for having 2 then 3)

and then use nested loops in the template to show the data

new Vue({
  el: "#app",
  data() {
    return {
      split: "2,3",
      items: [{"text": "hello"},{"text": "hello1"},{"text": "hello2"},{"text": "hello3"},{"text": "hello4"},{"text": "hello5"},{"text": "hello6"},{"text": "hello7"},{"text": "hello8"},{"text": "hello9"}]
    }
  },
  computed: {
    rows() {
      const { split, items } = this;
   let ret = [];
      let si = 0;
      let ci = 0;
      let splitArr = split.split(',');
      this.items.forEach(item => {
        if(!ret[si]){ret.push([])}
        ret[si][ci] = item
        ci = (ci + 1)
        if (ci >= splitArr[si % splitArr.length]) {
         ci = 0;
          si++;
        }

      })
      return ret
    }
  },
})

.row{
  display: block;
}
.col{
  box-sizing: border-box;
  padding: 10px;
  margin: 2px;
  border: 1px solid;
  display: inline-block;
}
.col-1-of-1{
  width: calc(100% - 4px);
}
.col-1-of-2{
  width: calc(50% - 4px);
}
.col-1-of-3{
  width: calc(33.3% - 4px);
}
.col-1-of-4{
  width: calc(25% - 4px);
}
.col-1-of-5{
  width: calc(20% - 4px);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div>
    SPLIT: <input v-model="split">
  </div>
  <div class="row" v-for="row in rows">
    <div :class="`col col-1-of-${row.length}`" v-for="col in row">
      {{col.text}}
    </div>
  </div>
</div>


问:
GWT interaction with external standalone application
I work on a standalone Java application that is a command-and-control system for an assortment of hardware.  The C&C software basically runs from a command line, and controls the system hardware which is spread out all over the place.  It does not require a GUI to meet the business requirements.  I have written a small swing GUI just so I can see what the overall status is of the system, but again, that is not essential.

Going forward, we would like to have a Administrative web GUI with system status and something that would give a user some level of control over the hardware.  We were thinking that GWT might be a viable solution.  Our GWT app would have to have some sort of IPC with the C&C software.  I don't know how viable that is, I don't know that we want the C&C software bundled as a web app that has to run under application server.

I just don't have much experience with this.  I was thinking that the GWT client would interact through RPC with the GWT server, and the GWT server would have some sort of RPC (RMI???) with the C&C.

答:
you dont have direct control on the client system with JavaScript (which GWT is based on). in your use-case that wouldn't even make sense, why using an external server for a website controlling a local program?

If you reverse this (the app server is running on the same system as the C&C software, and the web client is available from everywhere) than that would be possible, but that wouldn't have much to do with GWT. On the server you can write normal java code. GWT just would be used for the web GUI and the RPC-calls to the server.
The call to the C&C software from the app server could be realised with the following line (windows example):

Runtime.getRuntime().exec("C:\\PathTo\\Program.exe")

This function return a instance of class Process which provides an Input- and OutputStream to simulate user input and to read and process the programs output.

Please note that you lose platform independence with this method, because the parameter for exec() looks different for every OS.

EDIT
After re-reading your question, it would even make more sense to integrate the C&C software into the server code directly, as the comment on your question suggests. you need a application server to use GWT-RPC, not a webserver, but thats hairsplitting.
Informations on how GWT-RPC generally works can be found here: (tutorial), (detailed description)

ContentLicense: CC BY-SA 3.0


问:
Center text in rounded border
I want to create a rounded border, and put some text in the middle of the top border like this:

I tried altering the solution posted on this previous question, but I couldn't get the bottom border of the text to match up with the border of the div below (the snippet below is using tailwindcss, but you get the idea):

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"/>

    SOME TEXT

```

How can I accomplish this?

答:
Your span already hides the border, keep it on the container and remove it from title.

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"/>

    SOME TEXT

```

Title: Center text in rounded border

Body:
I want to create a rounded border, and put some text in the middle of the top border like this:

I tried altering the solution posted on this previous question, but I couldn't get the bottom border of the text to match up with the border of the div below (the snippet below is using tailwindcss, but you get the idea):

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"/>

    SOME TEXT

How can I accomplish this?

Body:
Your span already hides the border, keep it on the container and remove it from title.

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"/>

<div class="pt-3">
  <h2 class="w-full text-center" style="line-height: 0.1">
    <span class="bg-white px-3 text-sm font-medium">SOME TEXT</span>
  </h2>
  <div class="px-5 pb-5 pt-4 border-b border-t border-r border-l border-gray-600 rounded-md">
  </div>
</div>


问:
Unable To Get The Property Value Of An Object That Comes From An API Call In REACTJS
Why I'm unable to access the property value of the Object That comes from an API Call ?

I Have Two Components In The React App, Both Are Given Below.

Here Is First Component Named 'Weather'

```<code>import React, { useState, useEffect } from "react";
import Styles from "./Weather.module.css";
import WeatherCard from "../Weather Card/WeatherCard.component";

const Weather = () => {
  // Initializing State
  //For Location
  const [location, setLocation] = useState("karachi");
  //For Location
  //For Query
  const [query, setQuery] = useState(location);
  //For Query
  //For Weather Data
  const [weatherData, setWeatherData] = useState({});

  //For Weather Data

  // Initializing State

  // Calling data through api

  useEffect(() => {
    const fetchingData = async () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=6a571911f99d7d02c4974a178ff1d933`;

      let responseFromFetch = await fetch(url); // getting obj of promise.

      let data = await responseFromFetch.json(); // getting api/weather data.

      setWeatherData(data); // setting state that comes from api.
    };

    fetchingData(); // calling func that brings the data
  }, [query]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setQuery(location);
    setLocation("");
  };

  return (
    <>
      <div className={Styles.formContainer}>
        <form onSubmit={handleSubmit}>
          <input
            className={Styles.inputField}
            type="text"
            placeholder="Know Your City Weather!"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
          />
          <button type="submit" className={Styles.button}>
            Search
          </button>
        </form>
      </div>

      <WeatherCard weatherData={weatherData} />
    </>
  );
};

export default Weather;
</code>```

Okay, Now Here is the second Component Named 'WeatherCard'

```<code>import React, { Component } from "react";
import Styles from "../Whether/Weather.module.css";

export default class WeatherCard extends Component {
  render() {
    const accessObj = this.props.weatherData;

    console.log(accessObj); // getting whole obj - No error,
    console.log(accessObj.name); // getting the value of the key "name" - No error,       accessObj.name isn't an object
    console.log(accessObj.sys); // getting obj - No error,          accessObj.sys is an object
    console.log(accessObj.sys.country); // Not getting the value of key "country" - Error

    if (accessObj !== "undefined") {
      return (
        <>
          <div className={Styles.wrapper}>
            <div className={Styles.weatherContainer}>
              <div className={Styles.cityContainer}>
                <p className={Styles.city}>{accessObj.name}</p>
              </div>

              <div className={Styles.countryContainer}>
                {/* I want here to use the value of the property... But country is not available here.  */}

                <p className={Styles.country}>{accessObj.sys.country}</p>
              </div>

              <div className={Styles.tempContainer}>
                <p className={Styles.temp}>30 C</p>
              </div>

              <div className={Styles.humidityContainer}>
                <p className={Styles.humidity}>100</p>
              </div>
            </div>
          </div>
        </>
      );
    }
  }
}
</code>```

You Can Also see the error that occur's in the browser. screenshot link is HERE . Unable to attach the screenshot of the error here, because I'm new in this platform!

Advance Thanks For The Help !

答:
You're trying to access an object information that doesn't have anything at first, so it will be undefined until your components gets information from the parent. this happends because the request to get information in the main component is still ongoing in the first render.

Adding a condition to console.log in <WeatherCard> will likely fix your problem.

```<code>if(accessObj.sys){ //Will check if the accessObj.sys object is not undefined; if it's not undefined, it will return true and the console.logs will happen.
   console.log(accessObj);
   console.log(accessObj.name);
   console.log(accessObj.sys);
   console.log(accessObj.sys.country);
}
</code>```

For the rest of the code you did good, because you added a condition to render, which is basically what I put above.

Body:
Why I'm unable to access the property value of the Object That comes from an API Call ?

I Have Two Components In The React App, Both Are Given Below.

Here Is First Component Named 'Weather'

import React, { useState, useEffect } from "react";
import Styles from "./Weather.module.css";
import WeatherCard from "../Weather Card/WeatherCard.component";

const Weather = () => {
  // Initializing State
  //For Location
  const [location, setLocation] = useState("karachi");
  //For Location
  //For Query
  const [query, setQuery] = useState(location);
  //For Query
  //For Weather Data
  const [weatherData, setWeatherData] = useState({});

  //For Weather Data

  // Initializing State

  // Calling data through api

  useEffect(() => {
    const fetchingData = async () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=6a571911f99d7d02c4974a178ff1d933`;

      let responseFromFetch = await fetch(url); // getting obj of promise.

      let data = await responseFromFetch.json(); // getting api/weather data.

      setWeatherData(data); // setting state that comes from api.
    };

    fetchingData(); // calling func that brings the data
  }, [query]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setQuery(location);
    setLocation("");
  };

  return (
    <>

        <form onSubmit={handleSubmit}>
          <input
            className={Styles.inputField}
            type="text"
            placeholder="Know Your City Weather!"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
          />
          <button type="submit" className={Styles.button}>
            Search
          </button>
        </form>

      <WeatherCard weatherData={weatherData} />
    </>
  );
};

export default Weather;

Okay, Now Here is the second Component Named 'WeatherCard'

import React, { Component } from "react";
import Styles from "../Whether/Weather.module.css";

export default class WeatherCard extends Component {
  render() {
    const accessObj = this.props.weatherData;

    console.log(accessObj); // getting whole obj - No error,
    console.log(accessObj.name); // getting the value of the key "name" - No error,       accessObj.name isn't an object
    console.log(accessObj.sys); // getting obj - No error,          accessObj.sys is an object
    console.log(accessObj.sys.country); // Not getting the value of key "country" - Error

    if (accessObj !== "undefined") {
      return (
        <>

{accessObj.name}

                {/* I want here to use the value of the property... But country is not available here.  */}

{accessObj.sys.country}

30 C

100

        </>
      );
    }
  }
}

You Can Also see the error that occur's in the browser. screenshot link is HERE . Unable to attach the screenshot of the error here, because I'm new in this platform!

Advance Thanks For The Help !

Body:
You're trying to access an object information that doesn't have anything at first, so it will be undefined until your components gets information from the parent. this happends because the request to get information in the main component is still ongoing in the first render.

Adding a condition to console.log in <WeatherCard> will likely fix your problem.

if(accessObj.sys){ //Will check if the accessObj.sys object is not undefined; if it's not undefined, it will return true and the console.logs will happen.
   console.log(accessObj);
   console.log(accessObj.name);
   console.log(accessObj.sys);
   console.log(accessObj.sys.country);
}

For the rest of the code you did good, because you added a condition to render, which is basically what I put above.


问:
Shorten multiple lines of setState code in react
This question is just for the purpose of improving my codes in React which currently looks very dirty and unreadable. I have 10-15 forms field which updated once I get values from APIs.

Here is the code from which I did this,

```<code>            this.setState({smtpServer:res.data.data[0].smtpServer});
            this.setState({senderName:res.data.data[0].senderName});
            this.setState({senderEmail:res.data.data[0].senderEmail});
            this.setState({smtpPorts:res.data.data[0].smtpPort});
            this.setState({username:res.data.data[0].username});
            this.setState({password:res.data.data[0].password});
            this.setState({authType:res.data.data[0].authType});

</code>```

There is also lots more of setState method which I didn't add. This makes my component code complex. Is there any method to shorten these codes.

答:
It can be achieved in a very simple way as below:

You can take that data in one variable and then you can assign it in the state.

const data = res.data.data[0];

this.setState({...data});

You can assign it directly without the use of an extra variable.

this.setState({...res.data.data[0]});

Body:
This question is just for the purpose of improving my codes in React which currently looks very dirty and unreadable. I have 10-15 forms field which updated once I get values from APIs.

Here is the code from which I did this,

            this.setState({smtpServer:res.data.data[0].smtpServer});
            this.setState({senderName:res.data.data[0].senderName});
            this.setState({senderEmail:res.data.data[0].senderEmail});
            this.setState({smtpPorts:res.data.data[0].smtpPort});
            this.setState({username:res.data.data[0].username});
            this.setState({password:res.data.data[0].password});
            this.setState({authType:res.data.data[0].authType});

There is also lots more of setState method which I didn't add. This makes my component code complex. Is there any method to shorten these codes.


问:
java generic method signature
I'm a bit confused about the syntax of generic methods.
My understanding after reading this post was that generic method should be declared like this:

public static <E> void printArray( E[] inputArray )
```

<p>with <code><E></code> being a placeholder that informs that E is a generic type </p>

<p>So why do I find in the javadoc things like this: </p>

```Stream<T> filter(Predicate<? super T> predicate)
```

<p>No placeholder?  I would have expect</p>

```<T> Stream<T> filter(Predicate<? super T> predicate)
```

<p>And why</p>

```<R> Stream<R> map(Function<? super T,? extends R> mapper)
```

This time there is a placeholder, but only for R and not for T. Why?

答:
These methods are instance methods defined on the interface Stream, which defines the type parameter on the type:

```<code>public interface Stream<T> {
  Stream<T> filter(Predicate<? super T>)
}
</code>```

...so the type parameter is defined on the interface, not the method.

As you noticed, type parameters that aren't defined on the interface are defined on a method-by-method basis, in the case of map.

Title: java generic method signature

Body:
I'm a bit confused about the syntax of generic methods.
My understanding after reading this post was that generic method should be declared like this:

public static <E> void printArray( E[] inputArray )

with <E> being a placeholder that informs that E is a generic type

So why do I find in the javadoc things like this:

Stream<T> filter(Predicate<? super T> predicate)

No placeholder?  I would have expect

<T> Stream<T> filter(Predicate<? super T> predicate)

And why

<R> Stream<R> map(Function<? super T,? extends R> mapper)

This time there is a placeholder, but only for R and not for T. Why?

Body:
These methods are instance methods defined on the interface Stream, which defines the type parameter on the type:

public interface Stream<T> {
  Stream<T> filter(Predicate<? super T>)
}

...so the type parameter is defined on the interface, not the method.

As you noticed, type parameters that aren't defined on the interface are defined on a method-by-method basis, in the case of map.


问:
Union-Find: Successor with delete
I'm trying to solve this problem of Union-Find which goes like

Successor with delete. Given a set of N integers S={0,1,…,N−1} and a
  sequence of requests of the following form:

Remove x from S Find the successor of x: the smallest y in S such that
  y≥x. design a data type so that all operations (except construction)
  should take logarithmic time or better.

Even though I find few solution and article explaining how this can be done with Union-Find, I 'm not able to visualise how it's working.

For instance:
Delete(X) can be accomplished by Union(X,X+1), but how it is acting as delete I'm just not able to visualize. Similar with finding Successor(X).

Any help/direction or elaboration of explanations will be of great help.

答: Actually, I find this problem can be solved by finding the largest value in your components. You can directly use the original weighted union-find code without changing the arrangement of the trees and the roots. However, the successor here is not the root but the largest one in the components. Hope this will help you.</p>

Title: Union-Find: Successor with delete


问:
I get this error when I install acpi-call-dkms
```<code>$ sudo apt install acpi-call-dkms
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  acpi-call-dkms
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/13.6 kB of archives.
After this operation, 48.1 kB of additional disk space will be used.
Selecting previously unselected package acpi-call-dkms.
(Reading database ... 395855 files and directories currently installed.)
Preparing to unpack .../acpi-call-dkms_1.1.0-5_all.deb ...
Unpacking acpi-call-dkms (1.1.0-5) ...
Setting up acpi-call-dkms (1.1.0-5) ...
Loading new acpi-call-1.1.0 DKMS files...
Building for 5.6.0-trunk-amd64
Building initial module for 5.6.0-trunk-amd64
Error! Bad return status for module build on kernel: 5.6.0-trunk-amd64 (x86_64)
Consult /var/lib/dkms/acpi-call/1.1.0/build/make.log for more information.
dpkg: error processing package acpi-call-dkms (--configure):
 installed acpi-call-dkms package post-installation script subprocess returned error exit status 10
Errors were encountered while processing:
 acpi-call-dkms
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

These are the contents of the the /var/lib/dkms/acpi-call/1.1.0/build/make.log

```<code>DKMS make.log for acpi-call-1.1.0 for kernel 5.6.0-trunk-amd64 (x86_64)
Thu 28 May 2020 06:26:56 PM IST
make: Entering directory '/usr/src/linux-headers-5.6.0-trunk-amd64'
  AR      /var/lib/dkms/acpi-call/1.1.0/build/built-in.a
  CC [M]  /var/lib/dkms/acpi-call/1.1.0/build/acpi_call.o
/var/lib/dkms/acpi-call/1.1.0/build/acpi_call.c: In function ‘init_acpi_call’:
/var/lib/dkms/acpi-call/1.1.0/build/acpi_call.c:356:53: error: passing argument 4 of ‘proc_create’ from incompatible pointer type [-Werror=incompatible-pointer-types]
                                                     &proc_acpi_operations);
                                                     ^~~~~~~~~~~~~~~~~~~~~
In file included from /var/lib/dkms/acpi-call/1.1.0/build/acpi_call.c:6:
/usr/src/linux-headers-5.6.0-trunk-common/include/linux/proc_fs.h:64:24: note: expected ‘const struct proc_ops *’ but argument is of type ‘struct file_operations *’
 struct proc_dir_entry *proc_create(const char *name, umode_t mode, struct proc_dir_entry *parent, const struct proc_ops *proc_ops);
                        ^~~~~~~~~~~
cc1: some warnings being treated as errors
make[2]: *** [/usr/src/linux-headers-5.6.0-trunk-common/scripts/Makefile.build:273: /var/lib/dkms/acpi-call/1.1.0/build/acpi_call.o] Error 1
make[1]: *** [/usr/src/linux-headers-5.6.0-trunk-common/Makefile:1696: /var/lib/dkms/acpi-call/1.1.0/build] Error 2
make: *** [/usr/src/linux-headers-5.6.0-trunk-common/Makefile:180: sub-make] Error 2
make: Leaving directory '/usr/src/linux-headers-5.6.0-trunk-amd64'
</code>```

I use Thinkpad X1 Extreme. I try to install this package/software to set battery thresolds with TLP. Thanks for helping!

答:
Kernel ≥ 5.6 needs at least package version 1.1.0-6 (Debian unstable or Ubuntu 20.10) which contains the necessary patch.

https://linrunner.de/tlp/faq/battery.html#installation-of-package-acpi-call-dkms-failed

Body:
$ sudo apt install acpi-call-dkms
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  acpi-call-dkms
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/13.6 kB of archives.
After this operation, 48.1 kB of additional disk space will be used.
Selecting previously unselected package acpi-call-dkms.
(Reading database ... 395855 files and directories currently installed.)
Preparing to unpack .../acpi-call-dkms_1.1.0-5_all.deb ...
Unpacking acpi-call-dkms (1.1.0-5) ...
Setting up acpi-call-dkms (1.1.0-5) ...
Loading new acpi-call-1.1.0 DKMS files...
Building for 5.6.0-trunk-amd64
Building initial module for 5.6.0-trunk-amd64
Error! Bad return status for module build on kernel: 5.6.0-trunk-amd64 (x86_64)
Consult /var/lib/dkms/acpi-call/1.1.0/build/make.log for more information.
dpkg: error processing package acpi-call-dkms (--configure):
 installed acpi-call-dkms package post-installation script subprocess returned error exit status 10
Errors were encountered while processing:
 acpi-call-dkms
E: Sub-process /usr/bin/dpkg returned an error code (1)

These are the contents of the the /var/lib/dkms/acpi-call/1.1.0/build/make.log

DKMS make.log for acpi-call-1.1.0 for kernel 5.6.0-trunk-amd64 (x86_64)
Thu 28 May 2020 06:26:56 PM IST
make: Entering directory '/usr/src/linux-headers-5.6.0-trunk-amd64'
  AR      /var/lib/dkms/acpi-call/1.1.0/build/built-in.a
  CC [M]  /var/lib/dkms/acpi-call/1.1.0/build/acpi_call.o
/var/lib/dkms/acpi-call/1.1.0/build/acpi_call.c: In function ‘init_acpi_call’:
/var/lib/dkms/acpi-call/1.1.0/build/acpi_call.c:356:53: error: passing argument 4 of ‘proc_create’ from incompatible pointer type [-Werror=incompatible-pointer-types]
                                                     &proc_acpi_operations);
                                                     ^~~~~~~~~~~~~~~~~~~~~
In file included from /var/lib/dkms/acpi-call/1.1.0/build/acpi_call.c:6:
/usr/src/linux-headers-5.6.0-trunk-common/include/linux/proc_fs.h:64:24: note: expected ‘const struct proc_ops *’ but argument is of type ‘struct file_operations *’
 struct proc_dir_entry *proc_create(const char *name, umode_t mode, struct proc_dir_entry *parent, const struct proc_ops *proc_ops);
                        ^~~~~~~~~~~
cc1: some warnings being treated as errors
make[2]: *** [/usr/src/linux-headers-5.6.0-trunk-common/scripts/Makefile.build:273: /var/lib/dkms/acpi-call/1.1.0/build/acpi_call.o] Error 1
make[1]: *** [/usr/src/linux-headers-5.6.0-trunk-common/Makefile:1696: /var/lib/dkms/acpi-call/1.1.0/build] Error 2
make: *** [/usr/src/linux-headers-5.6.0-trunk-common/Makefile:180: sub-make] Error 2
make: Leaving directory '/usr/src/linux-headers-5.6.0-trunk-amd64'

I use Thinkpad X1 Extreme. I try to install this package/software to set battery thresolds with TLP. Thanks for helping!


问:
Flask - Uploading a file via Curl
I am trying to upload a file via curl to my flask application. I get no errors, but the curl command ends up sending a blank file, or the flask code doesn't read it properly.

The following is the flask code:

```<code>#Upload a new set of instructions for <ducky_name>.
@app.route('/upload/instructions/<ducky_name>/', methods = ['POST'])
def upload_Instruction(ducky_name):
    file = request.data
    print("file: ", file)`
    path = os.getcwd() +/files/" + ducky_name + ".txt"
    with open(path, "w") as f:
        f.write(file)
        print("f: ", f)
        f.close()
        return "Success"

</code>```

And the following curl command is:

```<code>curl -X POST -d @test.txt http://127.0.0.1:5000/upload/instructions/test1/
</code>```

This is the directory tree:

```<code>├── README.md
└── server_app
    ├── app
    │   ├── __init__.py
    │   ├── __init__.pyc
    │   ├── __pycache__
    │   │   └── __init__.cpython-36.pyc
    │   ├── routes.py
    │   └── routes.pyc
    ├── files
    │   ├── test1
    │   ├── test1.txt
    │   └── test.txt
    ├── __pycache__
    │   └── server_app.cpython-36.pyc
    ├── server_app.py
    └── server_app.pyc
</code>```

Is it a problem with the file = request.data line?

答:
Try this changes and let me know if it works

Add these two lines after your "app = Flask(name)" :

```<code>UPLOAD_FOLDER = 'files'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
</code>```

Make the following changes to your routes:

```<code>@app.route("/upload/instructions/<ducky_name>", methods=["POST"])
def post_file(ducky_name):
    """Upload a file."""

    file = request.files['secret']
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], ducky_name))

    # Return 201 CREATED
    return "", 201
</code>```

Where test.txt is the original name of your file that you are uploading and newname.txt is the name of the file you want to be saved as after uploading

```<code>curl -F  secret=@test.txt  http://127.0.0.1:5000/upload/instructions/newname.txt
</code>```

Title: Flask - Uploading a file via Curl

Body:
I am trying to upload a file via curl to my flask application. I get no errors, but the curl command ends up sending a blank file, or the flask code doesn't read it properly.

The following is the flask code:

#Upload a new set of instructions for <ducky_name>.
@app.route('/upload/instructions/<ducky_name>/', methods = ['POST'])
def upload_Instruction(ducky_name):
    file = request.data
    print("file: ", file)`
    path = os.getcwd() +/files/" + ducky_name + ".txt"
    with open(path, "w") as f:
        f.write(file)
        print("f: ", f)
        f.close()
        return "Success"

And the following curl command is:

curl -X POST -d @test.txt http://127.0.0.1:5000/upload/instructions/test1/

This is the directory tree:

├── README.md
└── server_app
    ├── app
    │   ├── __init__.py
    │   ├── __init__.pyc
    │   ├── __pycache__
    │   │   └── __init__.cpython-36.pyc
    │   ├── routes.py
    │   └── routes.pyc
    ├── files
    │   ├── test1
    │   ├── test1.txt
    │   └── test.txt
    ├── __pycache__
    │   └── server_app.cpython-36.pyc
    ├── server_app.py
    └── server_app.pyc

Is it a problem with the file = request.data line?

Body:
Try this changes and let me know if it works

Add these two lines after your "app = Flask(name)" :

UPLOAD_FOLDER = 'files'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

Make the following changes to your routes:

@app.route("/upload/instructions/<ducky_name>", methods=["POST"])
def post_file(ducky_name):
    """Upload a file."""

    file = request.files['secret']
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], ducky_name))

    # Return 201 CREATED
    return "", 201

Where test.txt is the original name of your file that you are uploading and newname.txt is the name of the file you want to be saved as after uploading

curl -F  secret=@test.txt  http://127.0.0.1:5000/upload/instructions/newname.txt


问:
PyQt5: Program crashes after a certain number of push buttons is added into a GridLayout
I am making a grid of push buttons. I realized that if I create a grid with rows > 80 and cols > 90, then my program crashes. What I mean by "crashes" is that the program window opens for one second, then closes again. What's even stranger is that I don't get any error messages in my command prompt.

Does anyone know why this may be happening?

```<code>self.midColLayout = QVBoxLayout()
self.graphWidget = QWidget(self)
self.graphWidget.setStyleSheet("background-color: white; padding:0px;")
self.graphWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

self.vLayout = QVBoxLayout()
self.hLayout = QHBoxLayout()

self.gridLayout = QGridLayout()
self.gridLayout.setSpacing(0)
self.hLayout.addLayout(self.gridLayout)
self.vLayout.addLayout(self.hLayout)

self.buttons = []
for x in range(0, 80): # If I put 81, then the program crashes
    l = []
    for y in range(0, 90): # If I put 91, then the program crashes
        self.button = QPushButton()
        l.append(self.button)
        self.gridLayout.addWidget(self.button, x, y)
    self.buttons.append(l)

self.graphWidget.setLayout(self.vLayout)
self.midColLayout.addWidget(self.graphWidget)

</code>```

答:
Try it

```<code>import sys
from PyQt5.Qt import *

class Widget(QWidget):
    def __init__(self):
        super().__init__()

        self.midColLayout = QVBoxLayout()
        self.graphWidget = QWidget(self)                                         ## self
        self.graphWidget.setStyleSheet("background-color: white; padding:0px;")
        self.graphWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

        self.vLayout = QVBoxLayout()
        self.hLayout = QHBoxLayout()

        self.gridLayout = QGridLayout()
        self.gridLayout.setSpacing(0)
        self.hLayout.addLayout(self.gridLayout)
        self.vLayout.addLayout(self.hLayout)

        self.buttons = []
        for x in range(0, 80): # If I put 81, then the program crashes
            l = []
            for y in range(0, 90): # If I put 91, then the program crashes
                self.button = QPushButton()
                l.append(self.button)
                self.gridLayout.addWidget(self.button, x, y)
            self.buttons.append(l)

        self.graphWidget.setLayout(self.vLayout)
#?        self.midColLayout.addWidget(self.mapLabel)
        self.midColLayout.addWidget(self.graphWidget)

if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    mywin = Widget()
    mywin.resize(400, 400)
    mywin.show()
    sys.exit(myapp.exec_())
</code>```

The code works! I noticed that the grid goes outside of the window. Is there a quick fix for that?

Try it

```<code>import sys
from PyQt5.Qt import *

class Widget(QWidget):
    def __init__(self):
        super().__init__()

        self.midColLayout = QVBoxLayout()
        self.graphWidget = QWidget(self)                                          ## self
        self.graphWidget.setStyleSheet("background-color: white; padding:0px;")
        self.graphWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

        self.vLayout = QVBoxLayout(self)                                          # +++ self
        self.hLayout = QHBoxLayout()

        self.gridLayout = QGridLayout()
        self.gridLayout.setSpacing(0)
        self.hLayout.addLayout(self.gridLayout)
        self.vLayout.addLayout(self.hLayout)

        self.buttons = []
        for x in range(0, 80): # If I put 81, then the program crashes
            l = []
            for y in range(0, 90): # If I put 91, then the program crashes
                self.button = QPushButton()
                l.append(self.button)
                self.gridLayout.addWidget(self.button, x, y)
            self.buttons.append(l)

#        self.graphWidget.setLayout(self.vLayout)                                   # ---
#?        self.midColLayout.addWidget(self.mapLabel)
        self.midColLayout.addWidget(self.graphWidget)

if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    mywin = Widget()
    mywin.resize(400, 400)
    mywin.show()
    sys.exit(myapp.exec_())
</code>```

Body:
I am making a grid of push buttons. I realized that if I create a grid with rows > 80 and cols > 90, then my program crashes. What I mean by "crashes" is that the program window opens for one second, then closes again. What's even stranger is that I don't get any error messages in my command prompt.

Does anyone know why this may be happening?

self.midColLayout = QVBoxLayout()
self.graphWidget = QWidget(self)
self.graphWidget.setStyleSheet("background-color: white; padding:0px;")
self.graphWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

self.vLayout = QVBoxLayout()
self.hLayout = QHBoxLayout()

self.gridLayout = QGridLayout()
self.gridLayout.setSpacing(0)
self.hLayout.addLayout(self.gridLayout)
self.vLayout.addLayout(self.hLayout)

self.buttons = []
for x in range(0, 80): # If I put 81, then the program crashes
    l = []
    for y in range(0, 90): # If I put 91, then the program crashes
        self.button = QPushButton()
        l.append(self.button)
        self.gridLayout.addWidget(self.button, x, y)
    self.buttons.append(l)

self.graphWidget.setLayout(self.vLayout)
self.midColLayout.addWidget(self.graphWidget)

Body:
Try it

import sys
from PyQt5.Qt import *

class Widget(QWidget):
    def __init__(self):
        super().__init__()

        self.midColLayout = QVBoxLayout()
        self.graphWidget = QWidget(self)                                         ## self
        self.graphWidget.setStyleSheet("background-color: white; padding:0px;")
        self.graphWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

        self.vLayout = QVBoxLayout()
        self.hLayout = QHBoxLayout()

        self.gridLayout = QGridLayout()
        self.gridLayout.setSpacing(0)
        self.hLayout.addLayout(self.gridLayout)
        self.vLayout.addLayout(self.hLayout)

        self.buttons = []
        for x in range(0, 80): # If I put 81, then the program crashes
            l = []
            for y in range(0, 90): # If I put 91, then the program crashes
                self.button = QPushButton()
                l.append(self.button)
                self.gridLayout.addWidget(self.button, x, y)
            self.buttons.append(l)

        self.graphWidget.setLayout(self.vLayout)
#?        self.midColLayout.addWidget(self.mapLabel)
        self.midColLayout.addWidget(self.graphWidget)

if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    mywin = Widget()
    mywin.resize(400, 400)
    mywin.show()
    sys.exit(myapp.exec_())

The code works! I noticed that the grid goes outside of the window. Is there a quick fix for that?

Try it

import sys
from PyQt5.Qt import *

class Widget(QWidget):
    def __init__(self):
        super().__init__()

        self.midColLayout = QVBoxLayout()
        self.graphWidget = QWidget(self)                                          ## self
        self.graphWidget.setStyleSheet("background-color: white; padding:0px;")
        self.graphWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

        self.vLayout = QVBoxLayout(self)                                          # +++ self
        self.hLayout = QHBoxLayout()

        self.gridLayout = QGridLayout()
        self.gridLayout.setSpacing(0)
        self.hLayout.addLayout(self.gridLayout)
        self.vLayout.addLayout(self.hLayout)

        self.buttons = []
        for x in range(0, 80): # If I put 81, then the program crashes
            l = []
            for y in range(0, 90): # If I put 91, then the program crashes
                self.button = QPushButton()
                l.append(self.button)
                self.gridLayout.addWidget(self.button, x, y)
            self.buttons.append(l)

#        self.graphWidget.setLayout(self.vLayout)                                   # ---
#?        self.midColLayout.addWidget(self.mapLabel)
        self.midColLayout.addWidget(self.graphWidget)

if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    mywin = Widget()
    mywin.resize(400, 400)
    mywin.show()
    sys.exit(myapp.exec_())


问:
Find objects in list that match elements in array
Starter code: https://dotnetfiddle.net/lJhMyo

```<code>    string[] names = { "Burke", "Laptop", "Computer",
                       "Mobile", "Ahemed", "Sania",
                       "Kungada", "David","United","Sinshia" };

     var empList =  new List<Employee> {
         new Employee {Name = "Burke", ID = "IHED123"},
         new Employee {Name = "David", ID = "QIUHD454"},
         new Employee {Name = "Batman", ID = "OIWQE565"},
     };

</code>```

How do I construct a linq query (method syntax) that gets all Employee objects where employee name is in the "names" array?

If there is a string in "names" that is not in empList, throw exception.

EDIT: What if empList is large and I want case-insensitive match for Name?

答:
.Contains  Tests if an array or list contains the item:

```<code>var Searched = emptList.Where(x => names.Contains(x.Name));
</code>```

If Searched.Length == 0, so no Items

If you want performance use for loop (nothing is more performant) and for case insensitive use StringComparer.OrdinalIgnoreCase.

```<code>List<string> Searched = new List<string>;
for(int i = 0; i < names.Length; i++)
{
    if(emptList.contains(name[i], StringComparer.OrdinalIgnoreCase)
        Searched.Add(name[i]);
}
</code>```

Body:
Starter code: https://dotnetfiddle.net/lJhMyo

    string[] names = { "Burke", "Laptop", "Computer",
                       "Mobile", "Ahemed", "Sania",
                       "Kungada", "David","United","Sinshia" };

     var empList =  new List<Employee> {
         new Employee {Name = "Burke", ID = "IHED123"},
         new Employee {Name = "David", ID = "QIUHD454"},
         new Employee {Name = "Batman", ID = "OIWQE565"},
     };

How do I construct a linq query (method syntax) that gets all Employee objects where employee name is in the "names" array?

If there is a string in "names" that is not in empList, throw exception.

EDIT: What if empList is large and I want case-insensitive match for Name?

Body:
.Contains  Tests if an array or list contains the item:

var Searched = emptList.Where(x => names.Contains(x.Name));

If Searched.Length == 0, so no Items

If you want performance use for loop (nothing is more performant) and for case insensitive use StringComparer.OrdinalIgnoreCase.

List<string> Searched = new List<string>;
for(int i = 0; i < names.Length; i++)
{
    if(emptList.contains(name[i], StringComparer.OrdinalIgnoreCase)
        Searched.Add(name[i]);
}


问:
:hover seems to not work and i have no idea why
I don't know why, but hover won't change the opacity of the image. I've even tried to make a separate HTML page and it has the same problem.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

OPACITY 0.2

OPACITY 0.5

OPACITY 1

```

答:
See specificity in the specification.

A rule in a style attribute will always override a rule with a selector (unless you use !important which is almost always more trouble then it is worth).

Replace your style attributes with, for example, classes and put the rules in your stylesheet with suitable (i.e. lower or equal to #div24 img:hover) specificity.


问:
Error in processing request Error code: 200. Error text: OK (rejected). It seems that the connection to server has been lost
I added the following code to add a new server to phpMyAdmin:

```<code>$i++;
$cfg['Servers'][$i]['verbose'] = 'cat';
$cfg['Servers'][$i]['host'] = '129.111.21.444';
$cfg['Servers'][$i]['port'] = '';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
</code>```

now, when I go to phpMyAdmin page, I see a drop down that I can use to connect to my desired server. After clicking the server name, I see a page where I should enter my user name and password. Once I do it, I can see the db on the left hand but I also see the following error:

```<code>Error in processing request
Error code: 200
Error text: OK (rejected)
It seems that the connection to server has been lost. Please check your network connectivity and server status.
</code>```

When I try to click on the db, it gets me back to the log in page.

A screenshot of the error is also attached:
I have updated phpMyAdmin as well, but, it did not help. Any other solution please?

答: Adding https:// in front of the URL at the address bar works for me due to Chrome's security policy

Body:
I added the following code to add a new server to phpMyAdmin:

$i++;
$cfg['Servers'][$i]['verbose'] = 'cat';
$cfg['Servers'][$i]['host'] = '129.111.21.444';
$cfg['Servers'][$i]['port'] = '';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

now, when I go to phpMyAdmin page, I see a drop down that I can use to connect to my desired server. After clicking the server name, I see a page where I should enter my user name and password. Once I do it, I can see the db on the left hand but I also see the following error:

Error in processing request
Error code: 200
Error text: OK (rejected)
It seems that the connection to server has been lost. Please check your network connectivity and server status.

When I try to click on the db, it gets me back to the log in page.

A screenshot of the error is also attached:
I have updated phpMyAdmin as well, but, it did not help. Any other solution please?


问:
desktop application / script to interact with javascript on web application
My work has tasked me with determining the feasibility of migrating our existing in-house built change management services(web based) to a Sharepoint solution. I've found everything to be easy except I've run into the issue that for each change management issue (several thousand) there may be any number of attachment files associated with them, called through javascript, that need to be downloaded and put into a document library.

(ex. ... onClick="DownloadAttachment(XXXXX,'ProjectID=YYYY');return false">Attachment... ).

To keep me from manually selecting them all I've been looking over posts of people wanting to do similar, and there seem to be many possible solutions, but they often seem more complicated than they need to be.

So I suppose in a nutshell I'm asking what would be the best way to approach this issue that yields some sort of desktop application or script that can interact with web pages and will let me select and organize all the attachments.  (Making a purely web based app (php, javascript, rails, etc.) is not an option for me, so throwing that out there now).

Thanks in advance.

答:
This is a "one off" migration, right?

Get access to your in-house application's database, and create an SQL query which pulls out rows showing the attachment names (XXXXX?) and the issue/project (YYYY?), ex:

```<code>|file_id|issue_id|file_name           |
|      5|     123|Feasibility Test.xls|
</code>```

Analyze the DownloadAttachment method and figure out how it generates the URL that it calls for each download.

Start a script (personally I'd go for Python) that will do the migration work.

Program the script to connect and run the SQL query, or can read a CSV file you create manually from step #1.

Program the script to use the details to determine the target-filename and the URL to download from.

Program the script to download the file from the given URL, and place it on the hard drive with the proper name. (In Python, you might use urllib.)

Hopefully that will get you as far as a bunch of files categorized by "issue" like:

```<code>issue123/Feasibility Test.xls
issue123/Billing Invoice.doc
issue456/Feasibility Test.xls
</code>```

Body:
This is a "one off" migration, right?

Get access to your in-house application's database, and create an SQL query which pulls out rows showing the attachment names (XXXXX?) and the issue/project (YYYY?), ex:

|file_id|issue_id|file_name           |
|      5|     123|Feasibility Test.xls|

Analyze the DownloadAttachment method and figure out how it generates the URL that it calls for each download.

Start a script (personally I'd go for Python) that will do the migration work.

Program the script to connect and run the SQL query, or can read a CSV file you create manually from step #1.

Program the script to use the details to determine the target-filename and the URL to download from.

Program the script to download the file from the given URL, and place it on the hard drive with the proper name. (In Python, you might use urllib.)

Hopefully that will get you as far as a bunch of files categorized by "issue" like:

issue123/Feasibility Test.xls
issue123/Billing Invoice.doc
issue456/Feasibility Test.xls


问:
Is there a way to take input(email-id) from the user and automatically mail the same excel sheet using vba code?

In Thisworksheet

```<code>Private Sub CommandButton1_Click()

     On Error GoTo ErrHandler
        ' SET Outlook APPLICATION OBJECT.
        Dim objOutlook As Object
        Set objOutlook = CreateObject("Outlook.Application")

    ' CREATE EMAIL OBJECT.
    Dim objEmail As Object
    Set objEmail = objOutlook.CreateItem(olMailItem)

        With objEmail
            .to = "webadmin@encodedna.com"
            .Subject = "This is a test message from Arun Banik"
            .Body = "Hi there"
            .Display           ' DISPLAY MESSAGE.
        End With

        ' CLEAR.
        Set objEmail = Nothing:    Set objOutlook = Nothing

ErrorHandler:
        '
    End Sub
</code>```

In Module,
  So is there way where i can take input from the user and the excel sheet gets sent to respective email id

```<code>With objEmail

    .To = "arunbanik21@rediffmail.com"
        .CC = "arun@mail.com"
        .BCC = "arun@hotmail.com"
        .Subject = "This is a test message from Arun"
        .Body = "Hi there"
        .Attachments.Add ("e:\report.doc")
        .Send

  End With
</code>```

答:
```<code>Sub Mail_workbook_Outlook_1()

Dim UserInputToEmail As String

    Dim OutApp As Object
    Dim OutMail As Object

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

 UserInputToEmail = Application.InputBox("Enter your email id")

    On Error Resume Next
    With OutMail
        .to = UserInputToEmail
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hi there"
        .Attachments.Add ActiveWorkbook.FullName
        .Send
 Application.Wait (Now + TimeValue("0:00:15"))
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub
</code>```

Body:
In Thisworksheet

Private Sub CommandButton1_Click()

     On Error GoTo ErrHandler
        ' SET Outlook APPLICATION OBJECT.
        Dim objOutlook As Object
        Set objOutlook = CreateObject("Outlook.Application")

    ' CREATE EMAIL OBJECT.
    Dim objEmail As Object
    Set objEmail = objOutlook.CreateItem(olMailItem)

        With objEmail
            .to = "webadmin@encodedna.com"
            .Subject = "This is a test message from Arun Banik"
            .Body = "Hi there"
            .Display           ' DISPLAY MESSAGE.
        End With

        ' CLEAR.
        Set objEmail = Nothing:    Set objOutlook = Nothing

ErrorHandler:
        '
    End Sub

In Module,
  So is there way where i can take input from the user and the excel sheet gets sent to respective email id

With objEmail

    .To = "arunbanik21@rediffmail.com"
        .CC = "arun@mail.com"
        .BCC = "arun@hotmail.com"
        .Subject = "This is a test message from Arun"
        .Body = "Hi there"
        .Attachments.Add ("e:\report.doc")
        .Send

  End With


答:
You can use .Contains. ie:

```<code>var result = empList.Where(x => names.Contains(x.Name));
</code>```

You can check if there is a missing name:

```<code>bool noneMissing = !names.Any(n => empList.Any(x => x.Name == n));
</code>```

Title: Find objects in list that match elements in array

Body:
You can use .Contains. ie:

var result = empList.Where(x => names.Contains(x.Name));

You can check if there is a missing name:

bool noneMissing = !names.Any(n => empList.Any(x => x.Name == n));


问:
Apache Has Default URL Rewrites
So I just ran across this oddity.  It appears that Ubuntu has a "feature" (or bug) that allows you to access the same file using differing methods.

```<code><domain>/phpinfo.php
<domain>/phpinfo/somthinghere
</code>```

It seems that both of these load the same file.  I would like to turn this off but so far haven't found a way to do so.  Any Debian/Ubuntu folks out there know how to do that?

Thanks

答:
Problem is default enabling of this option called MultiViews

You can disable it by having a line like this in your apache config or .htaccess file:

```<code>Options -MultiViews
</code>```

Title: Apache Has Default URL Rewrites

Body:
So I just ran across this oddity.  It appears that Ubuntu has a "feature" (or bug) that allows you to access the same file using differing methods.

<domain>/phpinfo.php
<domain>/phpinfo/somthinghere

It seems that both of these load the same file.  I would like to turn this off but so far haven't found a way to do so.  Any Debian/Ubuntu folks out there know how to do that?

Thanks

Body:
Problem is default enabling of this option called MultiViews

You can disable it by having a line like this in your apache config or .htaccess file:

Options -MultiViews


问:
Unspecified error on adding the Drawing Document
i was stuck in a problem, where i need to open a new drawing file with the specified template file, as shown below.

objInventorServer.Documents.Add(Inventor.DocumentTypeEnum.kDrawingDocumentObject, templatePath)

But this line is giving an unspecified error in the workitem log. Problem is happening with InventorServer object, i guess.
Because on using the same line in Local Machine with normal Inventor.Application object, its working fine. Please help me with issue.

答:
I only ran into a problem if the drawing file was from a newer version than the Inventor Server I was running, but then I got more messages:

```<code>[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 :
RunWithArguments called
[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 : Creating
drawing based on template T:\Aces\Applications\317779a582552210117f0484dd24ec3e.rGm0mO9jVSsD2yBEDk9MRtXQTwsa61y0.SampleBundle[9].package\SampleBundlePlugin.bundle\Contents\Templates\ANSI (in).idw
[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 : FileExists = True
[05/28/2020 16:23:54]     InventorCoreConsole.exe Error: 0 : Inventor message: This file was saved in a newer version of the product. Inventor can't open newer versions of drawing (.idw, .dwg) and presentation (.ipn) files.
[05/28/2020 16:23:54] To open a part (.ipt) or an assembly (.iam) file one year newer than your current version, install the latest updates.
[05/28/2020 16:23:54] T:\Aces\Applications\317779a582552210117f0484dd24ec3e.rGm0mO9jVSsD2yBEDk9MRtXQTwsa61y0.SampleBundle[9].package\SampleBundlePlugin.bundle\Contents\Templates\ANSI (in).idw (Inventor Server x64 SDK 2020 (Build 240168000, 168))
[05/28/2020 16:23:54] Search in the Inventor help for 'Troubleshooting Opening Newer Files' for information on how to open a newer file.
[05/28/2020 16:23:54]     InventorCoreConsole.exe Error: 0 : Inventor inner xml:
[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 : Deactivating plug-in: SampleBundlePlugin
[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 : : SampleBundlePlugin: deactivating...
[05/28/2020 16:23:54] T h e   p a r a m e t e r   i s   i n c o r r e c t .   ( E x c e p t i o n   f r o m   H R E S U L T :   0 x 8 0 0 7 0 0 5 7   ( E _ I N V A L I D A R G ) )
[05/28/2020 16:23:54]
</code>```

But in that case Open would fail as well

If I was using the same version for both the file and Inventor Server then this code succeeded:

```<code>public void RunWithArguments(Document doc, NameValueMap map)
{
LogTrace("RunWithArguments called");

string idwPath = map.Item["_1"];
LogTrace("Creating drawing based on template " + idwPath);
LogTrace("FileExists = " + System.IO.File.Exists(idwPath).ToString());
Document idwDoc = inventorApplication.Documents.Add(Inventor.DocumentTypeEnum.kDrawingDocumentObject, idwPath);
LogTrace("Created drawing based on template " + idwPath);
}
</code>```

This is the report:

```<code>[05/28/2020 16:33:33]     InventorCoreConsole.exe Information: 0 : RunWithArguments called
[05/28/2020 16:33:33]     InventorCoreConsole.exe Information: 0 : Creating drawing based on template T:\Aces\Applications\eb17e332f09e0e2951aafbe13df81d70.rGm0mO9jVSsD2yBEDk9MRtXQTwsa61y0.SampleBundle[10].package\SampleBundlePlugin.bundle\Contents\Templates\ANSI (in).idw
[05/28/2020 16:33:33]     InventorCoreConsole.exe Information: 0 : FileExists = True
[05/28/2020 16:33:34]     InventorCoreConsole.exe Information: 0 : Created drawing based on template T:\Aces\Applications\eb17e332f09e0e2951aafbe13df81d70.rGm0mO9jVSsD2yBEDk9MRtXQTwsa61y0.SampleBundle[10].package\SampleBundlePlugin.bundle\Contents\Templates\ANSI (in).idw
</code>```

Do you run into this problem with all your Inventor Drawing templates?

Body:
I only ran into a problem if the drawing file was from a newer version than the Inventor Server I was running, but then I got more messages:

[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 :
RunWithArguments called
[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 : Creating
drawing based on template T:\Aces\Applications\317779a582552210117f0484dd24ec3e.rGm0mO9jVSsD2yBEDk9MRtXQTwsa61y0.SampleBundle[9].package\SampleBundlePlugin.bundle\Contents\Templates\ANSI (in).idw
[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 : FileExists = True
[05/28/2020 16:23:54]     InventorCoreConsole.exe Error: 0 : Inventor message: This file was saved in a newer version of the product. Inventor can't open newer versions of drawing (.idw, .dwg) and presentation (.ipn) files.
[05/28/2020 16:23:54] To open a part (.ipt) or an assembly (.iam) file one year newer than your current version, install the latest updates.
[05/28/2020 16:23:54] T:\Aces\Applications\317779a582552210117f0484dd24ec3e.rGm0mO9jVSsD2yBEDk9MRtXQTwsa61y0.SampleBundle[9].package\SampleBundlePlugin.bundle\Contents\Templates\ANSI (in).idw (Inventor Server x64 SDK 2020 (Build 240168000, 168))
[05/28/2020 16:23:54] Search in the Inventor help for 'Troubleshooting Opening Newer Files' for information on how to open a newer file.
[05/28/2020 16:23:54]     InventorCoreConsole.exe Error: 0 : Inventor inner xml:
[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 : Deactivating plug-in: SampleBundlePlugin
[05/28/2020 16:23:54]     InventorCoreConsole.exe Information: 0 : : SampleBundlePlugin: deactivating...
[05/28/2020 16:23:54] T h e   p a r a m e t e r   i s   i n c o r r e c t .   ( E x c e p t i o n   f r o m   H R E S U L T :   0 x 8 0 0 7 0 0 5 7   ( E _ I N V A L I D A R G ) )
[05/28/2020 16:23:54]

But in that case Open would fail as well

If I was using the same version for both the file and Inventor Server then this code succeeded:

public void RunWithArguments(Document doc, NameValueMap map)
{
LogTrace("RunWithArguments called");

string idwPath = map.Item["_1"];
LogTrace("Creating drawing based on template " + idwPath);
LogTrace("FileExists = " + System.IO.File.Exists(idwPath).ToString());
Document idwDoc = inventorApplication.Documents.Add(Inventor.DocumentTypeEnum.kDrawingDocumentObject, idwPath);
LogTrace("Created drawing based on template " + idwPath);
}

This is the report:

[05/28/2020 16:33:33]     InventorCoreConsole.exe Information: 0 : RunWithArguments called
[05/28/2020 16:33:33]     InventorCoreConsole.exe Information: 0 : Creating drawing based on template T:\Aces\Applications\eb17e332f09e0e2951aafbe13df81d70.rGm0mO9jVSsD2yBEDk9MRtXQTwsa61y0.SampleBundle[10].package\SampleBundlePlugin.bundle\Contents\Templates\ANSI (in).idw
[05/28/2020 16:33:33]     InventorCoreConsole.exe Information: 0 : FileExists = True
[05/28/2020 16:33:34]     InventorCoreConsole.exe Information: 0 : Created drawing based on template T:\Aces\Applications\eb17e332f09e0e2951aafbe13df81d70.rGm0mO9jVSsD2yBEDk9MRtXQTwsa61y0.SampleBundle[10].package\SampleBundlePlugin.bundle\Contents\Templates\ANSI (in).idw

Do you run into this problem with all your Inventor Drawing templates?


问:
Cannot initialize a vector pointer with a known size that won't change for polymorphism
I'm making a snakes and ladders game with inheritance and polymorphism. The board is made of tiles which can be either Normal, Snake, or Ladder. Thus I have a class Board with a variable type Tile (an abstract class) that can be a Snake (child class) or Ladder (child class). The board can be as big as the user wants it to be, for this reason I'm using a vector pointer Tile.

I want to initialize such vector with a fix size given by the board's size but I get an error that says "function Board::getBoardSize() is not a type name" yet I find that everyone on the internet even my professor initializes vectors like this.

NOTE: Board is constructed inside another class (MyGame), specifically in the function called start() and in main I just create an object type MyGame to call the start function so everything happens.

Update: before Board didn't have all the variables setted up for its construction but now it does (had to move functions between classes and variables).

Now the question is how do I increment the vector size with Tile pointers?  As it's been pointed out I need to increment its size in the Board constructor after  BoardSize is known, but what is the syntax for that? Is there a need for push_back(new Tile*)? or just push_back()?

Board.h:

```<code>#ifndef BOARD_H
#define BOARD_H
#include <vector>
#include "Tile.h"

class Board
{
    public:
        Board();
        ~Board();
        void setBoardSize();
        void setNumSnakes();
        void setNumLadders();
        void setReward();
        void setPenalty();
        int getBoardSize();
        int getNumSnakes();
        int getNumLadders();
        int getReward();
        int getPenalty();

    public:
        int boardSize;
        int numSnakes;
        int numLadders;
        int reward;
        int penalty;
        std::vector<Tile*> place;
};

#endif
</code>```

Board.cpp:

```<code>#include <stdlib.h>
#include <time.h>
#include <iostream>
#include "Board.h"
#include "Snake.h"
#include "Ladder.h"

Board::Board()
{
    setBoardSize();
    setNumSnakes();
    setNumLadders();       //Now it has all it needs to construct
    setReward();
    setPenalty();

    place.reserve(getBoardSize());  // <------------ I think is something like this.
    for(int i = 0; i < getBoardSize(); i++)
        place.push_back();

    //initialize random seed to randomize snakes and ladders.
    srand(time(NULL));

    int index = rand() % getBoardSize() + 1;

    // All tiles are set to 'N' when the array of Tiles is created.

    //Creates (numSnakes value) Snake objets inside the vector Tile pointer in random indexes.
    for(int i = 0; i < getNumSnakes(); i++)
    {
        /*
            Makes sure it only replaces tiles when:
            - with type = 'N'
            - there is no 'S' tiles before tile 4.
            - there is no 'S' (penlaty value) tiles before the end.
        */
        while (index < getPenalty() || index > (getBoardSize() - getPenalty()) || place[index]->getType() != 'N')
            index = rand() % boardSize + 1;

        place[index] = new Snake(getPenalty());
    }

    index = rand() % getBoardSize() + 1;

    //Creates (numLadders value) Ladder objets inside the vector Tile pointer in random indexes.
    for(int i = 0; i < getNumLadders(); i++)
    {
        /*
            Makes sure it only replaces tiles when:
                - with type = 'N'.
                - there is no 'L' tiles before tile 4.
                - there is no 'L' (reward value) tiles before the end.
        */
        while (index < getReward() || index > (getBoardSize() - getReward()) || place[index]->getType() != 'N')
            index = rand() % boardSize + 1;

        place[index] = new Ladder(getReward());
    }
}

Board::~Board()
{

}

void Board::setBoardSize()
{
    int bz;

    std::cout << "Board size: ";
    std::cin >> bz;
    while (bz < 6);
    {
        std::cout << "Board size cannot be less than 6 " << std::endl << std::endl;
        std::cout << "Board size: ";
        std::cin >> bz;
    }

    boardSize = bz;
}

void Board::setNumSnakes()
{
    int numS;

    std::cout << "Number of Snake tiles: ";
    std::cin >> numS;

    if(numS >= 0)
        numSnakes = numS;
    else
        numSnakes = -numS;
}

void Board::setNumLadders()
{
    int numL;

    std::cout << "Number of ladder tiles: ";
    std::cin >> numL;

    if(numL >= 0)
        numLadders = numL;
    else
        numLadders = -numL;
}

void Board::setReward()
{
    int rew;

    std::cout << "Reward (Ladder's consequence): ";
    std::cin >> rew;
    while (rew == 0);
    {
        std::cout << "The reward cannot be zero." << std::endl << std::endl;
        std::cout << "Reward (Ladder's consequence): ";
        std::cin >> rew;
    }

    if(rew > 0)
        reward =  rew;
    else
        reward  = (rew * -1);
}

void Board::setPenalty()
{
    int pen;

    std::cout << "Penalty (Snake's consequence): ";
    std::cin >> pen;
    while (pen == 0);
    {
        std::cout << "The penalty cannot be zero." << std::endl << std::endl;
        std::cout << "Penalty (Snake's consequence): ";
        std::cin >> pen;
    }

    if(pen < 0)
        penalty =  pen;
    else
        penalty  = (penalty * -1);

}

int Board::getBoardSize()
{
    return boardSize;
}

int Board::getNumSnakes()
{
    return numSnakes;
}

int Board::getNumLadders()
{
    return numSnakes;
}

int Board::getReward()
{
    return reward;
}

int Board::getPenalty()
{
    return penalty;
}
</code>```

MyGame.h:

```<code>#ifndef MYGAME_H
#define MYGAME_H

class MyGame
{

    protected:
        int numPlayers;
        int maxTurns;

    public:
        MyGame();
        ~MyGame();
        void start();
        void setNumPlayers(int);
        void setMaxTurns(int);
        int getNumPlayers();
        int getMaxTurns();
};

#endif
</code>```

MyGame.cpp:

```<code>#include <iostream>
#include "MyGame.h"
#include "Board.h"

MyGame::MyGame()
{

}

MyGame::~MyGame()
{

}

void MyGame::start()
{
    /*
    std::cout << "Number of player: ";
    std::cin >> numPlayers;
    std::cout << std::endl;

    std::cout << "Maximum number of turns: ";
    std::cin >> maxTurns;
    std::cout << std::endl;

    int r = setReward();
    int p = setPenalty();
    */
    numPlayers = 2;
    maxTurns = 20;

    Board brd();

    //Prints Tile's type (debugging)
    for(int i = 0; i < brd.getBoardSize(); i++)
        std::cout << i + 1 << brd.place[i]->getType() << std::endl;

}

void MyGame::setNumPlayers(int numP)
{
    if(numP > 1)
        numPlayers = numP;
    else
    {
        std::cout << "The number of players isn't enough to start." << std::endl;
        numPlayers = 0;
    }

}

void MyGame::setMaxTurns(int max)
{
    if(max > 0)
        maxTurns = max;
    else
    {
        std::cout << "The Limit  of turns has to be higger than 0" << std::endl;
        maxTurns = 0;
    }
}

int MyGame::getNumPlayers()
{
    return numPlayers;
}

int MyGame::getMaxTurns()
{
    return maxTurns;
}
</code>```

main.cpp:

```<code>#include <iostream>
#include "MyGame.h"

using namespace std;

int main()
{
    MyGame snakes;

    snakes.start();
    cin.get();
}
</code>```

答:
So there seem to be two mistakes, the first is just technical. The way to write the code you are trying to write is to create the board in your constructor initaliser list, like this

```<code>Board::Board(int rwrd, int pnlty) : place (getBoardSize())
{
    ...
}
</code>```

But the second problem seems more serious. I don't see anything in your code that indicate that you know what the board size is when you create the Board object. In the code you've posted the board size is only known after you call the setBoardSize method, which never happens as far as I can see.

You should probably make the board size a parameter to your constructor.

Body:
I'm making a snakes and ladders game with inheritance and polymorphism. The board is made of tiles which can be either Normal, Snake, or Ladder. Thus I have a class Board with a variable type Tile (an abstract class) that can be a Snake (child class) or Ladder (child class). The board can be as big as the user wants it to be, for this reason I'm using a vector pointer Tile.

I want to initialize such vector with a fix size given by the board's size but I get an error that says "function Board::getBoardSize() is not a type name" yet I find that everyone on the internet even my professor initializes vectors like this.

NOTE: Board is constructed inside another class (MyGame), specifically in the function called start() and in main I just create an object type MyGame to call the start function so everything happens.

Update: before Board didn't have all the variables setted up for its construction but now it does (had to move functions between classes and variables).

Now the question is how do I increment the vector size with Tile pointers?  As it's been pointed out I need to increment its size in the Board constructor after  BoardSize is known, but what is the syntax for that? Is there a need for push_back(new Tile*)? or just push_back()?

Board.h:

#ifndef BOARD_H
#define BOARD_H
#include <vector>
#include "Tile.h"

class Board
{
    public:
        Board();
        ~Board();
        void setBoardSize();
        void setNumSnakes();
        void setNumLadders();
        void setReward();
        void setPenalty();
        int getBoardSize();
        int getNumSnakes();
        int getNumLadders();
        int getReward();
        int getPenalty();

    public:
        int boardSize;
        int numSnakes;
        int numLadders;
        int reward;
        int penalty;
        std::vector<Tile*> place;
};

#endif

Board.cpp:

#include <stdlib.h>
#include <time.h>
#include <iostream>
#include "Board.h"
#include "Snake.h"
#include "Ladder.h"

Board::Board()
{
    setBoardSize();
    setNumSnakes();
    setNumLadders();       //Now it has all it needs to construct
    setReward();
    setPenalty();

    place.reserve(getBoardSize());  // <------------ I think is something like this.
    for(int i = 0; i < getBoardSize(); i++)
        place.push_back();

    //initialize random seed to randomize snakes and ladders.
    srand(time(NULL));

    int index = rand() % getBoardSize() + 1;

    // All tiles are set to 'N' when the array of Tiles is created.

    //Creates (numSnakes value) Snake objets inside the vector Tile pointer in random indexes.
    for(int i = 0; i < getNumSnakes(); i++)
    {
        /*
            Makes sure it only replaces tiles when:
            - with type = 'N'
            - there is no 'S' tiles before tile 4.
            - there is no 'S' (penlaty value) tiles before the end.
        */
        while (index < getPenalty() || index > (getBoardSize() - getPenalty()) || place[index]->getType() != 'N')
            index = rand() % boardSize + 1;

        place[index] = new Snake(getPenalty());
    }

    index = rand() % getBoardSize() + 1;

    //Creates (numLadders value) Ladder objets inside the vector Tile pointer in random indexes.
    for(int i = 0; i < getNumLadders(); i++)
    {
        /*
            Makes sure it only replaces tiles when:
                - with type = 'N'.
                - there is no 'L' tiles before tile 4.
                - there is no 'L' (reward value) tiles before the end.
        */
        while (index < getReward() || index > (getBoardSize() - getReward()) || place[index]->getType() != 'N')
            index = rand() % boardSize + 1;

        place[index] = new Ladder(getReward());
    }
}

Board::~Board()
{

}

void Board::setBoardSize()
{
    int bz;

    std::cout << "Board size: ";
    std::cin >> bz;
    while (bz < 6);
    {
        std::cout << "Board size cannot be less than 6 " << std::endl << std::endl;
        std::cout << "Board size: ";
        std::cin >> bz;
    }

    boardSize = bz;
}

void Board::setNumSnakes()
{
    int numS;

    std::cout << "Number of Snake tiles: ";
    std::cin >> numS;

    if(numS >= 0)
        numSnakes = numS;
    else
        numSnakes = -numS;
}

void Board::setNumLadders()
{
    int numL;

    std::cout << "Number of ladder tiles: ";
    std::cin >> numL;

    if(numL >= 0)
        numLadders = numL;
    else
        numLadders = -numL;
}

void Board::setReward()
{
    int rew;

    std::cout << "Reward (Ladder's consequence): ";
    std::cin >> rew;
    while (rew == 0);
    {
        std::cout << "The reward cannot be zero." << std::endl << std::endl;
        std::cout << "Reward (Ladder's consequence): ";
        std::cin >> rew;
    }

    if(rew > 0)
        reward =  rew;
    else
        reward  = (rew * -1);
}

void Board::setPenalty()
{
    int pen;

    std::cout << "Penalty (Snake's consequence): ";
    std::cin >> pen;
    while (pen == 0);
    {
        std::cout << "The penalty cannot be zero." << std::endl << std::endl;
        std::cout << "Penalty (Snake's consequence): ";
        std::cin >> pen;
    }

    if(pen < 0)
        penalty =  pen;
    else
        penalty  = (penalty * -1);

}

int Board::getBoardSize()
{
    return boardSize;
}

int Board::getNumSnakes()
{
    return numSnakes;
}

int Board::getNumLadders()
{
    return numSnakes;
}

int Board::getReward()
{
    return reward;
}

int Board::getPenalty()
{
    return penalty;
}

MyGame.h:

#ifndef MYGAME_H
#define MYGAME_H

class MyGame
{

    protected:
        int numPlayers;
        int maxTurns;

    public:
        MyGame();
        ~MyGame();
        void start();
        void setNumPlayers(int);
        void setMaxTurns(int);
        int getNumPlayers();
        int getMaxTurns();
};

#endif

MyGame.cpp:

#include <iostream>
#include "MyGame.h"
#include "Board.h"

MyGame::MyGame()
{

}

MyGame::~MyGame()
{

}

void MyGame::start()
{
    /*
    std::cout << "Number of player: ";
    std::cin >> numPlayers;
    std::cout << std::endl;

    std::cout << "Maximum number of turns: ";
    std::cin >> maxTurns;
    std::cout << std::endl;

    int r = setReward();
    int p = setPenalty();
    */
    numPlayers = 2;
    maxTurns = 20;

    Board brd();

    //Prints Tile's type (debugging)
    for(int i = 0; i < brd.getBoardSize(); i++)
        std::cout << i + 1 << brd.place[i]->getType() << std::endl;

}

void MyGame::setNumPlayers(int numP)
{
    if(numP > 1)
        numPlayers = numP;
    else
    {
        std::cout << "The number of players isn't enough to start." << std::endl;
        numPlayers = 0;
    }

}

void MyGame::setMaxTurns(int max)
{
    if(max > 0)
        maxTurns = max;
    else
    {
        std::cout << "The Limit  of turns has to be higger than 0" << std::endl;
        maxTurns = 0;
    }
}

int MyGame::getNumPlayers()
{
    return numPlayers;
}

int MyGame::getMaxTurns()
{
    return maxTurns;
}

main.cpp:

#include <iostream>
#include "MyGame.h"

using namespace std;

int main()
{
    MyGame snakes;

    snakes.start();
    cin.get();
}

Body:
So there seem to be two mistakes, the first is just technical. The way to write the code you are trying to write is to create the board in your constructor initaliser list, like this

Board::Board(int rwrd, int pnlty) : place (getBoardSize())
{
    ...
}

But the second problem seems more serious. I don't see anything in your code that indicate that you know what the board size is when you create the Board object. In the code you've posted the board size is only known after you call the setBoardSize method, which never happens as far as I can see.

You should probably make the board size a parameter to your constructor.


问:
Detect a selection change in Excel VBA ListBox
I need to detect when a selection change is made in a listbox so I can write the value to a sheet, the moment an item is selected or deselected.

There doesn't seem to be an event to capture this.  OnChange doesnt get triggered, or OnClick.  I tried to use an OnMouseUp event, and this does get fired at the right time, but seems to then disable the selection - so the event fires, but the listbox doesnt register a change in the status of the row being selected.

答:
You should indeed be using the ListBox_Change event to capture this. Upon any change you would need to enumerate through the items and see if they are selected to update any worksheet data

For example:

```<code>Private Sub ListBox1_Change()
    Dim wsTarget As Worksheet: Set wsTarget = Worksheets("Sheet1")
    Dim wsTargetRange As Range: Set wsTargetRange = wsTarget.Range("A1:A100")

    Dim i As Long, RowIndex As Long

    RowIndex = 1
    wsTargetRange.ClearContents

    For i = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(i) = True Then
            wsTargetRange.Item(RowIndex) = ListBox1.List(i)
            RowIndex = RowIndex + 1
        End If
    Next
End Sub
</code>```

Body:
You should indeed be using the ListBox_Change event to capture this. Upon any change you would need to enumerate through the items and see if they are selected to update any worksheet data

For example:

Private Sub ListBox1_Change()
    Dim wsTarget As Worksheet: Set wsTarget = Worksheets("Sheet1")
    Dim wsTargetRange As Range: Set wsTargetRange = wsTarget.Range("A1:A100")

    Dim i As Long, RowIndex As Long

    RowIndex = 1
    wsTargetRange.ClearContents

    For i = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(i) = True Then
            wsTargetRange.Item(RowIndex) = ListBox1.List(i)
            RowIndex = RowIndex + 1
        End If
    Next
End Sub


答:
You are checking accessObj !== "undefined" but the initial value is an empty object ({}). The initial value comes from Weather component weatherData={weatherData}.
So your condition if (accessObj !== "undefined")is always true.
One possible solution is to initialise weatherData like this :

const [weatherData, setWeatherData] = useState(null);
And do the check like this :
if (accessObj) {}
This condition will be true after you fetched the data and setWeatherData

Title: Unable To Get The Property Value Of An Object That Comes From An API Call In REACTJS

Body:
Why I'm unable to access the property value of the Object That comes from an API Call ?

I Have Two Components In The React App, Both Are Given Below.

Here Is First Component Named 'Weather'

import React, { useState, useEffect } from "react";
import Styles from "./Weather.module.css";
import WeatherCard from "../Weather Card/WeatherCard.component";

const Weather = () => {
  // Initializing State
  //For Location
  const [location, setLocation] = useState("karachi");
  //For Location
  //For Query
  const [query, setQuery] = useState(location);
  //For Query
  //For Weather Data
  const [weatherData, setWeatherData] = useState({});

  //For Weather Data

  // Initializing State

  // Calling data through api

  useEffect(() => {
    const fetchingData = async () => {
      let url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=6a571911f99d7d02c4974a178ff1d933`;

      let responseFromFetch = await fetch(url); // getting obj of promise.

      let data = await responseFromFetch.json(); // getting api/weather data.

      setWeatherData(data); // setting state that comes from api.
    };

    fetchingData(); // calling func that brings the data
  }, [query]);

  const handleSubmit = (e) => {
    e.preventDefault();
    setQuery(location);
    setLocation("");
  };

  return (
    <>

        <form onSubmit={handleSubmit}>
          <input
            className={Styles.inputField}
            type="text"
            placeholder="Know Your City Weather!"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
          />
          <button type="submit" className={Styles.button}>
            Search
          </button>
        </form>

      <WeatherCard weatherData={weatherData} />
    </>
  );
};

export default Weather;

Okay, Now Here is the second Component Named 'WeatherCard'

import React, { Component } from "react";
import Styles from "../Whether/Weather.module.css";

export default class WeatherCard extends Component {
  render() {
    const accessObj = this.props.weatherData;

    console.log(accessObj); // getting whole obj - No error,
    console.log(accessObj.name); // getting the value of the key "name" - No error,       accessObj.name isn't an object
    console.log(accessObj.sys); // getting obj - No error,          accessObj.sys is an object
    console.log(accessObj.sys.country); // Not getting the value of key "country" - Error

    if (accessObj !== "undefined") {
      return (
        <>

{accessObj.name}

                {/* I want here to use the value of the property... But country is not available here.  */}

{accessObj.sys.country}

30 C

100

        </>
      );
    }
  }
}

You Can Also see the error that occur's in the browser. screenshot link is HERE . Unable to attach the screenshot of the error here, because I'm new in this platform!

Advance Thanks For The Help !


问:
SQL - Select pairs of users with equal count
I'm trying to write a query that returns pairs of users that have the same number of loans.

I have this table:

LOANS

```<code>id_loan  book_barcode id_user
1         123            1
2         321            2
3         456            3
4         678            4
5         721            1
6         934            2
</code>```

That's my code how to get pairs of users:

```<code>SELECT l1.id_user user_1, l2.id_user user_2
FROM loans l1
JOIN loans l2 ON l2.id_user > l2.id_user
GROUP BY l2.id_user, l2.id_user;
</code>```

This is what I want from my query, but I don't know how to compare in the right way two counts, I tried but it didn't work.

```<code>id_user1   id_user2  number_loan
 1            2           2
 3            4           1
</code>```

答:
The most reasonable way is to aggregate the loans before joining:

```<code>with u as (
      select id_user, count(*) as num_loans
      from loans l
      group by id_user
     )
select u1.id_user, u2.id_user
from u u1 join
     u u2
     on u1.num_loans = u2.num_loans and u1.id_user < u2.id_user;
</code>```

You could do this without pre-aggregating, but the query will be much more expensive:

```<code>select u1.id_user, u2.id_user
from loans u1 join
     loans u2
     on u1.id_user < u2.id_user
group by u1.id_user, u2.id_user
having count(distinct u1.id_loan) = count(distinct u2.id_loan);
</code>```

I don't recommend this approach.

Body:
I'm trying to write a query that returns pairs of users that have the same number of loans.

I have this table:

LOANS

id_loan  book_barcode id_user
1         123            1
2         321            2
3         456            3
4         678            4
5         721            1
6         934            2

That's my code how to get pairs of users:

SELECT l1.id_user user_1, l2.id_user user_2
FROM loans l1
JOIN loans l2 ON l2.id_user > l2.id_user
GROUP BY l2.id_user, l2.id_user;

This is what I want from my query, but I don't know how to compare in the right way two counts, I tried but it didn't work.

id_user1   id_user2  number_loan
 1            2           2
 3            4           1

Body:
The most reasonable way is to aggregate the loans before joining:

with u as (
      select id_user, count(*) as num_loans
      from loans l
      group by id_user
     )
select u1.id_user, u2.id_user
from u u1 join
     u u2
     on u1.num_loans = u2.num_loans and u1.id_user < u2.id_user;

You could do this without pre-aggregating, but the query will be much more expensive:

select u1.id_user, u2.id_user
from loans u1 join
     loans u2
     on u1.id_user < u2.id_user
group by u1.id_user, u2.id_user
having count(distinct u1.id_loan) = count(distinct u2.id_loan);

I don't recommend this approach.


问:
PHP Zend date format
I want to input a timestamp in below format to the database.

```<code>yyyy-mm-dd hh:mm:ss
</code>```

How can I get in above format?

When I use

```<code>$date = new Zend_Date();
</code>```

it returns  month dd, yyyy hh:mm:ss PM

I also use a JavaScript calender to insert a selected date and it returns in dd-mm-yyyy format

Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. Because date format not matching the database field format the date is not inserted and only filled with *00-00-00 00:00:00*

Thanks for answer

答:
This is how i did it:

```<code>abstract class App_Model_ModelAbstract extends Zend_Db_Table_Abstract
{

    const DATE_FORMAT = 'yyyy-MM-dd';

    public static function formatDate($date, $format = App_Model_ModelAbstract::DATE_FORMAT)
    {
        if (!$date instanceof Zend_Date && Zend_Date::isDate($date)) {
            $date = new Zend_Date($date);
        }

        if ($date instanceof Zend_Date) {
            return $date->get($format);
        }

        return $date;
    }
}
</code>```

this way you don't need to be concerned with whether or not its actually an instance of zend date, you can pass in a string or anything else that is a date.

Title: PHP Zend date format

Body:
I want to input a timestamp in below format to the database.

yyyy-mm-dd hh:mm:ss

How can I get in above format?

When I use

$date = new Zend_Date();

it returns  month dd, yyyy hh:mm:ss PM

I also use a JavaScript calender to insert a selected date and it returns in dd-mm-yyyy format

Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. Because date format not matching the database field format the date is not inserted and only filled with *00-00-00 00:00:00*

Thanks for answer

Body:
This is how i did it:

abstract class App_Model_ModelAbstract extends Zend_Db_Table_Abstract
{

    const DATE_FORMAT = 'yyyy-MM-dd';

    public static function formatDate($date, $format = App_Model_ModelAbstract::DATE_FORMAT)
    {
        if (!$date instanceof Zend_Date && Zend_Date::isDate($date)) {
            $date = new Zend_Date($date);
        }

        if ($date instanceof Zend_Date) {
            return $date->get($format);
        }

        return $date;
    }
}

this way you don't need to be concerned with whether or not its actually an instance of zend date, you can pass in a string or anything else that is a date.


问:
Execute Shell file functions in Mac
I have the following shell file that contains this:

```<code>sh
nightlyTag() {
    echo $1-alpha.$(date +%Y%m%d).$(($(date +%s%N)/1000000))
}

yarnPubCanaryVersion() {
    if [ -z "$1" ]
    then
        echo "No version argument supplied, maybe you meant v1.0.0?"
        return 1
    fi
    version=`nightlyTag $1`
    yarn version --new-version $version --no-git-tag-version
    npm publish --tag canary
    git reset --hard HEAD
}
</code>```

I make the file executable with chmod +x canary.sh, then I run it doing ./canary.sh  then my terminal changes to sh-3.2$ then I try to run the functions in the terminal like this nightlyTag and I get

sh: nightlyTag: command not found

Same for yarnPubCanaryVersion.

I was looking at this SO question

答:
You won't be able to run functions from the terminal after you run the script.

You need to source the script to do this:

```<code>source ./canary.sh
</code>```

Or add the contents of the file to the .bashrc file or its equivalent, and then source it.

The source command is used to load any function file into the current shell.

Now once you call those functions you will get the expected output.

At the top of your sh file you need to include:

```<code>#! /path/to/bash
</code>```

the path to the bash that you are using.

Title: Execute Shell file functions in Mac

Body:
I have the following shell file that contains this:

sh
nightlyTag() {
    echo $1-alpha.$(date +%Y%m%d).$(($(date +%s%N)/1000000))
}

yarnPubCanaryVersion() {
    if [ -z "$1" ]
    then
        echo "No version argument supplied, maybe you meant v1.0.0?"
        return 1
    fi
    version=`nightlyTag $1`
    yarn version --new-version $version --no-git-tag-version
    npm publish --tag canary
    git reset --hard HEAD
}

I make the file executable with chmod +x canary.sh, then I run it doing ./canary.sh  then my terminal changes to sh-3.2$ then I try to run the functions in the terminal like this nightlyTag and I get

sh: nightlyTag: command not found

Same for yarnPubCanaryVersion.

I was looking at this SO question

Body:
You won't be able to run functions from the terminal after you run the script.

You need to source the script to do this:

source ./canary.sh

Or add the contents of the file to the .bashrc file or its equivalent, and then source it.

The source command is used to load any function file into the current shell.

Now once you call those functions you will get the expected output.

At the top of your sh file you need to include:

#! /path/to/bash

the path to the bash that you are using.


问:
IBM ODM 8.10 : update existing dependencies on decision center when synchronizing
I developed two decision services (DS1 & DS2) in Rule designer, having the same dependencies artifacts (same name). When I synchronized with decision center for the first time DS1, dependencies were "loaded" to decision center. Then I made some changes to dependencies to able implementation of DS2. When I tried to synchronize with decision center, the dependencies were not updated. Only DS2 were updated.
How can I synchronize independently each decision service (with its own dependencies) with decision center? without renaming artifacts.

Thanks

答:
ODM supports below Synchronization Command:
Publish:sends artifacts from Designer to Decision Center
Update: receives artifacts from Decision Center into Designer
Override and Publish: resolves conflict by replacing the Decision Center artifact with the Designer version
Override and update: resolves conflict by replacing the Designer artifact with the Decision Center version

Hope this Help.


问:
Generate sequence no for row avoiding duplicate row in crystal report XI

code i have used

```<code>whileprintingrecords; numbervar var; var := var+1; var
</code>```

also i have used the supress if duplicate

I want to avoid count if duplicate as shown in image file
1922
1923
1924
1925
1926
but 1923 and 1924 are duplicate row so i want to avoid count 1924 display sno like
1922
1923
1924
1925

答:
This works fine for me

enter code here
    whileprintingrecords;
    Global  numbervar var;
    if OnFirstRecord then
        var := 1
    else if (({USP_Get_CVR_Project_Type_List;1.ProjectID}) =
       previous({USP_Get_CVR_Project_Type_List;1.ProjectID})) then
        var
    else
        var := var+1;

Body:
code i have used

whileprintingrecords; numbervar var; var := var+1; var

also i have used the supress if duplicate

I want to avoid count if duplicate as shown in image file
1922
1923
1924
1925
1926
but 1923 and 1924 are duplicate row so i want to avoid count 1924 display sno like
1922
1923
1924
1925