问:
Bigquery - parametrize tables and columns in a stored procedure
Consider an enterprise that captures sensor data for different production facilities. per facility, we create an aggregation query that averages the values to 5min timeslots. This query  exists out of a long list of with-clauses and writes data to a table (called aggregation_table).

Now my problem: currently we have n queries running that exactly run the same logic, the only thing that differs are table names (and sometimes column names but let's ignore that for now).

Instead of managing n different scripts that are basically the same, I would like to put it in a stored procedure that is able to work like this:

CALL aggregation_query(facility_name) -> resolve the different tables for that facility and then use them in the different with clauses

On top of that, instead of having this long set of clauses that give me the end-result, I would like to chunk them up in logical blocks that are parametrizable, So for example, if I call the aforementioned stored_procedure for facility A, I want to be able to pass / use this table name in these different functions, where the output can be re-used in the next statement (like you would do with with clauses).

Another argument of why I want to chunk this up in re-usable blocks is because we have many "derivatives" on this aggregation query, for example to manage historical data, to correct data or to have the sensor data on another aggregation level. As these become overly complex, it is much easier to manage them without having to copy paste and adjust these every time.

In the current set-up, it could be useful to know that I am only entitled to use plain BigQuery, As my team is not allowed to access the CI/CD / scheduling and repository. (meaning that I cannot solve the issue by having CI/CD that deploys the n different versions of the procedure and functions)

So in the end, I would like to end up with something like this using only bigquery:

```<code>CREATE OR REPLACE PROCEDURE
  `aggregation_function`()
BEGIN
DECLARE
  tablename STRING;
DECLARE
  active_table_name STRING; ##get list OF tables CREATE TEMP TABLE tableNames AS
SELECT
  table_catalog,
  table_schema,
  table_name
FROM
  `catalog.schema.INFORMATION_SCHEMA.TABLES`
WHERE
  table_name = tablename;
WHILE
  (
  SELECT
    COUNT(*)
  FROM
    tableNames) >= 1 DO ##build dataset + TABLE name
SET
  active_table_name = CONCAT('`',table_catalog,'.',table_schema,'.' ,table_name,'`'); ##use concat TO build string AND execute
EXECUTE IMMEDIATE '''
INSERT INTO
  `aggregation_table_for_facility` (timeslot, sensor_name, AVG_VALUE )
WITH
  STEP_1 AS (
  SELECT
    *
  FROM
    my_table_function_step_1(active_table_name,
      parameter1,
      parameter2) ),
  STEP_2 AS (
  SELECT
    *
  FROM
    my_table_function_step_2(STEP_1,
      parameter1,
      parameter2) )
  SELECT * FROM STEP_2
  '''
USING active_table_name as active_table_name;
DELETE
FROM
  tableNames
WHERE
  table_name = tablename;
END WHILE
  ;
END
  ;

</code>```

I was hoping someone could make a snippet on how I can do this in Standard SQL / Bigquery, so basically:

stored procedure that takes in a string variable and is able to use that as a table (partly solved in the approach above, but not sure if there are better ways)

(table) function that is able to take this table_name parameter as well and return back a table that can be used in the next with clause (or alternatively writes to a temp table)

答:
I think below code snippets should provide you with some insights when dealing with procedures, inserts and execute immediate statements.

Here I'm creating a procedure which will insert values into a table that exists on the information schema. Also, as a value I want to return I use OUT active_table_name to return the value I assigned inside the procedure.

```<code>CREATE OR REPLACE PROCEDURE `project-id.dataset`.custom_function(tablename STRING,OUT active_table_name STRING)
BEGIN

DECLARE query STRING;

SET active_table_name= (SELECT CONCAT('`',table_catalog,'.',table_schema,'.' ,table_name,'`')
                        FROM `project-id.dataset.INFORMATION_SCHEMA.TABLES`
                        WHERE table_name = tablename);

#multine query can be handled by using ''' or """
Set query =
'''
insert into %s (string_field_0,string_field_1,string_field_2,string_field_3,string_field_4,int64_field_5)
with custom_query as (
   select string_field_0,string_field_2,'169 BestCity',string_field_3,string_field_4,55677 from %s limit 1
)
select * from custom_query;
''';

# querys must perform operations and must be the last thing to perform
# pass parameters using format
execute immediate (format(query,active_table_name,active_table_name));

END
</code>```

You can also use a loop to iterate trough records from a working table so it will execute the procedure and also be able to get the value from the procedure to use somewhere else.ie:A second procedure to perform a delete operation.

```<code>DECLARE tablename STRING;
DECLARE out_value STRING;

FOR record IN
  (SELECT tablename from `my-project-id.dataset.table`)
DO
  SET tablename = record.tablename;
  LOOP
    call `project-id.dataset`.custom_function(tablename,out_value);
    select out_value;
  END LOOP;
END FOR;
</code>```

To recap, there are some restrictions such as the possibility to call procedures inside a execute immediate or to use execute immediate inside an execute immediate, to count a few. I think these snippets should help you dealing with your current situation.

For this sample I use the following documentation:

Data Manipulation Language

Dealing with outputs

Information Schema Tables

Execute Immediate

For...In

Loops

Body:
Consider an enterprise that captures sensor data for different production facilities. per facility, we create an aggregation query that averages the values to 5min timeslots. This query  exists out of a long list of with-clauses and writes data to a table (called aggregation_table).

Now my problem: currently we have n queries running that exactly run the same logic, the only thing that differs are table names (and sometimes column names but let's ignore that for now).

Instead of managing n different scripts that are basically the same, I would like to put it in a stored procedure that is able to work like this:

CALL aggregation_query(facility_name) -> resolve the different tables for that facility and then use them in the different with clauses

On top of that, instead of having this long set of clauses that give me the end-result, I would like to chunk them up in logical blocks that are parametrizable, So for example, if I call the aforementioned stored_procedure for facility A, I want to be able to pass / use this table name in these different functions, where the output can be re-used in the next statement (like you would do with with clauses).

Another argument of why I want to chunk this up in re-usable blocks is because we have many "derivatives" on this aggregation query, for example to manage historical data, to correct data or to have the sensor data on another aggregation level. As these become overly complex, it is much easier to manage them without having to copy paste and adjust these every time.

In the current set-up, it could be useful to know that I am only entitled to use plain BigQuery, As my team is not allowed to access the CI/CD / scheduling and repository. (meaning that I cannot solve the issue by having CI/CD that deploys the n different versions of the procedure and functions)

So in the end, I would like to end up with something like this using only bigquery:

CREATE OR REPLACE PROCEDURE
  `aggregation_function`()
BEGIN
DECLARE
  tablename STRING;
DECLARE
  active_table_name STRING; ##get list OF tables CREATE TEMP TABLE tableNames AS
SELECT
  table_catalog,
  table_schema,
  table_name
FROM
  `catalog.schema.INFORMATION_SCHEMA.TABLES`
WHERE
  table_name = tablename;
WHILE
  (
  SELECT
    COUNT(*)
  FROM
    tableNames) >= 1 DO ##build dataset + TABLE name
SET
  active_table_name = CONCAT('`',table_catalog,'.',table_schema,'.' ,table_name,'`'); ##use concat TO build string AND execute
EXECUTE IMMEDIATE '''
INSERT INTO
  `aggregation_table_for_facility` (timeslot, sensor_name, AVG_VALUE )
WITH
  STEP_1 AS (
  SELECT
    *
  FROM
    my_table_function_step_1(active_table_name,
      parameter1,
      parameter2) ),
  STEP_2 AS (
  SELECT
    *
  FROM
    my_table_function_step_2(STEP_1,
      parameter1,
      parameter2) )
  SELECT * FROM STEP_2
  '''
USING active_table_name as active_table_name;
DELETE
FROM
  tableNames
WHERE
  table_name = tablename;
END WHILE
  ;
END
  ;

I was hoping someone could make a snippet on how I can do this in Standard SQL / Bigquery, so basically:

stored procedure that takes in a string variable and is able to use that as a table (partly solved in the approach above, but not sure if there are better ways)

(table) function that is able to take this table_name parameter as well and return back a table that can be used in the next with clause (or alternatively writes to a temp table)

Body:
I think below code snippets should provide you with some insights when dealing with procedures, inserts and execute immediate statements.

Here I'm creating a procedure which will insert values into a table that exists on the information schema. Also, as a value I want to return I use OUT active_table_name to return the value I assigned inside the procedure.

CREATE OR REPLACE PROCEDURE `project-id.dataset`.custom_function(tablename STRING,OUT active_table_name STRING)
BEGIN

DECLARE query STRING;

SET active_table_name= (SELECT CONCAT('`',table_catalog,'.',table_schema,'.' ,table_name,'`')
                        FROM `project-id.dataset.INFORMATION_SCHEMA.TABLES`
                        WHERE table_name = tablename);

#multine query can be handled by using ''' or """
Set query =
'''
insert into %s (string_field_0,string_field_1,string_field_2,string_field_3,string_field_4,int64_field_5)
with custom_query as (
   select string_field_0,string_field_2,'169 BestCity',string_field_3,string_field_4,55677 from %s limit 1
)
select * from custom_query;
''';

# querys must perform operations and must be the last thing to perform
# pass parameters using format
execute immediate (format(query,active_table_name,active_table_name));

END

You can also use a loop to iterate trough records from a working table so it will execute the procedure and also be able to get the value from the procedure to use somewhere else.ie:A second procedure to perform a delete operation.

DECLARE tablename STRING;
DECLARE out_value STRING;

FOR record IN
  (SELECT tablename from `my-project-id.dataset.table`)
DO
  SET tablename = record.tablename;
  LOOP
    call `project-id.dataset`.custom_function(tablename,out_value);
    select out_value;
  END LOOP;
END FOR;

To recap, there are some restrictions such as the possibility to call procedures inside a execute immediate or to use execute immediate inside an execute immediate, to count a few. I think these snippets should help you dealing with your current situation.

For this sample I use the following documentation:

Data Manipulation Language

Dealing with outputs

Information Schema Tables

Execute Immediate

For...In

Loops


来源: stackexchange

问:
The requested registry access is invalid
I'm a learning System engineer and I have to Script a PowerShell Script who simply creates a Registry Key and a Value in it. I can't get it right, there is always this weird error popping up. Likewise, I already tried running it as an Administrator. Please Help!

Translation of the Error.
“The requested registry access is invalid.”

Script:

$regkey="HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Defender\Reporting"

$regparam="DisableEnhancedNotifications"

cd HKLM:\

New-ItemProperty -Path "$regkey" -Name "$regparam" -Value "test" -PropertyType "String"

Thanks!

答:
```<code>$regkey='HKLM:\SOFTWARE\Microsoft\Windows Defender\Reporting'
$regparam='DisableEnhancedNotifications'

# create key
New-Item -Path $regkey -Force

# create entry
New-ItemProperty -Path $regkey -Name $regparam -PropertyType String -Value 'test' -Force
</code>```

more examples: Working with Registry Entries (learn.microsoft.com)

ContentLicense: CC BY-SA 4.0

Body:
$regkey='HKLM:\SOFTWARE\Microsoft\Windows Defender\Reporting'
$regparam='DisableEnhancedNotifications'

# create key
New-Item -Path $regkey -Force

# create entry
New-ItemProperty -Path $regkey -Name $regparam -PropertyType String -Value 'test' -Force

more examples: Working with Registry Entries (learn.microsoft.com)


问:
Adding menus to child preference screens
I have a menu that comes up for my PreferenceActivity. In my child preference screens, I lose that menu (doesn't pop up). How can I make my menu pop up for children too?

Thanks.

Example:

```<code><PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:persistent="true">
  <PreferenceCategory
    android:title="some category"
    android:persistent="true"
    android:orderingFromXml="true">
    <PreferenceScreen
      android:title="some child screen"
      android:summary="some child summary">
      <PreferenceCategory
         ...
</code>```

The first preference screen has the menu, but when you click on the child one, no menu. How can you add the menu?

答:
I have better solution because Suriya's suffer from double showing of child's PreferenceScreen.

For child PreferenceScreen I use same PreferenceActivity. So at first for a child PreferenceScreen where we want to use option menu we set intent to our PreferenceActivity in onCreate method:

```<code>ourPreferenceScreen = (PreferenceScreen) findPreference("our_preference_screen");
if (ourPreferenceScreen != null) {
    Intent intent = new Intent(this, PreferenceActivity.class);
    intent.putExtra("ShowOurPreferenceScreen", true);
    ourPreferenceScreen.setIntent(intent);
}
</code>```

Then later in a same onCreate method we detect if our PreferenceActivity is started with extra flag. If so we switch to wanted PreferenceScreen:

```<code>if (getIntent().getBooleanExtra("ShowOurPreferenceScreen", false)) {
    setPreferenceScreen(ourPreferenceScreen);
    return;
}
</code>```

And at the end we hande onCreateOptionMenu and other related option menu methods like this:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (getPreferenceScreen().equals(ourPreferenceScreen)) {
        // your menu code
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a menu that comes up for my PreferenceActivity. In my child preference screens, I lose that menu (doesn't pop up). How can I make my menu pop up for children too?

Thanks.

Example:

<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:persistent="true">
  <PreferenceCategory
    android:title="some category"
    android:persistent="true"
    android:orderingFromXml="true">
    <PreferenceScreen
      android:title="some child screen"
      android:summary="some child summary">
      <PreferenceCategory
         ...

The first preference screen has the menu, but when you click on the child one, no menu. How can you add the menu?

Body:
I have better solution because Suriya's suffer from double showing of child's PreferenceScreen.

For child PreferenceScreen I use same PreferenceActivity. So at first for a child PreferenceScreen where we want to use option menu we set intent to our PreferenceActivity in onCreate method:

ourPreferenceScreen = (PreferenceScreen) findPreference("our_preference_screen");
if (ourPreferenceScreen != null) {
    Intent intent = new Intent(this, PreferenceActivity.class);
    intent.putExtra("ShowOurPreferenceScreen", true);
    ourPreferenceScreen.setIntent(intent);
}

Then later in a same onCreate method we detect if our PreferenceActivity is started with extra flag. If so we switch to wanted PreferenceScreen:

if (getIntent().getBooleanExtra("ShowOurPreferenceScreen", false)) {
    setPreferenceScreen(ourPreferenceScreen);
    return;
}

And at the end we hande onCreateOptionMenu and other related option menu methods like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (getPreferenceScreen().equals(ourPreferenceScreen)) {
        // your menu code
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

ContentLicense: CC BY-SA 3.0


问:
remove duplicate entries in two different JSON file
I have extensive data in many JSON files, but the problem is that they are many duplicate entries and it make lot's of trouble to find them is that any way to remove them with one click

How can I remove duplicate entries from two different JSON files using python?

First File

```<code>[
    {
        "client_id": "1343314236",
        "username": "Nandhu_y_z",
        "name": "nadhu Nandhan"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    }
]

</code>```

Second File

```<code>
[
    {
        "client_id": "1343314236",
        "username": "Na1dhu_y_z",
        "name": "nadhu Nandhan"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    }
]

</code>```

答:
```<code>#suppose here we have some json files with names using numbers ranging from 1 to 500 and ending with the extension .json
#such as 1.json, 2.json, etc
# but not limited to naming files using numbers,
# but here I use numbers for convenience only

import json
from pathlib import Path

def load_json(filename):
    file = open('{0}.json'.format(filename), 'r')
    return json.load(file)

def remove_duplicate(data1, data2):
    return [data for data in data2 if data not in data1]

def overwrite(filename, data):
    with open('{0}.json'.format(filename), 'w') as file:
        json.dump(data , file)

#start creating variables from the first file
lists = load_json('1');

#if you also want to remove duplicate data in the first file
lists  = [i for n, i in enumerate(lists) if i not in lists[n + 1:]]
#'1' is the filename
overwrite('1', lists)

#let's do it on all files
json_path = "./"
for file in Path(json_path).glob('*.json'):
    #get filename without extension
    name = file.name.replace('.json', '')
    #if file 1 then skip
    if(name == '1'): continue
    #remove duplicate data
    data = remove_duplicate(lists, load_json(name))
    #then overwrite the file
    overwrite(name, data)
    #add in lists to filter the next file
    lists += data
</code>```

Body:
I have extensive data in many JSON files, but the problem is that they are many duplicate entries and it make lot's of trouble to find them is that any way to remove them with one click

How can I remove duplicate entries from two different JSON files using python?

First File

[
    {
        "client_id": "1343314236",
        "username": "Nandhu_y_z",
        "name": "nadhu Nandhan"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    }
]

Second File

[
    {
        "client_id": "1343314236",
        "username": "Na1dhu_y_z",
        "name": "nadhu Nandhan"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    }
]


问:
Can't use ActiveX component, built on Visual Studio 2019
I have an ActiveX control that I build in Visual Studio. But once registered, it cannot be used. Specific examples:

It builds on Visual Studio 17 with all the latest updates, successfully registers and controls can be used, for example, in RadStudio, in Visual Basic, in C # in the studio, etc.

It builds on Visual Studio 19 with all the latest updates, registers successfully, but RadStudio does not see it. And in VisualBasic, the component is visible, but when you try to add it to the form, an "Unspecified Error" error pops up. At the same time, everything is ok in the studio in C #: everything sees and works.

At the same time, the source codes are absolutely the same, all those compilation flags, linking, etc. What could be the reason?

答: Ok. I found reason. Somehow in  my vs2019 PreferredToolArchitecture was set to x64 instead of x86. By changing it to x86 everything becomes good.


问:
How to attach multiple IAM policies to IAM roles using Terraform?
I want to attach multiple IAM Policy ARNs to a single IAM Role.

One method is to create a new policy with privileges of all the policies (multiple policies).

But in AWS, we have some predefined IAM policies like AmazonEC2FullAccess, AmazomS3FullAccess, etc. I want to use a combination of these for my role.

I could not find a way to do so in the Terraform documentation.

As per documentation we can use aws_iam_role_policy_attachment to attach a policy to a role, but not multiple policies to a role as this is available via AWS console.

Please let me know if there is a method to do the same or is it still a feature to be added.

The Terraform version I use is v0.9.5

答:
In my case I added multiple statements in one policy document:

```<code>data "aws_iam_policy_document" "sns-and-sqs-policy" {
  statement {
    sid    = "AllowToPublishToSns"
    effect = "Allow"
    actions = [
      "sns:Publish",
    ]
    resources = [
      data.resource.arn,
    ]
  }
  statement {
    sid    = "AllowToSubscribeFromSqs"
    effect = "Allow"
    actions = [
      "sqs:changeMessageVisibility*",
      "sqs:SendMessage",
      "sqs:ReceiveMessage",
      "sqs:GetQueue*",
      "sqs:DeleteMessage",
    ]
    resources = [
      data.resource.arn,
    ]
  }
}

resource "aws_iam_policy" "sns-and-sqs" {
  name   = "sns-and-sqs-policy"
  policy = data.aws_iam_policy_document.sns-and-sqs-policy.json
}

resource "aws_iam_role_policy_attachment" "sns-and-sqs-role" {
  role       = "role_name"
  policy_arn = aws_iam_policy.sns-and-sqs.arn
}
</code>```

simply combine your policies in one policy

Body:
In my case I added multiple statements in one policy document:

data "aws_iam_policy_document" "sns-and-sqs-policy" {
  statement {
    sid    = "AllowToPublishToSns"
    effect = "Allow"
    actions = [
      "sns:Publish",
    ]
    resources = [
      data.resource.arn,
    ]
  }
  statement {
    sid    = "AllowToSubscribeFromSqs"
    effect = "Allow"
    actions = [
      "sqs:changeMessageVisibility*",
      "sqs:SendMessage",
      "sqs:ReceiveMessage",
      "sqs:GetQueue*",
      "sqs:DeleteMessage",
    ]
    resources = [
      data.resource.arn,
    ]
  }
}

resource "aws_iam_policy" "sns-and-sqs" {
  name   = "sns-and-sqs-policy"
  policy = data.aws_iam_policy_document.sns-and-sqs-policy.json
}

resource "aws_iam_role_policy_attachment" "sns-and-sqs-role" {
  role       = "role_name"
  policy_arn = aws_iam_policy.sns-and-sqs.arn
}

simply combine your policies in one policy


问:
noSuchMethodError when starting spring boot application with eureka
When I start My Spring Boot Application with Eureka Server, I run into a NoSuchMethodError.
I tried the solutions of several similar questions from here, but sadly none of them worked in my case.

The Application worked like a charm before I decided to turn it into a cloud application by adding Eureka Server.

My stacktrace:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:161)

The following method did not exist:

    'void org.springframework.boot.builder.SpringApplicationBuilder.<init>(java.lang.Object[])'

The calling method's class, org.springframework.cloud.bootstrap.BootstrapApplicationListener, was loaded from the following location:

    jar:file:/C:/Users/ruthh/.m2/repository/org/springframework/cloud/spring-cloud-context/1.3.6.RELEASE/spring-cloud-context-1.3.6.RELEASE.jar!/org/springframework/cloud/bootstrap/BootstrapApplicationListener.class

The called method's class, org.springframework.boot.builder.SpringApplicationBuilder, is available from the following locations:

    jar:file:/C:/Users/ruthh/.m2/repository/org/springframework/boot/spring-boot/2.6.3/spring-boot-2.6.3.jar!/org/springframework/boot/builder/SpringApplicationBuilder.class

The called method's class hierarchy was loaded from the following locations:

    org.springframework.boot.builder.SpringApplicationBuilder: file:/C:/Users/ruthh/.m2/repository/org/springframework/boot/spring-boot/2.6.3/spring-boot-2.6.3.jar

Action:

Correct the classpath of your application so that it contains compatible versions of the classes org.springframework.cloud.bootstrap.BootstrapApplicationListener and org.springframework.boot.builder.SpringApplicationBuilder

</code>```

My Application.properties:

```<code>spring.datasource.url=jdbc:mariadb://localhost:3306/woerdl
spring.datasource.username=root
spring.datasource.password=[redacted]
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto=none
spring.sql.init.mode=always
server.port=8010

spring.application.name=woerdl_db
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.server.enable-self-preservation=true
eureka.server.waitTimeInMsWhenSyncEmpty=0
eureka.instance.lease-expiration-duration-in-seconds= 15
eureka.instance.lease-renewal-interval-in-seconds= 5
eureka.instance.hostname=localhost
</code>```

My Main class:

```<code>package de.derandy.woerdl_db;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

import de.derandy.woerdl_db.config.Config;

@EnableEurekaServer
@SpringBootApplication
public class Woerdl_dbApplication {

    public static void main(final String[] args) {
        Config.config(args);

    }

}
</code>```

My Config class:

```<code>package de.derandy.woerdl_db.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import de.derandy.woerdl_db.Woerdl_dbApplication;
import de.derandy.woerdl_db.wort.service.impl.WortServiceImpl;

@Configuration
public class Config {

    public static ApplicationContext context;

    public static Environment environment;

    public static String[] args;

    public static String random;

    @Autowired
    private static WortServiceImpl wortService;

    public static void config(final String[] args) {
        Config.args = args;
        Config.context = new SpringApplicationBuilder(Woerdl_dbApplication.class).registerShutdownHook(true)
                .run(Config.args);

        environment = Config.context.getEnvironment();

        wortService =   (WortServiceImpl) Config.context.getBean("wortServiceImpl");

        random = wortService.findRandom();
    }

}
</code>```

My pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>de.derandy</groupId>
    <artifactId>woerdl_db</artifactId>
    <version>1.0</version>
    <name>woerdl_db</name>
    <description>Ein Wortspiel</description>
    <properties>
        <java.version>17</java.version>
        <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-apache-client4</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>17</source> <!-- depending on your project -->
                    <target>17</target> <!-- depending on your project -->
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>
</code>```

答:
I resolved the issue by editing the Pom.
I added jaxb-runtime and spring-cloud-dependencies

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>de.derandy</groupId>
    <artifactId>woerdl_db</artifactId>
    <version>1.0</version>
    <name>woerdl_db</name>
    <description>Ein Wortspiel</description>
    <properties>
        <java.version>17</java.version>
        <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-apache-client4</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>17</source> <!-- depending on your project -->
                    <target>17</target> <!-- depending on your project -->
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>
</code>```

Body:
When I start My Spring Boot Application with Eureka Server, I run into a NoSuchMethodError.
I tried the solutions of several similar questions from here, but sadly none of them worked in my case.

The Application worked like a charm before I decided to turn it into a cloud application by adding Eureka Server.

My stacktrace:

***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:161)

The following method did not exist:

    'void org.springframework.boot.builder.SpringApplicationBuilder.<init>(java.lang.Object[])'

The calling method's class, org.springframework.cloud.bootstrap.BootstrapApplicationListener, was loaded from the following location:

    jar:file:/C:/Users/ruthh/.m2/repository/org/springframework/cloud/spring-cloud-context/1.3.6.RELEASE/spring-cloud-context-1.3.6.RELEASE.jar!/org/springframework/cloud/bootstrap/BootstrapApplicationListener.class

The called method's class, org.springframework.boot.builder.SpringApplicationBuilder, is available from the following locations:

    jar:file:/C:/Users/ruthh/.m2/repository/org/springframework/boot/spring-boot/2.6.3/spring-boot-2.6.3.jar!/org/springframework/boot/builder/SpringApplicationBuilder.class

The called method's class hierarchy was loaded from the following locations:

    org.springframework.boot.builder.SpringApplicationBuilder: file:/C:/Users/ruthh/.m2/repository/org/springframework/boot/spring-boot/2.6.3/spring-boot-2.6.3.jar

Action:

Correct the classpath of your application so that it contains compatible versions of the classes org.springframework.cloud.bootstrap.BootstrapApplicationListener and org.springframework.boot.builder.SpringApplicationBuilder

My Application.properties:

spring.datasource.url=jdbc:mariadb://localhost:3306/woerdl
spring.datasource.username=root
spring.datasource.password=[redacted]
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto=none
spring.sql.init.mode=always
server.port=8010

spring.application.name=woerdl_db
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.server.enable-self-preservation=true
eureka.server.waitTimeInMsWhenSyncEmpty=0
eureka.instance.lease-expiration-duration-in-seconds= 15
eureka.instance.lease-renewal-interval-in-seconds= 5
eureka.instance.hostname=localhost

My Main class:

package de.derandy.woerdl_db;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

import de.derandy.woerdl_db.config.Config;

@EnableEurekaServer
@SpringBootApplication
public class Woerdl_dbApplication {

    public static void main(final String[] args) {
        Config.config(args);

    }

}

My Config class:

package de.derandy.woerdl_db.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import de.derandy.woerdl_db.Woerdl_dbApplication;
import de.derandy.woerdl_db.wort.service.impl.WortServiceImpl;

@Configuration
public class Config {

    public static ApplicationContext context;

    public static Environment environment;

    public static String[] args;

    public static String random;

    @Autowired
    private static WortServiceImpl wortService;

    public static void config(final String[] args) {
        Config.args = args;
        Config.context = new SpringApplicationBuilder(Woerdl_dbApplication.class).registerShutdownHook(true)
                .run(Config.args);

        environment = Config.context.getEnvironment();

        wortService =   (WortServiceImpl) Config.context.getBean("wortServiceImpl");

        random = wortService.findRandom();
    }

}

My pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath />
    </parent>
    <groupId>de.derandy</groupId>
    <artifactId>woerdl_db</artifactId>
    <version>1.0</version>
    <name>woerdl_db</name>
    <description>Ein Wortspiel</description>
    <properties>
        <java.version>17</java.version>
        <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-apache-client4</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

Body:
I resolved the issue by editing the Pom.
I added jaxb-runtime and spring-cloud-dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>de.derandy</groupId>
    <artifactId>woerdl_db</artifactId>
    <version>1.0</version>
    <name>woerdl_db</name>
    <description>Ein Wortspiel</description>
    <properties>
        <java.version>17</java.version>
        <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-apache-client4</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>17</source> <!-- depending on your project -->
                    <target>17</target> <!-- depending on your project -->
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>


问:
How do I point to a location on map with a click event
In React, I'm trying to make an onClick event point a marker on a map to a new location using google-map-react library. My map is showing and I have a button on the map but I'm not sure how to make a marker on the map point to a new coordinates I have. The documentation on google-map-react isn't very helpful. I've tried to set new coordinates using the onChildClick parameter as seen in my code below but it isn' t working. The following is a section of my code</p>
```<code>...<GoogleMapReact
        bootstrapURLKeys={{
          key: 'API_KEY',
        }}
        defaultCenter={mapProp.center}
        defaultZoom={mapProp.zoom}
        options={mapOptions}
        yesIWantToUseGoogleMapApiInternals
        onGoogleApiLoaded={({ map, maps }) => handleApiLoaded(map, maps)}
        onChildClick={() => {
          setCoord({
            latitude: coord.latitude,
            longitude: coord.longitude,
          });
        }}
      >
        <Button
          variant="light"
          style={{
            position: 'absolute',
            left: '-20%',
            top: '-340px',
          }}
          onClick={handleCoordinates}
        >
          Find new place button
        </Button>
        {cardVisible && <MyMarker />}
        {cardVisible && (
          <MarkerComponent
            lat={59.965411}
            lng={30.377844}
            text={'Location Marker info here!'}
          />
        )}
      </GoogleMapReact>
</code>```

答:
Your code never updates the location of the marker.

const [coord, setCoord] = useState({latitude: 59.965411, longitude:30.377844});

...

return ...<GoogleMapReact
       ...
         <MarkerComponent
            lat={coord.latitude}
            lng={coord.longitude}
            text={'Location Marker info here!'}
          />
```

Body:
In React, I'm trying to make an onClick event point a marker on a map to a new location using google-map-react library. My map is showing and I have a button on the map but I'm not sure how to make a marker on the map point to a new coordinates I have. The documentation on google-map-react isn't very helpful. I've tried to set new coordinates using the onChildClick parameter as seen in my code below but it isn' t working. The following is a section of my code

...<GoogleMapReact
        bootstrapURLKeys={{
          key: 'API_KEY',
        }}
        defaultCenter={mapProp.center}
        defaultZoom={mapProp.zoom}
        options={mapOptions}
        yesIWantToUseGoogleMapApiInternals
        onGoogleApiLoaded={({ map, maps }) => handleApiLoaded(map, maps)}
        onChildClick={() => {
          setCoord({
            latitude: coord.latitude,
            longitude: coord.longitude,
          });
        }}
      >
        <Button
          variant="light"
          style={{
            position: 'absolute',
            left: '-20%',
            top: '-340px',
          }}
          onClick={handleCoordinates}
        >
          Find new place button
        </Button>
        {cardVisible && <MyMarker />}
        {cardVisible && (
          <MarkerComponent
            lat={59.965411}
            lng={30.377844}
            text={'Location Marker info here!'}
          />
        )}
      </GoogleMapReact>


问:
What's the difference between these two requests?
Why does the first request return 200,

```<code>fetch("https://api.peopledatalabs.com/v5/autocomplete?api_key=someAPIKey&field=location")
</code>```

but the second returns 400/401?

```<code>fetch(`https://api.peopledatalabs.com/v5/autocomplete`, {
    "api_key": "someAPIKey",
    "field": "location"
    });
</code>```

答:
In the second way, you passed the option parameter (with "api_key" and "field"), not queryParams as you meant.

You can change it to work using URLSearchParams

```<code>fetch('https://api.peopledatalabs.com/v5/autocomplete?' + new URLSearchParams({
    api_key: "someAPIKey",
    field: "location",
}))
</code>```

Body:
Why does the first request return 200,

fetch("https://api.peopledatalabs.com/v5/autocomplete?api_key=someAPIKey&field=location")

but the second returns 400/401?

fetch(`https://api.peopledatalabs.com/v5/autocomplete`, {
    "api_key": "someAPIKey",
    "field": "location"
    });

Body:
In the second way, you passed the option parameter (with "api_key" and "field"), not queryParams as you meant.

You can change it to work using URLSearchParams

fetch('https://api.peopledatalabs.com/v5/autocomplete?' + new URLSearchParams({
    api_key: "someAPIKey",
    field: "location",
}))


问:
Order the plotting of data by the contents of a date column
I have dataset as follows:

```<code>df = data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
            issued = c(UKS, USD, UKS, UKS, USD, USD),
            mat = c(2024-01-31, 2023-01-31, 2026-10-22, 2022-07-22, 2029-01-31, 2025-06-07)
            volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417)
</code>```

I currently plot (and filter) the data using the following code:

```<code>plot1<- ggplot(subset(df, issued == "UKS")) +
  geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),
        panel.background = element_rect(fill='white',color='black'),
        legend.position='right')+
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
</code>```

I'd like to be able to order this data using the 'mat' column as guide, namely with the data that has the earliest 'mat' date at the top of the Y axis and the most distant 'mat' date at the bottom. Does anyone have any advice on how to achieve this?

Edit: I use grid arrange to plot it against another chart.

```<code>grid.arrange(plot1,plot2,ncol=2)
</code>```

Sadly I get the following error:

```<code>Error in `-.POSIXt`(Maturity) : unary '-' is not defined for "POSIXt" objects
</code>```

答:
You can use stats::reorder() inside aes() to reorder the bars. If a factor is supplied you don't need to supply a FUN, but for a continuous variable like Date you can specify the way to sort. In your data (although you didn't post it this way in the question), it seems your mat variable is POSIXlt. This format cannot be directly operated on as a numeric. Instead, I suggest using POSIXct and then it will work. See ?stats::reorder for more info on how to control this. Another option is to set levels of the factor in the data before passing to ggplot() which might be a better option if you have complex sorting to do.

library(tidyverse)

df <- data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
                issued = c("UKS", "USD", "UKS", "UKS", "USD", "USD"),
                mat = c("2024-01-31", "2023-01-31", "2026-10-22", "2022-07-22", "2029-01-31", "2025-06-07"),
                volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417))

df %>%
  mutate(mat = as.POSIXct(mat)) %>%
  filter(issued == "UKS") %>%
  # mutate(name = fct_reorder(.f = name, .x = mat)) %>% ggplot(aes(volume, name)) +
  ggplot(aes(x = volume, y = reorder(x = name, X = mat, FUN = sort))) +
  geom_col(fill = "#1170aa") +
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name") +
    theme(
    title = element_text(size = 12),
    panel.background = element_rect(fill = 'white', color = 'black'),
    legend.position = 'right'
  )
```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
I have dataset as follows:

df = data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
            issued = c(UKS, USD, UKS, UKS, USD, USD),
            mat = c(2024-01-31, 2023-01-31, 2026-10-22, 2022-07-22, 2029-01-31, 2025-06-07)
            volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417)

I currently plot (and filter) the data using the following code:

plot1<- ggplot(subset(df, issued == "UKS")) +
  geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),
        panel.background = element_rect(fill='white',color='black'),
        legend.position='right')+
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")

I'd like to be able to order this data using the 'mat' column as guide, namely with the data that has the earliest 'mat' date at the top of the Y axis and the most distant 'mat' date at the bottom. Does anyone have any advice on how to achieve this?

Edit: I use grid arrange to plot it against another chart.

grid.arrange(plot1,plot2,ncol=2)

Sadly I get the following error:

Error in `-.POSIXt`(Maturity) : unary '-' is not defined for "POSIXt" objects

Body:
You can use stats::reorder() inside aes() to reorder the bars. If a factor is supplied you don't need to supply a FUN, but for a continuous variable like Date you can specify the way to sort. In your data (although you didn't post it this way in the question), it seems your mat variable is POSIXlt. This format cannot be directly operated on as a numeric. Instead, I suggest using POSIXct and then it will work. See ?stats::reorder for more info on how to control this. Another option is to set levels of the factor in the data before passing to ggplot() which might be a better option if you have complex sorting to do.

library(tidyverse)

df <- data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
                issued = c("UKS", "USD", "UKS", "UKS", "USD", "USD"),
                mat = c("2024-01-31", "2023-01-31", "2026-10-22", "2022-07-22", "2029-01-31", "2025-06-07"),
                volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417))

df %>%
  mutate(mat = as.POSIXct(mat)) %>%
  filter(issued == "UKS") %>%
  # mutate(name = fct_reorder(.f = name, .x = mat)) %>% ggplot(aes(volume, name)) +
  ggplot(aes(x = volume, y = reorder(x = name, X = mat, FUN = sort))) +
  geom_col(fill = "#1170aa") +
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name") +
    theme(
    title = element_text(size = 12),
    panel.background = element_rect(fill = 'white', color = 'black'),
    legend.position = 'right'
  )

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
Aggregation query takes more than hour Oracle
```<code>SELECT
  subs_key,
  sum(ROUNDED_DATA_VOLUME) AS RDV_SUM,
  CASE WHEN to_char(CALL_START_TIME , 'HH24:MI:SS') >= '00:00:00'
        AND to_char(CALL_START_TIME , 'HH24:MI:SS') <= '07:00:00' THEN 'Night'
       WHEN to_char(CALL_START_TIME , 'HH24:MI:SS') >  '07:00:00'
        AND to_char(CALL_START_TIME , 'HH24:MI:SS') <= '23:59:59' THEN 'Day'
  END AS Tariff_flag
FROM DWH.FCT_USAGE_PREP_OGPRS_N
WHERE CALL_START_TIME >= to_date('2021-11-01', 'YYYY-MM-DD')
  AND CALL_START_TIME <= to_date('2021-11-30', 'YYYY-MM-DD')
GROUP BY
  SUBS_KEY,
  CASE WHEN (to_char(CALL_START_TIME , 'HH24:MI:SS') >= '00:00:00'
    AND to_char(CALL_START_TIME, 'HH24:MI:SS') <= '07:00:00') THEN 'Night'
       WHEN (to_char(CALL_START_TIME , 'HH24:MI:SS') > '07:00:00'
    AND to_char(CALL_START_TIME, 'HH24:MI:SS') <= '23:59:59') THEN 'Day'
  END
</code>```

My query takes more than hour and still running. Is there any way to optimize it?

UPD:

Execution Plan

Is that what Ankit asked?

答:
You are grouping by a relatively complex function:

```<code>CASE WHEN (to_char(CALL_START_TIME , 'HH24:MI:SS') >= '00:00:00' AND to_char(CALL_START_TIME , 'HH24:MI:SS') <= '07:00:00') THEN 'Night'
WHEN (to_char(CALL_START_TIME , 'HH24:MI:SS') > '07:00:00' AND to_char(CALL_START_TIME , 'HH24:MI:SS') <= '23:59:59') THEN 'Day' END
</code>```

If this particular query is important enough you could index this whole thing, but I suspect you would be better off getting the hour using extract.

```<code>CASE WHEN extract(hour from CALL_START_TIME) > 7 then 'Night' --midnight (inclusive) - 7am (exclusive)
     else 'Day' --7am (inclusive) - midnight (exclusive)
END
</code>```

For your where clause I would
I have no way to tell whether this will speed up your query. Or speed it up sufficiently for your use case. But you can try out the two queries and see if one of them is significantly faster than the other. Also, if you're frequently using times, it might make sense to index extract(hour from CALL_START_TIME), whereas an index on your entire case statement is only likely to get used in this one query.

Your question is how to speed up the query but when I have a query that takes hours to run I will often not bother to optimize it. It's long enough that you're unlikely to get the kind of speed-ups you need to have an application executing the query based on a user's request, and if a query takes 1 hour or 12, you likely need to plan when you run it.

Body:
SELECT
  subs_key,
  sum(ROUNDED_DATA_VOLUME) AS RDV_SUM,
  CASE WHEN to_char(CALL_START_TIME , 'HH24:MI:SS') >= '00:00:00'
        AND to_char(CALL_START_TIME , 'HH24:MI:SS') <= '07:00:00' THEN 'Night'
       WHEN to_char(CALL_START_TIME , 'HH24:MI:SS') >  '07:00:00'
        AND to_char(CALL_START_TIME , 'HH24:MI:SS') <= '23:59:59' THEN 'Day'
  END AS Tariff_flag
FROM DWH.FCT_USAGE_PREP_OGPRS_N
WHERE CALL_START_TIME >= to_date('2021-11-01', 'YYYY-MM-DD')
  AND CALL_START_TIME <= to_date('2021-11-30', 'YYYY-MM-DD')
GROUP BY
  SUBS_KEY,
  CASE WHEN (to_char(CALL_START_TIME , 'HH24:MI:SS') >= '00:00:00'
    AND to_char(CALL_START_TIME, 'HH24:MI:SS') <= '07:00:00') THEN 'Night'
       WHEN (to_char(CALL_START_TIME , 'HH24:MI:SS') > '07:00:00'
    AND to_char(CALL_START_TIME, 'HH24:MI:SS') <= '23:59:59') THEN 'Day'
  END

My query takes more than hour and still running. Is there any way to optimize it?

UPD:

Execution Plan

Is that what Ankit asked?

Body:
You are grouping by a relatively complex function:

CASE WHEN (to_char(CALL_START_TIME , 'HH24:MI:SS') >= '00:00:00' AND to_char(CALL_START_TIME , 'HH24:MI:SS') <= '07:00:00') THEN 'Night'
WHEN (to_char(CALL_START_TIME , 'HH24:MI:SS') > '07:00:00' AND to_char(CALL_START_TIME , 'HH24:MI:SS') <= '23:59:59') THEN 'Day' END

If this particular query is important enough you could index this whole thing, but I suspect you would be better off getting the hour using extract.

CASE WHEN extract(hour from CALL_START_TIME) > 7 then 'Night' --midnight (inclusive) - 7am (exclusive)
     else 'Day' --7am (inclusive) - midnight (exclusive)
END

For your where clause I would
I have no way to tell whether this will speed up your query. Or speed it up sufficiently for your use case. But you can try out the two queries and see if one of them is significantly faster than the other. Also, if you're frequently using times, it might make sense to index extract(hour from CALL_START_TIME), whereas an index on your entire case statement is only likely to get used in this one query.

Your question is how to speed up the query but when I have a query that takes hours to run I will often not bother to optimize it. It's long enough that you're unlikely to get the kind of speed-ups you need to have an application executing the query based on a user's request, and if a query takes 1 hour or 12, you likely need to plan when you run it.


问:
SyntaxError: Cannot use import statement outside a module React JS Antd
For bundle size optimization instead of getting components from the lib folder, I am importing it from the es folder.

Example:

```<code>import Modal from 'antd/es/modal';
</code>```

So on writing test cases it is giving me the following error

SyntaxError: Cannot use import statement outside a module

I have gone through related questions possibly duplicate but couldn't resolve it with my current implementation as it does not fall to global scope.

So my question is, Is there any way to achieve this

I tried referring to the following links too but no help,

https://github.com/reactstrap/reactstrap/blob/master/package.json#L21
https://medium.com/@fredriccliver/syntaxerror-cannot-use-import-statement-outside-a-module-69182014b8c6

答:
Change

```<code>import frFR from 'antd/es/locale/fr_FR';
</code>```

to

```<code>import frFR from 'antd/lib/locale/fr_FR';
</code>```

fix this problem.

Body:
For bundle size optimization instead of getting components from the lib folder, I am importing it from the es folder.

Example:

import Modal from 'antd/es/modal';

So on writing test cases it is giving me the following error

SyntaxError: Cannot use import statement outside a module

I have gone through related questions possibly duplicate but couldn't resolve it with my current implementation as it does not fall to global scope.

So my question is, Is there any way to achieve this

I tried referring to the following links too but no help,

https://github.com/reactstrap/reactstrap/blob/master/package.json#L21
https://medium.com/@fredriccliver/syntaxerror-cannot-use-import-statement-outside-a-module-69182014b8c6

Body:
Change

import frFR from 'antd/es/locale/fr_FR';

to

import frFR from 'antd/lib/locale/fr_FR';

fix this problem.


问:
DNN List multiple documents on page
I am developing an intranet using DotNetNuke and would like know if anyone has come across a module for listing many files stored in a website folder.

I have many pages which need to list a lot of reference documents, and am happy with DNN's ability to upload them into the file manager, but am coming unstuck with regard to adding each file to the 'Documents' module one by one for each page on the site.

I have done heaps of searching on this and was wondering if anyone had come across the same problem.

答:
Yes indeed. Check out Ventrian's file links module

Use the core DNN file component to make directories and upload files into those directories. Then use Ventrian File Links to drop that module onto a page on your DNN site. You can then tell it what directory to show files for and it will list them nicely on the site for you.

It's very slick. Ventrian is a yearly fee, but their Articles module and Photo Gallery module are also amazing and I use them in majority of my projects.

Title: DNN List multiple documents on page


问:
Is there a way to allow Google Sheets to IMPORTXML that is inside my company's corporate network?
My company is on an enterprise plan and behind a FW. This means I cannot IMPORT... in a Google Sheet to any URL inside the corporate network.

Is there way to make it so files in my company's G-Suite organization (example.com) can access my internal corporate network? Like some kind of virtual private network or something?

答:
If I'm not mistaken, you need to whitelist all these hosts in the firewall side for it to work </p>
```<code>For the following hosts, [N] means any single decimal digit and * means any string not containing a period.

www.google.com:443/HTTPS
accounts.google.com:443/HTTPS
googledrive.com:443/HTTPS
drive.google.com:443/HTTPS
*.drive.google.com:443/HTTPS
docs.google.com:443/HTTPS
*.docs.google.com:443/HTTPS
*.c.docs.google.com:443/HTTPS
sheets.google.com:443/HTTPS
slides.google.com:443/HTTPS
talk.google.com:5222/XMPP (needed only for Backup and Sync)
takeout.google.com:443/HTTPS
gg.google.com:443/HTTPS
script.google.com:443/HTTPS
ssl.google-analytics.com:443/HTTPS
video.google.com:443/HTTPS
s.ytimg.com:443/HTTPS
apis.google.com:443/HTTPS
*.clients[N].google.com:443/HTTPS
*.googleapis.com:443/HTTPS
*.googleusercontent.com:443/HTTPS
*.gstatic.com:443/HTTPS
*.gvt1.com:443/HTTPS
lh[N].google.com:443/HTTPS
[N].client-channel.google.com:443/HTTPS
clients[N].google.com:443/HTTPS
inputtools.google.com:443/HTTPS
sites.google.com:443/HTTPS
sites.google.com:80/HTTP
sites.google.com:443/HTTPS
*.sites.google.com:443/HTTPS
*.googlegroups.com:443/HTTPS
ipv4.google.com:443/HTTPS
ipv4.google.com:80/HTTP
</code>```
<p> Documentation can be found here</p>

Body:
If I'm not mistaken, you need to whitelist all these hosts in the firewall side for it to work

For the following hosts, [N] means any single decimal digit and * means any string not containing a period.

www.google.com:443/HTTPS
accounts.google.com:443/HTTPS
googledrive.com:443/HTTPS
drive.google.com:443/HTTPS
*.drive.google.com:443/HTTPS
docs.google.com:443/HTTPS
*.docs.google.com:443/HTTPS
*.c.docs.google.com:443/HTTPS
sheets.google.com:443/HTTPS
slides.google.com:443/HTTPS
talk.google.com:5222/XMPP (needed only for Backup and Sync)
takeout.google.com:443/HTTPS
gg.google.com:443/HTTPS
script.google.com:443/HTTPS
ssl.google-analytics.com:443/HTTPS
video.google.com:443/HTTPS
s.ytimg.com:443/HTTPS
apis.google.com:443/HTTPS
*.clients[N].google.com:443/HTTPS
*.googleapis.com:443/HTTPS
*.googleusercontent.com:443/HTTPS
*.gstatic.com:443/HTTPS
*.gvt1.com:443/HTTPS
lh[N].google.com:443/HTTPS
[N].client-channel.google.com:443/HTTPS
clients[N].google.com:443/HTTPS
inputtools.google.com:443/HTTPS
sites.google.com:443/HTTPS
sites.google.com:80/HTTP
sites.google.com:443/HTTPS
*.sites.google.com:443/HTTPS
*.googlegroups.com:443/HTTPS
ipv4.google.com:443/HTTPS
ipv4.google.com:80/HTTP

 Documentation can be found here


问:
'creating' images effectively
I'll first tell you the problem and then I'll tell you my solution.

Problem: I have a blank white PNG image approximately 900x900 pixels. I want to copy circles 30x30 pixels in size, which are essentially circles with a different colour. There are 8 different circles, and placed on the image depending on data values which I've created elsewhere.

Solution: I've used ImageMagicK, it's suppose to be good for general purpose image editing etc. I created a blank image

```<code>    Image.outimage("900x900","white");
</code>```

I upload all other small 30x30 pixel images with 'read' function.

I upload the data and extract vales.

I place the small 'circle' images on the blank one using the composite command.

```<code>    outimage.composite("some file.png",pixelx,pixely,InCompositeOp);
</code>```

This all works fine and the images come up the way I want them too.

However its painfully SLOW. It takes 20 seconds to do one image, and I have 1000 of them. Surely there must be a better way to do this. I've seen other researchers simulate images way more complex and way faster. It's quite possible I took the wrong approach. Maybe I sould be 'drawing' circles instead of 'pasting' them or something. I'm quite baffled. Any input is appreciated.

答:
I suspect that you just need some library that is capable of drawing circles on bitmap and saving that bitmap as png.

For example my Graphin library: http://code.google.com/p/graphin/
Or some such. With Graphin you can also draw one PNG on surface of another as in your case.

Title: 'creating' images effectively

Body:
I'll first tell you the problem and then I'll tell you my solution.

Problem: I have a blank white PNG image approximately 900x900 pixels. I want to copy circles 30x30 pixels in size, which are essentially circles with a different colour. There are 8 different circles, and placed on the image depending on data values which I've created elsewhere.

Solution: I've used ImageMagicK, it's suppose to be good for general purpose image editing etc. I created a blank image

    Image.outimage("900x900","white");

I upload all other small 30x30 pixel images with 'read' function.

I upload the data and extract vales.

I place the small 'circle' images on the blank one using the composite command.

    outimage.composite("some file.png",pixelx,pixely,InCompositeOp);

This all works fine and the images come up the way I want them too.

However its painfully SLOW. It takes 20 seconds to do one image, and I have 1000 of them. Surely there must be a better way to do this. I've seen other researchers simulate images way more complex and way faster. It's quite possible I took the wrong approach. Maybe I sould be 'drawing' circles instead of 'pasting' them or something. I'm quite baffled. Any input is appreciated.


问:
Visual Studio Code - Python - Windows - Black runs but does not format code
I am running VS Code on Windows and am trying to set up black to format my Python code when saving. It looks like black is running whenever I save, but the file is not getting updated. When I look at the Output > Python tab in VS Code, it looks like black is running with the --diff flag, which is why I'm assuming that the file does not update. Does anyone know how to fix this?

Here is my .vscode/settings.json in the project:

```<code>{
    "editor.defaultFormatter": "ms-python.python",
    "python.pythonPath": "C:\\Users\\me\\Anaconda3\\python.exe",
    "python.formatting.provider": "black"
}
</code>```

答: The fix for me was to install black package in my virtualenv. Using the one installed at the system level was not working, even though that one worked from terminal, etc.</p>

Body:
I am running VS Code on Windows and am trying to set up black to format my Python code when saving. It looks like black is running whenever I save, but the file is not getting updated. When I look at the Output > Python tab in VS Code, it looks like black is running with the --diff flag, which is why I'm assuming that the file does not update. Does anyone know how to fix this?

Here is my .vscode/settings.json in the project:

{
    "editor.defaultFormatter": "ms-python.python",
    "python.pythonPath": "C:\\Users\\me\\Anaconda3\\python.exe",
    "python.formatting.provider": "black"
}


问:
If a variable is created within the scope of a function that returns a function that uses that variable. Is it possible to acces that variable outside
```<code>function creatPrintNumFunction()
{
  var num= 12;
  return function printNum()
  {
     console.log(num);
  }
}

 var printer = creatPrintNumFunction();
printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();

</code>```

So how can I get this code to print 13 instead of 12 most importantly with out changing any of the code of the createPrintNumFunction().

For more context on what I really need to use this theory for. I'm using an external module express-sessions in node.js that I don't want to change. There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function.There is another way i could access it but it's not really convenient

答:
Looking for something like this?

function creatPrintNumFunction() {
  const f = function printNum() {
    console.log(f.num);
  };
  f.num = 12;           // set .num property to initial value
  return f;             // return function "printNum"
}

var printer = creatPrintNumFunction();
printer.num = 13;
printer();

printer.num = 42;
printer();```

Body:
function creatPrintNumFunction()
{
  var num= 12;
  return function printNum()
  {
     console.log(num);
  }
}

 var printer = creatPrintNumFunction();
printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside the creatPrintNumFunction, The printer function must be finding the num variable from somewhere.
printer();

So how can I get this code to print 13 instead of 12 most importantly with out changing any of the code of the createPrintNumFunction().

For more context on what I really need to use this theory for. I'm using an external module express-sessions in node.js that I don't want to change. There is this 'store' variable where all the sessions are stored that I need to access only problem is that it's created within a function.There is another way i could access it but it's not really convenient


问:
How to enhance the speed of my C++ program in reading delimited text files?
I show you C# and C++ code that execute the same job: to read the same text file delimited by “|” and save  with “#” delimited text.

When I execute  C++ program, the time elapsed is 169 seconds.

UPDATE 1: Thanks to Seth (compilation with: cl /EHsc /Ox /Ob2 /Oi) and GWW for changing the positions of string s outside the loops, the elapsed time was reduced to 53 seconds. I updated the code also.

UPDATE 2: Do you have any other suggestion to enhace the C++ code?

When I execute the C# program, the elapsed time is 34 seconds!

The question is, how can I enhance the speed of C++ comparing with the C# one?

C++ Program:

```<code>int main ()
{
    Timer t;
    cout << t.ShowStart() << endl;

    ifstream input("in.txt");
    ofstream output("out.txt", ios::out);
    char const row_delim = '\n';
    char const field_delim = '|';
    string s1, s2;

    while (input)
    {
        if (!getline( input, s1, row_delim ))
            break;
        istringstream iss(s1);
        while (iss)
        {
            if (!getline(iss, s2, field_delim ))
                break;
            output << s2 << "#";
        }
        output << "\n";
    }

    t.Stop();
    cout << t.ShowEnd() << endl;
    cout << "Executed in: " << t.ElapsedSeconds() << " seconds." << endl;
    return 0;
}
</code>```

C# program:

```<code>    static void Main(string[] args)
    {
        long i;
        Stopwatch sw = new Stopwatch();
        Console.WriteLine(DateTime.Now);
        sw.Start();
        StreamReader sr = new StreamReader("in.txt", Encoding.Default);
        StreamWriter wr = new StreamWriter("out.txt", false, Encoding.Default);
        object[] cols = new object[0];  // allocates more elements automatically when filling
        string line;
        while (!string.Equals(line = sr.ReadLine(), null)) // Fastest way
        {
        cols = line.Split('|');  // Faster than using a List<>
        foreach (object col in cols)
            wr.Write(col + "#");
        wr.WriteLine();
        }
        sw.Stop();
        Console.WriteLine("Conteo tomó {0} secs", sw.Elapsed);
        Console.WriteLine(DateTime.Now);
    }
</code>```

UPDATE 3:

Well, I must say I am very happy for the help received and because the answer to my question has been satisfied.

I changed the text of the question a little to be more specific, and I tested the solutions that kindly raised Molbdlino and Bo Persson.

Keeping Seth indications for the compile command (i.e. cl /EHsc /Ox /Ob2 /Oi pgm.cpp):

Bo Persson's solution took 18 seconds on average to complete the execution, really a good one taking in account that the code is near to what I like).

Molbdlino solution took 6 seconds on average, really amazing!! (thanks to Constantine also).

Never too late to learn, and I learned valuable things with my question.

My best regards.

答:
It seems to me that Your slow part is within getline. I don't have precise documentation which would support my idea, but it's how it feels for me. You should try using read instead. Because getline has the delimiter, so it need to check every symbol whether it has found the delimiter symbol, so that looks like multiple in operations, so Your program accesses a symbol in a file, then write it to the memory of your program, in other words, the time consumed on disk head movement. But if You use read function, You will copy the block of symbols and then work with them within program's memory, that may reduce time consuming.

PS again, I don't have documentation about getline and how it works, but I'm sure about read, hope it is helpful.

Body:
I show you C# and C++ code that execute the same job: to read the same text file delimited by “|” and save  with “#” delimited text.

When I execute  C++ program, the time elapsed is 169 seconds.

UPDATE 1: Thanks to Seth (compilation with: cl /EHsc /Ox /Ob2 /Oi) and GWW for changing the positions of string s outside the loops, the elapsed time was reduced to 53 seconds. I updated the code also.

UPDATE 2: Do you have any other suggestion to enhace the C++ code?

When I execute the C# program, the elapsed time is 34 seconds!

The question is, how can I enhance the speed of C++ comparing with the C# one?

C++ Program:

int main ()
{
    Timer t;
    cout << t.ShowStart() << endl;

    ifstream input("in.txt");
    ofstream output("out.txt", ios::out);
    char const row_delim = '\n';
    char const field_delim = '|';
    string s1, s2;

    while (input)
    {
        if (!getline( input, s1, row_delim ))
            break;
        istringstream iss(s1);
        while (iss)
        {
            if (!getline(iss, s2, field_delim ))
                break;
            output << s2 << "#";
        }
        output << "\n";
    }

    t.Stop();
    cout << t.ShowEnd() << endl;
    cout << "Executed in: " << t.ElapsedSeconds() << " seconds." << endl;
    return 0;
}

C# program:

    static void Main(string[] args)
    {
        long i;
        Stopwatch sw = new Stopwatch();
        Console.WriteLine(DateTime.Now);
        sw.Start();
        StreamReader sr = new StreamReader("in.txt", Encoding.Default);
        StreamWriter wr = new StreamWriter("out.txt", false, Encoding.Default);
        object[] cols = new object[0];  // allocates more elements automatically when filling
        string line;
        while (!string.Equals(line = sr.ReadLine(), null)) // Fastest way
        {
        cols = line.Split('|');  // Faster than using a List<>
        foreach (object col in cols)
            wr.Write(col + "#");
        wr.WriteLine();
        }
        sw.Stop();
        Console.WriteLine("Conteo tomó {0} secs", sw.Elapsed);
        Console.WriteLine(DateTime.Now);
    }

UPDATE 3:

Well, I must say I am very happy for the help received and because the answer to my question has been satisfied.

I changed the text of the question a little to be more specific, and I tested the solutions that kindly raised Molbdlino and Bo Persson.

Keeping Seth indications for the compile command (i.e. cl /EHsc /Ox /Ob2 /Oi pgm.cpp):

Bo Persson's solution took 18 seconds on average to complete the execution, really a good one taking in account that the code is near to what I like).

Molbdlino solution took 6 seconds on average, really amazing!! (thanks to Constantine also).

Never too late to learn, and I learned valuable things with my question.

My best regards.


问:
Sampling by group in R without duplicates between groups
I have a 'data.frame' with two columns ID_1 and ID_2. I want to sample to ID_1, but there must be no duplicates. That is, I want to draw a sample within a group, but the selection within the group must be one that has not been previously selected in other ID_1 groups.

I have already consulted this question:
Sampling by Group in R with no replacement but the final result cannot contain any repeats as well probably solves the problem, but when I work with the largest data set, an error occurs.  I have tested the suggestion of @LMc.

Example with simulated data.

```<code>library(data.table)
library(dplyr)
# Creating artificial data
set.seed(1)
dt <- data.table(ID_2 = sample(10^2,1000,replace = T))
x <- c(sort(sample(1000-1,200,replace = F)),1000)
x2 <- x-lag(x)
x2[1] <- 1
id_1 <- rep(1:uniqueN(x),x2)
id_1 <- if (length(id_1) == 1000) id_1 else c(id_1,rep(id_1[length(id_1)],1000-length(id_1)))
dt[, ID_1 := id_1]

# testing LMs code
my_sample <- function(x, ...){
  if (length(x) == 0L) return(NA) else sample(x, ...)
}

dt %>%
  group_by(ID_1) %>%
  slice_sample(n = 1) %>%
  ungroup() %>%
  mutate(resample = duplicated(ID_2)) %>%
  rowwise() %>%
  mutate(ID_2 = if (resample) my_sample(dt[dt$ID_1 == ID_1 & dt$ID_2 != ID_2, "ID_2"], 1) else ID_2) %>%
  ungroup() %>%
  select(-resample)
</code>```

Visual idea with little data

The suggestion is not clever, because if the value ID_2 assigned to ID_1 has already been assigned to an earlier ID_1, an error occurs. I include a small example where there is only a one-time solution, so you have to run the @LMc code several times until the assignment is correct.

```<code>dt_joke <-
  data.table(ID_2 = c(15L, 60L, 50L, 47L, 60L, 60L, 31L, 31, 22L),
           ID_1 = c(1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L))
dt_joke
   ID_2 ID_1
1:   15    1
2:   60    2
3:   50    2
4:   47    2
5:   60    3
6:   60    3
7:   31    3
8:   31    4
9:   22    4
</code>```

Expected result

```<code>   ID_2 ID_1
1:   15    1
2:   47    2
3:   60    3
4:   31    4
</code>```

答:
If you intend to sample ID_2 grouped by ID_1 without duplication of ID_2 between groups, then you're going to run into insufficient data: using this seed, there are 42 groups with single rows here, at least two of which share an ID_2. This means either some values will be duplicated between groups or some groups will go unrepresented. This compounds, since once you've sampled all the 1-row tables, the 2-row tables are also in a pinch, again likely to be under-sampled.

If you can accept this, then:

head(dt)
#     ID_2  ID_1
#    <int> <int>
# 1:    68     1
# 2:    39     2
# 3:     1     2
# 4:    34     2
# 5:    87     2
# 6:    43     3

set.seed(42)
dtspl <- split(dt, dt$ID_1)
dtspl <- dtspl[order(sapply(dtspl, nrow))]
set.seed(42)
out <- Reduce(function(prev, this)
                rbindlist(list(
                  prev,
                  this[!ID_2 %in% prev$ID_2,][,.SD[sample(nrow(.SD), size=1),]]
                )),
              dtspl)
out
#       ID_2  ID_1
#      <int> <int>
#   1:    68     1
#   2:    54     5
#   3:    42     9
#   4:    40    12
#   5:    89    13
#   6:    90    17
#   7:    51    19
#   8:    37    34
#   9:   100    40
#  10:    82    48
#  ---
#  91:    69   117
#  92:    61   154
#  93:    83    16
#  94:    15    47
#  95:    16   199
#  96:     7    27
#  97:    39   171
#  98:    22   186
#  99:    76    21
# 100:    32    10
```
<p>We have all <code>ID_2</code> covered, but not all <code>ID_1</code>s.</p>
<pre class="lang-r prettyprint-override"><code>all(dt$ID_2 %in% out$ID_2)
# [1] TRUE
all(dt$ID_1 %in% out$ID_1)
# [1] FALSE
</code>```

Body:
I have a 'data.frame' with two columns ID_1 and ID_2. I want to sample to ID_1, but there must be no duplicates. That is, I want to draw a sample within a group, but the selection within the group must be one that has not been previously selected in other ID_1 groups.

I have already consulted this question:
Sampling by Group in R with no replacement but the final result cannot contain any repeats as well probably solves the problem, but when I work with the largest data set, an error occurs.  I have tested the suggestion of @LMc.

Example with simulated data.

library(data.table)
library(dplyr)
# Creating artificial data
set.seed(1)
dt <- data.table(ID_2 = sample(10^2,1000,replace = T))
x <- c(sort(sample(1000-1,200,replace = F)),1000)
x2 <- x-lag(x)
x2[1] <- 1
id_1 <- rep(1:uniqueN(x),x2)
id_1 <- if (length(id_1) == 1000) id_1 else c(id_1,rep(id_1[length(id_1)],1000-length(id_1)))
dt[, ID_1 := id_1]

# testing LMs code
my_sample <- function(x, ...){
  if (length(x) == 0L) return(NA) else sample(x, ...)
}

dt %>%
  group_by(ID_1) %>%
  slice_sample(n = 1) %>%
  ungroup() %>%
  mutate(resample = duplicated(ID_2)) %>%
  rowwise() %>%
  mutate(ID_2 = if (resample) my_sample(dt[dt$ID_1 == ID_1 & dt$ID_2 != ID_2, "ID_2"], 1) else ID_2) %>%
  ungroup() %>%
  select(-resample)

Visual idea with little data

The suggestion is not clever, because if the value ID_2 assigned to ID_1 has already been assigned to an earlier ID_1, an error occurs. I include a small example where there is only a one-time solution, so you have to run the @LMc code several times until the assignment is correct.

dt_joke <-
  data.table(ID_2 = c(15L, 60L, 50L, 47L, 60L, 60L, 31L, 31, 22L),
           ID_1 = c(1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L))
dt_joke
   ID_2 ID_1
1:   15    1
2:   60    2
3:   50    2
4:   47    2
5:   60    3
6:   60    3
7:   31    3
8:   31    4
9:   22    4

Expected result

   ID_2 ID_1
1:   15    1
2:   47    2
3:   60    3
4:   31    4

Body:
If you intend to sample ID_2 grouped by ID_1 without duplication of ID_2 between groups, then you're going to run into insufficient data: using this seed, there are 42 groups with single rows here, at least two of which share an ID_2. This means either some values will be duplicated between groups or some groups will go unrepresented. This compounds, since once you've sampled all the 1-row tables, the 2-row tables are also in a pinch, again likely to be under-sampled.

If you can accept this, then:

head(dt)
#     ID_2  ID_1
#    <int> <int>
# 1:    68     1
# 2:    39     2
# 3:     1     2
# 4:    34     2
# 5:    87     2
# 6:    43     3

set.seed(42)
dtspl <- split(dt, dt$ID_1)
dtspl <- dtspl[order(sapply(dtspl, nrow))]
set.seed(42)
out <- Reduce(function(prev, this)
                rbindlist(list(
                  prev,
                  this[!ID_2 %in% prev$ID_2,][,.SD[sample(nrow(.SD), size=1),]]
                )),
              dtspl)
out
#       ID_2  ID_1
#      <int> <int>
#   1:    68     1
#   2:    54     5
#   3:    42     9
#   4:    40    12
#   5:    89    13
#   6:    90    17
#   7:    51    19
#   8:    37    34
#   9:   100    40
#  10:    82    48
#  ---
#  91:    69   117
#  92:    61   154
#  93:    83    16
#  94:    15    47
#  95:    16   199
#  96:     7    27
#  97:    39   171
#  98:    22   186
#  99:    76    21
# 100:    32    10

We have all ID_2 covered, but not all ID_1s.

all(dt$ID_2 %in% out$ID_2)
# [1] TRUE
all(dt$ID_1 %in% out$ID_1)
# [1] FALSE


问:
How to convert a recursive algorithm to a function that outputs a number, given the time
I have a recursive algorithm that runs multiple times, replacing currentValue each time with the output of the previous run (except for the first run, where the value is supplied by the user). Each run calculates the value one year later.

```<code>value = constant
+ population_factor * coeff_population_factor
+ currentValue * coeff_currentValue
+ initialValue * coeff_initialValue%
+ duration_of_period * coeff_duration_of_period
</code>```

I would like to be able to convert that into a function of time, so that for a given value t in years, it would return the expected value at that point? I think that would be a regression algorithm, but I'm not sure how to get to that.

I have modelled the curve using the the formula above in excel to get my coefficients, but that obviously only runs on my computer and I'd like to run this in the cloud using node or something, so I can develop some front-ends against it. Ideally some pointers using pure maths or JS, or a library, even, would be greatly appreciated!

答:
I believe you are looking for a for loop.
Try this:

# define all of the variables here
currentValue = #put the first-run value here
for i in range(t):
    currentValue = constant \
                   + (population_factor * coeff_population_factor) \
                   + (currentValue * coeff_currentValue) \
                   + (initialValue * coeff_initialValue) \
                   + (duration_of_period * coeff_duration_of_period)
# currentValue will have the final result once outside of the for loop
```

It is not recursive and still gives the accurate answer!

Body:
I have a recursive algorithm that runs multiple times, replacing currentValue each time with the output of the previous run (except for the first run, where the value is supplied by the user). Each run calculates the value one year later.

value = constant
+ population_factor * coeff_population_factor
+ currentValue * coeff_currentValue
+ initialValue * coeff_initialValue%
+ duration_of_period * coeff_duration_of_period

I would like to be able to convert that into a function of time, so that for a given value t in years, it would return the expected value at that point? I think that would be a regression algorithm, but I'm not sure how to get to that.

I have modelled the curve using the the formula above in excel to get my coefficients, but that obviously only runs on my computer and I'd like to run this in the cloud using node or something, so I can develop some front-ends against it. Ideally some pointers using pure maths or JS, or a library, even, would be greatly appreciated!

Body:
I believe you are looking for a for loop.
Try this:

# define all of the variables here
currentValue = #put the first-run value here
for i in range(t):
    currentValue = constant \
                   + (population_factor * coeff_population_factor) \
                   + (currentValue * coeff_currentValue) \
                   + (initialValue * coeff_initialValue) \
                   + (duration_of_period * coeff_duration_of_period)
# currentValue will have the final result once outside of the for loop

It is not recursive and still gives the accurate answer!


问:
Convert ANSI (Windows 1252) to UTF8 in C#
I've asked this before in a round-about manner before here on Stack Overflow, and want to get it right this time. How do I convert ANSI (Codepage 1252) to UTF-8, while preserving the special characters? (I am aware that UTF-8 supports a larger character set than ANSI, but it is okay if I can preserve all UTF-8 characters that are supported by ANSI and substitute the rest with a ? or something)

Why I Want To Convert ANSI → UTF-8

I am basically writing a program that splits vCard files (VCF) into individual files, each containing a single contact. I've noticed that Nokia and Sony Ericsson phones save the backup VCF file in UTF-8 (without BOM), but Android saves it in ANSI (1252). And God knows in what formats the other phones save them in!

So my questions are

Isn't there an industry standard for vCard files' character encoding?

Which is easier for my solving my problem? Converting ANSI to UTF8 (and/or the other way round) or trying to detect which encoding the input file has and notifying the user about it?

tl;dr
Need to know how to convert the character encoding from (ANSI / UTF8) to (UTF8 / ANSI) while preserving all special characters.

答:
This is what I use in C# (I've been using it to convert from Windows-1252 to UTF8)</p>

```<code>    public static String readFileAsUtf8(string fileName)
    {
        Encoding encoding = Encoding.Default;
        String original = String.Empty;

        using (StreamReader sr = new StreamReader(fileName, Encoding.Default))
        {
            original = sr.ReadToEnd();
            encoding = sr.CurrentEncoding;
            sr.Close();
        }

        if (encoding == Encoding.UTF8)
            return original;

        byte[] encBytes = encoding.GetBytes(original);
        byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encBytes);
        return Encoding.UTF8.GetString(utf8Bytes);
    }
</code>```

Body:
This is what I use in C# (I've been using it to convert from Windows-1252 to UTF8)

    public static String readFileAsUtf8(string fileName)
    {
        Encoding encoding = Encoding.Default;
        String original = String.Empty;

        using (StreamReader sr = new StreamReader(fileName, Encoding.Default))
        {
            original = sr.ReadToEnd();
            encoding = sr.CurrentEncoding;
            sr.Close();
        }

        if (encoding == Encoding.UTF8)
            return original;

        byte[] encBytes = encoding.GetBytes(original);
        byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encBytes);
        return Encoding.UTF8.GetString(utf8Bytes);
    }


问:
Variable undefined error in laravel blade component view
Component InputError.php

```<code><?php

namespace App\View\Components;

use Illuminate\View\Component;

class InputError extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.input-error');
    }
}
</code>```

Blade input-error.blade.php

```<code>@props(['for'])

@error($for)
    <label {!! $attributes->merge(['class' => 'error']) !!}>
        {{ $message }}
    </label>
@enderror
</code>```

Blade View

```<code><x-input-error for="title" />
</code>```

Errors

Undefined variable: for

i'm not want change original jetstream component, how can i fix it?

答:
From the docs:

You should define the component's required data in its class constructor. All public properties on a component will automatically be made available to the component's view. It is not necessary to pass the data to the view from the component's render method: (...)

So, in your case:

```<code>class InputError extends Component
{
    public $for;

    public function __construct($for)
    {
        $this->for = $for;
    }

    public function render()
    {
        return view('components.input-error');
    }
}
</code>```

Then you should be able to pass data:

```<code><x-input-error for="my-title" />
</code>```

PS: I think the issue is with the use of the @prop directive. The directive is used in anonymous components that don't have a dedicated component class linked to the view. I almost always use anonymous components so I cannot be fully sure of this behaviour.

PS2: In your  tag use the {{ }} instead of {!! !!}

Body:
Component InputError.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class InputError extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.input-error');
    }
}

Blade input-error.blade.php

@props(['for'])

@error($for)
    merge(['class' => 'error']) !!}>
        {{ $message }}

@enderror

Blade View

<x-input-error for="title" />

Errors

Undefined variable: for

i'm not want change original jetstream component, how can i fix it?

Body:
From the docs:

You should define the component's required data in its class constructor. All public properties on a component will automatically be made available to the component's view. It is not necessary to pass the data to the view from the component's render method: (...)

So, in your case:

class InputError extends Component
{
    public $for;

    public function __construct($for)
    {
        $this->for = $for;
    }

    public function render()
    {
        return view('components.input-error');
    }
}

Then you should be able to pass data:

<x-input-error for="my-title" />

PS: I think the issue is with the use of the @prop directive. The directive is used in anonymous components that don't have a dedicated component class linked to the view. I almost always use anonymous components so I cannot be fully sure of this behaviour.

PS2: In your <label> tag use the {{ }} instead of {!! !!}