问:
Enable Micrometer TomcatMetrics without spring (how to get tomcat manager)
I want to plug in the Micrometer TomcatMetrics metrics class into an existing tomcat application that doesn't have Spring integration

From the looks of the source that seems quite possible by just calling

```<code> public static void monitor(MeterRegistry registry, @Nullable Manager manager, String... tags)
</code>```

However, I can't seem to figure out how to get a hold of the org.apache.catalina.Manager instance.

Without the manager (null) it works but lacks session info which i would like to have.

So how do a get a hold of it in a proper way (servletContextListener or something)

答:
Sample micrometer.jsp page for Prometheus registry with JVM and Tomcat metrics.

Include in your app classloader micrometer jars (Ex. micrometer-core-1.8.2.jar, micrometer-registry-prometheus-1.8.2.jar)

```<code><%@ page contentType="text/plain" trimDirectiveWhitespaces="true" %>
<%@ page import="io.micrometer.prometheus.PrometheusMeterRegistry" %>
<%@ page import="io.micrometer.prometheus.PrometheusConfig" %>
<%@ page import="io.prometheus.client.exporter.common.TextFormat" %>
<%@ page import="io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.jvm.JvmGcMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.system.ProcessorMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.tomcat.TomcatMetrics"%>
<%@ page import="org.apache.catalina.core.ApplicationContextFacade"%>
<%@ page import="java.lang.reflect.Field"%>
<%@ page import="org.apache.catalina.core.ApplicationContext"%>
<%@ page import="org.apache.catalina.core.StandardContext"%>
<%
    PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
    prometheusRegistry.config().commonTags("application", "myset-worker");
    //prometheusRegistry.config().meterFilter(new PrometheusRenameFilter());

    // JVM metrics
    new ClassLoaderMetrics().bindTo(prometheusRegistry);
    new JvmMemoryMetrics().bindTo(prometheusRegistry);
    new JvmGcMetrics().bindTo(prometheusRegistry);
    new ProcessorMetrics().bindTo(prometheusRegistry);
    new JvmThreadMetrics().bindTo(prometheusRegistry);

    // Tomcat metrics
    ApplicationContextFacade acf = (ApplicationContextFacade)request.getServletContext();
    Field applicationContextFacadeField = ApplicationContextFacade.class.getDeclaredField("context");
    applicationContextFacadeField.setAccessible(true);
    ApplicationContext appContext = (ApplicationContext) applicationContextFacadeField.get(acf);
    Field applicationContextField = ApplicationContext.class.getDeclaredField("context");
    applicationContextField.setAccessible(true);
    StandardContext stdContext = (StandardContext) applicationContextField.get(appContext);
    new TomcatMetrics(stdContext.getManager(),null).bindTo(prometheusRegistry);

    // Print metrics
    //out.print(prometheusRegistry.scrape());
    out.print(prometheusRegistry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100));
%>
</code>```

Body:
I want to plug in the Micrometer TomcatMetrics metrics class into an existing tomcat application that doesn't have Spring integration

From the looks of the source that seems quite possible by just calling

 public static void monitor(MeterRegistry registry, @Nullable Manager manager, String... tags)

However, I can't seem to figure out how to get a hold of the org.apache.catalina.Manager instance.

Without the manager (null) it works but lacks session info which i would like to have.

So how do a get a hold of it in a proper way (servletContextListener or something)

Body:
Sample micrometer.jsp page for Prometheus registry with JVM and Tomcat metrics.

Include in your app classloader micrometer jars (Ex. micrometer-core-1.8.2.jar, micrometer-registry-prometheus-1.8.2.jar)

<%@ page contentType="text/plain" trimDirectiveWhitespaces="true" %>
<%@ page import="io.micrometer.prometheus.PrometheusMeterRegistry" %>
<%@ page import="io.micrometer.prometheus.PrometheusConfig" %>
<%@ page import="io.prometheus.client.exporter.common.TextFormat" %>
<%@ page import="io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.jvm.JvmGcMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.system.ProcessorMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics"%>
<%@ page import="io.micrometer.core.instrument.binder.tomcat.TomcatMetrics"%>
<%@ page import="org.apache.catalina.core.ApplicationContextFacade"%>
<%@ page import="java.lang.reflect.Field"%>
<%@ page import="org.apache.catalina.core.ApplicationContext"%>
<%@ page import="org.apache.catalina.core.StandardContext"%>
<%
    PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
    prometheusRegistry.config().commonTags("application", "myset-worker");
    //prometheusRegistry.config().meterFilter(new PrometheusRenameFilter());

    // JVM metrics
    new ClassLoaderMetrics().bindTo(prometheusRegistry);
    new JvmMemoryMetrics().bindTo(prometheusRegistry);
    new JvmGcMetrics().bindTo(prometheusRegistry);
    new ProcessorMetrics().bindTo(prometheusRegistry);
    new JvmThreadMetrics().bindTo(prometheusRegistry);

    // Tomcat metrics
    ApplicationContextFacade acf = (ApplicationContextFacade)request.getServletContext();
    Field applicationContextFacadeField = ApplicationContextFacade.class.getDeclaredField("context");
    applicationContextFacadeField.setAccessible(true);
    ApplicationContext appContext = (ApplicationContext) applicationContextFacadeField.get(acf);
    Field applicationContextField = ApplicationContext.class.getDeclaredField("context");
    applicationContextField.setAccessible(true);
    StandardContext stdContext = (StandardContext) applicationContextField.get(appContext);
    new TomcatMetrics(stdContext.getManager(),null).bindTo(prometheusRegistry);

    // Print metrics
    //out.print(prometheusRegistry.scrape());
    out.print(prometheusRegistry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100));
%>


来源: stackexchange

问:
Convert JSON date in the "mm dd yyyy" format
In my application the Date Fiend JSON response comes as this type:

```<code> "CreatedOn": "\/Date(1313572467987+0000)\/"
</code>```

I want to convert this date in the "MM DD YYYY" format. How can I convert this?

答:
That date in your JSON response looks like a standard timestamp (e.g. number of milliseconds since January 1, 1970). If you parse out the timestamp something like:

```<code>    String timestamp = jsonValue.split("\\(")[1].split("\\+")[0];
    Date createdOn = new Date(Long.parseLong(timestamp));
</code>```

Now you can use SimpleDateFormat to format a date string:

```<code>    SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
    String formattedDate = sdf.format(createdOn);
</code>```

This is ignoring the timezone adjustment in that response (the '+0000') you might also want to parse out this value and add/remove the hours from your timestamp value before formatting..

ContentLicense: CC BY-SA 3.0

Body:
In my application the Date Fiend JSON response comes as this type:

 "CreatedOn": "\/Date(1313572467987+0000)\/"

I want to convert this date in the "MM DD YYYY" format. How can I convert this?

Body:
That date in your JSON response looks like a standard timestamp (e.g. number of milliseconds since January 1, 1970). If you parse out the timestamp something like:

    String timestamp = jsonValue.split("\\(")[1].split("\\+")[0];
    Date createdOn = new Date(Long.parseLong(timestamp));

Now you can use SimpleDateFormat to format a date string:

    SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
    String formattedDate = sdf.format(createdOn);

This is ignoring the timezone adjustment in that response (the '+0000') you might also want to parse out this value and add/remove the hours from your timestamp value before formatting..


问:
How to change domain name (entire url) in react-router-dom
If I am in http://localhost:3000/Authpage I want to redirect to new URL http://www.example.com/

Usehostory() -> histor.push() is appending new url to old url.
http://localhost:3000/Authpage/http://www.example.com/

But I need new location something like below
http://www.example.com/

答:
You should use window.location.assign. For example</p>
```<code> handleClick() {
    window.location.assign('http://www.example.com/');
  }

  render() {
    return (
      <button onClick={this.handleClick.bind(this)} />
    );
  }`
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You should use window.location.assign. For example

 handleClick() {
    window.location.assign('http://www.example.com/');
  }

  render() {
    return (
      <button onClick={this.handleClick.bind(this)} />
    );
  }`


问:
How to disable an <a> tag in React after clicking it?
How can I disable the below anchor tag in React after it has been clicked? Like the onClick functionality is not working on the anchor tag.</p>
```<code><td align="left">
  <input
    type="file"
    accept=".csv,.xlsx,.xls"
    name="image"
    className="file-upload-input"
    onChange={(e: any) => {
      handleFileChange(e, data.c_id);
    }}
  />

  <a
    href="javascript:;"
    className="btn btn-secondary"
    style={{
      width: "125.62px",
      backgroundColor: "#0b5ed7",
      borderColor: "#0a58ca"
    }}
  >
    <img src={UploadIcon.default} />
    Upload
  </a>
</td>
</code>```

答:
How about setting a conditional class on the anchor tag and disabling it through css? It would need a state variable to hold the disabled state. Code would look something like.

```<code>const [disabled, setDisabled] = useState();

<a
  href="javascript:;"
  onClick={() => {
  // setting the state on click
    setDisabled(true);
  }}
  // Adding class here
  className={`btn btn-secondary${disabled ? " disabled" : ""}`}
  style={{
    width: "125.62px",
    backgroundColor: "#0b5ed7",
    borderColor: "#0a58ca"
  }}
>
  <img src={""} />
  Upload
</a>
</code>```

And the disabled class

```<code>.disabled {
  pointer-events: none;
  cursor: pointer;
}
</code>```

Body:
How can I disable the below anchor tag in React after it has been clicked? Like the onClick functionality is not working on the anchor tag.

  <input
    type="file"
    accept=".csv,.xlsx,.xls"
    name="image"
    className="file-upload-input"
    onChange={(e: any) => {
      handleFileChange(e, data.c_id);
    }}
  />

    Upload

Body:
How about setting a conditional class on the anchor tag and disabling it through css? It would need a state variable to hold the disabled state. Code would look something like.

const [disabled, setDisabled] = useState();

<a
  href="javascript:;"
  onClick={() => {
  // setting the state on click
    setDisabled(true);
  }}
  // Adding class here
  className={`btn btn-secondary${disabled ? " disabled" : ""}`}
  style={{
    width: "125.62px",
    backgroundColor: "#0b5ed7",
    borderColor: "#0a58ca"
  }}
>
  <img src={""} />
  Upload
</a>

And the disabled class

.disabled {
  pointer-events: none;
  cursor: pointer;
}


答:
not knowing what the data represents makes it harder, so I had to try and explore.

I used groupby with mean to reduce rows

```<code>dfx = pd.DataFrame()
for idx,group in enumerate(groups):
    group = group.groupby(cat_columns).mean().reset_index()
    group['group'] = 'df' + str(idx+1).zfill(2)
    dfx = pd.concat([dfx, group])
</code>```

I imagined the binary columns are input and decimal are output, so i pivot to make them into one row

making new column named input:

```<code>dfx['input'] = dfx[cat_columns].apply(lambda x: ''.join(x), axis=1)
</code>```

pivoting the needed columns and adjusting the names:

```<code>dfx.drop(cat_columns, axis=1, inplace=True)
dfxp = dfx.pivot(index='group', columns='input', values=['X1', 'X5'])
dfxp = dfxp.reset_index().fillna(0)
dfxp.columns = ['_'.join(x) for x in dfxp.columns]
</code>```

reducing the columns with PCA

```<code>from sklearn.decomposition import PCA
dft = PCA(n_components=2, svd_solver='full').fit_transform(dfxp.drop(columns = 'group_'))
dft = pd.DataFrame(dft, columns=['x', 'y'], index=dfxp.group_).reset_index()
px.scatter(dft, x='x', y='y', color='group_', title='t-SNE', height=600, width=600)
</code>```

df7 seems the outlier.

thanks for reading :)

Title: Identifying statistical outliers with pandas: groupby and reduce rows into different dataframe

Body:
I'm trying to understand how to identify statistical outliers in groups of dataframe. I will need to group the rows by the conditions and then reduce those groups into a single row and later find the outliers in all reduced rows.

df = pd.DataFrame({'X0': {0: 1, 1: 1, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1, 7: 1, 8: 0, 9: 1, 10: 0, 11: 1, 12: 0, 13: 1, 14: 1, 15: 1, 16: 0, 17: 0, 18: 0, 19: 1, 20: 0, 21: 1, 22: 1, 23: 1, 24: 1, 25: 0, 26: 1, 27: 1, 28: 1, 29: 1, 30: 0, 31: 1, 32: 0, 33: 1, 34: 0, 35: 1, 36: 1, 37: 0, 38: 1, 39: 0, 40: 1, 41: 0, 42: 1, 43: 0, 44: 0, 45: 1, 46: 1, 47: 1, 48: 1, 49: 0}, 'X1': {0: -0.037112917323895135, 1: -0.10487134240202785, 2: -1.2231079338781112, 3: -1.4422747724730558, 4: 1.1903093112171788, 5: 0.16264503017608584, 6: 0.09575885513801816, 7: -0.04065753545650327, 8: 0.9811627656097434, 9: -1.0895731715012618, 10: 1.2771663221280398, 11: 0.20642136730493899, 12: 1.4502341066082816, 13: 0.393823431298906, 14: 0.3451716634317143, 15: 0.4709902758164765, 16: 0.9982956103799087, 17: 1.189077916373609, 18: 0.9234439359961105, 19: -1.3255857892440723, 20: 1.2098373846214483, 21: -1.0264301443260604, 22: -1.2752711175444444, 23: -1.1775143284917524, 24: 0.259560479915767, 25: 0.8873566136283076, 26: 0.21516987874467863, 27: -1.1480968752611762, 28: -1.1903434754082, 29: 0.16553499639585526, 30: -0.027563846470247143, 31: 0.19474819789386086, 32: 1.5332001783034717, 33: -1.4746621814990961, 34: 0.9251147862187328, 35: 0.009242841373200278, 36: -1.4155649459675044, 37: 1.1476020465617858, 38: -1.3349528515873126, 39: 1.3090049690691499, 40: -1.0159692538569027, 41: 1.006261902461321, 42: -1.161160155994317, 43: 0.8833114074575376, 44: 1.0811966452823563, 45: -1.368200135415236, 46: -1.556580287072397, 47: -1.2006674694322674, 48: 0.13038922844618558, 49: 0.9941283827531714}, 'X2': {0: 1, 1: 1, 2: 0, 3: 0, 4: 0, 5: 1, 6: 1, 7: 1, 8: 0, 9: 0, 10: 0, 11: 1, 12: 0, 13: 1, 14: 1, 15: 1, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 0, 22: 0, 23: 0, 24: 1, 25: 0, 26: 1, 27: 0, 28: 0, 29: 1, 30: 1, 31: 1, 32: 0, 33: 0, 34: 0, 35: 1, 36: 0, 37: 0, 38: 0, 39: 0, 40: 0, 41: 0, 42: 0, 43: 0, 44: 0, 45: 0, 46: 0, 47: 0, 48: 1, 49: 0}, 'X3': {0: 0, 1: 0, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0, 9: 1, 10: 0, 11: 0, 12: 1, 13: 0, 14: 0, 15: 0, 16: 1, 17: 0, 18: 1, 19: 1, 20: 1, 21: 1, 22: 1, 23: 0, 24: 0, 25: 1, 26: 0, 27: 1, 28: 1, 29: 0, 30: 0, 31: 0, 32: 1, 33: 1, 34: 1, 35: 0, 36: 1, 37: 1, 38: 1, 39: 0, 40: 1, 41: 1, 42: 1, 43: 1, 44: 1, 45: 1, 46: 1, 47: 1, 48: 0, 49: 1}, 'X4': {0: 1, 1: 1, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1, 7: 1, 8: 0, 9: 1, 10: 0, 11: 1, 12: 0, 13: 1, 14: 1, 15: 1, 16: 0, 17: 0, 18: 0, 19: 1, 20: 0, 21: 1, 22: 1, 23: 1, 24: 1, 25: 0, 26: 1, 27: 1, 28: 1, 29: 1, 30: 1, 31: 1, 32: 0, 33: 1, 34: 0, 35: 1, 36: 1, 37: 0, 38: 1, 39: 0, 40: 1, 41: 0, 42: 1, 43: 0, 44: 0, 45: 1, 46: 1, 47: 1, 48: 1, 49: 0}, 'X5': {0: -1.6251996907891026, 1: -1.4952824550113089, 2: 0.5929477365851917, 3: 0.5188383985894559, 4: 0.8379329230408614, 5: -1.459754180360659, 6: -1.3954747896019781, 7: -1.4228738797414382, 8: 0.7961049502619677, 9: 0.5969844287269782, 10: 0.6254616540670719, 11: -1.1973174138607352, 12: 0.6743779844553507, 13: -1.3773048616218415, 14: -1.5502881165079259, 15: -1.410649926526345, 16: 0.966418551153225, 17: 0.8413042649713098, 18: 0.5947398261267023, 19: 0.5285211133411081, 20: 0.8154880527487283, 21: 0.685523955516477, 22: 0.7052301139466511, 23: 0.5694387744666269, 24: -1.3660759251156689, 25: 0.7376392137717523, 26: -1.2965881798979835, 27: 0.3247985508699227, 28: 0.8492845744063385, 29: -1.3631982627466268, 30: -1.5593937453283628, 31: -1.5647378670163918, 32: 0.7184017737689418, 33: 0.5401478202493889, 34: 0.8549277265014412, 35: -1.4324174459510242, 36: 0.5699907448414805, 37: 0.5278269967299144, 38: 0.6544095431196703, 39: 0.9956765313323911, 40: 0.49341021793456574, 41: 0.8777030715347666, 42: 0.5628001790223106, 43: 0.6932468790071539, 44: 0.5944907552098264, 45: 0.6628094310909329, 46: 0.660678722318602, 47: 0.68454503898171, 48: -1.5961965190965848, 49: 0.7606527604851616}, 'X6': {0: 0, 1: 0, 2: 0, 3: 0, 4: 1, 5: 0, 6: 0, 7: 0, 8: 1, 9: 0, 10: 1, 11: 0, 12: 1, 13: 0, 14: 0, 15: 0, 16: 1, 17: 1, 18: 1, 19: 0, 20: 1, 21: 0, 22: 0, 23: 0, 24: 0, 25: 1, 26: 0, 27: 0, 28: 0, 29: 0, 30: 0, 31: 0, 32: 1, 33: 0, 34: 1, 35: 0, 36: 0, 37: 1, 38: 0, 39: 1, 40: 0, 41: 1, 42: 0, 43: 1, 44: 1, 45: 0, 46: 0, 47: 0, 48: 0, 49: 1}, 'X7': {0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0, 21: 1, 22: 0, 23: 1, 24: 0, 25: 0, 26: 0, 27: 0, 28: 1, 29: 0, 30: 0, 31: 0, 32: 0, 33: 1, 34: 0, 35: 0, 36: 1, 37: 0, 38: 1, 39: 0, 40: 1, 41: 0, 42: 0, 43: 0, 44: 0, 45: 1, 46: 0, 47: 1, 48: 0, 49: 0}})

Using a dataset like this I would like to group by different conditions such as:

df1 = df[(df['X0'] == 0) & (df['X2'] == 0)]
df2 = df[(df['X0'] == 1) & (df['X3'] == 1)]
df3 = df[(df['X0'] == 1) & (df['X4'] == 1)]
df4 = df[(df['X0'] == 1) & (df['X7'] == 0)]

df5 = df[(df['X2'] == 1) & (df['X6'] == 0)]
df6 = df[(df['X2'] == 1) & (df['X4'] == 1)]
df7 = df[(df['X2'] == 1) & (df['X3'] == 0)]

df8 = df[(df['X3'] == 1) & (df['X7'] == 0)]
df9 = df[(df['X3'] == 1) & (df['X6'] == 1)]

df10 = df[(df['X7'] == 1) & (df['X2'] == 0)]

At this step, I am reducing each data frame into a single row, for that, I have a few ideas, a straightforward way is to take the mean of each dataframe but the problem is some of the columns are categorical and some of them are continuous, to take the mean of the entire data frame, I am converting the categorical columns into freq count columns :

cat_columns = ['X0', 'X2', 'X3', 'X4', 'X6', 'X7']
def add_freq(df, column_name):

    for col in cat_columns:
        df[f'{col}_freq'] = df[col].map(df[col].value_counts())
        df = df.drop(col, axis = 1)
    return df

all_groups  = [df1, df2, df3, df4, df5,
              df6, df7, df8, df9, df10]

all_freq_df = [add_freq(group, cat_columns) for group in all_groups]

which looks like this for each df group:

Now I can take the mean and reduce the data frames into a single row :

all_mean_df = [pd.DataFrame(group.mean()).T for group in all_freq_df]

concatinating all reduced rows in single dataframe :

all_groups  = pd.concat(all_mean_df).reset_index(drop=True)

The final reduced rows data frame looks like this, where each row represents reduced data frame group:

I want to find the outliers in this reduced dataset, I tried to find outliers using zscore such as :

from scipy import stats
all_groups[(np.abs(stats.zscore(all_groups)) < 3).all(axis=1)]

But it doesn't seem to work.
I feel like there has to be a way to do this without too much complexity but I've been stuck on how to proceed.

How can I reduce the groups into single rows and find the outliers in the reduced dataset?

Body:
not knowing what the data represents makes it harder, so I had to try and explore.

I used groupby with mean to reduce rows

dfx = pd.DataFrame()
for idx,group in enumerate(groups):
    group = group.groupby(cat_columns).mean().reset_index()
    group['group'] = 'df' + str(idx+1).zfill(2)
    dfx = pd.concat([dfx, group])

I imagined the binary columns are input and decimal are output, so i pivot to make them into one row

making new column named input:

dfx['input'] = dfx[cat_columns].apply(lambda x: ''.join(x), axis=1)

pivoting the needed columns and adjusting the names:

dfx.drop(cat_columns, axis=1, inplace=True)
dfxp = dfx.pivot(index='group', columns='input', values=['X1', 'X5'])
dfxp = dfxp.reset_index().fillna(0)
dfxp.columns = ['_'.join(x) for x in dfxp.columns]

reducing the columns with PCA

from sklearn.decomposition import PCA
dft = PCA(n_components=2, svd_solver='full').fit_transform(dfxp.drop(columns = 'group_'))
dft = pd.DataFrame(dft, columns=['x', 'y'], index=dfxp.group_).reset_index()
px.scatter(dft, x='x', y='y', color='group_', title='t-SNE', height=600, width=600)

df7 seems the outlier.

thanks for reading :)


问:
Find the best grade with Classes in C++
This is the code I have to make 3 students and below i have the logic to find the best grade, in this case nota_mesatare is the best value that it should be.

But the problem this logic is not dyanmic, and I don't know how to do it it dinamicly.

So I can get rid of those ifs

```<code>#include <iostream>
using namespace std;

class Studenti{
    private:
        string name;
        string fakulteti;

    public:
        double nota_mesatare;

    Studenti(string n, string f, double mes){
        name = n;
        fakulteti = f;
        nota_mesatare = mes;
    }
};

int main() {

    Studenti one("Benjamin", "UNT", 5.5);
    Studenti two("Amar", "UNT", 2.6);
    Studenti thre("Sheat", "UNT", 5.3);

    double best;

    if(one.nota_mesatare > two.nota_mesatare &&
       one.nota_mesatare > thre.nota_mesatare){
        best = one.nota_mesatare;
    }

    else if(two.nota_mesatare > one.nota_mesatare &&
       two.nota_mesatare > thre.nota_mesatare){
        best = two.nota_mesatare;
    }

    else best = thre.nota_mesatare;;

    cout << "Nota mesatare me e mira eshte: " << best;

    return 0;
}
</code>```

答:
If you are interested only in the largest grade, you can use std::max in the algorithm header with the grades from your objects:

```<code>Studenti one("Benjamin", "UNT", 5.5);
Studenti two("Amar", "UNT", 2.6);
Studenti thre("Sheat", "UNT", 5.3);

double best = std::max(std::max(one.nota_mesatare, two.nota_mesatare), thre.nota_mesatare);
</code>```

A more elegant and Object Oriented way is to define a comparison rule between two objects of type Studenti. You can do that by overloading the less operator (<) like this:

```<code>bool operator<(const Studenti & otherStudent) const {
    return nota_mesatare < otherStudent.nota_mesatare;
}
</code>```

That operator says that two students will be sorted by their grade, and the code should go inside your class, in the public section. Then, if you know you have exactly three students, you can use the same std::max in the algorithm header to find the max grade. std::max takes two objects of the same type and returns the larger one.

```<code>Studenti one("Benjamin", "UNT", 5.5);
Studenti two("Amar", "UNT", 2.6);
Studenti thre("Sheat", "UNT", 5.3);

double best = std::max(std::max(one, two), thre).nota_mesatare;
</code>```

If you have multiple students, you can use std::max_element in header algorithm to get an iterator to the largest element (in your case, the student with the highest grade). Having multiple students, means you need to place them in some sort of a list container, like a regular array or a smarter std::vector<Studenti>.

Title: Find the best grade with Classes in C++

Body:
This is the code I have to make 3 students and below i have the logic to find the best grade, in this case nota_mesatare is the best value that it should be.

But the problem this logic is not dyanmic, and I don't know how to do it it dinamicly.

So I can get rid of those ifs

#include <iostream>
using namespace std;

class Studenti{
    private:
        string name;
        string fakulteti;

    public:
        double nota_mesatare;

    Studenti(string n, string f, double mes){
        name = n;
        fakulteti = f;
        nota_mesatare = mes;
    }
};

int main() {

    Studenti one("Benjamin", "UNT", 5.5);
    Studenti two("Amar", "UNT", 2.6);
    Studenti thre("Sheat", "UNT", 5.3);

    double best;

    if(one.nota_mesatare > two.nota_mesatare &&
       one.nota_mesatare > thre.nota_mesatare){
        best = one.nota_mesatare;
    }

    else if(two.nota_mesatare > one.nota_mesatare &&
       two.nota_mesatare > thre.nota_mesatare){
        best = two.nota_mesatare;
    }

    else best = thre.nota_mesatare;;

    cout << "Nota mesatare me e mira eshte: " << best;

    return 0;
}

Body:
If you are interested only in the largest grade, you can use std::max in the algorithm header with the grades from your objects:

Studenti one("Benjamin", "UNT", 5.5);
Studenti two("Amar", "UNT", 2.6);
Studenti thre("Sheat", "UNT", 5.3);

double best = std::max(std::max(one.nota_mesatare, two.nota_mesatare), thre.nota_mesatare);

A more elegant and Object Oriented way is to define a comparison rule between two objects of type Studenti. You can do that by overloading the less operator (<) like this:

bool operator<(const Studenti & otherStudent) const {
    return nota_mesatare < otherStudent.nota_mesatare;
}

That operator says that two students will be sorted by their grade, and the code should go inside your class, in the public section. Then, if you know you have exactly three students, you can use the same std::max in the algorithm header to find the max grade. std::max takes two objects of the same type and returns the larger one.

Studenti one("Benjamin", "UNT", 5.5);
Studenti two("Amar", "UNT", 2.6);
Studenti thre("Sheat", "UNT", 5.3);

double best = std::max(std::max(one, two), thre).nota_mesatare;

If you have multiple students, you can use std::max_element in header algorithm to get an iterator to the largest element (in your case, the student with the highest grade). Having multiple students, means you need to place them in some sort of a list container, like a regular array or a smarter std::vector<Studenti>.


问:
Allow slash & æ,ø,å in preg_match
As the title says, I simply need to allow a normal slash in preg_match. I thought it was something like / or something. But that doesn't work.

I also need to allow european letters: æ,ø,å. How is this done?

Could someone tell me this? :-)

Example

```<code>if(preg_match("/^[a-zA-Z -]+$/", $_POST["last_name"]) == 0)
                {
                    $errMsg = "Dit efternavn må kun indeholde bogstaver, mellemrum og bindestreg.<br>";
                }
</code>```

And then I'm doing a
if(count($errMsg)==0){
 }

Thanks in advance.

答:
```<code>if(preg_match("/^[a-zA-Z -\/æøå]+$/u", $_POST["last_name"]) == 0)
if(preg_match("~^[a-zA-Z -/æøå]+$~u", $_POST["last_name"]) == 0)
</code>```

u modifier is for UTF-8
Modifiers

You need to escape slash or change delimiter to any other i.e ~ as in second example

u modofier is important

Example:

```<code>$str=ord(166);
if(preg_match('~[æ]~',$str)){
    print 'without';
}
if(preg_match('~[æ]~u',$str)){
    print 'with';
}
</code>```

prints only without
In first example æ treated as two symbols and every of them is matched

Title: Allow slash & æ,ø,å in preg_match

Body:
As the title says, I simply need to allow a normal slash in preg_match. I thought it was something like / or something. But that doesn't work.

I also need to allow european letters: æ,ø,å. How is this done?

Could someone tell me this? :-)

Example

if(preg_match("/^[a-zA-Z -]+$/", $_POST["last_name"]) == 0)
                {
                    $errMsg = "Dit efternavn må kun indeholde bogstaver, mellemrum og bindestreg.
";
                }

And then I'm doing a
if(count($errMsg)==0){
 }

Thanks in advance.

Body:
if(preg_match("/^[a-zA-Z -\/æøå]+$/u", $_POST["last_name"]) == 0)
if(preg_match("~^[a-zA-Z -/æøå]+$~u", $_POST["last_name"]) == 0)

u modifier is for UTF-8
Modifiers

You need to escape slash or change delimiter to any other i.e ~ as in second example

u modofier is important

Example:

$str=ord(166);
if(preg_match('~[æ]~',$str)){
    print 'without';
}
if(preg_match('~[æ]~u',$str)){
    print 'with';
}

prints only without
In first example æ treated as two symbols and every of them is matched


问:
Receiving JSON data back from HTTP request
I have a web request that is working properly, but it is just returning the status OK, but I need the object I am asking for it to return. I am not sure how to get the json value I am requesting. I am new to using the object HttpClient, is there a property I am missing out on? I really need the returning object. Thanks for any help

Making the call - runs fine returns the status OK.

```<code>HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept
  .Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMsg = client.GetAsync(string.Format("http://localhost:5057/api/Photo")).Result;
</code>```

The api get method

```<code>//Cut out alot of code but you get the idea
public string Get()
{
    return JsonConvert.SerializeObject(returnedPhoto);
}
</code>```

答:
The code below is to access your HttpResponseMessage and extract your response from HttpContent.

```<code>string result = ret.Result.Content.ReadAsStringAsync().Result;
</code>```

Convert your json in a structure according with your business
In my case BatchPDF is a complex object that it is being populated by result variable.

```<code>BatchPDF batchJson = JsonConvert.DeserializeObject<BatchPDF>(result);

return batchJson;
</code>```

Body:
I have a web request that is working properly, but it is just returning the status OK, but I need the object I am asking for it to return. I am not sure how to get the json value I am requesting. I am new to using the object HttpClient, is there a property I am missing out on? I really need the returning object. Thanks for any help

Making the call - runs fine returns the status OK.

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept
  .Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMsg = client.GetAsync(string.Format("http://localhost:5057/api/Photo")).Result;

The api get method

//Cut out alot of code but you get the idea
public string Get()
{
    return JsonConvert.SerializeObject(returnedPhoto);
}

Body:
The code below is to access your HttpResponseMessage and extract your response from HttpContent.

string result = ret.Result.Content.ReadAsStringAsync().Result;

Convert your json in a structure according with your business
In my case BatchPDF is a complex object that it is being populated by result variable.

BatchPDF batchJson = JsonConvert.DeserializeObject<BatchPDF>(result);

return batchJson;


问:
React collapse not working after navbar set to fixed
In my react app, using React-Bootstrap, I set the navbar to fixed after srcolling, but after that I'm unable to use the toggler button, that was working before scrolling :

```<code>const [sticky, setSticky] = useState('');
React.useEffect(() => {
    window.addEventListener('scroll', stickNavbar);
    return () => window.removeEventListener('scroll', stickNavbar);
  }, []);
const stickNavbar = () => {
    if (window !== undefined) {
      let windowHeight = window.scrollY;
      // window height changed for the demo
      windowHeight > 150 ? setSticky('top') : setSticky('');
    }
  };

 return (
    <Navbar bg="light" fixed={stickyClass} className="menu">
       <Container fluid >

       </Container>
    </Navbar>
     <Collapse in={open} timeout={200}>
      <Container fluid className="dropdown-container">
        <Row className="dropdown">

        </Row>
      </Container>
     </Collapse>
    )
</code>```

CSS

```<code>.menu {
   max-width: 100%;
   height: 7rem;
   border-bottom: 2px solid rgb(228, 228, 228);
}
.dropdown-container {
    position: absolute;
}

.dropdown {
    background-color: #f8f9fa;
    border-bottom: 2px solid rgb(228, 228, 228);
    position: relative;
}
</code>```

答:
Solution: I created for the useState, useEffect and stickNavbar corresponding items:

```<code>const [scroll, setScroll] = useState(0);
React.useEffect(() => {
    window.addEventListener('scroll', stickNavbar);
    return () => window.removeEventListener('scroll', stickNavbar);
  }, []);
const scrollPos = () => {
if (window !== undefined) {
  let posHeight = window.scrollY;
  setScroll(posHeight)
}
</code>```

};

than I used them to follow the change in the scroll Y coordinates to set the distance of the  position + rem in pixels of the height of the navbar:

```<code><Container fluid className="dropdown-container" style=
  {{top:`${112+scroll}`+"px"}}>
</code>```

Body:
In my react app, using React-Bootstrap, I set the navbar to fixed after srcolling, but after that I'm unable to use the toggler button, that was working before scrolling :

const [sticky, setSticky] = useState('');
React.useEffect(() => {
    window.addEventListener('scroll', stickNavbar);
    return () => window.removeEventListener('scroll', stickNavbar);
  }, []);
const stickNavbar = () => {
    if (window !== undefined) {
      let windowHeight = window.scrollY;
      // window height changed for the demo
      windowHeight > 150 ? setSticky('top') : setSticky('');
    }
  };

 return (
    <Navbar bg="light" fixed={stickyClass} className="menu">
       <Container fluid >

       </Container>
    </Navbar>
     <Collapse in={open} timeout={200}>
      <Container fluid className="dropdown-container">
        <Row className="dropdown">

        </Row>
      </Container>
     </Collapse>
    )

CSS

.menu {
   max-width: 100%;
   height: 7rem;
   border-bottom: 2px solid rgb(228, 228, 228);
}
.dropdown-container {
    position: absolute;
}

.dropdown {
    background-color: #f8f9fa;
    border-bottom: 2px solid rgb(228, 228, 228);
    position: relative;
}

Body:
Solution: I created for the useState, useEffect and stickNavbar corresponding items:

const [scroll, setScroll] = useState(0);
React.useEffect(() => {
    window.addEventListener('scroll', stickNavbar);
    return () => window.removeEventListener('scroll', stickNavbar);
  }, []);
const scrollPos = () => {
if (window !== undefined) {
  let posHeight = window.scrollY;
  setScroll(posHeight)
}

};

than I used them to follow the change in the scroll Y coordinates to set the distance of the  position + rem in pixels of the height of the navbar:

<Container fluid className="dropdown-container" style=
  {{top:`${112+scroll}`+"px"}}>


问:
Google API Node.js Library - Permission denied on `getIamPolicy` for projects in organization

Goal

get and set IAM Policies for auto-provisioned GCP Projects and Service Accounts within said projects using the Node.js Client Library for Google APIs. As well as give a the service account in the project the Dialogflow API Admin role (roles/dialogflow.admin)

Issue

I get the following error when I try to get the IAM policy for a project I just automatically created.

```<code>Error: 7 PERMISSION_DENIED: Permission 'resourcemanager.projects.getIamPolicy' denied on resource '//cloudresourcemanager.googleapis.com/projects/va-31b899e6' (or it may not exist).
    at Object.callErrorFromStatus (/home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/call.js:31:26)
    at Object.onReceiveStatus (/home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/client.js:180:52)
    at Object.onReceiveStatus (/home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:365:141)
    at Object.onReceiveStatus (/home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:328:181)
    at /home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/call-stream.js:182:78
    at processTicksAndRejections (node:internal/process/task_queues:78:11) {
  code: 7,
  details: "Permission 'resourcemanager.projects.getIamPolicy' denied on resource '//cloudresourcemanager.googleapis.com/projects/va-31b899e6' (or it may not exist).",
  metadata: Metadata {
    internalRepr: Map(3) {
      'grpc-server-stats-bin' => [Array],
      'google.rpc.errorinfo-bin' => [Array],
      'grpc-status-details-bin' => [Array]
    },
    options: {}
  },
  note: 'Exception occurred in retry method that was not classified as transient'
}
</code>```

Here is the function I am trying to do this in.

```<code>async function setServiceAccountRolesV2(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    const resourcemanagerClient = new ProjectsClient();
    var request = {
        resource: "projects/"+projectID,
        auth: authClient
    }
    await resourcemanagerClient.getIamPolicy(request, function(err, response) {
        if (err) {
          console.error(err);
          return;
        }
        console.log(JSON.stringify(response, null, 2));
      });
}
</code>```

Authentication Info

I am using a service account key to authenticate all of my functions in this node app with. This service account has the following permissions granted at the organization level

This service account I am using to authenticate my app with succeeds at getIamPolicy when I try to get the policy of the project it was created in itself. But I get the error when I try to get the policy of new projects I have created using this "admin project" service account.

Summary

Why is permissions denied when trying to get the IAM Policy of projects I have created programmatically, but successful when getting the policy of the "admin" project that I have this service account and the node.js app running. I thought that if I granted my service account proper permissions at the organization level, and the projects I am creating programmatically were in that same organization, my authenticating service account should inherit all of the right permissions to grant service account roles and change IAM policy in these newly generated accounts.

A potential thought/gut feeling I have that could be completely wrong - is it possible these new projects I'm making don't have IAM Policies at all? so when I try to get and set them there's nothing to change?

Update for clarifications

I have a project that acts as an "administration project" which contain hosts the VM my Node.js app for provisioning GCP resources runs on.

This project is also where I created my service account that the Node.js app authenticates with.

I am creating new projects and service accounts within those projects with this Node.js app.

I have given the aforementioned service account the Owner permission at the organization level.

In my setServiceAccountRolesV2() method, I have tried making the resource my provisioned project manually, as opposed to passed as a parameter to make sure the the project is located correctly. I manually copy and pasted the project ID from one of the auto-provisioned projects into the resource field like this for example

```<code>resource: "projects/va-31b899e6",
</code>```

and I get the same permission denied error (full error message shown above).

However when I try to use this getIamPolicy method with the "admin" project that my node.js app and service account were created in, I get a successful policy return.

```<code>resource: "projects/provisioning-admin-339515"
</code>```

I don't understand why one works, and one doesn't while the service account I'm using to make the call has Owner role at the organization level. The va-31b899e6 project shown above is in fact under the same organization my admin project is.

When I run the gcloud command gcloud projects get-iam-policy va-31b899e6 --format=json > ~/policy.json to check the policy of the api-generated project (not the admin project), I get the following policy back:

```<code>{
  "bindings": [
    {
      "members": [
        "serviceAccount:tf-admin-sa@provisioner-admin-339515.iam.gserviceaccount.com"      ],
      "role": "roles/owner"
    }
  ],
  "etag": "ByXXh29efSc=",
  "version": 1
}
</code>```

This service account listed in the members is the service account I authenticate my Node app with. Again, Owner granted at the Org level. This to me looks like it should be able to use the get and setIamPolicy methods on this project, as well as any other project in my organization.

New edits to follow trouble shooting tips from answer.

1

Confirmed I am using the correct project in the api call:

```<code>async function setServiceAccountRolesV2(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    const resourcemanagerClient = new ProjectsClient();
    var request = {
        resource: "projects/va-31b899e6",

        auth: authClient
    };
    await resourcemanagerClient.getIamPolicy(request, function(err, response) {
        if (err) {
          console.error(err);
          return;
        }
        console.log(JSON.stringify(response, null, 2));
      });
}
</code>```

(project ID copied from GCP Console) : resource: "projects/va-31b899e6",

2

I have verified my credentials are used correctly, I am using a json key file of the service account I created to create more projects and service accounts programmatically. This is how I am authenticating :

```<code>const auth = new google.auth.GoogleAuth({
  keyFile: 'provisioner-admin-339515-411d1e284a77.json',
  scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
</code>```

Then in my function, I create a new instance of auth like this:
 const authClient = await auth.getClient();
which is then sent in the request of the api call: auth: authClient

3

Verified permissions for my authenticating service account:
When I run

```<code>gcloud projects get-iam-policy va-31b899e6  \
--flatten="bindings[].members" \
--format="table(bindings.role)" \
--filter="bindings.members:tf-admin-sa@provisioner-admin-339515.iam.gserviceaccount.com"
</code>```

I get the output ROLE: roles/owner

答:
Your service account has too many roles. Most of the roles are redundant and included within other roles that you assigned. For example, Billing Account Administrator contains the permissions of Billing Account User. The role Owner possesses almost all of the roles in your screenshot.

Next, you need to understand the Principle of Least Privilege. Seth Vargo put together a good intro video. In summary, only grant the required privileges and no more. Your service account IAM roles are vast and a serious security weakness.

To solve the problem in your question, follow these steps:

STEP 1:

Confirm that the Project ID is correct in the API call. Make sure you are using the Project ID and not the Project Name. List the projects:

gcloud projects list

STEP 2:

Verify that your code is using the correct credentials (the ones you think you configured). Your question does not show how you are authorizing your code. You are using ADC (Application Default Credentials) which means the credentials could be found from several sources (CLI remembered credentials, the environment variable, metadata server).

If you are using the environment variable GOOGLE_APPLICATION_CREDENTIALS, open the file using the variable and make sure that it is a service account JSON key:

```<code>vi $GOOGLE_APPLICATION_CREDENTIALS
</code>```

If you are using the CLI credentials, verify which identity is being used:

```<code>gcloud auth list
</code>```

As a debugging test, clear the environment variable and use a user identity that has the role Owner and then login. Then retest your application.

```<code>unset GOOGLE_APPLICATION_CREDENTIALS
gcloud auth application-default login
</code>```

STEP 3:

Once you have determined the correct Project ID and which service account your code is using, double-check the roles assigned to the service account at the project level. List the IAM roles with this command. Replace with your Project ID and Service Account Email address:

```<code>gcloud projects get-iam-policy <PROJECT_ID>  \
--flatten="bindings[].members" \
--format="table(bindings.role)" \
--filter="bindings.members:<SERVICE_ACCOUNT_EMAIL>"
</code>```

The service account needs one of these roles or similar to view IAM bindings:

```<code>roles/browser aka Browser
roles/iam.roleViewer aka Viewer
</code>```

The service account needs this role or similar to modify IAM bindings:

```<code>roles/resourcemanager.projectIamAdmin aka Project IAM Admin
</code>```

Manage access to projects, folders, and organizations

Body:
Goal

get and set IAM Policies for auto-provisioned GCP Projects and Service Accounts within said projects using the Node.js Client Library for Google APIs. As well as give a the service account in the project the Dialogflow API Admin role (roles/dialogflow.admin)

Issue

I get the following error when I try to get the IAM policy for a project I just automatically created.

Error: 7 PERMISSION_DENIED: Permission 'resourcemanager.projects.getIamPolicy' denied on resource '//cloudresourcemanager.googleapis.com/projects/va-31b899e6' (or it may not exist).
    at Object.callErrorFromStatus (/home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/call.js:31:26)
    at Object.onReceiveStatus (/home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/client.js:180:52)
    at Object.onReceiveStatus (/home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:365:141)
    at Object.onReceiveStatus (/home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:328:181)
    at /home/aeglad22/va-project-provisioning/node_modules/@grpc/grpc-js/build/src/call-stream.js:182:78
    at processTicksAndRejections (node:internal/process/task_queues:78:11) {
  code: 7,
  details: "Permission 'resourcemanager.projects.getIamPolicy' denied on resource '//cloudresourcemanager.googleapis.com/projects/va-31b899e6' (or it may not exist).",
  metadata: Metadata {
    internalRepr: Map(3) {
      'grpc-server-stats-bin' => [Array],
      'google.rpc.errorinfo-bin' => [Array],
      'grpc-status-details-bin' => [Array]
    },
    options: {}
  },
  note: 'Exception occurred in retry method that was not classified as transient'
}

Here is the function I am trying to do this in.

async function setServiceAccountRolesV2(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    const resourcemanagerClient = new ProjectsClient();
    var request = {
        resource: "projects/"+projectID,
        auth: authClient
    }
    await resourcemanagerClient.getIamPolicy(request, function(err, response) {
        if (err) {
          console.error(err);
          return;
        }
        console.log(JSON.stringify(response, null, 2));
      });
}

Authentication Info

I am using a service account key to authenticate all of my functions in this node app with. This service account has the following permissions granted at the organization level

This service account I am using to authenticate my app with succeeds at getIamPolicy when I try to get the policy of the project it was created in itself. But I get the error when I try to get the policy of new projects I have created using this "admin project" service account.

Summary

Why is permissions denied when trying to get the IAM Policy of projects I have created programmatically, but successful when getting the policy of the "admin" project that I have this service account and the node.js app running. I thought that if I granted my service account proper permissions at the organization level, and the projects I am creating programmatically were in that same organization, my authenticating service account should inherit all of the right permissions to grant service account roles and change IAM policy in these newly generated accounts.

A potential thought/gut feeling I have that could be completely wrong - is it possible these new projects I'm making don't have IAM Policies at all? so when I try to get and set them there's nothing to change?

Update for clarifications

I have a project that acts as an "administration project" which contain hosts the VM my Node.js app for provisioning GCP resources runs on.

This project is also where I created my service account that the Node.js app authenticates with.

I am creating new projects and service accounts within those projects with this Node.js app.

I have given the aforementioned service account the Owner permission at the organization level.

In my setServiceAccountRolesV2() method, I have tried making the resource my provisioned project manually, as opposed to passed as a parameter to make sure the the project is located correctly. I manually copy and pasted the project ID from one of the auto-provisioned projects into the resource field like this for example

resource: "projects/va-31b899e6",

and I get the same permission denied error (full error message shown above).

However when I try to use this getIamPolicy method with the "admin" project that my node.js app and service account were created in, I get a successful policy return.

resource: "projects/provisioning-admin-339515"

I don't understand why one works, and one doesn't while the service account I'm using to make the call has Owner role at the organization level. The va-31b899e6 project shown above is in fact under the same organization my admin project is.

When I run the gcloud command gcloud projects get-iam-policy va-31b899e6 --format=json > ~/policy.json to check the policy of the api-generated project (not the admin project), I get the following policy back:

{
  "bindings": [
    {
      "members": [
        "serviceAccount:tf-admin-sa@provisioner-admin-339515.iam.gserviceaccount.com"      ],
      "role": "roles/owner"
    }
  ],
  "etag": "ByXXh29efSc=",
  "version": 1
}

This service account listed in the members is the service account I authenticate my Node app with. Again, Owner granted at the Org level. This to me looks like it should be able to use the get and setIamPolicy methods on this project, as well as any other project in my organization.

New edits to follow trouble shooting tips from answer.

1

Confirmed I am using the correct project in the api call:

async function setServiceAccountRolesV2(projectID, serviceAccountID){
    const authClient = await auth.getClient();
    const resourcemanagerClient = new ProjectsClient();
    var request = {
        resource: "projects/va-31b899e6",

        auth: authClient
    };
    await resourcemanagerClient.getIamPolicy(request, function(err, response) {
        if (err) {
          console.error(err);
          return;
        }
        console.log(JSON.stringify(response, null, 2));
      });
}

(project ID copied from GCP Console) : resource: "projects/va-31b899e6",

2

I have verified my credentials are used correctly, I am using a json key file of the service account I created to create more projects and service accounts programmatically. This is how I am authenticating :

const auth = new google.auth.GoogleAuth({
  keyFile: 'provisioner-admin-339515-411d1e284a77.json',
  scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});

Then in my function, I create a new instance of auth like this:
 const authClient = await auth.getClient();
which is then sent in the request of the api call: auth: authClient

3

Verified permissions for my authenticating service account:
When I run

gcloud projects get-iam-policy va-31b899e6  \
--flatten="bindings[].members" \
--format="table(bindings.role)" \
--filter="bindings.members:tf-admin-sa@provisioner-admin-339515.iam.gserviceaccount.com"

I get the output ROLE: roles/owner

Body:
Your service account has too many roles. Most of the roles are redundant and included within other roles that you assigned. For example, Billing Account Administrator contains the permissions of Billing Account User. The role Owner possesses almost all of the roles in your screenshot.

Next, you need to understand the Principle of Least Privilege. Seth Vargo put together a good intro video. In summary, only grant the required privileges and no more. Your service account IAM roles are vast and a serious security weakness.

To solve the problem in your question, follow these steps:

STEP 1:

Confirm that the Project ID is correct in the API call. Make sure you are using the Project ID and not the Project Name. List the projects:

gcloud projects list

STEP 2:

Verify that your code is using the correct credentials (the ones you think you configured). Your question does not show how you are authorizing your code. You are using ADC (Application Default Credentials) which means the credentials could be found from several sources (CLI remembered credentials, the environment variable, metadata server).

If you are using the environment variable GOOGLE_APPLICATION_CREDENTIALS, open the file using the variable and make sure that it is a service account JSON key:

vi $GOOGLE_APPLICATION_CREDENTIALS

If you are using the CLI credentials, verify which identity is being used:

gcloud auth list

As a debugging test, clear the environment variable and use a user identity that has the role Owner and then login. Then retest your application.

unset GOOGLE_APPLICATION_CREDENTIALS
gcloud auth application-default login

STEP 3:

Once you have determined the correct Project ID and which service account your code is using, double-check the roles assigned to the service account at the project level. List the IAM roles with this command. Replace with your Project ID and Service Account Email address:

gcloud projects get-iam-policy <PROJECT_ID>  \
--flatten="bindings[].members" \
--format="table(bindings.role)" \
--filter="bindings.members:<SERVICE_ACCOUNT_EMAIL>"

The service account needs one of these roles or similar to view IAM bindings:

roles/browser aka Browser
roles/iam.roleViewer aka Viewer

The service account needs this role or similar to modify IAM bindings:

roles/resourcemanager.projectIamAdmin aka Project IAM Admin

Manage access to projects, folders, and organizations


答:
You can have a look at this thread here for an answer.

To summarize it, in your event handler you can add

```<code>const eventHandler = () => {
    window.location.assign('http://www.example.com/')
}
</code>```

However, the way I see it, it's just easier to create a simple regular HTML  tag:

click to redirect```

Title: How to change domain name (entire url) in react-router-dom

Body:
If I am in http://localhost:3000/Authpage I want to redirect to new URL http://www.example.com/

Usehostory() -> histor.push() is appending new url to old url.
http://localhost:3000/Authpage/http://www.example.com/

But I need new location something like below
http://www.example.com/

Body:
You can have a look at this thread here for an answer.

To summarize it, in your event handler you can add

const eventHandler = () => {
    window.location.assign('http://www.example.com/')
}

However, the way I see it, it's just easier to create a simple regular HTML <a> tag:

<a href='http://www.example.com/'>click to redirect</a>


问:
android facebook: Not showing my Message in dialog
I am working on facebook android application but there is one problem i am facing

i am using the following example

Android/Java -- Post simple text to Facebook wall?

so the problem is that everything works here fine, the dialogs etc etc but When it open the screen to upload Walla Message that i have setted up here

```<code>        try
        {
            System.out.println("*** IN TRY ** ");
            Bundle parameters = new Bundle();
            parameters.putString("message", "this is a test");// the message to post to the wall
            facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
        }
        catch (Exception e)
        {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }
</code>```

It does not show me my Message written in the dialog. Whats the problem with that

can anybody Guide me please..

Thanks alot.

答:
Message has been ignored. You can read about it here: https://developers.facebook.com/docs/reference/dialogs/feed/

This field will be ignored on July 12, 2011 The message to prefill the text field that the user will type in. To be compliant with Facebook Platform Policies, your application may only set this field if the user manually generated the content earlier in the workflow. Most applications should not set this.

Body:
I am working on facebook android application but there is one problem i am facing

i am using the following example

Android/Java -- Post simple text to Facebook wall?

so the problem is that everything works here fine, the dialogs etc etc but When it open the screen to upload Walla Message that i have setted up here

        try
        {
            System.out.println("*** IN TRY ** ");
            Bundle parameters = new Bundle();
            parameters.putString("message", "this is a test");// the message to post to the wall
            facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
        }
        catch (Exception e)
        {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }

It does not show me my Message written in the dialog. Whats the problem with that

can anybody Guide me please..

Thanks alot.


问:
Unable to click on suggestion provided by textbox (Selenium)
When I send text manually, suggestion area provided by first textbox , it works fine. But when I send the text using selenium library it cannot able to select the option from suggestion area, although that option is present inside the textbox. Is there any one who can help me out of that.

```<code>import time
from selenium.webdriver.support.ui import Select
path=r"C:\Users\AbdulRehman\Downloads\chromedriver_win32\chromedriver.exe"
# driver =  webdriver.Chrome(path)
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

driver.get("https://www4.sii.cl/mapasui/internet/#/contenido/index.html")

try:
    element = WebDriverWait(driver, 1000).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="ng-app"]/body/div[5]/div/div/div[3]/div/button'))
         )
    element.click()
    print("prints its working fine now ..")

    element = WebDriverWait(driver, 1000).until(
        EC.presence_of_element_located((By.XPATH,'//*[@id="titulo"]/div[8]/i'))
         )
    element.click()

#     element = WebDriverWait(driver, 1000).until(
#         EC.presence_of_element_located((By.XPATH,'//*[@id="rolsearch"]/div[2]/div[1]/input'))
#          )

#     element.send_keys("PEDRO AGUIRRE CERD"+Keys.ENTER)

#     search = WebDriverWait(driver, 60).until(
#         EC.visibility_of_element_located((By.XPATH, '//*[@id="rolsearch"]/div[2]/div[1]/input'))
#     )
#     search.send_keys("EL MONTE" + Keys.ENTER)
#     time.sleep(3)
    search = WebDriverWait(driver, 60).until(
    EC.visibility_of_element_located((By.XPATH, '//*[@id="rolsearch"]/div[2]/div[1]/input'))
    )
    ActionChains(driver).click(on_element=search).send_keys("EL MONTE").send_keys(Keys.ENTER).perform()

    suggestion = WebDriverWait(driver, 60).until(
    EC.visibility_of_element_located((By.XPATH, '//strong[text()="EL MONTE"]'))
    )
    suggestion.click()
#     auto_complete = driver.find_elements_by_xpath('//*[@id="rolsearch"]/div[2]/div[1]/input')
#     auto_complete[0].click()
#     auto_complete.send_keys(Keys.RETURN)
#     element.send_keys("somehting in text")
#     search =  driver.find_element_by_xpath().click()

#     search.send_keys(Keys.RETURN)
    search_1 =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[2]/input')
    search_1.send_keys("PEDRO AGUIRRE CERDA")
    search_1.send_keys(Keys.RETURN)

    search_2 =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[3]/input')
    search_2.send_keys("somehting in text")
    search_2.send_keys(Keys.RETURN)

    print("Its also working now ......")

    time.sleep(3)
except Exception as e:
    print(e)
    driver.quit()

</code>```

答:
The desired element is a Angular element, so to send a character sequence to the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following Locator Strategy:

Using XPATH:

```<code>driver.get('https://www4.sii.cl/mapasui/internet/#/contenido/index.html')
WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Aceptar']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//i[@data-ng-click='mostrarBusquedaRol()']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@data-ng-include, '/mapasui/common/_content/busqueda-rol.html')]//div[@id='rolsearch']//label[contains(., 'Comuna')]//following::input[1]"))).send_keys("PEDRO AGUIRRE CERD" + Keys.ENTER)
</code>```

Note: You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Browser Snapshot:

Body:
When I send text manually, suggestion area provided by first textbox , it works fine. But when I send the text using selenium library it cannot able to select the option from suggestion area, although that option is present inside the textbox. Is there any one who can help me out of that.

import time
from selenium.webdriver.support.ui import Select
path=r"C:\Users\AbdulRehman\Downloads\chromedriver_win32\chromedriver.exe"
# driver =  webdriver.Chrome(path)
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

driver.get("https://www4.sii.cl/mapasui/internet/#/contenido/index.html")

try:
    element = WebDriverWait(driver, 1000).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="ng-app"]/body/div[5]/div/div/div[3]/div/button'))
         )
    element.click()
    print("prints its working fine now ..")

    element = WebDriverWait(driver, 1000).until(
        EC.presence_of_element_located((By.XPATH,'//*[@id="titulo"]/div[8]/i'))
         )
    element.click()

#     element = WebDriverWait(driver, 1000).until(
#         EC.presence_of_element_located((By.XPATH,'//*[@id="rolsearch"]/div[2]/div[1]/input'))
#          )

#     element.send_keys("PEDRO AGUIRRE CERD"+Keys.ENTER)

#     search = WebDriverWait(driver, 60).until(
#         EC.visibility_of_element_located((By.XPATH, '//*[@id="rolsearch"]/div[2]/div[1]/input'))
#     )
#     search.send_keys("EL MONTE" + Keys.ENTER)
#     time.sleep(3)
    search = WebDriverWait(driver, 60).until(
    EC.visibility_of_element_located((By.XPATH, '//*[@id="rolsearch"]/div[2]/div[1]/input'))
    )
    ActionChains(driver).click(on_element=search).send_keys("EL MONTE").send_keys(Keys.ENTER).perform()

    suggestion = WebDriverWait(driver, 60).until(
    EC.visibility_of_element_located((By.XPATH, '//strong[text()="EL MONTE"]'))
    )
    suggestion.click()
#     auto_complete = driver.find_elements_by_xpath('//*[@id="rolsearch"]/div[2]/div[1]/input')
#     auto_complete[0].click()
#     auto_complete.send_keys(Keys.RETURN)
#     element.send_keys("somehting in text")
#     search =  driver.find_element_by_xpath().click()

#     search.send_keys(Keys.RETURN)
    search_1 =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[2]/input')
    search_1.send_keys("PEDRO AGUIRRE CERDA")
    search_1.send_keys(Keys.RETURN)

    search_2 =  driver.find_element_by_xpath('//*[@id="rolsearch"]/div[2]/div[3]/input')
    search_2.send_keys("somehting in text")
    search_2.send_keys(Keys.RETURN)

    print("Its also working now ......")

    time.sleep(3)
except Exception as e:
    print(e)
    driver.quit()

Body:
The desired element is a Angular element, so to send a character sequence to the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following Locator Strategy:

Using XPATH:

driver.get('https://www4.sii.cl/mapasui/internet/#/contenido/index.html')
WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Aceptar']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//i[@data-ng-click='mostrarBusquedaRol()']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@data-ng-include, '/mapasui/common/_content/busqueda-rol.html')]//div[@id='rolsearch']//label[contains(., 'Comuna')]//following::input[1]"))).send_keys("PEDRO AGUIRRE CERD" + Keys.ENTER)

Note: You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Browser Snapshot:


问:
Insert new records where one doesn't already exist
I need some help inserting new data where it doesn't already exist.

Currently I use this query:

```<code>INSERT INTO dbo.Table (column1, column2, column3, column4)
    SELECT value1, value2, value3, value4
    FROM dbo.staginTable
    LEFT JOIN dbo.Table AS A ON A.column1 = value1
                             AND A.column2 = value2
                             AND A.column3 = value3
                             AND A.column4 = value4
    WHERE A.column1 IS NULL
      AND A.column2 IS NULL
      AND A.column3 IS NULL
      AND A.column4 IS NULL
</code>```

This query works fine and doesn't insert data which already exists in the dbo.Table if none of the variables (value1, value2, value3, value4) is null.

My problem is that it`s very common that e.g. either value3 or value4 or both can be null and in this case the values will be inserted

Works:

```<code>(value1, value2, value3, value4)
('one', 'two', 'three', 'four')
</code>```

Doesn't work:

```<code>(value1, value2, value3, value4)
('one', 'two', NULL, 'four')
</code>```

I know that I could add a Unique index on the 4 columns to bypass this problem or I could use another query like insert expect but I would like to know if it's possible to use the query above or what I need to change in the query.

Thanks for your help

答:
Given the fact that the columns you are comparing are all nullable, EXCEPT can be a more compact form

INSERT INTO dbo.MyTable (column1, column2, column3, column4)
SELECT ST.value1, ST.value2, ST.value3, ST.value4
    FROM dbo.StagingTable ST
EXCEPT
SELECT MT.value1, MT.value2, MT.value3, MT.value4
    FROM dbo.MyTable MT;
```
<p>Alternatively, you can do it in a correlated subquery, this is especially useful if other columns are involved that are not being compared</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO dbo.MyTable (column1, column2, column3, column4, column5)
    SELECT ST.value1, ST.value2, ST.value3, ST.value4, ST.value5
    FROM dbo.StagingTable ST
    WHERE NOT EXISTS (
      SELECT ST.value1, ST.value2, ST.value3, ST.value4
      INTERSECT
      SELECT MT.value1, MT.value2, MT.value3, MT.value4
      FROM dbo.MyTable MT
    );
</code>```

Fear not: this subquery is completely elided by the compiler

Body:
I need some help inserting new data where it doesn't already exist.

Currently I use this query:

INSERT INTO dbo.Table (column1, column2, column3, column4)
    SELECT value1, value2, value3, value4
    FROM dbo.staginTable
    LEFT JOIN dbo.Table AS A ON A.column1 = value1
                             AND A.column2 = value2
                             AND A.column3 = value3
                             AND A.column4 = value4
    WHERE A.column1 IS NULL
      AND A.column2 IS NULL
      AND A.column3 IS NULL
      AND A.column4 IS NULL

This query works fine and doesn't insert data which already exists in the dbo.Table if none of the variables (value1, value2, value3, value4) is null.

My problem is that it`s very common that e.g. either value3 or value4 or both can be null and in this case the values will be inserted

Works:

(value1, value2, value3, value4)
('one', 'two', 'three', 'four')

Doesn't work:

(value1, value2, value3, value4)
('one', 'two', NULL, 'four')

I know that I could add a Unique index on the 4 columns to bypass this problem or I could use another query like insert expect but I would like to know if it's possible to use the query above or what I need to change in the query.

Thanks for your help

Body:
Given the fact that the columns you are comparing are all nullable, EXCEPT can be a more compact form

INSERT INTO dbo.MyTable (column1, column2, column3, column4)
SELECT ST.value1, ST.value2, ST.value3, ST.value4
    FROM dbo.StagingTable ST
EXCEPT
SELECT MT.value1, MT.value2, MT.value3, MT.value4
    FROM dbo.MyTable MT;

Alternatively, you can do it in a correlated subquery, this is especially useful if other columns are involved that are not being compared

INSERT INTO dbo.MyTable (column1, column2, column3, column4, column5)
    SELECT ST.value1, ST.value2, ST.value3, ST.value4, ST.value5
    FROM dbo.StagingTable ST
    WHERE NOT EXISTS (
      SELECT ST.value1, ST.value2, ST.value3, ST.value4
      INTERSECT
      SELECT MT.value1, MT.value2, MT.value3, MT.value4
      FROM dbo.MyTable MT
    );

Fear not: this subquery is completely elided by the compiler


问:
Smarty substring after last occurrence?
Need to get the style number out of text string:

'The style number is A456RT'
'Style A456RT'
'Style number is A456RT'

Need to get the A456RT part only, i.e. after the last space. Tried to adapt similar answers but no luck:

```<code>{$product.name|regex_replace:"/^\d+ /":""}
</code>```

Is there an easy way to achieve this?

答:
You can use

{$product.name|regex_replace:'/.*\s(\w+)$/':'$1'}
```
<p>See the regex demo.</p>
<p>If the codes are not just alphanumeric, then you can use</p>
<pre class="lang-none prettyprint-override"><code>{$product.name|regex_replace:'/.*\s(\S+)$/':'$1'}
</code>```

and if there can be any trailing spaces:

{$product.name|regex_replace:'/.*\s(\S+)\s*$/':'$1'}
```

Details:

.* - any zero or more chars other than line break chars (if there can be line breaks, add s after the second /) as many as possible

\s - a whitespace

(\S+) - Group 1: any one or more non-whitespace chars (\w+ matches one or more letters, digits or underscores)

\s* - zero or more whitespaces

$ - end of string.

Title: Smarty substring after last occurrence?

Body:
Need to get the style number out of text string:

'The style number is A456RT'
'Style A456RT'
'Style number is A456RT'

Need to get the A456RT part only, i.e. after the last space. Tried to adapt similar answers but no luck:

{$product.name|regex_replace:"/^\d+ /":""}

Is there an easy way to achieve this?

Body:
You can use

{$product.name|regex_replace:'/.*\s(\w+)$/':'$1'}

See the regex demo.

If the codes are not just alphanumeric, then you can use

{$product.name|regex_replace:'/.*\s(\S+)$/':'$1'}

and if there can be any trailing spaces:

{$product.name|regex_replace:'/.*\s(\S+)\s*$/':'$1'}

Details:

.* - any zero or more chars other than line break chars (if there can be line breaks, add s after the second /) as many as possible

\s - a whitespace

(\S+) - Group 1: any one or more non-whitespace chars (\w+ matches one or more letters, digits or underscores)

\s* - zero or more whitespaces

$ - end of string.


问:
Given a list of filenames, group filenames with all derivatives based on similarity of the filename
I might not be searching the best terms to find a solution but so far nothing I've found has been able to solve my problem and I really don't know where to start or even what mechanisms to investigate.

I have a large list of image files in various locations on my hard drive and I'm trying to clean it up by removing the duplicates. Most of these are easy to find using hash codes but I have a lot of corrupted or edited versions which aren't so easy to find. I know I'll need some user interaction to identify and delete (archive) the unwanted files and I'll be doing some further processing to make sure metadata such as dates and geotagging are correct (also used to potentially match files) and then display similar images with all known data through a simple html interface.

One of the steps I've identified is grouping similarly named files or files which have part of another filename in its name. Sometimes these can be completely unrelated and so the user interaction will be required.

Below is a sample of files, what I would like is to group them into filenames which are similar, disregarding path and file extension.

```<code>[
"/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335.jpg",
"/Users/stu/Documents/Backup/IMG_20140413_072335(4).png",
"/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg",
"/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg",
"/Users/stu/Photos/2013/IMAG0097.jpg",
"/Users/stu/Photos/2014/IMAG0097.jpg",
"/Users/stu/Photos/2013/IMAG0126.jpg",
"/Users/stu/Photos/Holidays/IMAG0132.jpg",
"/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg",
"/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg",
"/Users/stu/Downloads/Photos/IMG_20140412_195105.png",
"/Users/stu/Photos/2014/IMG_20140412_195110.png",
"/Users/stu/Photos/2014/IMG_20140413_143245(6).png",
"/Users/stu/Photos/2014/IMG_20140413_143245(7).png",
"/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245.png",
"/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg",
"/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg",
"/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png",
"/Users/stu/Photos/2013/IMG_20140413_072335.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg",
"/Users/stu/Photos/2013/IMAG0126-edited.jpg",
"/Users/stu/Photos/2013/IMAG0126546.jpg"
]
</code>```

The list of files above should output something like this:

```<code>{
    "IMG_20140413_072335": [
        "/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335.jpg",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(4).png",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg",
        "/Users/stu/Photos/2013/IMG_20140413_072335.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg"
    ],
    "IMAG0097": [
        "/Users/stu/Photos/2013/IMAG0097.jpg",
        "/Users/stu/Photos/2014/IMAG0097.jpg"
    ],
    "IMAG0126": [
        "/Users/stu/Photos/2013/IMAG0126.jpg",
        "/Users/stu/Photos/2013/IMAG0126-edited.jpg",
        "/Users/stu/Photos/2013/IMAG0126546.jpg"
    ],
    "IMAG0132": [
        "/Users/stu/Photos/Holidays/IMAG0132.jpg"
    ],
    "IMG_20140322_142557": [
        "/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg"
    ],
    "IMG_20140330_200132": [
        "/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg"
    ],
    "IMG_20140412_195105": [
        "/Users/stu/Downloads/Photos/IMG_20140412_195105.png"
    ],
    "IMG_20140412_195110": [
        "/Users/stu/Photos/2014/IMG_20140412_195110.png"
    ],
    "IMG_20140413_143245": [
        "/Users/stu/Photos/2014/IMG_20140413_143245(6).png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(7).png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245.png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg",
        "/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg",
        "/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png"
    ]
}
</code>```

Any ideas how to do this in Python3?

Thanks

Edit: I just added a few more examples to the sample set of filenames.

答:
It appears that your pictures are identified by what is between the last 'G' (from 'IMG' or 'IMAG') and the next '.' or '(' or '-'.

Using that portion of the strings as a key, we can easily group filenames into a dict of lists.

files = ['/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg', '/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg', '/Users/stu/Photos/2014/IMG_20140413_072335.jpg', '/Users/stu/Documents/Backup/IMG_20140413_072335(4).png', '/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg', '/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg', '/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg', '/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg', '/Users/stu/Photos/2013/IMAG0097.jpg', '/Users/stu/Photos/2014/IMAG0097.jpg', '/Users/stu/Photos/2013/IMAG0126.jpg', '/Users/stu/Photos/Holidays/IMAG0132.jpg', '/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg', '/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg', '/Users/stu/Downloads/Photos/IMG_20140412_195105.png', '/Users/stu/Photos/2014/IMG_20140412_195110.png', '/Users/stu/Photos/2014/IMG_20140413_143245(6).png', '/Users/stu/Photos/2014/IMG_20140413_143245(7).png', '/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg', '/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg', '/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg', '/Users/stu/Photos/2014/IMG_20140413_143245.png', '/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg', '/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg', '/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png', '/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg', '/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg', '/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png', '/Users/stu/Photos/2013/IMG_20140413_072335.jpg', '/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg', '/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg', '/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg', '/Users/stu/Photos/2013/IMAG0126-edited.jpg', '/Users/stu/Photos/2013/IMAG0126546.jpg']

def photo_id(filename):
    i = filename.rfind('G') + 1
    j1 = filename.find('.', i)
    j2 = filename.find('(', i)
    j3 = filename.find('-', i)
    j = min(j for j in (j1,j2,j3,len(filename)) if j > -1)
    return filename[i:j]

photos = {}
for filename in files:
    photos.setdefault(photo_id(filename), []).append(filename)

print(photos)
# {'_20140413_072335': ['/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg', '/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg', '/Users/stu/Photos/2014/IMG_20140413_072335.jpg', '/Users/stu/Documents/Backup/IMG_20140413_072335(4).png', '/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg', '/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg', '/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg', '/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg', '/Users/stu/Photos/2013/IMG_20140413_072335.jpg', '/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg'],
#  '0097': ['/Users/stu/Photos/2013/IMAG0097.jpg', '/Users/stu/Photos/2014/IMAG0097.jpg'],
#  '0126': ['/Users/stu/Photos/2013/IMAG0126.jpg', '/Users/stu/Photos/2013/IMAG0126-edited.jpg'],
#  '0132': ['/Users/stu/Photos/Holidays/IMAG0132.jpg'],
#  '_20140322_142557': ['/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg'],
#  '_20140330_200132': ['/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg'],
#  '_20140412_195105': ['/Users/stu/Downloads/Photos/IMG_20140412_195105.png'],
#  '_20140412_195110': ['/Users/stu/Photos/2014/IMG_20140412_195110.png'],
#  '_20140413_143245': ['/Users/stu/Photos/2014/IMG_20140413_143245(6).png', '/Users/stu/Photos/2014/IMG_20140413_143245(7).png', '/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg', '/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg', '/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg', '/Users/stu/Photos/2014/IMG_20140413_143245.png', '/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg', '/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg', '/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png', '/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg', '/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg', '/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg', '/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png'],
#  '_20140413_072335_01': ['/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg'],
#  '_20140413_072335_9352': ['/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg'],
#  '0126546': ['/Users/stu/Photos/2013/IMAG0126546.jpg']}
```

Body:
I might not be searching the best terms to find a solution but so far nothing I've found has been able to solve my problem and I really don't know where to start or even what mechanisms to investigate.

I have a large list of image files in various locations on my hard drive and I'm trying to clean it up by removing the duplicates. Most of these are easy to find using hash codes but I have a lot of corrupted or edited versions which aren't so easy to find. I know I'll need some user interaction to identify and delete (archive) the unwanted files and I'll be doing some further processing to make sure metadata such as dates and geotagging are correct (also used to potentially match files) and then display similar images with all known data through a simple html interface.

One of the steps I've identified is grouping similarly named files or files which have part of another filename in its name. Sometimes these can be completely unrelated and so the user interaction will be required.

Below is a sample of files, what I would like is to group them into filenames which are similar, disregarding path and file extension.

[
"/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335.jpg",
"/Users/stu/Documents/Backup/IMG_20140413_072335(4).png",
"/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg",
"/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg",
"/Users/stu/Photos/2013/IMAG0097.jpg",
"/Users/stu/Photos/2014/IMAG0097.jpg",
"/Users/stu/Photos/2013/IMAG0126.jpg",
"/Users/stu/Photos/Holidays/IMAG0132.jpg",
"/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg",
"/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg",
"/Users/stu/Downloads/Photos/IMG_20140412_195105.png",
"/Users/stu/Photos/2014/IMG_20140412_195110.png",
"/Users/stu/Photos/2014/IMG_20140413_143245(6).png",
"/Users/stu/Photos/2014/IMG_20140413_143245(7).png",
"/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245.png",
"/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg",
"/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg",
"/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png",
"/Users/stu/Photos/2013/IMG_20140413_072335.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg",
"/Users/stu/Photos/2013/IMAG0126-edited.jpg",
"/Users/stu/Photos/2013/IMAG0126546.jpg"
]

The list of files above should output something like this:

{
    "IMG_20140413_072335": [
        "/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335.jpg",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(4).png",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg",
        "/Users/stu/Photos/2013/IMG_20140413_072335.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg"
    ],
    "IMAG0097": [
        "/Users/stu/Photos/2013/IMAG0097.jpg",
        "/Users/stu/Photos/2014/IMAG0097.jpg"
    ],
    "IMAG0126": [
        "/Users/stu/Photos/2013/IMAG0126.jpg",
        "/Users/stu/Photos/2013/IMAG0126-edited.jpg",
        "/Users/stu/Photos/2013/IMAG0126546.jpg"
    ],
    "IMAG0132": [
        "/Users/stu/Photos/Holidays/IMAG0132.jpg"
    ],
    "IMG_20140322_142557": [
        "/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg"
    ],
    "IMG_20140330_200132": [
        "/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg"
    ],
    "IMG_20140412_195105": [
        "/Users/stu/Downloads/Photos/IMG_20140412_195105.png"
    ],
    "IMG_20140412_195110": [
        "/Users/stu/Photos/2014/IMG_20140412_195110.png"
    ],
    "IMG_20140413_143245": [
        "/Users/stu/Photos/2014/IMG_20140413_143245(6).png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(7).png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245.png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg",
        "/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg",
        "/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png"
    ]
}

Any ideas how to do this in Python3?

Thanks

Edit: I just added a few more examples to the sample set of filenames.


问:
How Facebook parses blogspot.com open graph properties
Some pages of blogspot.com do not contain open graph tags, but Facebook Object Debugger still parse the open graph properties correctly. How does it get the open graph information?

For example, I don't see any open graph meta tag in http://sushiwens.blogspot.com/ source code. But it is correctly parsed by facebook https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fsushiwens.blogspot.com%2F

I need to implement something like the open graph parsing function in python, so I need to know how to do it.

答:
I don't have true source to be sure how facebook does, but this site may help you.

I used his ideas to develop a parser in python. If it can help you, the python project is here.

If I try to sum up a strategy to get data without og tags:

Title:

search the title tag

search h1 in body

search h2 in body ...

Description:

search in <meta name="description">

search in visible text in body (first
 for instance)

search for <meta name="twitter:description"> is a solution, but I don't do that: usually the description is bad, more related to twitter stuff than the true content of the link.

Domain name:

search <link rel="canonical">

search og:url

but I do simpler: extract the domain from the target link (in python: urlparse(url).netloc

Last but not least: images:

search <link rel="image_src" href="image url" />

parse the target link html for all  tags and "sort" them:

small images: those with one dimension <= 50px

bad ratio images: the remaining with ratio longest side / shortest side > 3

good images: the remaining

Then choose the biggest image in good images. If no good image: the biggest in bad ratio. Otherwise: the biggest in small images. (biggest = the max width x height)

Fetching all images can be time consuming! One can get the dimensions with the first bytes of the images, but that's another story (see 2nd link)

Body:
I don't have true source to be sure how facebook does, but this site may help you.

I used his ideas to develop a parser in python. If it can help you, the python project is here.

If I try to sum up a strategy to get data without og tags:

Title:

search the title tag

search h1 in body

search h2 in body ...

Description:

search in <meta name="description">

search in visible text in body (first <p> for instance)

search for <meta name="twitter:description"> is a solution, but I don't do that: usually the description is bad, more related to twitter stuff than the true content of the link.

Domain name:

search <link rel="canonical">

search og:url

but I do simpler: extract the domain from the target link (in python: urlparse(url).netloc

Last but not least: images:

search <link rel="image_src" href="image url" />

parse the target link html for all <img> tags and "sort" them:

small images: those with one dimension <= 50px

bad ratio images: the remaining with ratio longest side / shortest side > 3

good images: the remaining

Then choose the biggest image in good images. If no good image: the biggest in bad ratio. Otherwise: the biggest in small images. (biggest = the max width x height)

Fetching all images can be time consuming! One can get the dimensions with the first bytes of the images, but that's another story (see 2nd link)


问:
Upgrade from VS2015 to VS2022: Error LNK1104 cannot open file 'msvcprtd.lib'
I am trying to upgrade a project from VS2015 to VS2022 and getting the following error:

Error LNK1104 cannot open file 'msvcprtd.lib'

When I compile it as 2015 project, it works, but once I switch it to 2022, it fails.

答:
In my case, I needed to select the checkmark 'Inherit from parent or project defaults' in library directories

I created a new empty project and compared the library settings with my older project to see what was the difference.