问:
Is there a way to use an SSIS Merge Join with a SQLServer OLEDB source and MySQL/ODBC source
I’m using SQL Server 2012 and need to do a full outer join using the Merge Join in order to do delta updates/inserts/deletes.

We would really like to avoid using the sort transformation as it is fully blocking but I’m running out of ideas.

Both source outputs are sorted using order by clauses and the IsSorted property set to true/columnSort order set to 1.

The Character set of the MySQL database is UTF8 And in the order by clause of the source query I am collating using UTF8_bin

The collation of the SQLServer database is SQL_Latin1_General_CP1_CI_AS but in the order by clause within the source query I have collated to Latin1_General_bin (so the sort methods are the same)

However I am finding that the sets are not joining correctly. Most records do match but I have instances where values exist on the left and right side but the opposite side of the join is null (in theory they should match)

The Values we are trying to match on are in the following format(99999-99999-9999 AAA BBB CCC)

I am aware that UTF8 support in SQL server had not been introduced until SQL Server 2019 so could this be the issue. Are we inevitably going to have to use the Sort transformation?

答:
I have managed to solve this after doing some research into character encodings.

MySQL UTF8 is more centred around linux and UNIX, Windows UTF8 support is very limited so UTF8 collations are likely to cause issues.

However Windows does support UTF16... It still isn't straight forward though.

In MySQL there are character sets UTF16 and UTF16LE. The LE stands for little endian. UTF16 uses big endian which in short will order by the most significant value in a sequence as opposed to little endian which orders by the least significant value in a sequence. For more info read the below.

[https://searchnetworking.techtarget.com/definition/big-endian-and-little-endian][1]

The encoding used by Windows Servers will mainly use little endian because as explained in the above article, it is determined by the CPUs of the servers (Intel processors are an example that use little endian).

With this in mind I collated the Join/Sort column (nvarchar(55)) in the SQL Server Source to Latin1_General_Bin which in theory should be UTF16 little endian Encoding.

I then converted the Join/Sort Columns in the MySQL source to UTF16LE character set and in the Order By Collated to UTF16LE_Bin

```<code>SELECT
CONVERT(UPPER(CONCAT_WS('-', Column1, Column2, Column3, 'AAA BBB CCC')) USING UTF16LE) AS DerivedColumn,
...
...
ORDER BY DerivedColumn COLLATE UTF16LE_bin;
</code>```

This Sorted the data correctly without need for using the Sort Transformation.

Body:
I have managed to solve this after doing some research into character encodings.

MySQL UTF8 is more centred around linux and UNIX, Windows UTF8 support is very limited so UTF8 collations are likely to cause issues.

However Windows does support UTF16... It still isn't straight forward though.

In MySQL there are character sets UTF16 and UTF16LE. The LE stands for little endian. UTF16 uses big endian which in short will order by the most significant value in a sequence as opposed to little endian which orders by the least significant value in a sequence. For more info read the below.

[https://searchnetworking.techtarget.com/definition/big-endian-and-little-endian][1]

The encoding used by Windows Servers will mainly use little endian because as explained in the above article, it is determined by the CPUs of the servers (Intel processors are an example that use little endian).

With this in mind I collated the Join/Sort column (nvarchar(55)) in the SQL Server Source to Latin1_General_Bin which in theory should be UTF16 little endian Encoding.

I then converted the Join/Sort Columns in the MySQL source to UTF16LE character set and in the Order By Collated to UTF16LE_Bin

SELECT
CONVERT(UPPER(CONCAT_WS('-', Column1, Column2, Column3, 'AAA BBB CCC')) USING UTF16LE) AS DerivedColumn,
...
...
ORDER BY DerivedColumn COLLATE UTF16LE_bin;

This Sorted the data correctly without need for using the Sort Transformation.


来源: stackexchange

问:
How to connect signal to signal with new syntax QT5?
I am trying to connect a signal to a signal using the new syntax:

```<code>connect(ui->line,&QLineEdit::returnPressed,ui->button,&QPushButton::clicked);
</code>```

But the compiler throws an error, with all this the old syntax works:

```<code>connect(ui->line,SIGNAL(returnPressed()),ui->button,SIGNAL(clicked()));
</code>```

I know this can be connected to function click:

```<code>connect(ui->line,&QLineEdit::returnPressed,ui->button,&QPushButton::click);
</code>```

But is there a way to connect it to the signal use new syntax?

答:
From a quick glance at the documentation, the mismatch stems from the extra argument to the clickedsignal.

One option is to use a lambda to inject that argument:

```<code>connect(ui->line,&QLineEdit::returnPressed, this, [this]() { ui->button->clicked(false); });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to connect a signal to a signal using the new syntax:

connect(ui->line,&QLineEdit::returnPressed,ui->button,&QPushButton::clicked);

But the compiler throws an error, with all this the old syntax works:

connect(ui->line,SIGNAL(returnPressed()),ui->button,SIGNAL(clicked()));

I know this can be connected to function click:

connect(ui->line,&QLineEdit::returnPressed,ui->button,&QPushButton::click);

But is there a way to connect it to the signal use new syntax?

Body:
From a quick glance at the documentation, the mismatch stems from the extra argument to the clickedsignal.

One option is to use a lambda to inject that argument:

connect(ui->line,&QLineEdit::returnPressed, this, [this]() { ui->button->clicked(false); });


问:
container_class isn't being applied for wp_nav_menu
I'm trying to add a wordpress menu to my wordpress theme and when I follow the specified instructions online, it doesn't work.

I have this in functions.php

```<code><?php

function register_my_menus() {
  register_nav_menus(
    array(
      'header-menu' => __( 'Header Menu' ),
      'sidebar-menu' => __( 'Sidebar Menu' )
     )
   );
 }
 add_action( 'init', 'register_my_menus' );
</code>```

In sidebar.php of my theme theme I have this code

```<code>       <?php
        wp_nav_menu(
          array(
            'theme_location' => 'sidebar-menu',
            'container_class' => 'sidebar'
          )
        );
        ?>
</code>```

But when I inspect the HTML code that is outputted, my menu doesn't have the sidebar class on it, instead it is given a menu class.

Why?

答:
It gives you a

...

 (default wrapper is
 tag)

if you want to change class on
 tag, you should add param menu_class:

```<code>wp_nav_menu(
    array(
        'theme_location'  => 'sidebar-menu',
        'container_class' => 'wrapper_class',
        'menu_class'      => 'sidebar',
    )
);
</code>```

if you don't need wrapper
, then

```<code>wp_nav_menu(
    array(
        'theme_location'  => 'sidebar-menu',
        'container'       => false,
        'menu_class'      => 'sidebar',

    )
);
</code>```

Body:
I'm trying to add a wordpress menu to my wordpress theme and when I follow the specified instructions online, it doesn't work.

I have this in functions.php

<?php

function register_my_menus() {
  register_nav_menus(
    array(
      'header-menu' => __( 'Header Menu' ),
      'sidebar-menu' => __( 'Sidebar Menu' )
     )
   );
 }
 add_action( 'init', 'register_my_menus' );

In sidebar.php of my theme theme I have this code

       <?php
        wp_nav_menu(
          array(
            'theme_location' => 'sidebar-menu',
            'container_class' => 'sidebar'
          )
        );
        ?>

But when I inspect the HTML code that is outputted, my menu doesn't have the sidebar class on it, instead it is given a menu class.

Why?

Body:
It gives you a <div class="sidebar"><ul class="menu">...</ul></div> (default wrapper is <div> tag)

if you want to change class on <ul> tag, you should add param menu_class:

wp_nav_menu(
    array(
        'theme_location'  => 'sidebar-menu',
        'container_class' => 'wrapper_class',
        'menu_class'      => 'sidebar',
    )
);

if you don't need wrapper <div class="wrapper_class">, then

wp_nav_menu(
    array(
        'theme_location'  => 'sidebar-menu',
        'container'       => false,
        'menu_class'      => 'sidebar',

    )
);


问:
Formik Trying to Validate Invisible Fields
I am running into this issue with Formik Validation Schema. My form has 3 shapes it takes and a few fields that are present in each shape depending on the given params type and upperType.  The issue is when I try submit my form if one of the below fields in not visible and doesn't have a value the submitForm function doesn't fire. I've set the conditional logic as best I think I can so why is .nullable not allowing form submission?

examples of form shape:

type === expire => only endDate

type === permanent => lower & upper(depending on upperType) & startDate

etc.

The issue is when only endDate is visible the form still tries to validate the rest of the form fields and same with the other shapes of the form. Is my validation logic incorrect?

```<code>export const validationSchema = (type: string, upperType: RangeType | undefined) => {
  const result = Yup.object({
    lower: Yup.string().when([], {
      is: type !== 'expire',
      then: Yup.string().required(errorMessages.lowerRequired),
      otherwise: Yup.string().nullable(true)
    }),
    upper: Yup.string().when([], {
      is: (type !== 'expire' && (upperType === ASYMMETRICAL || upperType === OUTER)),
      then: Yup.string().required(errorMessages.upperRequired),
      otherwise: Yup.string().nullable(true)
    }),
    startDate: Yup.date()
      .when([], {
        is: type === 'permanent' || type === 'temporary',
        then: Yup.date().nullable(true)
      })
      .max(dateMaxServer(), errorMessages.dateMax),
    endDate: Yup.date().when([], {
      is: type === 'temporary' || type === 'expire',
      then: Yup.date().required(errorMessages.dateRequired),
      otherwise: Yup.date().nullable(true)
    }),
  })
  return result
}

</code>```

答:
I think is expects function if you want to compare in a custom way .

```<code>is: type !== 'expire', //always resolves to **true** if it is used without function
</code>```

Give it a try.

Replace

```<code>is: type !== 'expire'
</code>```

to

```<code>is: ()=>type !== 'expire',
</code>```

Body:
I am running into this issue with Formik Validation Schema. My form has 3 shapes it takes and a few fields that are present in each shape depending on the given params type and upperType.  The issue is when I try submit my form if one of the below fields in not visible and doesn't have a value the submitForm function doesn't fire. I've set the conditional logic as best I think I can so why is .nullable not allowing form submission?

examples of form shape:

type === expire => only endDate

type === permanent => lower & upper(depending on upperType) & startDate

etc.

The issue is when only endDate is visible the form still tries to validate the rest of the form fields and same with the other shapes of the form. Is my validation logic incorrect?

export const validationSchema = (type: string, upperType: RangeType | undefined) => {
  const result = Yup.object({
    lower: Yup.string().when([], {
      is: type !== 'expire',
      then: Yup.string().required(errorMessages.lowerRequired),
      otherwise: Yup.string().nullable(true)
    }),
    upper: Yup.string().when([], {
      is: (type !== 'expire' && (upperType === ASYMMETRICAL || upperType === OUTER)),
      then: Yup.string().required(errorMessages.upperRequired),
      otherwise: Yup.string().nullable(true)
    }),
    startDate: Yup.date()
      .when([], {
        is: type === 'permanent' || type === 'temporary',
        then: Yup.date().nullable(true)
      })
      .max(dateMaxServer(), errorMessages.dateMax),
    endDate: Yup.date().when([], {
      is: type === 'temporary' || type === 'expire',
      then: Yup.date().required(errorMessages.dateRequired),
      otherwise: Yup.date().nullable(true)
    }),
  })
  return result
}

Body:
I think is expects function if you want to compare in a custom way .

is: type !== 'expire', //always resolves to **true** if it is used without function

Give it a try.

Replace

is: type !== 'expire'

to

is: ()=>type !== 'expire',


问:
How to change the value of outside variable from inside the method
I am trying to change the value of a variable "memes"
in a function called "joke". Joke function should change the value of memes to 1313, but it does not and when the print(str(memes)) is triggered the value of "memes" variable is still 0.

```<code>class Bruhmoment:
    memes = 0
    def __init__(self, name):
        self.name=name
    global memes
    def joke(self):
        memes=1313
        print(str(memes))
</code>```

答:
try st like this:</p>

```<code>memes = 0
def joke():
    global memes
    memes = 1313
joke()
print(str(memes))
</code>```

Body:
I am trying to change the value of a variable "memes"
in a function called "joke". Joke function should change the value of memes to 1313, but it does not and when the print(str(memes)) is triggered the value of "memes" variable is still 0.

class Bruhmoment:
    memes = 0
    def __init__(self, name):
        self.name=name
    global memes
    def joke(self):
        memes=1313
        print(str(memes))

Body:
try st like this:

memes = 0
def joke():
    global memes
    memes = 1313
joke()
print(str(memes))


问:
How to loop over multiple fields in Django template?
I have models that inherit from an abstract model like this:

```<code>class ImprovementAbstraction(models.Model):
    needsImprovement = models.BooleanField()
    hasFallacies = models.BooleanField()
    hasEmotionalDeficiency = models.BooleanField()
    isNecessaryToObtain = models.BooleanField()
    doesAReallyCauseB = models.BooleanField()
    areAllStepsPresent = models.BooleanField()
    isCauseSufficient = models.BooleanField()
    areAllClausesIdentified = models.BooleanField()
    isCausalityCertain = models.BooleanField()
    languageIsEnglish = models.BooleanField()
    isTautologyPresent = models.BooleanField()

    class Meta:
        abstract = True

class Assumption(MainAbstractModel, ImprovementAbstraction):
    need = models.ForeignKey(Need, on_delete=models.SET_NULL, null=True)
    assumption = models.CharField(max_length=500, default="", null=True)

    def __str__(self):
        return self.assumption
</code>```

In the template I would like to display all of the "ToImprovementAbstraction" Model fields associated with the Assumption model. Is there a way to loop over all the fields in the template, something like Assumption.ImprovementAbstractionFields.all() (made up code)?

答:
Not exactly sure what your desired outcome is, but this is the basic approach to query data from the database and render the html:

You will first have to query the data from the database like so:

Views.py

```<code>def search(request):
    queryset = ToImprovementAbstraction.objects.all()
    context = {
        'queryset': queryset
    }
    return render(request, 'your_template.html', context)
</code>```

Then you can use the data to render your template like so:

your_template.html

```<code>{% for item in queryset %}

<p>{{ item.needsImprovement }}</p>
[...]
[...]

{% endfor %}
</code>```

If oyu have multiple models you can make multiple queries to use one/many-to-many fields in your models to link them straight away.

Body:
I have models that inherit from an abstract model like this:

class ImprovementAbstraction(models.Model):
    needsImprovement = models.BooleanField()
    hasFallacies = models.BooleanField()
    hasEmotionalDeficiency = models.BooleanField()
    isNecessaryToObtain = models.BooleanField()
    doesAReallyCauseB = models.BooleanField()
    areAllStepsPresent = models.BooleanField()
    isCauseSufficient = models.BooleanField()
    areAllClausesIdentified = models.BooleanField()
    isCausalityCertain = models.BooleanField()
    languageIsEnglish = models.BooleanField()
    isTautologyPresent = models.BooleanField()

    class Meta:
        abstract = True

class Assumption(MainAbstractModel, ImprovementAbstraction):
    need = models.ForeignKey(Need, on_delete=models.SET_NULL, null=True)
    assumption = models.CharField(max_length=500, default="", null=True)

    def __str__(self):
        return self.assumption

In the template I would like to display all of the "ToImprovementAbstraction" Model fields associated with the Assumption model. Is there a way to loop over all the fields in the template, something like Assumption.ImprovementAbstractionFields.all() (made up code)?

Body:
Not exactly sure what your desired outcome is, but this is the basic approach to query data from the database and render the html:

You will first have to query the data from the database like so:

Views.py

def search(request):
    queryset = ToImprovementAbstraction.objects.all()
    context = {
        'queryset': queryset
    }
    return render(request, 'your_template.html', context)

Then you can use the data to render your template like so:

your_template.html

{% for item in queryset %}

<p>{{ item.needsImprovement }}</p>
[...]
[...]

{% endfor %}

If oyu have multiple models you can make multiple queries to use one/many-to-many fields in your models to link them straight away.


问:
How Blazor manage user Session?
new to Blazor I'm not sure to understand how user session is working.

I'm trying to do a web site with Blazor Server Hosting (.NET Core 3.1).
I have a service to Store a Customer like this :

```<code> public class AppData
    {
        public Customer CurrentCustomer { get; set; }

        public AppData()
        {
            this.CurrentCustomer = new Customer() { IsWebConnected = false };
        }
    }
</code>```

On Startup.cs I add :

```<code> public void ConfigureServices(IServiceCollection services)
{
            services.AddRazorPages();
            services.AddServerSideBlazor();

            AppData data = new AppData();
            services.AddSingleton<Service.AppData>(data);
}
</code>```

What does it mean ?
When a CurrentCustomer is set (with a login page for exemple), I can access it with relative data on different pages when I launch on a browser.
But when I launch another browser on my pc, I cab see the same user set (with same vaues). It seems to be shared.

I have been working on old ASP.NET Webform and I'm trying to do the same things than Session (One session by user), but is it the same way with Blazor ?

Thanks for your help.

答:
```<code>AppData data = new AppData();
services.AddSingleton<Service.AppData>(data);
</code>```

This adds a Singleton instance. And yes, that is shared between all users. Cookies are not involved. This behaves like the Application[] object in WebForms.

Session[] has no direct counterpart, but there are many solutions. The docs list them here.

Note that you should try to be as 'stateless' as possible, so consider fetching your data from the Db every time the page Initializes.

Title: How Blazor manage user Session?

Body:
new to Blazor I'm not sure to understand how user session is working.

I'm trying to do a web site with Blazor Server Hosting (.NET Core 3.1).
I have a service to Store a Customer like this :

 public class AppData
    {
        public Customer CurrentCustomer { get; set; }

        public AppData()
        {
            this.CurrentCustomer = new Customer() { IsWebConnected = false };
        }
    }

On Startup.cs I add :

 public void ConfigureServices(IServiceCollection services)
{
            services.AddRazorPages();
            services.AddServerSideBlazor();

            AppData data = new AppData();
            services.AddSingleton<Service.AppData>(data);
}

What does it mean ?
When a CurrentCustomer is set (with a login page for exemple), I can access it with relative data on different pages when I launch on a browser.
But when I launch another browser on my pc, I cab see the same user set (with same vaues). It seems to be shared.

I have been working on old ASP.NET Webform and I'm trying to do the same things than Session (One session by user), but is it the same way with Blazor ?

Thanks for your help.

Body:
AppData data = new AppData();
services.AddSingleton<Service.AppData>(data);

This adds a Singleton instance. And yes, that is shared between all users. Cookies are not involved. This behaves like the Application[] object in WebForms.

Session[] has no direct counterpart, but there are many solutions. The docs list them here.

Note that you should try to be as 'stateless' as possible, so consider fetching your data from the Db every time the page Initializes.


问:
Spring boot connect to alibaba e-mapreduce kafka
I'm trying to connect spring boot kafka app to kafka on alibaba cloud.

The cloud is on e-mapreduce service.

However, I can't connect from boot, maybe due to some security credential that I need to provide?

I've already tried to set the boot properties as follows:

```<code>spring.kafka.properties.security.protocol=SSL
</code>```

Get error : Connection to node -1 (/xx.xx.xx.xx:9092) terminated during authentication. This may happen due to any of the following reasons: (1) Authentication failed due to invalid credentials with brokers older than 1.0.0, (2) Firewall blocking Kafka TLS traffic (eg it may only allow HTTPS traffic), (3) Transient network issue.

```<code>spring.kafka.properties.security.protocol=SASL_SSL
</code>```

Throws Caused by: java.lang.IllegalArgumentException: Could not find a 'KafkaClient' entry in the JAAS configuration. System property 'java.security.auth.login.config' is not set

Anybody has experience connect to kafka on alibaba cloud?

答:
I believe Kafka Connect could solve your problems of connect spring boot kafka app to kafka on Alibaba cloud:

Step 1: Create Kafka clusters
Create a source Kafka cluster and a target Kafka cluster in E-MapReduce.

Step 2: Create a topic for storing the data to be migrated
Create a topic named connect in the source Kafka cluster.

Step 3: Create a Kafka Connect connector
Use Secure Shell (SSH) to log on to the header node of the source Kafka cluster.
Optional:Customize Kafka Connect configuration.

Step 4: View the status of the Kafka Connect connector and task node
View the status of the Kafka Connect connector and task node and make sure that they are in normal status.

Follow other steps as your job needs are.

Detail instructions may be find on Use Kafka Connect to migrate data link: https://www.alibabacloud.com/help/doc-detail/127685.htm

Hope this will help you,

Body:
I'm trying to connect spring boot kafka app to kafka on alibaba cloud.

The cloud is on e-mapreduce service.

However, I can't connect from boot, maybe due to some security credential that I need to provide?

I've already tried to set the boot properties as follows:

spring.kafka.properties.security.protocol=SSL

Get error : Connection to node -1 (/xx.xx.xx.xx:9092) terminated during authentication. This may happen due to any of the following reasons: (1) Authentication failed due to invalid credentials with brokers older than 1.0.0, (2) Firewall blocking Kafka TLS traffic (eg it may only allow HTTPS traffic), (3) Transient network issue.

spring.kafka.properties.security.protocol=SASL_SSL

Throws Caused by: java.lang.IllegalArgumentException: Could not find a 'KafkaClient' entry in the JAAS configuration. System property 'java.security.auth.login.config' is not set

Anybody has experience connect to kafka on alibaba cloud?


问:
[disabled]="!isValid()" is not working in IE11 for Angular 8
disabled attribute with function is not working in IE11. It remains disable all the time. Please refer below code:

HTML:

```<code> <button type="submit" (click)="onSubmit()" [disabled]="!isValid()">SAVE</button>
</code>```

Component (.ts)

```<code>isValid(){
    return this.providedId != null;
}
</code>```

答:
Do you need that function isValid()? Are you having more logic in there?

Otherwise you can directly bind to providedId:

```<code><button [disabled]="!providedId">
I am a button
</button>
</code>```

Stackblitz: https://stackblitz.com/edit/angular-ivy-disabled-binding

Body:
disabled attribute with function is not working in IE11. It remains disable all the time. Please refer below code:

HTML:

 <button type="submit" (click)="onSubmit()" [disabled]="!isValid()">SAVE</button>

Component (.ts)

isValid(){
    return this.providedId != null;
}

Body:
Do you need that function isValid()? Are you having more logic in there?

Otherwise you can directly bind to providedId:

<button [disabled]="!providedId">
I am a button
</button>

Stackblitz: https://stackblitz.com/edit/angular-ivy-disabled-binding


问:
How can I monitor the system tray icon notification once it pops up using python in Windows10?
I want to set an SMS alert once a system tray popup message appears on my windows system. What are the ways to monitor the system tray icon popup messages on Windows 10?</p>

答:
Either create your own custom handler for creating notifications, or track changes in tray icons.
Libraries: win32file, win32con, win32gui.
Maybe you can help: GitHub
The task is interesting.</p>


问:
java: Why does my app crashed when i try to restart a thread?
So i'm writing an app where i can remote control the light of another device. Now i want to have a timer that runs as long as the light is turned on and stops running when i turn them off again.

Now that works perfectly fine for the first time: Meaning when i turn the light on for the first time, the timer stars running, when i turn it off, it stops. But when i try to do that again, the app crashes. Anyone have any idea where the problem might be?

Here is my code:

```<code>
 //thread for the timer it's in the onCreate method
        t = new Thread()
        {
            @Override
            public void run(){

                while(!(t.isInterrupted())){

                    try {
                        Thread.sleep(1000);  //1000ms = 1 sec

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                runningtime++;
                                runningTime.setText("Running since: " + String.valueOf(runningtime) + "seconds" );
                            }
                        });

                    } catch (InterruptedException e) {
                        t.interrupt();
                    }

                }
            }
        };
    }

</code>```

```<code>//the buttons and the button listeners

    final Button buttonOn = findViewById(R.id.lightOn);
        buttonOn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Code here executes on main thread after user presses button
                turnLightOn();
                //timer-thread gets started
                t.start();
                test.setText("Status: ON");
            }
        });

        final Button buttonOff = findViewById(R.id.lightOff);
        buttonOff.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Code here executes on main thread after user presses button
                turnLightOff();
                //timer thread gets interrupted
                t.interrupt();
                test.setText("Status: OFF");
            }
        });

</code>```

答:
You simply can not restart a Thread in Java

From the java API docs at https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

It is never legal to start a thread more than once. In particular, a
  thread may not be restarted once it has completed execution.

Basically, you will want to recreate this thread using the same logic that you showed above. It likely makes sense to put that in a new method that returns a Thread, and then call that new method from your onClick to populate t.
Watch out for someone hammering the click button though, it could cause weird behavior.

```<code> //thread for the timer it's in the onCreate method
public Thread makeNewThread() {
        return new Thread()
        {
            @Override
            public void run(){

                while(!(t.isInterrupted())){

                    try {
                        Thread.sleep(1000);  //1000ms = 1 sec

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                runningtime++;
                                runningTime.setText("Running since: " + String.valueOf(runningtime) + "seconds" );
                            }
                        });

                    } catch (InterruptedException e) {
                        t.interrupt();
                    }

                }
            }
        };
    }

}
</code>```

Body:
So i'm writing an app where i can remote control the light of another device. Now i want to have a timer that runs as long as the light is turned on and stops running when i turn them off again.

Now that works perfectly fine for the first time: Meaning when i turn the light on for the first time, the timer stars running, when i turn it off, it stops. But when i try to do that again, the app crashes. Anyone have any idea where the problem might be?

Here is my code:

 //thread for the timer it's in the onCreate method
        t = new Thread()
        {
            @Override
            public void run(){

                while(!(t.isInterrupted())){

                    try {
                        Thread.sleep(1000);  //1000ms = 1 sec

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                runningtime++;
                                runningTime.setText("Running since: " + String.valueOf(runningtime) + "seconds" );
                            }
                        });

                    } catch (InterruptedException e) {
                        t.interrupt();
                    }

                }
            }
        };
    }

//the buttons and the button listeners

    final Button buttonOn = findViewById(R.id.lightOn);
        buttonOn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Code here executes on main thread after user presses button
                turnLightOn();
                //timer-thread gets started
                t.start();
                test.setText("Status: ON");
            }
        });

        final Button buttonOff = findViewById(R.id.lightOff);
        buttonOff.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Code here executes on main thread after user presses button
                turnLightOff();
                //timer thread gets interrupted
                t.interrupt();
                test.setText("Status: OFF");
            }
        });

Body:
You simply can not restart a Thread in Java

From the java API docs at https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

It is never legal to start a thread more than once. In particular, a
  thread may not be restarted once it has completed execution.

Basically, you will want to recreate this thread using the same logic that you showed above. It likely makes sense to put that in a new method that returns a Thread, and then call that new method from your onClick to populate t.
Watch out for someone hammering the click button though, it could cause weird behavior.

 //thread for the timer it's in the onCreate method
public Thread makeNewThread() {
        return new Thread()
        {
            @Override
            public void run(){

                while(!(t.isInterrupted())){

                    try {
                        Thread.sleep(1000);  //1000ms = 1 sec

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                runningtime++;
                                runningTime.setText("Running since: " + String.valueOf(runningtime) + "seconds" );
                            }
                        });

                    } catch (InterruptedException e) {
                        t.interrupt();
                    }

                }
            }
        };
    }

}


问:
Resource Unavailable Error in AWS Glue Job
We are using AWS Glue service to convert json files to parquet. Intermittently Glue job is failing with Resource unavailable Error.
Can anyone help us how to resolve the same?</p>

答:
I have recently struggled with Resource Unavailable thrown by Glue Job

Also i was not able to make a direct connection in Glue using RDS -it said "no suitable security group found"

I faced this issue while trying to connect with AWS RDS using Glue Job.

The problem was with the Security Group that the RDS was using. There is a need to place a self referencing inbound rule in the Security Group.

For those who dont know what is self referencing inbound rule, follow the steps

1) Go to the Security Group you are using (VPC -> Security Group)

2) In the Inbound Rules select Edit Inbound Rules

3) Add a Rule

a) Type - All Traffic
   b) Protocol - All
   c) Port Range - ALL
   d) Source - custom and in space available write the initial of your security group and select it.
   e) Save it.

Its done !

if you were missing this condition in your Security Group Inbound Rules

Try creating the connection you will be able to create the connection.

Also job should work this time.


问:
Is a drag-over checkbox list useful?
A while ago I created a drag-over check box list which allows you to check many check boxes in a single gesture. Do you think it is viable and usable on the web where people might not know how to use it. The default behaviour still works for the individual check boxes.</p>

答:
1 - The idea

The idea is nice and can probably be used in professional applications where you have direct contact with users and can explain them how things work, but not necessarily on public websites where users don't want to RTFM and are just looking for familiar behaviours. Unless it was just a sample exercise or a control meant to be included it in a control pack, it violates the YAGNI principle ;)

2 - The implementation

You certainly noticed that the implementation is buggy (at least on IE7 and FF3.1B2). Sometimes, a gesture above all checkboxes will select all of them but one or two. Moving the mouse over the div's above or below the list will stop the drag (I know it's a "feature", but it's not very user friendly). I Checked the source code and to be honnest, while it looks pretty neat, I just didn't want to deal with it because it is plain javascript. Don't you know that...

3 - Possible improvements

...you can write less and do more with a javascript library, typically jQuery. I would completely rewrite this control as a jQuery plugin. It will provide you with a lot of tools to make your code much easier to write, maintain and extend. Just try it, you'll love it. This is from a technical point of view. From a user point of view, try to make you control as familiar as possible, like what Angela suggested, windows explorer : a nice selection rectangle, the ability to use shit + click, or something like that. Finally, remember that for many windows checklistbox users, "selected" and "checked" are two different things.

OwnerDisplayName: Jonathan Parker

ContentLicense: CC BY-SA 3.0

Title: Is a drag-over checkbox list useful?

OwnerDisplayName: ybo

ContentLicense: CC BY-SA 2.5


问:
Listeners for changes to app config/resources files
I have an app running in tomcat6 which reads a resource file (a simple text file, no xml) at startup to configure/instantiate some classes. Now I want to be able to modify that file and the changes to be reflected in the app without having to restart the server. Is there a way to do that? </p>

<p>Basically if I could define and attach a listener to that resource, that's all I need. </p>

答: Not sure if there is a built in resource listener, but it would be fairly simple to start a new thread that monitors the file in the file system ( on date/time last updated for example ) and refreshed the classes if it changed.</p>

Body:
I have an app running in tomcat6 which reads a resource file (a simple text file, no xml) at startup to configure/instantiate some classes. Now I want to be able to modify that file and the changes to be reflected in the app without having to restart the server. Is there a way to do that?

Basically if I could define and attach a listener to that resource, that's all I need.


问:
how to remove a string from a code using methods, arrays and loops?
I made a code that removes symbols and characters from a "string text" using "method" and "arrays" and "loops", and everything was built in successfully.

But, when I tried testing it on an actual String text, it wasn't running. Someone clarify what I did wrong. here is the code:

```<code>public static String remove(String text, char symbol){
    String a= " ";
    for(int i=1; i<text.length();i++){
        char letter=text.charAt(i);
        if(letter !=symbol){
            a+=letter;
        }
    }
    return a;
}
</code>```

答:
There are a few problems in your code:

a = " " doesn't seem to be correct, unless you want to have a space at the beginning of the result-string.

The iteration in your for-loop starts at i = 1. That's not correct either, because that way you will not work on the first letter in the string.

A corrected - and working - solution looks like this:

```<code>public class RemoveLetter {
    public static void main(String[] args) {
        System.out.println(remove("Hello World", 'o'));
    }
    public static String remove(String text, char symbol){
        String a= "";
        for(int i = 0; i < text.length(); i++){
            char letter = text.charAt(i);
            if(letter != symbol) {
                a += letter;
            }
        }
        return a;
    }
}
</code>```

This example will give the output Hell Wrld, which certainly is correct.

Edit To remove more than one letter, you will have to call the method multiple times:

```<code>public class RemoveLetter {
    public static void main(String[] args) {
        String string = "Hello World";
        String result = remove(string, 'o');
        result = remove(result, 'H');
        System.out.println(result);
    }
    public static String remove(String text, char symbol){
        String a= "";
        for(int i = 0; i < text.length(); i++){
            char letter = text.charAt(i);
            if(letter != symbol) {
                a += letter;
            }
        }
        return a;
    }
}
</code>```

This will give you the output ell Wrld.

Body:
I made a code that removes symbols and characters from a "string text" using "method" and "arrays" and "loops", and everything was built in successfully.

But, when I tried testing it on an actual String text, it wasn't running. Someone clarify what I did wrong. here is the code:

public static String remove(String text, char symbol){
    String a= " ";
    for(int i=1; i<text.length();i++){
        char letter=text.charAt(i);
        if(letter !=symbol){
            a+=letter;
        }
    }
    return a;
}

Body:
There are a few problems in your code:

a = " " doesn't seem to be correct, unless you want to have a space at the beginning of the result-string.

The iteration in your for-loop starts at i = 1. That's not correct either, because that way you will not work on the first letter in the string.

A corrected - and working - solution looks like this:

public class RemoveLetter {
    public static void main(String[] args) {
        System.out.println(remove("Hello World", 'o'));
    }
    public static String remove(String text, char symbol){
        String a= "";
        for(int i = 0; i < text.length(); i++){
            char letter = text.charAt(i);
            if(letter != symbol) {
                a += letter;
            }
        }
        return a;
    }
}

This example will give the output Hell Wrld, which certainly is correct.

Edit To remove more than one letter, you will have to call the method multiple times:

public class RemoveLetter {
    public static void main(String[] args) {
        String string = "Hello World";
        String result = remove(string, 'o');
        result = remove(result, 'H');
        System.out.println(result);
    }
    public static String remove(String text, char symbol){
        String a= "";
        for(int i = 0; i < text.length(); i++){
            char letter = text.charAt(i);
            if(letter != symbol) {
                a += letter;
            }
        }
        return a;
    }
}

This will give you the output ell Wrld.


问:
Passing text into a label on tkinter
I have a 2 files: main.py and gui.py. Main.py - kinda back end, where all calculations are happening.
gui.py is a front side. I am having problem with passing the text from main.py to the label in gui.py.

```<code>predicted = loaded_model.predict(X_new_tfidf)
print(category_list[predicted[0]])
gui.lblClassify.set(category_list[predicted[0]])
</code>```

The print(category_list[predicted[0]]) is giving a output (text) that i have to pass to the label in gui.

Label in gui.py looks like the following:

```<code>lblClassify = tk.Label(frame, textvariable = buttonText)
lblClassify.place(relx=0.69, rely=0.6, relheight=0.1, relwidth=0.3)
lblClassify.pack()
</code>```

答:
Try this method out:
    lblClassify = tk.Label(frame, text = "Your text goes here")

if you want to change text after creation of Label, this should do the trick:
    lblClassify.config(text="Updated value")

Title: Passing text into a label on tkinter

Body:
I have a 2 files: main.py and gui.py. Main.py - kinda back end, where all calculations are happening.
gui.py is a front side. I am having problem with passing the text from main.py to the label in gui.py.

predicted = loaded_model.predict(X_new_tfidf)
print(category_list[predicted[0]])
gui.lblClassify.set(category_list[predicted[0]])

The print(category_list[predicted[0]]) is giving a output (text) that i have to pass to the label in gui.

Label in gui.py looks like the following:

lblClassify = tk.Label(frame, textvariable = buttonText)
lblClassify.place(relx=0.69, rely=0.6, relheight=0.1, relwidth=0.3)
lblClassify.pack()


问:
python error with summarizing the values in vocabularie
Sorry, can you help me?
I'm trying to calculate the values for the same key, exported form csv file:

dd = {}

with open('input_1.csv') as File:

    reader = csv.reader(File, delimiter=';')
    g=list(reader)
    for key,value in g.items():
        key = row[0]
        value = int(row[1])
        if key in reader:
            dd[key] += value

print(dd)
```

<p>It comes out:</p>

<pre class="lang-py prettyprint-override"><code>  File "C:/Users/User/Documents/Visual Studio 2017/DjangoWebProject1/DjangoWebProject1/app/6_8.py", line 20, in <module>
    for key,value in g.items():
AttributeError: 'list' object has no attribute 'items'
</code>```

答:
When you do g=list(reader) you're reading the values into a list. Later, you treat it as if it were a dictionary.

for key,value in g.items(): would work if g was a dictionary instead of a list. The csv library doesn't seem to provide an easy helper method to read it as a dictionary instead, but another stackoverflow answer can help you there: Creating a dictionary from a CSV file

Body:
Sorry, can you help me?
I'm trying to calculate the values for the same key, exported form csv file:

dd = {}

with open('input_1.csv') as File:

    reader = csv.reader(File, delimiter=';')
    g=list(reader)
    for key,value in g.items():
        key = row[0]
        value = int(row[1])
        if key in reader:
            dd[key] += value

print(dd)

It comes out:

  File "C:/Users/User/Documents/Visual Studio 2017/DjangoWebProject1/DjangoWebProject1/app/6_8.py", line 20, in <module>
    for key,value in g.items():
AttributeError: 'list' object has no attribute 'items'


问:
Removing permission from Role in Liferay 7.3
Im trying to hide unnecessary parts from drop-down menu.
To be precise Notifications, Shared Content, My Submissions, My Workflow Tasks etc..

I was able to remove them via
Control panel -> Users -> Roles -> User -> Permissions

Is there way to achieve same result through Hooks or through config file?

Im running docker with liferay/portal:7.3.0-ga1 image and therefore need to be able to achieve this without GUI.

答:
After various research i came up with this:

```<code>private void removePermissions() throws PortalException {
    List<String> portletList = Arrays.asList("com_liferay_users_admin_web_portlet_MyOrganizationsPortlet",
            "com_liferay_my_account_web_portlet_MyAccountPortlet",
            "com_liferay_portal_workflow_web_internal_portlet_UserWorkflowPortlet",
            "com_liferay_portal_workflow_task_web_portlet_MyWorkflowTaskPortlet",
            "com_liferay_notifications_web_portlet_NotificationsPortlet",
            "com_liferay_sharing_web_portlet_SharedAssetsPortlet",
            "com_liferay_oauth2_provider_web_internal_portlet_OAuth2ConnectedApplicationsPortlet"
    );

    String primKey = String.valueOf(company.getPrimaryKey());

    for (String portlet : portletList) {
        ResourcePermissionLocalServiceUtil.removeResourcePermission(
                companyId,
                portlet,
                ResourceConstants.SCOPE_COMPANY,
                primKey,
                userRole.getRoleId(),
                "ACCESS_IN_CONTROL_PANEL");
    }

}
</code>```

companyId, userRole can be achieved via RoleLocalServiceUtil and CompanyLocalServiceUtil. PrimKey is differs based on scope, this blog helped me a lot understanding it. I sniffed names of portlets through developer console when removing permissions through GUI. I haven't found cleaner solution.

Body:
After various research i came up with this:

private void removePermissions() throws PortalException {
    List<String> portletList = Arrays.asList("com_liferay_users_admin_web_portlet_MyOrganizationsPortlet",
            "com_liferay_my_account_web_portlet_MyAccountPortlet",
            "com_liferay_portal_workflow_web_internal_portlet_UserWorkflowPortlet",
            "com_liferay_portal_workflow_task_web_portlet_MyWorkflowTaskPortlet",
            "com_liferay_notifications_web_portlet_NotificationsPortlet",
            "com_liferay_sharing_web_portlet_SharedAssetsPortlet",
            "com_liferay_oauth2_provider_web_internal_portlet_OAuth2ConnectedApplicationsPortlet"
    );

    String primKey = String.valueOf(company.getPrimaryKey());

    for (String portlet : portletList) {
        ResourcePermissionLocalServiceUtil.removeResourcePermission(
                companyId,
                portlet,
                ResourceConstants.SCOPE_COMPANY,
                primKey,
                userRole.getRoleId(),
                "ACCESS_IN_CONTROL_PANEL");
    }

}

companyId, userRole can be achieved via RoleLocalServiceUtil and CompanyLocalServiceUtil. PrimKey is differs based on scope, this blog helped me a lot understanding it. I sniffed names of portlets through developer console when removing permissions through GUI. I haven't found cleaner solution.


问:
python docopt: "expected string or buffer"
I am using docopt module to handle python script options :

```<code>from docopt import docopt
"""Usage:
  ./convert [ -h | -i | -t | -c ]

Options:
  -h          Show this help
  -i          Convert image to vertical scroll box
  -t          Convert text to vertical scroll box
  -c          Convert command list to html
"""

def main(docopt_args):
...
if __name__ == '__main__':
    args = docopt(__doc__, version='v0.1')
    main(args)
</code>```

Traceback (most recent call last):   File

"/home/ajn/Converter-yaml-to-html-blocks/convert.py", line 66, in

args = docopt(doc, version='v0.1')   File   "/usr/local/lib/python3.4/dist-packages/docopt.py", line 558, in
docopt

DocoptExit.usage = printable_usage(doc)   File   "/usr/local/lib/python3.4/dist-packages/docopt.py", line 466, in
printable_usage

usage_split = re.split(r'([Uu][Ss][Aa][Gg][Ee]:)', doc)   File   "/usr/lib/python3.4/re.py", line 196, in split

return _compile(pattern, flags).split(string, maxsplit) TypeError:
expected string or buffer

Any hint?

答:
To anyone confused, when using docopt you should write a docstring before the from docopt import docopt. The options for the arguments are generated by parsing that string automatically. In this question the docstring is:

```<code>"""Usage:
  ./convert [ -h | -i | -t | -c ]

Options:
  -h          Show this help
  -i          Convert image to vertical scroll box
  -t          Convert text to vertical scroll box
  -c          Convert command list to html
"""
</code>```

and should have been placed before the import.

See more examples at the README of the project here

Body:
I am using docopt module to handle python script options :

from docopt import docopt
"""Usage:
  ./convert [ -h | -i | -t | -c ]

Options:
  -h          Show this help
  -i          Convert image to vertical scroll box
  -t          Convert text to vertical scroll box
  -c          Convert command list to html
"""

def main(docopt_args):
...
if __name__ == '__main__':
    args = docopt(__doc__, version='v0.1')
    main(args)

Traceback (most recent call last):   File

"/home/ajn/Converter-yaml-to-html-blocks/convert.py", line 66, in

args = docopt(doc, version='v0.1')   File   "/usr/local/lib/python3.4/dist-packages/docopt.py", line 558, in
docopt

DocoptExit.usage = printable_usage(doc)   File   "/usr/local/lib/python3.4/dist-packages/docopt.py", line 466, in
printable_usage

usage_split = re.split(r'([Uu][Ss][Aa][Gg][Ee]:)', doc)   File   "/usr/lib/python3.4/re.py", line 196, in split

return _compile(pattern, flags).split(string, maxsplit) TypeError:
expected string or buffer

Any hint?

Body:
To anyone confused, when using docopt you should write a docstring before the from docopt import docopt. The options for the arguments are generated by parsing that string automatically. In this question the docstring is:

"""Usage:
  ./convert [ -h | -i | -t | -c ]

Options:
  -h          Show this help
  -i          Convert image to vertical scroll box
  -t          Convert text to vertical scroll box
  -c          Convert command list to html
"""

and should have been placed before the import.

See more examples at the README of the project here


问:
assimp cmake mingw-w64 VSCode win10
UPDATE

later version of assimp (5.2.5) can be successfully built by mingw-w64 (gcc version 12.2.0) by disabling ASSIMP_WARNING_AS_ERROR.

However, it cannot load .obj model (the model doesn't show in the opengl scene) previously loaded by msvc built assimp.

Assimp 5.2.5 compiled by cmake-gui and mingw-w64 faild to load .obj model in opengl rendering

UPDATE: the developer of assimp has confirmed the bug and planned to fix it by adding this to ToDo in Planning for Release V5.1 on 26 May.

https://github.com/assimp/assimp/issues/3221

I'm trying to use assimp in opengl, following building instructions here: https://github.com/assimp/assimp/blob/master/Build.md under the following environment:

```<code>assimp 5.0.1
cmake 3.17.2
mingw-w64 with gcc/g++ 8.1.0
VSCode in Win10
</code>```

I tried in cmake-gui, use MinGW Makefile , I can obtain a makefile in the build path.

I then tried to make it by mingw32-make and stopped at 69% with

```<code>[ 67%] Linking CXX shared library libassimp.dll
[ 67%] Built target assimp
Scanning dependencies of target assimp_cmd
[ 67%] Building RC object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/assimp_cmd.rc.obj
[ 68%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/CompareDump.cpp.obj
[ 68%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/ImageExtractor.cpp.obj
[ 68%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/Main.cpp.obj
[ 68%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/WriteDumb.cpp.obj
[ 69%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/Info.cpp.obj
[ 69%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/Export.cpp.obj
[ 69%] Linking CXX executable assimp.exe
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0x8d): undefined reference to `Assimp::Importer::ValidateFlags(unsigned int) const'
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0xc4): undefined reference to `Assimp::Importer::ReadFile(char const*, unsigned int)'
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0x14e): undefined reference to `Assimp::DefaultLogger::create(char const*, Assimp::Logger::LogSeverity, unsigned int, Assimp::IOSystem*)'
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0x183): undefined reference to `Assimp::DefaultLogger::kill()'
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0x1b8): undefined reference to `Assimp::Importer::GetErrorString() const'
......
......
......
CMakeFiles\assimp_cmd.dir/objects.a(Export.cpp.obj):Export.cpp:(.text+0xf44): undefined reference to `Assimp::Exporter::GetExportFormatDescription(unsigned long long) const'
collect2.exe: error: ld returned 1 exit status
mingw32-make[2]: *** [tools\assimp_cmd\CMakeFiles\assimp_cmd.dir\build.make:197: tools/assimp_cmd/assimp.exe] Error 1
mingw32-make[1]: *** [CMakeFiles\Makefile2:297: tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/all] Error 2
mingw32-make: *** [Makefile:149: all] Error 2
</code>```

Though I can get a "libassimp.dll" and a "libassimp.dll.a" in the build directory, I failed to link them into my project. there are many "undefined reference to xxxx" errors.

I placed the .dll in the exe path, placed .a file in lib path, placed all the assimp .h files in the include path.

VSCode doesn't seem to support the file name "libassimp.dll.a", I have to rename it as libassimpdll.a and write "-lassimp" in tasks.json. But "undefined reference" errors exists.

I tried to build assimp to VS2017 and I can get dll and lib.

I tried to directly link the assimp 3.1.1 (with x86/x64 dll and lib already provided officially) but also failed.

So my question is if anyone succeed in building assimp with cmake and mingw-w64 and link it in the project in VSCode Win10?

答:
I am able to build assimp 5.0.1 with:

```<code>cmake.exe -G"MSYS Makefiles" -DCMAKE_INSTALL_PREFIX:PATH=/usr/local -DCMAKE_BUILD_TYPE:STRING=Release -DBUILD_SHARED_LIBS:BOOL=OFF -DASSIMP_BUILD_ASSIMP_TOOLS:BOOL=OFF -DASSIMP_HEADERCHECK:BOOL=OFF -DASSIMP_OPT_BUILD_PACKAGES:BOOL=OFF -DSYSTEM_IRRXML:BOOL=OFF -DASSIMP_BUILD_SAMPLES:BOOL=OFF -DBUILD_DOCS:BOOL=OFF -DASSIMP_BUILD_TESTS:BOOL=OFF -S. -Bbuild_win &&
make -Cbuild_win &&
echo Success
</code>```

and even the same with -DBUILD_SHARED_LIBS:BOOL=ON under the MSYS2 shell.

It doesn't work with -DASSIMP_BUILD_ASSIMP_TOOLS:BOOL=ON though.

Title: assimp cmake mingw-w64 VSCode win10

Body:
UPDATE

later version of assimp (5.2.5) can be successfully built by mingw-w64 (gcc version 12.2.0) by disabling ASSIMP_WARNING_AS_ERROR.

However, it cannot load .obj model (the model doesn't show in the opengl scene) previously loaded by msvc built assimp.

Assimp 5.2.5 compiled by cmake-gui and mingw-w64 faild to load .obj model in opengl rendering

UPDATE: the developer of assimp has confirmed the bug and planned to fix it by adding this to ToDo in Planning for Release V5.1 on 26 May.

https://github.com/assimp/assimp/issues/3221

I'm trying to use assimp in opengl, following building instructions here: https://github.com/assimp/assimp/blob/master/Build.md under the following environment:

assimp 5.0.1
cmake 3.17.2
mingw-w64 with gcc/g++ 8.1.0
VSCode in Win10

I tried in cmake-gui, use MinGW Makefile , I can obtain a makefile in the build path.

I then tried to make it by mingw32-make and stopped at 69% with

[ 67%] Linking CXX shared library libassimp.dll
[ 67%] Built target assimp
Scanning dependencies of target assimp_cmd
[ 67%] Building RC object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/assimp_cmd.rc.obj
[ 68%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/CompareDump.cpp.obj
[ 68%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/ImageExtractor.cpp.obj
[ 68%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/Main.cpp.obj
[ 68%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/WriteDumb.cpp.obj
[ 69%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/Info.cpp.obj
[ 69%] Building CXX object tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/Export.cpp.obj
[ 69%] Linking CXX executable assimp.exe
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0x8d): undefined reference to `Assimp::Importer::ValidateFlags(unsigned int) const'
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0xc4): undefined reference to `Assimp::Importer::ReadFile(char const*, unsigned int)'
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0x14e): undefined reference to `Assimp::DefaultLogger::create(char const*, Assimp::Logger::LogSeverity, unsigned int, Assimp::IOSystem*)'
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0x183): undefined reference to `Assimp::DefaultLogger::kill()'
CMakeFiles\assimp_cmd.dir/objects.a(Main.cpp.obj):Main.cpp:(.text+0x1b8): undefined reference to `Assimp::Importer::GetErrorString() const'
......
......
......
CMakeFiles\assimp_cmd.dir/objects.a(Export.cpp.obj):Export.cpp:(.text+0xf44): undefined reference to `Assimp::Exporter::GetExportFormatDescription(unsigned long long) const'
collect2.exe: error: ld returned 1 exit status
mingw32-make[2]: *** [tools\assimp_cmd\CMakeFiles\assimp_cmd.dir\build.make:197: tools/assimp_cmd/assimp.exe] Error 1
mingw32-make[1]: *** [CMakeFiles\Makefile2:297: tools/assimp_cmd/CMakeFiles/assimp_cmd.dir/all] Error 2
mingw32-make: *** [Makefile:149: all] Error 2

Though I can get a "libassimp.dll" and a "libassimp.dll.a" in the build directory, I failed to link them into my project. there are many "undefined reference to xxxx" errors.

I placed the .dll in the exe path, placed .a file in lib path, placed all the assimp .h files in the include path.

VSCode doesn't seem to support the file name "libassimp.dll.a", I have to rename it as libassimpdll.a and write "-lassimp" in tasks.json. But "undefined reference" errors exists.

I tried to build assimp to VS2017 and I can get dll and lib.

I tried to directly link the assimp 3.1.1 (with x86/x64 dll and lib already provided officially) but also failed.

So my question is if anyone succeed in building assimp with cmake and mingw-w64 and link it in the project in VSCode Win10?

Body:
I am able to build assimp 5.0.1 with:

cmake.exe -G"MSYS Makefiles" -DCMAKE_INSTALL_PREFIX:PATH=/usr/local -DCMAKE_BUILD_TYPE:STRING=Release -DBUILD_SHARED_LIBS:BOOL=OFF -DASSIMP_BUILD_ASSIMP_TOOLS:BOOL=OFF -DASSIMP_HEADERCHECK:BOOL=OFF -DASSIMP_OPT_BUILD_PACKAGES:BOOL=OFF -DSYSTEM_IRRXML:BOOL=OFF -DASSIMP_BUILD_SAMPLES:BOOL=OFF -DBUILD_DOCS:BOOL=OFF -DASSIMP_BUILD_TESTS:BOOL=OFF -S. -Bbuild_win &&
make -Cbuild_win &&
echo Success

and even the same with -DBUILD_SHARED_LIBS:BOOL=ON under the MSYS2 shell.

It doesn't work with -DASSIMP_BUILD_ASSIMP_TOOLS:BOOL=ON though.


问:
Building a Media Player in React Native expo and Getting duration of song
I am implementing a Media player in React Native expo. I have designed my player, play song, next and previous songs functionality but I am having an issue getting the duration of the song, in order to be able to display the progress of the song using a progress bar.

I have gone through https://docs.expo.io/versions/latest/sdk/audio/ and didn't find anything on how to get the duration of the file or how to get any information that can help me in the progress bar implementation. Any ideas are highly welcome.

The code I'm experimenting with:

// Create new object from Expo.Audio.Sound
   this.soundObject = new Audio.Sound();
   await this.soundObject.loadAsync(url);
   await this.soundObject.playAsync();

   getCurrentItemArtistName = ()=> {
        return this.list[this.index].artistname;
    };

   getCurrentItemCover = ()=> {
        return this.list[this.index].cover;
    };
```

thank you in advance

答:
I am not sure if you still interested, however, as follow a way to get the duration.

```<code>const sound = new Audio.Sound();

try {

   const track = await sound.loadAsync(require('../../models/smw_bonus_game_end.mp3'));

   console.log(track.durationMillis); // Prints the duration in milliseconds

  } catch (err) {
   console.log(err);
  };
</code>```

You can get the duration after you have loaded the file.

Additional information can be found in the object. Using the same code below, just try to print only the const track:

```<code>console.log(track);
</code>```

It will print an object as follow:

```<code> Object {
  "didJustFinish": false,
  "durationMillis": 3108,
  "hasJustBeenInterrupted": false,
  "isBuffering": false,
  "isLoaded": true,
  "isLooping": false,
  "isMuted": false,
  "isPlaying": false,
  "pitchCorrectionQuality": "Varispeed",
  "playableDurationMillis": 3108,
  "positionMillis": 0,
  "progressUpdateIntervalMillis": 500,
  "rate": 1,
  "shouldCorrectPitch": false,
  "shouldPlay": false,
  "uri": "THE URI OF THE FILE IN YOUR DEVICE",
  "volume": 1,
}
</code>```

Many other information are available, let me know if you need something specific.

I hope this helps!

Cheers,

Body:
I am implementing a Media player in React Native expo. I have designed my player, play song, next and previous songs functionality but I am having an issue getting the duration of the song, in order to be able to display the progress of the song using a progress bar.

I have gone through https://docs.expo.io/versions/latest/sdk/audio/ and didn't find anything on how to get the duration of the file or how to get any information that can help me in the progress bar implementation. Any ideas are highly welcome.

The code I'm experimenting with:

// Create new object from Expo.Audio.Sound
   this.soundObject = new Audio.Sound();
   await this.soundObject.loadAsync(url);
   await this.soundObject.playAsync();

   getCurrentItemArtistName = ()=> {
        return this.list[this.index].artistname;
    };

   getCurrentItemCover = ()=> {
        return this.list[this.index].cover;
    };

thank you in advance

Body:
I am not sure if you still interested, however, as follow a way to get the duration.

const sound = new Audio.Sound();

try {

   const track = await sound.loadAsync(require('../../models/smw_bonus_game_end.mp3'));

   console.log(track.durationMillis); // Prints the duration in milliseconds

  } catch (err) {
   console.log(err);
  };

You can get the duration after you have loaded the file.

Additional information can be found in the object. Using the same code below, just try to print only the const track:

console.log(track);

It will print an object as follow:

 Object {
  "didJustFinish": false,
  "durationMillis": 3108,
  "hasJustBeenInterrupted": false,
  "isBuffering": false,
  "isLoaded": true,
  "isLooping": false,
  "isMuted": false,
  "isPlaying": false,
  "pitchCorrectionQuality": "Varispeed",
  "playableDurationMillis": 3108,
  "positionMillis": 0,
  "progressUpdateIntervalMillis": 500,
  "rate": 1,
  "shouldCorrectPitch": false,
  "shouldPlay": false,
  "uri": "THE URI OF THE FILE IN YOUR DEVICE",
  "volume": 1,
}

Many other information are available, let me know if you need something specific.

I hope this helps!

Cheers,


问:
flask-socketio on uWSGI
I have this flask-socketio app

```<code>(venv) ubuntu@ip-172-31-18-21:~/code$ more app.py
from flask_socketio import SocketIO, send, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from time import sleep
from threading import Thread, Event

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app, async_mode='gevent')

thread = Thread()
thread_stop_event = Event()

def firstFunction():
    print("*** First function")

def backgroundTask():
    while not thread_stop_event.isSet():
        socketio.emit('bg-socketio', {'data':'background-data'}, namespace='/', broadcast=True)
        socketio.sleep(2)

def startBackgroundTask():
    global thread

    if not thread.is_alive():
        thread = socketio.start_background_task(backgroundTask)

@app.route('/')
def main():
    return render_template('index.html', title='SocketIO')

@socketio.on('connect_event', namespace='/')
def handle_message_client_connected(message):
    print("*** Client connected")
    emit('c-socketio', {'data':' you connected!'}, namespace='/')

if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    socketio.run(app, host='0.0.0.0', port=5000)
</code>```

I want firstFunction() and startBackgroundTask() to run whenever the app starts.

What is the best practice for running this on uWSGI?
I've been trying to do this without any success, keep getting errors
https://flask-socketio.readthedocs.io/en/latest/#uwsgi-web-server

Error:
* running gevent loop engine [addr:0x5561d3f745a0] *
DAMN ! worker 1 (pid: 13772) died :( trying respawn ...
worker respawning too fast !!! i have to sleep a bit (2 seconds)...
Respawned uWSGI worker 1 (new pid: 13773)

Also tried this

```<code>uwsgi --socket 0.0.0.0:5000 --protocol=http --enable-threads -w wsgi:app

(venv) ubuntu@ip-172-31-18-21:~/code$ more wsgi.py
from uapp import app

if __name__ == "__main__":
    app.run()
</code>```

with uapp.py changed to

```<code>if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    app.run(host='0.0.0.0', port=5000)
</code>```

but this does not run firstFunction() or startBackgroundTask()

I'm pretty much stuck, looking for some suggestions.

答: Was not working with gevent 20.5.2 which I installed with 'pip install gevent'.  Changed to gevent==1.4.0 and now it uWSGI starts as expected.

Title: flask-socketio on uWSGI

Body:
I have this flask-socketio app

(venv) ubuntu@ip-172-31-18-21:~/code$ more app.py
from flask_socketio import SocketIO, send, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from time import sleep
from threading import Thread, Event

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app, async_mode='gevent')

thread = Thread()
thread_stop_event = Event()

def firstFunction():
    print("*** First function")

def backgroundTask():
    while not thread_stop_event.isSet():
        socketio.emit('bg-socketio', {'data':'background-data'}, namespace='/', broadcast=True)
        socketio.sleep(2)

def startBackgroundTask():
    global thread

    if not thread.is_alive():
        thread = socketio.start_background_task(backgroundTask)

@app.route('/')
def main():
    return render_template('index.html', title='SocketIO')

@socketio.on('connect_event', namespace='/')
def handle_message_client_connected(message):
    print("*** Client connected")
    emit('c-socketio', {'data':' you connected!'}, namespace='/')

if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    socketio.run(app, host='0.0.0.0', port=5000)

I want firstFunction() and startBackgroundTask() to run whenever the app starts.

What is the best practice for running this on uWSGI?
I've been trying to do this without any success, keep getting errors
https://flask-socketio.readthedocs.io/en/latest/#uwsgi-web-server

Error:
* running gevent loop engine [addr:0x5561d3f745a0] *
DAMN ! worker 1 (pid: 13772) died :( trying respawn ...
worker respawning too fast !!! i have to sleep a bit (2 seconds)...
Respawned uWSGI worker 1 (new pid: 13773)

Also tried this

uwsgi --socket 0.0.0.0:5000 --protocol=http --enable-threads -w wsgi:app

(venv) ubuntu@ip-172-31-18-21:~/code$ more wsgi.py
from uapp import app

if __name__ == "__main__":
    app.run()

with uapp.py changed to

if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    app.run(host='0.0.0.0', port=5000)

but this does not run firstFunction() or startBackgroundTask()

I'm pretty much stuck, looking for some suggestions.


问:
How to scrape information inside an unordered list selenium + python
I am working on a web scraping project, where I try to scrape information from the amazon website. In the website, there exists an unordered list with such information

```<code>Item Weight: 17.2 pounds
Shipping Weight: 17.4 pounds (View shipping rates and policies)
ASIN: B00HC767P6
UPC: 766789717088 885720483186 052000201628
Item model number: mark-1hooi-toop842
Customer Reviews: 4.8 out of 5 stars1,352 customer ratings
Amazon Best Sellers Rank: #514 in Grocery & Gourmet Food (See Top 100 in Grocery & Gourmet Food)
#12 in Sports Drinks
</code>```

The list itself does not have any class to it. The problem is I do not want all the information from the list. Only the ASIN code. the li tags do not have any specific class or ID to them. here is the link to the product details page

Before selenium, I was working with BeautifulSoup and this is how I tackled the issue

```<code>asin = str(soup.find('bdi', {'dir': 'ltr'}).find_parent('li'))[38:].split('<')[0]
</code>```

I am now switching to selenium. How do I scrape the information.

答:
You can use the css selector to get the related li item as follow:

Finding the child element by index by css selector

```<code>$(".content > ul > li:nth-child(2)").textContent >>> "Shipping Weight: 33 pounds (View shipping rates and policies)"
$(".content > ul > li:nth-child(3)").textContent >>> "ASIN: B07QKN2ZT9"
</code>```

related python selenium code:

```<code>driver.find_element_by_css_selector(".content > ul > li:nth-child(3)").text.split(": ")[1] >>> 'B07QKN2ZT9'
</code>```

Finding the ancestors element by XPATH

If the ASIN is not always in the same index, then you can find the bdi element that has text ASIN text and find its ancestor::li then get its text and extract the related part. Like the following:

driver.find_element_by_xpath("//bdi[text()='ASIN']/ancestor::li").text.split(": ")[1] >>> 'B07QKN2ZT9'
```

<h3>Generate XPATH</h3>

```//<element type>[<attribute type> = <attribute value>]/<descendant>
//bdi[text() = 'ASIN'] >>> bdi element with text 'ASIN'
//bdi[@dir = 'ltr'] >>> bdi element with dir attribute equals to 'ltr'
```

<h3>Access to an ancestor of an element</h3>

```/ancestor::<ancestor element type>
//bdi[text()='ASIN']/ancestor::li >>> li
//bdi[text()='ASIN']/ancestor::ul >>> ul
```

You can check this as a reference

Body:
I am working on a web scraping project, where I try to scrape information from the amazon website. In the website, there exists an unordered list with such information

Item Weight: 17.2 pounds
Shipping Weight: 17.4 pounds (View shipping rates and policies)
ASIN: B00HC767P6
UPC: 766789717088 885720483186 052000201628
Item model number: mark-1hooi-toop842
Customer Reviews: 4.8 out of 5 stars1,352 customer ratings
Amazon Best Sellers Rank: #514 in Grocery & Gourmet Food (See Top 100 in Grocery & Gourmet Food)
#12 in Sports Drinks

The list itself does not have any class to it. The problem is I do not want all the information from the list. Only the ASIN code. the li tags do not have any specific class or ID to them. here is the link to the product details page

Before selenium, I was working with BeautifulSoup and this is how I tackled the issue

asin = str(soup.find('bdi', {'dir': 'ltr'}).find_parent('li'))[38:].split('<')[0]

I am now switching to selenium. How do I scrape the information.

Body:
You can use the css selector to get the related li item as follow:

Finding the child element by index by css selector

$(".content > ul > li:nth-child(2)").textContent >>> "Shipping Weight: 33 pounds (View shipping rates and policies)"
$(".content > ul > li:nth-child(3)").textContent >>> "ASIN: B07QKN2ZT9"

related python selenium code:

driver.find_element_by_css_selector(".content > ul > li:nth-child(3)").text.split(": ")[1] >>> 'B07QKN2ZT9'

Finding the ancestors element by XPATH

If the ASIN is not always in the same index, then you can find the bdi element that has text ASIN text and find its ancestor::li then get its text and extract the related part. Like the following:

driver.find_element_by_xpath("//bdi[text()='ASIN']/ancestor::li").text.split(": ")[1] >>> 'B07QKN2ZT9'

Generate XPATH

//<element type>[<attribute type> = <attribute value>]/<descendant>
//bdi[text() = 'ASIN'] >>> bdi element with text 'ASIN'
//bdi[@dir = 'ltr'] >>> bdi element with dir attribute equals to 'ltr'

Access to an ancestor of an element

/ancestor::<ancestor element type>
//bdi[text()='ASIN']/ancestor::li >>> li
//bdi[text()='ASIN']/ancestor::ul >>> ul

You can check this as a reference


问:
an XNA way to make a menustrip
I will preface this by I am new to XNA and I realize what I am asking for doesn't exist.

However I am curious if I wanted to create something similar to a menustrip from winforms in XNA, how would I do that? Is there a best way? Or even a way?

I appreciate it, thanks!

答:
Well, if you're only targeting windows, you can always render XNA in a winforms project or wpf app. Once you do that, you can use the built-in controls to render the menu.

If however you're looking for something that will work on xbox or windows phone, you will have to do the work of rendering and positioning the menu yourself using whatever rendering techniques you are familiar with (ie. SpriteBatch, etc.)

Title: an XNA way to make a menustrip


问:
How to display/print out multiple inputs from a form as a table underneath with JS?
Background:

I have the following form. Once the [verify] button is hit, I can show only 1 "first name". I would like to print out the all the input fields (empty or full) when [verify] is pressed as a table like the form is in.

Research:

JS How to output values from function into HTML table

Questions:

How can I print the inputs of the form as a table like this:

<!DOCTYPE html>

Personnel Details

       Salutation:

        <select name="gender">
          <option value=""></option>
          <option value="male">Mr.</option>
          <option value="female">Ms.</option>
        </select>

       First Name:

       <input id="first_name">

       Middle Name:

          <input id="middle_name">

       Last Name:

          <input id="last_name">

       Email:

          <input id="email">

       DOB:

          <input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31">

            <button onclick="onVerify()">Verify</button>

      <button  onclick="onCommit()">Commit</button>
      <button  onclick="onCancel()">Cancel</button>

    Committed! :)

```

答:
this should be it. all i did is add more lines in the onVerify() and the div's it needs to fill when submitted

    $(document).ready(function() {
        document.getElementById("verify").style.display = "none";
        document.getElementById("committed").style.display = "none";
    })
    function onVerify() {
      document.getElementById("verifySalutation").innerHTML = document.getElementById("Salutation").value;
        document.getElementById("verifyName").innerHTML = document.getElementById("first_name").value;
        document.getElementById("verify-Middle-Name").innerHTML = document.getElementById("middle_name").value;
        document.getElementById("verify-Last-Name").innerHTML = document.getElementById("last_name").value;
        document.getElementById("verify-Email").innerHTML = document.getElementById("email").value;
    document.getElementById("verify-DOB").innerHTML = document.getElementById("date").value;
        document.getElementById("verify").style.display = "block";
    }
    function onCommit() {
        document.getElementById("form").style.display = "none";
        document.getElementById("verify").style.display = "none";
        document.getElementById("committed").style.display = "block";
    }
    function onCancel() {
        document.getElementById("form").style.display = "block";
        document.getElementById("verify").style.display = "none";
        document.getElementById("name").value = ""
}

    ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h3 {text-align: center;}
        .right {
            text-align: right;
            margin-right: 1em;
            }
        .center {
            display: flex;
            justify-content: center;
            align-items: center;
            }
            #verify table{
              display:flex;
              justify-content: center;
              align-items: center;
            }</code>```

<!DOCTYPE html>

Personnel Details

       Salutation:

        <select name="gender" id="Salutation">
          <option value=""></option>
          <option value="male">Mr.</option>
          <option value="female">Ms.</option>
        </select>

       First Name:

       <input id="first_name">

       Middle Name:

          <input id="middle_name">

       Last Name:

          <input id="last_name">

       Email:

          <input id="email">

       DOB:

          <input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31" id="date">

            <button onclick="onVerify()">Verify</button>

       Salutation:

       First Name:

       Middle Name:

       Last Name:

       Email:

       DOB:

      <button  onclick="onCommit()">Commit</button>
      <button  onclick="onCancel()">Cancel</button>

    Committed! :)

```

Body:
this should be it. all i did is add more lines in the onVerify() and the div's it needs to fill when submitted

    $(document).ready(function() {
        document.getElementById("verify").style.display = "none";
        document.getElementById("committed").style.display = "none";
    })
    function onVerify() {
      document.getElementById("verifySalutation").innerHTML = document.getElementById("Salutation").value;
        document.getElementById("verifyName").innerHTML = document.getElementById("first_name").value;
        document.getElementById("verify-Middle-Name").innerHTML = document.getElementById("middle_name").value;
        document.getElementById("verify-Last-Name").innerHTML = document.getElementById("last_name").value;
        document.getElementById("verify-Email").innerHTML = document.getElementById("email").value;
    document.getElementById("verify-DOB").innerHTML = document.getElementById("date").value;
        document.getElementById("verify").style.display = "block";
    }
    function onCommit() {
        document.getElementById("form").style.display = "none";
        document.getElementById("verify").style.display = "none";
        document.getElementById("committed").style.display = "block";
    }
    function onCancel() {
        document.getElementById("form").style.display = "block";
        document.getElementById("verify").style.display = "none";
        document.getElementById("name").value = ""
}

h3 {text-align: center;}
        .right {
            text-align: right;
            margin-right: 1em;
            }
        .center {
            display: flex;
            justify-content: center;
            align-items: center;
            }
            #verify table{
              display:flex;
              justify-content: center;
              align-items: center;
            }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<h3>Personnel Details</h3>
<div class="center" id="form">
 <table>
    <tr>
      <td class="right">
       <label>Salutation:</label>
      </td>
      <td>
        <select name="gender" id="Salutation">
          <option value=""></option>
          <option value="male">Mr.</option>
          <option value="female">Ms.</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="right">
       <label>First Name:</label>
      </td>
      <td>
       <input id="first_name">
      </td>
    </tr>
    <tr>
      <td class="right">
       <label>Middle Name:</label>
      </td>
      <td>
          <input id="middle_name">
      </td>
 </tr>
    <tr>
      <td class="right">
       <label>Last Name:</label>
      </td>
      <td>
          <input id="last_name">
      </td>
 </tr>
    <tr>
      <td class="right">
       <label>Email:</label>
      </td>
      <td>
          <input id="email">
      </td>
 </tr>    <tr>
      <td class="right">
       <label>DOB:</label>
      </td>
      <td>
          <input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31" id="date">
      </td>
 </tr>
    <tr>
      <td  colspan="2" style="text-align:center;">
        <div>
            <button onclick="onVerify()">Verify</button>
        </div>
      </td>
    </tr>

    </table>
</div>
<div id="verify">
    <br>
    <br>
    <table>
    <tr>
      <td class="right">
       <label>Salutation:</label>
      </td>
      <td>
        <div id="verifySalutation" class="center"></div>
      </td>
    </tr>
    <tr>
      <td class="right">
       <label>First Name:</label>
      </td>
      <td>
       <div id="verifyName" class="center"></div>
      </td>
    </tr>
    <tr>
      <td class="right">
       <label>Middle Name:</label>
      </td>
      <td>
          <div id="verify-Middle-Name" class="center"></div>
      </td>
 </tr>
    <tr>
      <td class="right">
       <label>Last Name:</label>
      </td>
      <td>
          <div id="verify-Last-Name" class="center"></div>
      </td>
 </tr>
    <tr>
      <td class="right">
       <label>Email:</label>
      </td>
      <td>
          <div id="verify-Email" class="center"></div>
      </td>
 </tr>    <tr>
      <td class="right">
       <label>DOB:</label>
      </td>
      <td>
          <div id="verify-DOB" class="center"></div>
      </td>
 </tr>
    </table>

    <div class="center">
      <button  onclick="onCommit()">Commit</button>
      <button  onclick="onCancel()">Cancel</button>
   </div>

</div>
<div id="committed">
    Committed! :)
</div>
</html>


问:
PHP Warning: PHP Startup: Unable to load dynamic library 'php_fileinfo.dll'
Good morning,

I'm struggerling to understand the below error. I believe it was caused when i migrated a cPanel account from one WHM to another.

I'm currently running Laravel but my log files are repeatedly growing with the same error.

```<code>[02-Jun-2020 10:46:47 UTC] PHP Warning:  PHP Startup: Unable to load dynamic library 'php_fileinfo.dll' (tried: /opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll (/opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll.so (/opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
</code>```

Has anyone experienced this before? or no of how i can resolve it...

Regards

Ross

答:
You may be missing a library. See this related question:

How to enable php_fileinfo extension in PHP?

If you have cpanel just go to

Select PHP Version

and search for the extension

fileinfo

check it and you're good to go.

Body:
Good morning,

I'm struggerling to understand the below error. I believe it was caused when i migrated a cPanel account from one WHM to another.

I'm currently running Laravel but my log files are repeatedly growing with the same error.

[02-Jun-2020 10:46:47 UTC] PHP Warning:  PHP Startup: Unable to load dynamic library 'php_fileinfo.dll' (tried: /opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll (/opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll.so (/opt/cpanel/ea-php73/root/usr/lib64/php/modules/php_fileinfo.dll.so: cannot open shared object file: No such file or directory)) in Unknown on line 0

Has anyone experienced this before? or no of how i can resolve it...

Regards

Ross


问:
Index-time boosting using DIH with JdbcDataSource
Is it possible to add boosts to docs and fields in Solr 1.4 DIH when using a JdbcDataSource? The documentation seem to suggest it's possible but I can't find any examples.

There are a few examples of how to add the boost="2.0" attribute to your docs/fields in XML imports, but how do you do the same with the JdbcDataSource?

The closest I could get to an answer was http://www.nabble.com/data-import-handler---going-deeper...-td20731715.html

Add a special value $fieldBoost. to the row map

Has this been implemented yet?

答:
This is not an answer, If you want to change the score of the field or the document you have added
http://wiki.apache.org/solr/SolrRelevancyFAQ#How_can_I_boost_the_score_of_newer_documents
just go through above link</p>


问:
Retrieve nested object into array in es6 or lodash
I am trying to extract nested objects of same keys into an array from array of objects.

Example:

There is an array as shown below:

```<code>[
 {
  id:1,
  model:'car',
  manufacturer:{
   id:1,
   name:'benz',
   year:2010
  }
 },
 {
  id:1,
  model:'car',
  manufacturer:{
   id:2,
   name:'benz',
   year:2012
  }
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]
</code>```

I need the result as shown below:

```<code>[
 {
   id:1,
   model:'car',
   manufacturer:[
    {
     id:1,
     name:'benz',
     year:2010
    },
    {
     id:2,
     name:'benz',
     year:2012
    }
   ]
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]
</code>```

How to achieve this? I tried all the possible ways using lodash but unable to get desired result. Please help me. Thank you.

答:
let data =[
 {
  id:1,
  model:'car',
  manufacturer:{
   id:1,
   name:'benz',
   year:2010
  }
 },
 {
  id:1,
  model:'car',
  manufacturer:{
   id:2,
   name:'benz',
   year:2012
  }
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]

   let temp=[];
    for(var  i=0;i<=data.length-1;i++){
      let pos = temp.findIndex(el=>el.id==data[i]['id']);
      if(pos == -1){
        temp.push(data[i]);
      }else{
       let obj = temp[pos]['manufacturer'];
       temp[pos]['manufacturer'] = Array.isArray(obj) ? [...obj,data[i]['manufacturer']] : [obj,data[i]['manufacturer']]
      }
    }

console.log(temp)

 ```

Body:
I am trying to extract nested objects of same keys into an array from array of objects.

Example:

There is an array as shown below:

[
 {
  id:1,
  model:'car',
  manufacturer:{
   id:1,
   name:'benz',
   year:2010
  }
 },
 {
  id:1,
  model:'car',
  manufacturer:{
   id:2,
   name:'benz',
   year:2012
  }
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]

I need the result as shown below:

[
 {
   id:1,
   model:'car',
   manufacturer:[
    {
     id:1,
     name:'benz',
     year:2010
    },
    {
     id:2,
     name:'benz',
     year:2012
    }
   ]
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]

How to achieve this? I tried all the possible ways using lodash but unable to get desired result. Please help me. Thank you.


问:
Read the date of a text file, change if pass two days and add a counter in the second line increment by 1
I want to read a date saved in a text document in the format "Y/M/D", compare it with the current date, and if it is ok, do nothing, but if two days pass from the file date, add a line below with an incremental number (1, 2, 3, 4 ...). And update the date in the file with the present date.

This is what I have for now.
Example if today is 2020/06/02 the file is:

2020/06/02

1

And don't change if execute.

But if today is 2020/06/05 and execute the file should change like this:

2020/06/05

2

Etc.

I'm stuck, and this is my code:

```<code>from datetime import datetime, timedelta, date

# Generate file 1.txt
file = open("xxx\\1.txt", "w")

# Var
today = date.today()
counter = 1

# GEnerate present date
file.write(str(date.today()) + "\n")
file.close()
</code>```

答:
This below code will generate a new file with the present date and an integer. Now if you run this code after two days it will update as you asked.</p>

```<code>import os
from datetime import datetime, timedelta, date

# Generate file 1.txt
if os.path.exists("xxx.txt"):
    file = open("xxx.txt",'r+')
else:
    file = open("xxx.txt","w+")
# replacing '-' to your default datetime in the txt file
today = str(date.today()).replace('-','/')
# reading the lines in the txt file
data = file.readlines()
# retriving only the date from the txt file dat
try:
# To check whether it is 2 days pass from the txt file date
    date_in_file = datetime.strptime(str(data[0].replace('\n','').replace('/','')),'%Y%m%d').date()
    print(date_in_file)
    if str(date_in_file+timedelta(2)).replace('-','/') == today:
        # To get the increment value from the txt file
        try:
            t=data[1]
        except:
            t=1
        #print(t)
            # deleting all the data from the file
        file.truncate(0)
        file.seek(0)
        # Updating the file with the present date
        file.write(today+'\n')
        if t!=1:
            file.write(str(int(t)+1))
        else:
            file.write(str(t))
        file.close()
except:

    file.write(today+'\n')
    file.close()
</code>```

Body:
I want to read a date saved in a text document in the format "Y/M/D", compare it with the current date, and if it is ok, do nothing, but if two days pass from the file date, add a line below with an incremental number (1, 2, 3, 4 ...). And update the date in the file with the present date.

This is what I have for now.
Example if today is 2020/06/02 the file is:

2020/06/02

1

And don't change if execute.

But if today is 2020/06/05 and execute the file should change like this:

2020/06/05

2

Etc.

I'm stuck, and this is my code:

from datetime import datetime, timedelta, date

# Generate file 1.txt
file = open("xxx\\1.txt", "w")

# Var
today = date.today()
counter = 1

# GEnerate present date
file.write(str(date.today()) + "\n")
file.close()

Body:
This below code will generate a new file with the present date and an integer. Now if you run this code after two days it will update as you asked.

import os
from datetime import datetime, timedelta, date

# Generate file 1.txt
if os.path.exists("xxx.txt"):
    file = open("xxx.txt",'r+')
else:
    file = open("xxx.txt","w+")
# replacing '-' to your default datetime in the txt file
today = str(date.today()).replace('-','/')
# reading the lines in the txt file
data = file.readlines()
# retriving only the date from the txt file dat
try:
# To check whether it is 2 days pass from the txt file date
    date_in_file = datetime.strptime(str(data[0].replace('\n','').replace('/','')),'%Y%m%d').date()
    print(date_in_file)
    if str(date_in_file+timedelta(2)).replace('-','/') == today:
        # To get the increment value from the txt file
        try:
            t=data[1]
        except:
            t=1
        #print(t)
            # deleting all the data from the file
        file.truncate(0)
        file.seek(0)
        # Updating the file with the present date
        file.write(today+'\n')
        if t!=1:
            file.write(str(int(t)+1))
        else:
            file.write(str(t))
        file.close()
except:

    file.write(today+'\n')
    file.close()


问:
Google Cloud managed instance group issue with plesk
I'm losing my mind over this so i thought I would ask about it. I have a VM instance that I was asked to put into managed instance group so that later on we can stuff like load balancing and Cloud armor.

This Vm instance has plesk panel that is configured with a website on it which is configured with a public domain to point to it.
I shut down the vm instance, create an image, then create instance template and finally create the managed instance group. The problem is that the instances that launch will have their internal and external ip addresses different then the original vm obviously so none of them will work until I ssh inside the vm instances and do some repairs like : Plesk repair all and that doesn't fix everything.

Essentially lets say original vm has internal ip : 11.11.11.1 and external ip : 20.20.20.1
when i create the managed instance group the first vm launching from the template will have
internal ip  : 11.11.11.2 and external ip  20.20.20.2
but the config for plesk was setup for the first set of ips, so every instance created will be usesless as a webserver till they are fixed

Ive watched a lot of the tutorials on Managed vm instance groups, but none of them solve this issue. I'm trying to create a managed instance group of webservers that will go into a load balancer later.The tutorials online show just some simple start up script with one page being load balanced...
Any help is appreciated.
Thank you

答:
As long as you want to host a single VM in Managed Instance Group, you can create an instance template that is bound to specific internal and/or external IP.

You can follow by analogy this example of creation MIGs with fixed IP addresses:
https://cloud.google.com/vpc/docs/special-configurations#configuring_the_gateways

As I don't know Plesk, please clarify in your question:

whether you need to host more than 1 VM in the group

whether Plask needs to know each individual VM by its both external & internal IP. It seems more natural to point Plesk to the loadbalancer's IP that routes the traffic to one of the VMs in the group.

why the solution with registration in startup-script didn't worked out.


问:
Index Match with searches between different dates and values
I'm trying to complete a lookup against 2 sets of criteria. From the attached, I need to return the Fee in column E, where the search date falls between a From and To Date (Cols A&B) and also where the Property Value falls between a Lower & Upper limit (Cols C&D). I've attached some screenshots to help make this clearer.

The formula I have is in cell K3 (Result table): {=INDEX($E$2:$E$21,MATCH(1,($A$2:$A$21>=H3)*($B$2:$B$21<=H3)*($C$2:$C$21>=I3)*($D$2:$D$21<=I3)),0)}

At the moment though, this formula returns the bottom figure on the table (£137.17)....whereas it should return £95 - I'm not sure why it's doing this.

The Raw Data

The Result table

Hopefully that makes sense and someone would be kind enough to help.
Thanks, Paul

答:
Let's break down the conditions for your MATCH

```<code>($A$2:$A$21>=H3) * ($B$2:$B$21<=H3) * ($C$2:$C$21>=I3) * ($D$2:$D$21<=I3)
</code>```

First condition: Start Date is On-or-After the Target Date

Second condition: End Date is On-or-Before the Target Date

Third condition: Minimum Value is Less-than-or-Equal-to the Target Value

Fourth condition: Maximum Value is Greater-than-or-Equal-to the Target Value.

We can simplify this to 2 Limits:

```<code>Start_Date ≥ Target_Date ≥ End_Date
Min_Value ≥ Target_Value ≥ Max_Value
</code>```

You may be able to see the issue here, but let's plug some figures in.  First, the Target values from the Results table:

```<code>Start_Date ≥ {2018-06-18} ≥ End_Date
Min_Value ≥ 80000 ≥ Max_Value
</code>```

Now, the numbers from Row 3 of the Raw Data:

```<code>{2018-05-21} ≥ {2018-06-18} ≥ {2020-06-02}
50001 ≥ 80000 ≥ 100000
</code>```

Hopefully, you now notice that you got your >= and <= mixed up!  There is no Date which is both After June 2020 and Before May 2018, and there is also no number that is Less than 50,000 and Greater than 100,000.

If we swap these over, you get this instead:

```<code>=INDEX($E$2:$E$21,MATCH(1,($A$2:$A$21<=H3)*($B$2:$B$21>=H3)*($C$2:$C$21<=I3)*($D$2:$D$21>=I3)),0)
</code>```

Of course, this still won't work, because your INDEX MATCH is written wrong.  You have this:

```<code>=INDEX(Range, MATCH(1, Condition), 0)
</code>```

But you should have this:

```<code>=INDEX(Range, Match(1, Condition, 0))
</code>```

Like so:

```<code>=INDEX($E$2:$E$21, MATCH(1, ($A$2:$A$21<=H3)*($B$2:$B$21>=H3)*($C$2:$C$21<=I3)*($D$2:$D$21>=I3), 0))
</code>```

Ideally though, I would recommend changing stuff like 50001 to 50000, and just use < instead of <= (otherwise, 50000.5 will error!)

Body:
Let's break down the conditions for your MATCH

($A$2:$A$21>=H3) * ($B$2:$B$21<=H3) * ($C$2:$C$21>=I3) * ($D$2:$D$21<=I3)

First condition: Start Date is On-or-After the Target Date

Second condition: End Date is On-or-Before the Target Date

Third condition: Minimum Value is Less-than-or-Equal-to the Target Value

Fourth condition: Maximum Value is Greater-than-or-Equal-to the Target Value.

We can simplify this to 2 Limits:

Start_Date ≥ Target_Date ≥ End_Date
Min_Value ≥ Target_Value ≥ Max_Value

You may be able to see the issue here, but let's plug some figures in.  First, the Target values from the Results table:

Start_Date ≥ {2018-06-18} ≥ End_Date
Min_Value ≥ 80000 ≥ Max_Value

Now, the numbers from Row 3 of the Raw Data:

{2018-05-21} ≥ {2018-06-18} ≥ {2020-06-02}
50001 ≥ 80000 ≥ 100000

Hopefully, you now notice that you got your >= and <= mixed up!  There is no Date which is both After June 2020 and Before May 2018, and there is also no number that is Less than 50,000 and Greater than 100,000.

If we swap these over, you get this instead:

=INDEX($E$2:$E$21,MATCH(1,($A$2:$A$21<=H3)*($B$2:$B$21>=H3)*($C$2:$C$21<=I3)*($D$2:$D$21>=I3)),0)

Of course, this still won't work, because your INDEX MATCH is written wrong.  You have this:

=INDEX(Range, MATCH(1, Condition), 0)

But you should have this:

=INDEX(Range, Match(1, Condition, 0))

Like so:

=INDEX($E$2:$E$21, MATCH(1, ($A$2:$A$21<=H3)*($B$2:$B$21>=H3)*($C$2:$C$21<=I3)*($D$2:$D$21>=I3), 0))

Ideally though, I would recommend changing stuff like 50001 to 50000, and just use < instead of <= (otherwise, 50000.5 will error!)