问:
What is the best way to achieve the following use case in Mulesoft? Which salesforce connector or method will be the most performant?
I've got an array of Ids as an input. I've got to dynamically execute a salesforce query as many number of times as there are Ids. Example:

If my input is ["a", "b", "c"] and the salesforce query is : SELECT Id, Name FROM Account WHERE Name = ""

Then, three queries should be generated,

```<code>1.SELECT Id, Name FROM Account WHERE Name = 'a'
2.SELECT Id, Name FROM Account WHERE Name = 'b'
3.SELECT Id, Name FROM Account WHERE Name = 'c'
</code>```

P.S. : The Salesforce queries should be executed together, minimising the number of calls, I thought of using composite connector, but it has a limit of 25 requests in a call (I can have as high as 100 Ids), Also thought about composite graph API, but it doesn't support querying.

答:
I recommend using an IN operator on the query to lower the number of API calls you do. It will look something like this:

```<code>SELECT Id, Name FROM Account WHERE Name IN ('a', 'b', 'c')
</code>```

I'm not sure about the maximum (I feel it's 100). You need to use DataWeave to build that query. It will look something like this:

```<code>"SELECT Id, Name FROM Account WHERE Name IN ('" ++ (vars.ids joinBy "','") ++ "')"
</code>```

Ref:

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_comparisonoperators.htm

https://docs.mulesoft.com/dataweave/2.4/dw-core-functions-joinby

Body:
I've got an array of Ids as an input. I've got to dynamically execute a salesforce query as many number of times as there are Ids. Example:

If my input is ["a", "b", "c"] and the salesforce query is : SELECT Id, Name FROM Account WHERE Name = ""

Then, three queries should be generated,

1.SELECT Id, Name FROM Account WHERE Name = 'a'
2.SELECT Id, Name FROM Account WHERE Name = 'b'
3.SELECT Id, Name FROM Account WHERE Name = 'c'

P.S. : The Salesforce queries should be executed together, minimising the number of calls, I thought of using composite connector, but it has a limit of 25 requests in a call (I can have as high as 100 Ids), Also thought about composite graph API, but it doesn't support querying.

Body:
I recommend using an IN operator on the query to lower the number of API calls you do. It will look something like this:

SELECT Id, Name FROM Account WHERE Name IN ('a', 'b', 'c')

I'm not sure about the maximum (I feel it's 100). You need to use DataWeave to build that query. It will look something like this:

"SELECT Id, Name FROM Account WHERE Name IN ('" ++ (vars.ids joinBy "','") ++ "')"

Ref:

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_comparisonoperators.htm

https://docs.mulesoft.com/dataweave/2.4/dw-core-functions-joinby


来源: stackexchange

问:
Data structure problem related to items filtering
I have this data:

There are three columns r_code, wtg_code and rr. Every row can be treated as a collection of object properties. We have to select n number of rows from the existing rows. Considering the row are sorted in decreasing order of r_code, constraints are,

Select the rows in decreasing order of r_code, many rows can have the same r_code.

If many rows have the same r_code, then select on the basis of decreasing wtg_code.

If multiple rows have the same wtg_code then select on the basis of lowest rr.

If you can give the solution in Javascript then it will be better otherwise I welcome any language.

答:
In JavaScript, the data can be represented like this:

```<code>let data = [
    { r_code: 5, wtg_code: 8, rr: 3.4 },
    { r_code: 5, wtg_code: 8, rr: 3.4 },
    { r_code: 5, wtg_code: 7, rr: 4.5 },
    { r_code: 4, wtg_code: 6, rr: 1.2 },
    { r_code: 4, wtg_code: 6, rr: 2.4 },
    { r_code: 4, wtg_code: 6, rr: 4.5 },
    { r_code: 2, wtg_code: 6, rr: 1.6 },
    { r_code: 2, wtg_code: 5, rr: 7.4 },
    { r_code: 1, wtg_code: 4, rr: 3.1 },
    { r_code: 1, wtg_code: 4, rr: 2.9 },
    { r_code: 1, wtg_code: 3, rr: 3.3 },
];
</code>```

Considering the row are sorted in decreasing order of r_code

That could still allow for several permutations. The rules for selection really mean that you should sort the data more precisely: by descending r_code, descending wtg_code and ascending wtg_code.

For that you can use the sort method.

```<code>data.sort((a, b) => b.r_code - a.r_code || b.wtg_code - a.wtg_code || a.rr - b.rr);
</code>```

Finally, if you are interested in the first 10 (n=10), then slice:

```<code>let n = 10;
console.log(data.slice(0, n));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In JavaScript, the data can be represented like this:

let data = [
    { r_code: 5, wtg_code: 8, rr: 3.4 },
    { r_code: 5, wtg_code: 8, rr: 3.4 },
    { r_code: 5, wtg_code: 7, rr: 4.5 },
    { r_code: 4, wtg_code: 6, rr: 1.2 },
    { r_code: 4, wtg_code: 6, rr: 2.4 },
    { r_code: 4, wtg_code: 6, rr: 4.5 },
    { r_code: 2, wtg_code: 6, rr: 1.6 },
    { r_code: 2, wtg_code: 5, rr: 7.4 },
    { r_code: 1, wtg_code: 4, rr: 3.1 },
    { r_code: 1, wtg_code: 4, rr: 2.9 },
    { r_code: 1, wtg_code: 3, rr: 3.3 },
];

Considering the row are sorted in decreasing order of r_code

That could still allow for several permutations. The rules for selection really mean that you should sort the data more precisely: by descending r_code, descending wtg_code and ascending wtg_code.

For that you can use the sort method.

data.sort((a, b) => b.r_code - a.r_code || b.wtg_code - a.wtg_code || a.rr - b.rr);

Finally, if you are interested in the first 10 (n=10), then slice:

let n = 10;
console.log(data.slice(0, n));


问:
When saving, how can you check if a field has changed?
In my model I have :

```<code>class Alias(MyBaseModel):
    remote_image = models.URLField(
        max_length=500, null=True,
        help_text='''
            A URL that is downloaded and cached for the image.
            Only used when the alias is made
        '''
    )
    image = models.ImageField(
        upload_to='alias', default='alias-default.png',
        help_text="An image representing the alias"
    )

    def save(self, *args, **kw):
        if (not self.image or self.image.name == 'alias-default.png') and self.remote_image :
            try :
                data = utils.fetch(self.remote_image)
                image = StringIO.StringIO(data)
                image = Image.open(image)
                buf = StringIO.StringIO()
                image.save(buf, format='PNG')
                self.image.save(
                    hashlib.md5(self.string_id).hexdigest() + ".png", ContentFile(buf.getvalue())
                )
            except IOError :
                pass
</code>```

Which works great for the first time the remote_image changes.

How can I fetch a new image when someone has modified the remote_image on the alias? And secondly, is there a better way to cache a remote image?

答:
Sometimes I want to check for changes on the same specific fields on multiple models that share those fields, so I define a list of those fields and use a signal.  In this case, geocoding addresses only if something has changed, or if the entry is new:

```<code>from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=SomeUserProfileModel)
@receiver(pre_save, sender=SomePlaceModel)
@receiver(pre_save, sender=SomeOrganizationModel)
@receiver(pre_save, sender=SomeContactInfoModel)
def geocode_address(sender, instance, *args, **kwargs):

    input_fields = ['address_line', 'address_line_2', 'city', 'state', 'postal_code', 'country']

    try:
        orig = sender.objects.get(id=instance.id)
        if orig:
            changes = 0
            for field in input_fields:
                if not (getattr(instance, field)) == (getattr(orig, field)):
                    changes += 1
            if changes > 0:
                # do something here because at least one field changed...
                my_geocoder_function(instance)
    except:
        # do something here because there is no original, or pass.
        my_geocoder_function(instance)

</code>```

Writing it once and attaching with "@receiver" sure beats overriding multiple model save methods, but perhaps some others have better ideas.

Body:
In my model I have :

class Alias(MyBaseModel):
    remote_image = models.URLField(
        max_length=500, null=True,
        help_text='''
            A URL that is downloaded and cached for the image.
            Only used when the alias is made
        '''
    )
    image = models.ImageField(
        upload_to='alias', default='alias-default.png',
        help_text="An image representing the alias"
    )

    def save(self, *args, **kw):
        if (not self.image or self.image.name == 'alias-default.png') and self.remote_image :
            try :
                data = utils.fetch(self.remote_image)
                image = StringIO.StringIO(data)
                image = Image.open(image)
                buf = StringIO.StringIO()
                image.save(buf, format='PNG')
                self.image.save(
                    hashlib.md5(self.string_id).hexdigest() + ".png", ContentFile(buf.getvalue())
                )
            except IOError :
                pass

Which works great for the first time the remote_image changes.

How can I fetch a new image when someone has modified the remote_image on the alias? And secondly, is there a better way to cache a remote image?

Body:
Sometimes I want to check for changes on the same specific fields on multiple models that share those fields, so I define a list of those fields and use a signal.  In this case, geocoding addresses only if something has changed, or if the entry is new:

from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=SomeUserProfileModel)
@receiver(pre_save, sender=SomePlaceModel)
@receiver(pre_save, sender=SomeOrganizationModel)
@receiver(pre_save, sender=SomeContactInfoModel)
def geocode_address(sender, instance, *args, **kwargs):

    input_fields = ['address_line', 'address_line_2', 'city', 'state', 'postal_code', 'country']

    try:
        orig = sender.objects.get(id=instance.id)
        if orig:
            changes = 0
            for field in input_fields:
                if not (getattr(instance, field)) == (getattr(orig, field)):
                    changes += 1
            if changes > 0:
                # do something here because at least one field changed...
                my_geocoder_function(instance)
    except:
        # do something here because there is no original, or pass.
        my_geocoder_function(instance)

Writing it once and attaching with "@receiver" sure beats overriding multiple model save methods, but perhaps some others have better ideas.


问:
How to create the intent via code in dialogflow?
I am beginner in dialogflow and trying to create intent and context through code, but i am unable to achieve it.This is the code i am using,
i referred the below link also but no help,

https://cloud.google.com/dialogflow/es/docs/how/manage-intents#create_intent

but getting below error:

```<code>
    function main(
            projectId = 'trainer-gulw',
            displayName = 'intent_001',
            trainingPhrasesParts = [
              'Hello, What is weather today?',
              'How is the weather today?',
            ],
            messageTexts = ['Rainy', 'Sunny']
          ) {
            const dialogflow = require('@google-cloud/dialogflow');
            // Instantiates the Intent Client
            const intentsClient = new dialogflow.IntentsClient();
            async function createIntent() {
              // Construct request
              // The path to identify the agent that owns the created intent.
              const agentPath = intentsClient.projectAgentPath(projectId);
              const trainingPhrases = [];
              trainingPhrasesParts.forEach(trainingPhrasesPart => {
                const part = {
                  text: trainingPhrasesPart,
                };
                // Here we create a new training phrase for each provided part.
                const trainingPhrase = {
                  type: 'EXAMPLE',
                  parts: [part],
                };
                trainingPhrases.push(trainingPhrase);
              });
              const messageText = {
                text: messageTexts,
              };
              const message = {
                text: messageText,
              };
              const intent = {
                displayName: displayName,
                trainingPhrases: trainingPhrases,
                messages: [message],
              };
              const createIntentRequest = {
              parent: agentPath,
              intent: intent,
              };
              // Create the intent
              const [response] = await intentsClient.createIntent(createIntentRequest);
              console.log(`Intent ${response.name} created`);
        }

    createIntent();

    // [END dialogflow_create_intent]
  }

</code>```

TIA

答:
From the screen shot, it looks like you're running this on your local machine. The error message suggests that the environment variables that point to your credentials isn't setup.

See the Before you Begin section of the library documentation for how to setup that environment. One of the steps includes setting up authentication by downloading credentials and setting an environment variable to point to them. This will also set the project ID you're working with.

Body:
I am beginner in dialogflow and trying to create intent and context through code, but i am unable to achieve it.This is the code i am using,
i referred the below link also but no help,

https://cloud.google.com/dialogflow/es/docs/how/manage-intents#create_intent

but getting below error:

    function main(
            projectId = 'trainer-gulw',
            displayName = 'intent_001',
            trainingPhrasesParts = [
              'Hello, What is weather today?',
              'How is the weather today?',
            ],
            messageTexts = ['Rainy', 'Sunny']
          ) {
            const dialogflow = require('@google-cloud/dialogflow');
            // Instantiates the Intent Client
            const intentsClient = new dialogflow.IntentsClient();
            async function createIntent() {
              // Construct request
              // The path to identify the agent that owns the created intent.
              const agentPath = intentsClient.projectAgentPath(projectId);
              const trainingPhrases = [];
              trainingPhrasesParts.forEach(trainingPhrasesPart => {
                const part = {
                  text: trainingPhrasesPart,
                };
                // Here we create a new training phrase for each provided part.
                const trainingPhrase = {
                  type: 'EXAMPLE',
                  parts: [part],
                };
                trainingPhrases.push(trainingPhrase);
              });
              const messageText = {
                text: messageTexts,
              };
              const message = {
                text: messageText,
              };
              const intent = {
                displayName: displayName,
                trainingPhrases: trainingPhrases,
                messages: [message],
              };
              const createIntentRequest = {
              parent: agentPath,
              intent: intent,
              };
              // Create the intent
              const [response] = await intentsClient.createIntent(createIntentRequest);
              console.log(`Intent ${response.name} created`);
        }

    createIntent();

    // [END dialogflow_create_intent]
  }

TIA


问:
How to check if elements of list exists within list of dictionaries?
```<code>list1= ['paraben', 'alcohol','mica','talc','perfume']

products = [{'name': 'Product01', 'ingredients': 'Iron Oxides, Talc, Mica, Zinc Stearate, Dimethicone, Octyldodecyl Stearoyl Stearate, Maltodextrin'}
,{'name': 'Product02', 'ingredients': 'Octyldodecanol - Capric Triglyceride - Isononyl Isononanoate - Neopentyl Glycol Diethylhexanoate'}]
</code>```

How can I check if one or more elements of the list1 does exist in values of the products, and print which list1 item exists in which product?

Result should look like this:
#Product01 contains talc, mica.

答:
Here's one way to do that:</p>
```<code>list1= ['paraben', 'alcohol','mica','talc','perfume']

products = [{'name': 'Product01', 'ingredients': 'Iron Oxides, Talc, Mica, Zinc Stearate, Dimethicone, Octyldodecyl Stearoyl Stearate, Maltodextrin'}
,{'name': 'Product02', 'ingredients': 'Octyldodecanol - Capric Triglyceride - Isononyl Isononanoate - Neopentyl Glycol Diethylhexanoate'}]

for d in products:
    name = d['name']
    from_list = list(filter(lambda x:x.lower() in list1,d['ingredients'].split(', ')))
    if from_list:
        print(f"{name} contains:",', '.join(from_list))
    else:
        print(f"{name} contains no ingredients from list")

#Result:
#Product01 contains: Talc, Mica
#Product02 contains no ingredients from list
</code>```

Body:
list1= ['paraben', 'alcohol','mica','talc','perfume']

products = [{'name': 'Product01', 'ingredients': 'Iron Oxides, Talc, Mica, Zinc Stearate, Dimethicone, Octyldodecyl Stearoyl Stearate, Maltodextrin'}
,{'name': 'Product02', 'ingredients': 'Octyldodecanol - Capric Triglyceride - Isononyl Isononanoate - Neopentyl Glycol Diethylhexanoate'}]

How can I check if one or more elements of the list1 does exist in values of the products, and print which list1 item exists in which product?

Result should look like this:
#Product01 contains talc, mica.

Body:
Here's one way to do that:

list1= ['paraben', 'alcohol','mica','talc','perfume']

products = [{'name': 'Product01', 'ingredients': 'Iron Oxides, Talc, Mica, Zinc Stearate, Dimethicone, Octyldodecyl Stearoyl Stearate, Maltodextrin'}
,{'name': 'Product02', 'ingredients': 'Octyldodecanol - Capric Triglyceride - Isononyl Isononanoate - Neopentyl Glycol Diethylhexanoate'}]

for d in products:
    name = d['name']
    from_list = list(filter(lambda x:x.lower() in list1,d['ingredients'].split(', ')))
    if from_list:
        print(f"{name} contains:",', '.join(from_list))
    else:
        print(f"{name} contains no ingredients from list")

#Result:
#Product01 contains: Talc, Mica
#Product02 contains no ingredients from list


问:
SSIS Catalog - All Executions report only shows #Error in all headings and hyperlinks
I'm running an SSIS package on a recent install of SQL Server 2016. Recently the All Axecutions report of the Integrations Services Catalogs SSISDB started looking like the screenshot below. The package that is executed on a 5 minute basis runs fine. No errors. I can see the data being transferred as expected. Something is wrong with this report. I did some searching around and can't seem to find anything.

Anybody have any ideas as to what is wrong? Why is it showing #Error everywhere?

答:
RE: "I restarted SSMS 13.0.16106.4, which solved the issue. This could be a SSMS memory issue." from @James Bourne

RE: "Using SSMS Microsoft SQL Server Management Studio 14.0.17285.0. Solved this by closing SSMS and restarting it." from @Ade

I had some very large nHibernate queries (captured from Extended Events) open in a couple of SSMS tabs.  I closed each tab and restarted SSMS version 18.8.

Problem solved!

ContentLicense: CC BY-SA 3.0


问:
How to assign user activity task to all members of a team?
I would like to assign an user activity to all members of a team, so every member will receive the activity and act.

I've been using multi-instance loop, but dunno what to set in Start quantity so that all team members that the task is assigned for, to run the activity in parallel.

答:
So, based on what you wrote what you actually want is N tasks, where each task is assigned to a specific person on the team you are targeting.  This is different than assigning to a team as if you assigned all N tasks to the team, one person on the team could claim and close all the tasks created for the instance.

Assuming you know the Team, you can use the "members" to get the array of people on the team.  You can use the array length to know how many instances you are creating, and you would use the step counter to assign to the specific team member.

You can use the tw.system.org.findTeamByName() call to get the team object.


问:
How to Read Synapse Analytics SQL Script (JSON Format) as a SQL Script in an IDE?
I have a Synapse Git Project that has SQL Scripts created in the Azure Portal like so Microsoft Docs SQL Scriptand the challenge is that in GIT they appear as this kinda bulky JSON file and I would love to read it as SQL File DBEAVER or IntelliJ …

Any way to do this without having to manually select the Query Section of the file and kinda clean it?

答:
First Some Background

Synapse stores all artifacts in JSON format. In the Git repo, they are in the following folder structure:

Inside each folder are the JSON files that define the artifacts. Folder sqlscript contains the JSON for SQL Scripts in the following format:

NOTE: the Synapse folder of the script is just a property - this is why all SQL Script names have to be unique across the entire workspace.

Extracting the script

The workspace does allow you to Export SQL to a .sql file:

There are drawbacks: you have to do it manually, 1 file at a time, and you cannot control the output location or SQL file name.

To pull the SQL back out of the JSON, you have to access the properties.content.query property value and save it as a .sql file. As far as I know, there is no built in feature to automatically save a Script as SQL. Simple Copy/Paste doesn't really work because of the \ns.

I think you could automate at least part of this with an Azure DevOps Pipeline (or a GitHub Action). You might need to copy the JSON file out to another location, and then have a process (Data Factory, Azure Function, Logic App, etc.) read the file and extract the query.


问:
How can I make current Data and time show up in cell a1 and c1 respectively when I type a text in cell b1?
am using sheets and I want my cell to auto-populate with the date today in one cell and the time now to populate in another, so this is what I've tried doing.

I added the forumla in column C to show the time now, using the NOW() function, but it returns both date and time, when I only want the time, and everytime I make a new entry in Column B or anywhere in the sheet the entire Column C updates as show in the picture having the same seconds

In column A I added this formula =IF(ISTEXT(B1), TODAY(), "") it show the exactly what I want but I don't know if it will update the entire column once I enter a new data in column B the next day.

What I got got from trying

The result I want my sheet to do is this one.

What I want my sheet to do

It's a real life example on how this sheet will be used, it's like a logging entry for employees, like a tracker,whenever they put their name on Column B, Column A and C, should auto populate with the Date now, and the current time they entered their name, and it should not update when someone else updates the sheet with their own entry.

答:
if you are ok to turn on Iterative Calculations, then you can try this...

Open the google sheets file.

Click File in the top menu bar

Go to Settings

Change to the Calculation tab

Set Max number of iterations to 1

Click Save settings

Put this formula into cell C1

```<code>=ARRAYFORMULA(IF(ISBLANK($B:$B),"",IF(C:C="",NOW(),C:C)))
</code>```

Select the entire column C

Click Format

Hover over Number

Select Time

NOTE: You can change the time format to whatever custom format you like.

To do the same for the date, just change the formula to:

```<code>=ARRAYFORMULA(IF(ISBLANK($B:$B),"",IF(A:A="",NOW(),A:A)))
</code>```

and put it into cell A1
Then follow steps 8-11 as above, but selecting column A and using a Date format

NOTE: If you get a date for the year 1899 in cell A1, then copy the data from cell B1, then delete the contents of cell B1, then paste it back in again, and it will return the current date/time.

Body:
if you are ok to turn on Iterative Calculations, then you can try this...

Open the google sheets file.

Click File in the top menu bar

Go to Settings

Change to the Calculation tab

Set Max number of iterations to 1

Click Save settings

Put this formula into cell C1

=ARRAYFORMULA(IF(ISBLANK($B:$B),"",IF(C:C="",NOW(),C:C)))

Select the entire column C

Click Format

Hover over Number

Select Time

NOTE: You can change the time format to whatever custom format you like.

To do the same for the date, just change the formula to:

=ARRAYFORMULA(IF(ISBLANK($B:$B),"",IF(A:A="",NOW(),A:A)))

and put it into cell A1
Then follow steps 8-11 as above, but selecting column A and using a Date format

NOTE: If you get a date for the year 1899 in cell A1, then copy the data from cell B1, then delete the contents of cell B1, then paste it back in again, and it will return the current date/time.


问:
Android Studio Bumblebee crashes frequently
I am wondering if anyone else has encountered this problem and figured a way to deal with it.

Android Studio Bumblebee crashes randomly and frequently. There is no pattern. It crashes when I do something (e.g., editing code) or sometimes when I do nothing. It can crash soon after I start AS or after I use it for a little while. It crashes once every hour or so on average.

Are there any parameters that I can change to make AS stabler? Is there a good way to diagnose the crash?

I usually have over a dozen programs running on the same computer (Visual Studio, Outlook, browsers...). AS is the only program that crashes. All others work fine.

```<code>Android Studio Bumblebee | 2021.1.1
Build #AI-211.7628.21.2111.8092744, built on January 19, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 4096M
Cores: 16
Registry: external.system.auto.import.disabled=true, debugger.watches.in.variables=false
Non-Bundled Plugins: com.intellij.marketplace (211.7628.36), com.thoughtworks.gauge (211.6693.111), org.jetbrains.kotlin (211-1.6.10-release-923-AS7442.40), com.android.aas (3.5.1), com.google.mad-scorecard (1.2), org.intellij.plugins.markdown (211.7142.37)
</code>```

答: I faced the same issue until I disabled the Launch in tool window. Just go to File -> Settings -> Tools -> Emulator and disable the launch in a tool window checkbox.</p>

Body:
I am wondering if anyone else has encountered this problem and figured a way to deal with it.

Android Studio Bumblebee crashes randomly and frequently. There is no pattern. It crashes when I do something (e.g., editing code) or sometimes when I do nothing. It can crash soon after I start AS or after I use it for a little while. It crashes once every hour or so on average.

Are there any parameters that I can change to make AS stabler? Is there a good way to diagnose the crash?

I usually have over a dozen programs running on the same computer (Visual Studio, Outlook, browsers...). AS is the only program that crashes. All others work fine.

Android Studio Bumblebee | 2021.1.1
Build #AI-211.7628.21.2111.8092744, built on January 19, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 4096M
Cores: 16
Registry: external.system.auto.import.disabled=true, debugger.watches.in.variables=false
Non-Bundled Plugins: com.intellij.marketplace (211.7628.36), com.thoughtworks.gauge (211.6693.111), org.jetbrains.kotlin (211-1.6.10-release-923-AS7442.40), com.android.aas (3.5.1), com.google.mad-scorecard (1.2), org.intellij.plugins.markdown (211.7142.37)


问:
Finding MBUS telegramms in an byte[]
I'm trying to read MBUS telegramms from a serial port.
I put everything from the serialport into an byte array.

Every MBUS telegramms starts with this pattern (in hex):   68 XX XX 68

where XX is the lenght of the telegramm in byte.

Example:
Example http://img97.imageshack.us/img97/6004/mbustele.jpg

Here you see an example, highlighted is the beginning of an telegramm with lenght 99 (in hex)

I want to add every telegramm to a list like this

```<code>List<byte[]> telegramms;
</code>```

An idea how to achieve this?

答:
I've just typed this up in VisualStudio 2010, it makes all sorts of assumptions about endian-ness and does't managed the potential problem of the MBus packet being bigger that the sampled byte from the serial port, or more importantly, if the packet header itself is across the boundary between packets from the serial port.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace StackOverflowTest
{
    [TestClass]
    public class ByteTest
    {
        private bool FindEndMark(byte[] source, int index, out int size)
        {
            int endIndex = index + 3;
            if (endIndex > source.Count())
            {
                // need to cope with the fact that the datapacket might be shorter than the MBus message.
                throw new Exception("end count > length of array");
            }

        if (source[endIndex] == 0x68)
        {
            // According to the updated spec, the size is emitted twice as a verification
            if (source[index + 1] == source[index + 2])
            {
                size = source[index] + 1;
                return true;
            }
        }
            size = 0;
            return false;
        }

        [TestMethod]
        public void FindMbusDatagram()
        {
            byte[] src = new byte[]
                {
                    // Random junk to start
                    00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb, 0xc, 0xd,
                    // An MBus Packet
                    0x68, 06, 00, 0x68, 08, 05, 72, 00, 00, 00,
                    // More junk
                    00, 00, 00, 0x16, 00, 00, 00, 00, 01,
                    // Put a rogue 0x68 in so we can prove we don't get false positives in the datastream
                    0x68, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb, 0xc, 0xd,
                    // Another Packet
                    0x68, 01, 00, 0x68, 0xFF,
                    //final junk
                     00, 16, 00, 00, 00, 01, 02, 03
                };

            List<byte[]> packets = new List<byte[]>();

            for (int i = 0; i < src.Length; i++ )
            {
                if (src[i] != 0x68)
                {
                    continue;
                }
                else
                {
                    int packetSize = 0;
                    if (FindEndMark(src, i, out packetSize))
                    {
                        if (packetSize > (src.Length - i))
                        {
                            // read more data from your port and append it somehow.
                        }
                        else
                        {
                            // We're packetSize+4 includes the header information + checksum and end
                        // NB: packetSize+5 is a checksum byte
                        // NB: packetSize+6 should be 0x16 according to the MBus spec.
                            byte[] packet = new byte[packetSize + 4];
                            int count = 0;

                            // Copy the packet + header into a byte[]
                            for (int j = i; j < (i + packetSize + 4); j++)
                            {
                                packet[count++] = src[j];
                            }

                            packets.Add(packet);

                            // Move the counter along
                            i += (packetSize + 4);
                        }
                    }
                }
            }

            // Should have two packets here.
            Assert.IsTrue(packets.Count > 0);
        }
    }
}
</code>```

Title: Finding MBUS telegramms in an byte[]

Body:
I'm trying to read MBUS telegramms from a serial port.
I put everything from the serialport into an byte array.

Every MBUS telegramms starts with this pattern (in hex):   68 XX XX 68

where XX is the lenght of the telegramm in byte.

Example:
Example http://img97.imageshack.us/img97/6004/mbustele.jpg

Here you see an example, highlighted is the beginning of an telegramm with lenght 99 (in hex)

I want to add every telegramm to a list like this

List<byte[]> telegramms;

An idea how to achieve this?

Body:
I've just typed this up in VisualStudio 2010, it makes all sorts of assumptions about endian-ness and does't managed the potential problem of the MBus packet being bigger that the sampled byte from the serial port, or more importantly, if the packet header itself is across the boundary between packets from the serial port.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace StackOverflowTest
{
    [TestClass]
    public class ByteTest
    {
        private bool FindEndMark(byte[] source, int index, out int size)
        {
            int endIndex = index + 3;
            if (endIndex > source.Count())
            {
                // need to cope with the fact that the datapacket might be shorter than the MBus message.
                throw new Exception("end count > length of array");
            }

        if (source[endIndex] == 0x68)
        {
            // According to the updated spec, the size is emitted twice as a verification
            if (source[index + 1] == source[index + 2])
            {
                size = source[index] + 1;
                return true;
            }
        }
            size = 0;
            return false;
        }

        [TestMethod]
        public void FindMbusDatagram()
        {
            byte[] src = new byte[]
                {
                    // Random junk to start
                    00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb, 0xc, 0xd,
                    // An MBus Packet
                    0x68, 06, 00, 0x68, 08, 05, 72, 00, 00, 00,
                    // More junk
                    00, 00, 00, 0x16, 00, 00, 00, 00, 01,
                    // Put a rogue 0x68 in so we can prove we don't get false positives in the datastream
                    0x68, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb, 0xc, 0xd,
                    // Another Packet
                    0x68, 01, 00, 0x68, 0xFF,
                    //final junk
                     00, 16, 00, 00, 00, 01, 02, 03
                };

            List<byte[]> packets = new List<byte[]>();

            for (int i = 0; i < src.Length; i++ )
            {
                if (src[i] != 0x68)
                {
                    continue;
                }
                else
                {
                    int packetSize = 0;
                    if (FindEndMark(src, i, out packetSize))
                    {
                        if (packetSize > (src.Length - i))
                        {
                            // read more data from your port and append it somehow.
                        }
                        else
                        {
                            // We're packetSize+4 includes the header information + checksum and end
                        // NB: packetSize+5 is a checksum byte
                        // NB: packetSize+6 should be 0x16 according to the MBus spec.
                            byte[] packet = new byte[packetSize + 4];
                            int count = 0;

                            // Copy the packet + header into a byte[]
                            for (int j = i; j < (i + packetSize + 4); j++)
                            {
                                packet[count++] = src[j];
                            }

                            packets.Add(packet);

                            // Move the counter along
                            i += (packetSize + 4);
                        }
                    }
                }
            }

            // Should have two packets here.
            Assert.IsTrue(packets.Count > 0);
        }
    }
}


问:
Return common element indices between two numpy arrays
I have two arrays, a1 and a2. Assume len(a2) >> len(a1), and that a1 is a subset of a2.

I would like a quick way to return the a2 indices of all elements in a1. The time-intensive way to do this is obviously:

```<code>from operator import indexOf
indices = []
for i in a1:
    indices.append(indexOf(a2,i))
</code>```

This of course takes a long time where a2 is large. I could also use numpy.where() instead (although each entry in a1 will appear just once in a2), but I'm not convinced it will be quicker. I could also traverse the large array just once:

```<code>for i in xrange(len(a2)):
    if a2[i] in a1:
        indices.append(i)
</code>```

But I'm sure there is a faster, more 'numpy' way - I've looked through the numpy method list, but cannot find anything appropriate.

Many thanks in advance,

D

答:
These all methods are slow for me. Following method is doing quite fast. The index list has the index of the elements from first list which are common in second list.</p>
```<code>index=[]
d={}
for j in range(len(first_list)):
    name=first_list[j]
    d[name]=j

for i in range(len(second_list)):
    name=second_list[i]
    index.append(d[name])
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have two arrays, a1 and a2. Assume len(a2) >> len(a1), and that a1 is a subset of a2.

I would like a quick way to return the a2 indices of all elements in a1. The time-intensive way to do this is obviously:

from operator import indexOf
indices = []
for i in a1:
    indices.append(indexOf(a2,i))

This of course takes a long time where a2 is large. I could also use numpy.where() instead (although each entry in a1 will appear just once in a2), but I'm not convinced it will be quicker. I could also traverse the large array just once:

for i in xrange(len(a2)):
    if a2[i] in a1:
        indices.append(i)

But I'm sure there is a faster, more 'numpy' way - I've looked through the numpy method list, but cannot find anything appropriate.

Many thanks in advance,

D

Body:
These all methods are slow for me. Following method is doing quite fast. The index list has the index of the elements from first list which are common in second list.

index=[]
d={}
for j in range(len(first_list)):
    name=first_list[j]
    d[name]=j

for i in range(len(second_list)):
    name=second_list[i]
    index.append(d[name])


问:
this.props.location.state is undefined in React Link Router
I've seen several of these questions on Stack Overflow, but none of the fixes seem to work. this.props.location.state always returns undefined. Here is my AppContainer, ExamplePageParent, and ExamplePage.

```<code>import {Router, Route, Switch} from "react-router-dom";

class AppContainer extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/page" component={Page}
          <Route exact path="/examplePage" component={ExamplePage}/>
        </Switch>
      </Router>
    )
  }
}
//has mapStateToProps and mapDispatch to Props here

export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);
</code>```

--

```<code>class Page extends Component {

  render() {
   return(
     <AnotherPage key=this.props.id>
   );
  }
    }

// has mapStateToProps here (this.props.id comes from here)

export default connect(mapStateToProps, mapDispatchToProps)(Page);
</code>```

--

```<code>class AnotherPage extends Component {

  render() {
   return(
     <ExamplePageParent key=this.props.id>
   );
  }
    }

// has mapStateToProps here (this.props.id comes from here)

export default connect(mapStateToProps, null)(AnotherPage);
</code>```

--

```<code>class ExamplePageParent extends Component {

  //pathName and dataPassed content filled, not relevant to question

  render() {
   return(
     <Link
       class={'link-styling'}
       target="_blank"
       rel="noreferrer"
       to={{pathname: this.state.pathName, state: {dataPassed: true} }}
     >
       Click Me
     </Link>
   );
  }
    }

//has mapStateToProps here

export default connect(mapStateToProps, null)(ExamplePageParent);
</code>```

--

```<code>import {withRouter} from "react-router";

class ExamplePage extends Component {

  constructor(props) {
    super(props);

    //this has content:
    console.log(this.props.location);

    //undefined:
    console.log(this.props.location.state);
  }

  render() {
   return(
     // do stuff
   );
  }
}
export default withRouter(ExamplePage);
</code>```

答:
Issues

You are using the low-level Router which needs a history object to have a defined location object to work with.

The code is linking to a new window, so the app is loaded/mounted from scratch and the passed route state isn't transferred.

To address the undefined location you have a couple options:

Import a custom history creator from the history package:

```<code>import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

...

<Router history={history}>
  ...
</Router>
</code>```

Use one of the higer-level routers, i.e. BrowserRouter, HashRouter, MemoryRouter, etc...:

```<code>import { BrowserRouter as Router } from 'react-router-dom';

...

<Router>
  ...
</Router>
</code>```

To address accessing the "state" in the receiving component you'll need to add a bit of logic. When the app is started in a new window/tab the state isn't transferred, so to combat this you can send the route state serialized as a queryString search param.

```<code><Link
  className={"link-styling"}
  target="_blank"
  rel="noreferrer"
  to={{
    pathname: this.state.pathName,
    search:
      "stuff=content&moreStuff=moreContent" + // existing search params
      "&dataPassed=This is the passed data.", // additional for state
    state: { dataPassed: "This is the passed data." }
  }}
>
  Click Me
</Link>
</code>```

And then in ExamplePage process the queryString to extract and delete the added "dataPassed" query param, and redirect with populated route state previously existing queryString.

```<code>class ExamplePage extends Component {
  componentDidMount() {
    const { history, location } = this.props;
    const { pathname, state, search } = location;

    console.log({ location });

    const searchParams = new URLSearchParams(search);
    let dataPassed;

    if (searchParams.has("dataPassed")) {
      dataPassed = searchParams.get("dataPassed");
      searchParams.delete("dataPassed");
    }
    history.replace({
      pathname,
      search: searchParams.toString(),
      state: { dataPassed }
    });
  }

  render() {
    return (
      ...
    );
  }
}
</code>```

Body:
I've seen several of these questions on Stack Overflow, but none of the fixes seem to work. this.props.location.state always returns undefined. Here is my AppContainer, ExamplePageParent, and ExamplePage.

import {Router, Route, Switch} from "react-router-dom";

class AppContainer extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/page" component={Page}
          <Route exact path="/examplePage" component={ExamplePage}/>
        </Switch>
      </Router>
    )
  }
}
//has mapStateToProps and mapDispatch to Props here

export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);

--

class Page extends Component {

  render() {
   return(
     <AnotherPage key=this.props.id>
   );
  }
    }

// has mapStateToProps here (this.props.id comes from here)

export default connect(mapStateToProps, mapDispatchToProps)(Page);

--

class AnotherPage extends Component {

  render() {
   return(
     <ExamplePageParent key=this.props.id>
   );
  }
    }

// has mapStateToProps here (this.props.id comes from here)

export default connect(mapStateToProps, null)(AnotherPage);

--

class ExamplePageParent extends Component {

  //pathName and dataPassed content filled, not relevant to question

  render() {
   return(
     <Link
       class={'link-styling'}
       target="_blank"
       rel="noreferrer"
       to={{pathname: this.state.pathName, state: {dataPassed: true} }}
     >
       Click Me
     </Link>
   );
  }
    }

//has mapStateToProps here

export default connect(mapStateToProps, null)(ExamplePageParent);

--

import {withRouter} from "react-router";

class ExamplePage extends Component {

  constructor(props) {
    super(props);

    //this has content:
    console.log(this.props.location);

    //undefined:
    console.log(this.props.location.state);
  }

  render() {
   return(
     // do stuff
   );
  }
}
export default withRouter(ExamplePage);

Body:
Issues

You are using the low-level Router which needs a history object to have a defined location object to work with.

The code is linking to a new window, so the app is loaded/mounted from scratch and the passed route state isn't transferred.

To address the undefined location you have a couple options:

Import a custom history creator from the history package:

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

...

<Router history={history}>
  ...
</Router>

Use one of the higer-level routers, i.e. BrowserRouter, HashRouter, MemoryRouter, etc...:

import { BrowserRouter as Router } from 'react-router-dom';

...

<Router>
  ...
</Router>

To address accessing the "state" in the receiving component you'll need to add a bit of logic. When the app is started in a new window/tab the state isn't transferred, so to combat this you can send the route state serialized as a queryString search param.

<Link
  className={"link-styling"}
  target="_blank"
  rel="noreferrer"
  to={{
    pathname: this.state.pathName,
    search:
      "stuff=content&moreStuff=moreContent" + // existing search params
      "&dataPassed=This is the passed data.", // additional for state
    state: { dataPassed: "This is the passed data." }
  }}
>
  Click Me
</Link>

And then in ExamplePage process the queryString to extract and delete the added "dataPassed" query param, and redirect with populated route state previously existing queryString.

class ExamplePage extends Component {
  componentDidMount() {
    const { history, location } = this.props;
    const { pathname, state, search } = location;

    console.log({ location });

    const searchParams = new URLSearchParams(search);
    let dataPassed;

    if (searchParams.has("dataPassed")) {
      dataPassed = searchParams.get("dataPassed");
      searchParams.delete("dataPassed");
    }
    history.replace({
      pathname,
      search: searchParams.toString(),
      state: { dataPassed }
    });
  }

  render() {
    return (
      ...
    );
  }
}


问:
how to create range for pages (from 1 page to x)
```<code>from bs4 import BeautifulSoup
import requests
url="https://bararanonline.com/letter/%D5%A1?page=1"
response=requests.get(url)
soup=BeautifulSoup(response.content, "lxml")
words=soup.find_all('a',"word-href")
for word in words:
  print(word.text)
</code>```

So, I got the first page. Now, I want to scrape information from all pages and I have to put URL page number in {} (page={}), but I can't figure out how to do it.

Thanks in advance.

答:
Simply define a for loop and set your range() parameters:

```<code>from bs4 import BeautifulSoup
import requests
url="https://bararanonline.com/letter/%D5%A1?page="

words = []

for i in range(1, 3):
    response=requests.get(f'{url}{i}')
    ##or as olvin roght mentioned by setting params
    ##response=requests.get("https://bararanonline.com/letter/ա", params={"page": i})
    soup=BeautifulSoup(response.content, "lxml")
    words.extend([word.text.strip() for word in soup.find_all('a',"word-href")])

words
</code>```

Alternativ is to go by while - Example starts with 207 just to show, that it stops, if there is no next page, but you can change it if you like:

```<code>from bs4 import BeautifulSoup
import requests
url="https://bararanonline.com/letter/%D5%A1?page=207"

words = []

while True:
    response=requests.get(url)
    soup=BeautifulSoup(response.content, "lxml")
    words.extend([word.text.strip() for word in soup.find_all('a',"word-href")])

    if a := soup.select_one('a[rel="next"]'):
        url = a['href']
    else:
        break
words
</code>```

Body:
from bs4 import BeautifulSoup
import requests
url="https://bararanonline.com/letter/%D5%A1?page=1"
response=requests.get(url)
soup=BeautifulSoup(response.content, "lxml")
words=soup.find_all('a',"word-href")
for word in words:
  print(word.text)

So, I got the first page. Now, I want to scrape information from all pages and I have to put URL page number in {} (page={}), but I can't figure out how to do it.

Thanks in advance.

Body:
Simply define a for loop and set your range() parameters:

from bs4 import BeautifulSoup
import requests
url="https://bararanonline.com/letter/%D5%A1?page="

words = []

for i in range(1, 3):
    response=requests.get(f'{url}{i}')
    ##or as olvin roght mentioned by setting params
    ##response=requests.get("https://bararanonline.com/letter/ա", params={"page": i})
    soup=BeautifulSoup(response.content, "lxml")
    words.extend([word.text.strip() for word in soup.find_all('a',"word-href")])

words

Alternativ is to go by while - Example starts with 207 just to show, that it stops, if there is no next page, but you can change it if you like:

from bs4 import BeautifulSoup
import requests
url="https://bararanonline.com/letter/%D5%A1?page=207"

words = []

while True:
    response=requests.get(url)
    soup=BeautifulSoup(response.content, "lxml")
    words.extend([word.text.strip() for word in soup.find_all('a',"word-href")])

    if a := soup.select_one('a[rel="next"]'):
        url = a['href']
    else:
        break
words


问:
How to use groupby + transform instead of pipe?
Let's say I have a dataframe like this

```<code>import pandas as pd
from scipy import stats

df = pd.DataFrame(
    {
        'group': list('abaab'),
        'val1': range(5),
        'val2': range(2, 7),
        'val3': range(4, 9)
    }
)

  group  val1  val2  val3
0     a     0     2     4
1     b     1     3     5
2     a     2     4     6
3     a     3     5     7
4     b     4     6     8
</code>```

Now I want to calculate linear regressions for each group in column group using two of the vali columns (potentially all pairs, so I don't want to hardcode column names anywhere).

A potential implementation could look like this based on pipe

```<code>def do_lin_reg_pipe(df, group_col, col1, col2):
    group_names = df[group_col].unique()
    df_subsets = []
    for s in group_names:
        df_subset = df.loc[df[group_col] == s]
        x = df_subset[col1].values
        y = df_subset[col2].values
        slope, intercept, r, p, se = stats.linregress(x, y)
        df_subset = df_subset.assign(
            slope=slope,
            intercept=intercept,
            r=r,
            p=p,
            se=se
        )
        df_subsets.append(df_subset)
    return pd.concat(df_subsets)
</code>```

and then I can use

```<code>df_linreg_pipe = (
    df.pipe(do_lin_reg_pipe, group_col='group', col1='val1', col2='val3')
      .assign(p=lambda d: d['p'].round(3))
)
</code>```

which gives the desired outcome

```<code>  group  val1  val2  val3  slope  intercept    r    p   se
0     a     0     2     4    1.0        4.0  1.0  0.0  0.0
2     a     2     4     6    1.0        4.0  1.0  0.0  0.0
3     a     3     5     7    1.0        4.0  1.0  0.0  0.0
1     b     1     3     5    1.0        4.0  1.0  0.0  0.0
4     b     4     6     8    1.0        4.0  1.0  0.0  0.0
</code>```

What I don't like is that I have to loop through the groups, use and append and then also concat, so I thought I should somehow use a groupby and transform but I don't get this to work. The function call should be something like

```<code>df_linreg_transform = df.copy()
df_linreg_transform[['slope', 'intercept', 'r', 'p', 'se']] = (
    df.groupby('group').transform(do_lin_reg_transform, col1='val1', col2='val3')
)
</code>```

question is how to define do_lin_reg_transform; I would like to have something along these lines

```<code>def do_lin_reg_transform(df, col1, col2):

    x = df[col1].values
    y = df[col2].values
    slope, intercept, r, p, se = stats.linregress(x, y)

    return (slope, intercept, r, p, se)
</code>```

but that - of course - crashes with a KeyError

KeyError: 'val1'

How could one implement do_lin_reg_transform to make it work with groupby and transform?

答:
As you can use groupby_transform because you need extra columns to compute the result, the idea is to use groupby_apply with map to broadcast the result to each rows:

```<code>cols = ['slope', 'intercept', 'r', 'p', 'se']
lingress = lambda x: stats.linregress(x['val1'], x['val3'])

df[cols] = pd.DataFrame.from_records(df['group'].map(df.groupby('group').apply(lingress)))
print(df)

# Output
  group  val1  val2  val3  slope  intercept    r             p   se
0     a     0     2     4    1.0        4.0  1.0  9.003163e-11  0.0
1     b     1     3     5    1.0        4.0  1.0  0.000000e+00  0.0
2     a     2     4     6    1.0        4.0  1.0  9.003163e-11  0.0
3     a     3     5     7    1.0        4.0  1.0  9.003163e-11  0.0
4     b     4     6     8    1.0        4.0  1.0  0.000000e+00  0.0
</code>```

Body:
Let's say I have a dataframe like this

import pandas as pd
from scipy import stats

df = pd.DataFrame(
    {
        'group': list('abaab'),
        'val1': range(5),
        'val2': range(2, 7),
        'val3': range(4, 9)
    }
)

  group  val1  val2  val3
0     a     0     2     4
1     b     1     3     5
2     a     2     4     6
3     a     3     5     7
4     b     4     6     8

Now I want to calculate linear regressions for each group in column group using two of the vali columns (potentially all pairs, so I don't want to hardcode column names anywhere).

A potential implementation could look like this based on pipe

def do_lin_reg_pipe(df, group_col, col1, col2):
    group_names = df[group_col].unique()
    df_subsets = []
    for s in group_names:
        df_subset = df.loc[df[group_col] == s]
        x = df_subset[col1].values
        y = df_subset[col2].values
        slope, intercept, r, p, se = stats.linregress(x, y)
        df_subset = df_subset.assign(
            slope=slope,
            intercept=intercept,
            r=r,
            p=p,
            se=se
        )
        df_subsets.append(df_subset)
    return pd.concat(df_subsets)

and then I can use

df_linreg_pipe = (
    df.pipe(do_lin_reg_pipe, group_col='group', col1='val1', col2='val3')
      .assign(p=lambda d: d['p'].round(3))
)

which gives the desired outcome

  group  val1  val2  val3  slope  intercept    r    p   se
0     a     0     2     4    1.0        4.0  1.0  0.0  0.0
2     a     2     4     6    1.0        4.0  1.0  0.0  0.0
3     a     3     5     7    1.0        4.0  1.0  0.0  0.0
1     b     1     3     5    1.0        4.0  1.0  0.0  0.0
4     b     4     6     8    1.0        4.0  1.0  0.0  0.0

What I don't like is that I have to loop through the groups, use and append and then also concat, so I thought I should somehow use a groupby and transform but I don't get this to work. The function call should be something like

df_linreg_transform = df.copy()
df_linreg_transform[['slope', 'intercept', 'r', 'p', 'se']] = (
    df.groupby('group').transform(do_lin_reg_transform, col1='val1', col2='val3')
)

question is how to define do_lin_reg_transform; I would like to have something along these lines

def do_lin_reg_transform(df, col1, col2):

    x = df[col1].values
    y = df[col2].values
    slope, intercept, r, p, se = stats.linregress(x, y)

    return (slope, intercept, r, p, se)

but that - of course - crashes with a KeyError

KeyError: 'val1'

How could one implement do_lin_reg_transform to make it work with groupby and transform?

Body:
As you can use groupby_transform because you need extra columns to compute the result, the idea is to use groupby_apply with map to broadcast the result to each rows:

cols = ['slope', 'intercept', 'r', 'p', 'se']
lingress = lambda x: stats.linregress(x['val1'], x['val3'])

df[cols] = pd.DataFrame.from_records(df['group'].map(df.groupby('group').apply(lingress)))
print(df)

# Output
  group  val1  val2  val3  slope  intercept    r             p   se
0     a     0     2     4    1.0        4.0  1.0  9.003163e-11  0.0
1     b     1     3     5    1.0        4.0  1.0  0.000000e+00  0.0
2     a     2     4     6    1.0        4.0  1.0  9.003163e-11  0.0
3     a     3     5     7    1.0        4.0  1.0  9.003163e-11  0.0
4     b     4     6     8    1.0        4.0  1.0  0.000000e+00  0.0


问:
Replacing a youtube embed
I'm trying to replace a youtube link within HTML, just that link and nothing else, with the youtube embed.

Example here:

https://regex101.com/r/5JhmpW/4

```<code>(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])))

<p>http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index</p><p>Para</p>
<p>http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o</p><p>Para</p>
<p>http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0</p><p>Para</p>
<p>http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s</p><p>Para</p>
<p>http://www.youtube.com/embed/0zM3nApSvMg?rel=0</p><p>Para</p>
<p>http://www.youtube.com/watch?v=0zM3nApSvMg</p><p>Para</p>
<p>http://youtu.be/0zM3nApSvMg</p><p>Para</p>
<p>https://youtube.com/shorts/0dPkkQeRwTI?feature=share</p><p>Para</p>
<p>https://youtube.com/shorts/0dPkkQeRwTI</p><p>Para</p>

<p>https://www.youtube.com/watch?v=0dPkkQeRwTI&ab_channel=RelaxedChan</p><p>Para</p>
</code>```

The problems currently are that it doesn't match enough to replace everything and I couldn't get it to go to the end of the link without interfering with the markup.

Edit:

They should all look like this:

```<code><p><iframe width="100%" src="https://www.youtube.com/embed/0zM3nApSvMg" frameborder="0" allowfullscreen></iframe><iframe width="100%" src="https://www.youtube.com/embed/0dPkkQeRwTI" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
<p><iframe width="100%" src="https://www.youtube.com/embed/QdK8U-VIH_o" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
<p><iframe width="100%" src="https://www.youtube.com/embed/0zM3nApSvMg" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
<p><iframe width="100%" src="https://www.youtube.com/embed/0zM3nApSvMg" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
<p><iframe width="100%" src="https://www.youtube.com/embed/0zM3nApSvMg" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
<p><iframe width="100%" src="https://www.youtube.com/embed/0zM3nApSvMg" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
<p><br><iframe width="100%" src="https://www.youtube.com/embed/0zM3nApSvMg" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
<div><iframe width="100%" src="https://www.youtube.com/embed/0dPkkQeRwTI" frameborder="0" allowfullscreen></iframe></div><p>Para</p>
<p><iframe width="100%" src="https://www.youtube.com/embed/0dPkkQeRwTI" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
<p><iframe width="100%" src="https://www.youtube.com/embed/0dPkkQeRwTI" frameborder="0" allowfullscreen></iframe></p><p>Para</p>
</code>```

Title: Replacing a youtube embed

Body:
I'm trying to replace a youtube link within HTML, just that link and nothing else, with the youtube embed.

Example here:

https://regex101.com/r/5JhmpW/4

(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])))

http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index

Para

http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o

Para

http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0

Para

http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s

Para

http://www.youtube.com/embed/0zM3nApSvMg?rel=0

Para

http://www.youtube.com/watch?v=0zM3nApSvMg

Para

http://youtu.be/0zM3nApSvMg

Para

https://youtube.com/shorts/0dPkkQeRwTI?feature=share

Para

https://youtube.com/shorts/0dPkkQeRwTI

Para

https://www.youtube.com/watch?v=0dPkkQeRwTI&ab_channel=RelaxedChan

Para

The problems currently are that it doesn't match enough to replace everything and I couldn't get it to go to the end of the link without interfering with the markup.

Edit:

They should all look like this:

Para

Para

Para

Para

Para

Para

Para

Para

Para

Para

Body:
How about this:

http.+(?:(?:v=)|(?:\/a\/u\/1\/)|(?:(?:v|embed|youtu\.be|shorts)\/))(?<videoId>.{11})[^<]*

https://regex101.com/r/oaS7U5/1


问:
Change javac path from ant
Can I specify the javac path from within ant, when using fork ? I'm asking this because I need to run a script from an automation framwork(cruisecontrol) , however when I use fork, it uses jdk of a lower version bundled with the framework. Hence is there any way I can specify a different path for javac?</p>

答: set JAVA_HOME.  If you want to use multiple JVMs in a single build that's not possible, you would need to run two ant commands and set the JAVA_HOME before each one.</p>

Title: Change javac path from ant


问:
SSIS Expression to append file extension
I'll get a Full filepath(FilePath and FileName) from a variable (@[User::V_FullPath])  as C:/Users/ABCD/Documents/Development/SampleFile.txt

I have a file with the same name but with .xlsx (SampleFile.xlsx) in another folder(A) that I want to copy to another folder(B)

To get just the filename I'm using the expression:

```<code>SUBSTRING(@[User::V_FullPath],37,47)
</code>```

How can I append .xlsx to the above expression
My goal is to get SampleFile.xlsx

答:
Why not just replace .txt with .xlsx?

```<code>REPLACE( @[User::V_FullPath]),".txt",".xlsx")
</code>```

This will result in the following value:

C:/Users/ABCD/Documents/Development/SampleFile.xlsx

If you need only the filename Sample.xlsx, you can use TOKEN and TOKENCOUNT functions as follows:

```<code>TOKEN(TOKEN(@[User::V_FullPath],"/", TOKENCOUNT(@[User::V_FullPath],"/")), ".", 1) +".xlsx"
</code>```

Expression result:

Sample.xlsx

Similar questions:

How do I extract file name from a path within an SSIS package?

Body:
I'll get a Full filepath(FilePath and FileName) from a variable (@[User::V_FullPath])  as C:/Users/ABCD/Documents/Development/SampleFile.txt

I have a file with the same name but with .xlsx (SampleFile.xlsx) in another folder(A) that I want to copy to another folder(B)

To get just the filename I'm using the expression:

SUBSTRING(@[User::V_FullPath],37,47)

How can I append .xlsx to the above expression
My goal is to get SampleFile.xlsx

Body:
Why not just replace .txt with .xlsx?

REPLACE( @[User::V_FullPath]),".txt",".xlsx")

This will result in the following value:

C:/Users/ABCD/Documents/Development/SampleFile.xlsx

If you need only the filename Sample.xlsx, you can use TOKEN and TOKENCOUNT functions as follows:

TOKEN(TOKEN(@[User::V_FullPath],"/", TOKENCOUNT(@[User::V_FullPath],"/")), ".", 1) +".xlsx"

Expression result:

Sample.xlsx

Similar questions:

How do I extract file name from a path within an SSIS package?


问:
How to append a line from .txt file without new line character "/n"
I have to read a txt file with for example this:

```<code>test
test2
test3
test4
</code>```

If I use a this code

```<code>read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.readlines()
print(read_of_string)
</code>```

a output is ["test/n","test2/n","test3/n","test4/n"]

if I use this code

```<code>print(read_of_string[0])
</code>```

output is "test" (enter)

I have to append it into a

```<code>listofstring = []
listofsting.append(read_of_string)
</code>```

it is not working
Output should be a list with strings without enters like

```<code>["test","test2","test3","test4"]
</code>```

答:
How does this work?</p>
```<code>a = ["test\n","test2\n","test3\n","test4\n"]
b = [item.rstrip() for item in a]
print(b)
['test', 'test2', 'test3', 'test4']
</code>```

Body:
I have to read a txt file with for example this:

test
test2
test3
test4

If I use a this code

read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.readlines()
print(read_of_string)

a output is ["test/n","test2/n","test3/n","test4/n"]

if I use this code

print(read_of_string[0])

output is "test" (enter)

I have to append it into a

listofstring = []
listofsting.append(read_of_string)

it is not working
Output should be a list with strings without enters like

["test","test2","test3","test4"]

Body:
How does this work?

a = ["test\n","test2\n","test3\n","test4\n"]
b = [item.rstrip() for item in a]
print(b)
['test', 'test2', 'test3', 'test4']


问:
The requested resource is in use. (Exception from HRESULT: 0x800700AA) - Microsoft WebView
I have following code to launch webview

```<code>var env = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(userDataFolder: Path.Combine(Path.GetTempPath(), $"{Environment.UserName}_Browser"));
await webView21.EnsureCoreWebView2Async(env);

 var url = $"Field1=A2&TypeId=1&ItemId=1234";

 var postData = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(url));
 var request = webView21.CoreWebView2.Environment.CreateWebResourceRequest("https://xxxx/xxxx", "POST", postData, "Content-Type: application/x-www-form-urlencoded");
 webView21.CoreWebView2.NavigateWithWebResourceRequest(request);
</code>```

As for my understanding, providing unique userDataFolder should not create problem when multiple users using the application on a same server. It works for some but for some users throws the exception. Is there anything Im missing?

Using Microsoft.Web.WebView2 -Version 1.0.1108.44

Exception

```<code>System.Runtime.InteropServices.COMException (0x800700AA): The requested resource is in use. (Exception from HRESULT: 0x800700AA)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at Microsoft.Web.WebView2.Core.CoreWebView2Environment.<CreateCoreWebView2ControllerAsync>d__54.MoveNext()
</code>```

答:
By looking at the exception, you included, it indicates that the same userdatafolder is used by more than one WebView2 instance. To get around that problem, I suggest you create a new folder for each instance of WebView2 you run.

To do that you can simply create a random name for the folder instead of using one per user. Something like this:

```<code>Random rnd = new Random();
string subFolder = rnd.Next().toString();
var env = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(userDataFolder: Path.Combine(Path.GetTempPath(), $"{Environment.UserName}", subFolder));
</code>```

However, you should consider deleting that folder again, when the program shuts down (or you will get a lot of temp folders).

Body:
I have following code to launch webview

var env = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(userDataFolder: Path.Combine(Path.GetTempPath(), $"{Environment.UserName}_Browser"));
await webView21.EnsureCoreWebView2Async(env);

 var url = $"Field1=A2&TypeId=1&ItemId=1234";

 var postData = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(url));
 var request = webView21.CoreWebView2.Environment.CreateWebResourceRequest("https://xxxx/xxxx", "POST", postData, "Content-Type: application/x-www-form-urlencoded");
 webView21.CoreWebView2.NavigateWithWebResourceRequest(request);

As for my understanding, providing unique userDataFolder should not create problem when multiple users using the application on a same server. It works for some but for some users throws the exception. Is there anything Im missing?

Using Microsoft.Web.WebView2 -Version 1.0.1108.44

Exception

System.Runtime.InteropServices.COMException (0x800700AA): The requested resource is in use. (Exception from HRESULT: 0x800700AA)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at Microsoft.Web.WebView2.Core.CoreWebView2Environment.<CreateCoreWebView2ControllerAsync>d__54.MoveNext()

Body:
By looking at the exception, you included, it indicates that the same userdatafolder is used by more than one WebView2 instance. To get around that problem, I suggest you create a new folder for each instance of WebView2 you run.

To do that you can simply create a random name for the folder instead of using one per user. Something like this:

Random rnd = new Random();
string subFolder = rnd.Next().toString();
var env = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(userDataFolder: Path.Combine(Path.GetTempPath(), $"{Environment.UserName}", subFolder));

However, you should consider deleting that folder again, when the program shuts down (or you will get a lot of temp folders).


问:
Collapse rows of a dataframe with common values and fill in blanks
I have a single data frame and every row is duplicated except for two values. In all cases the corresponding duplicate has a blank value in the corresponding row. I want to 'collapse' these rows and fill in the blanks.

In the example below, I want to collapse the top DataFrame to mirror the bottom

答:
You can use groupby + first; first skips over NaN values by default:

```<code>collapsed_df = df.groupby("feature_id").first().reset_index()
</code>```

If the empty spaces are not NaN values, probably will want to fill them with NaN first:

```<code>df = df.replace('', np.nan)
</code>```

Body:
You can use groupby + first; first skips over NaN values by default:

collapsed_df = df.groupby("feature_id").first().reset_index()

If the empty spaces are not NaN values, probably will want to fill them with NaN first:

df = df.replace('', np.nan)


问:
Could not find module FindOpenCV.cmake ( Error in configuration process)
I wrote a CMakeLists.txt for a project in C++, which uses OpenCV libraries. When I try to create the project using cmake, I get the next configuration problem:

```<code>CMake Error at CMakeLists.txt:15 (find_package):
  Could not find module FindOpenCV.cmake or a configuration file for package
  OpenCV.

  Adjust CMAKE_MODULE_PATH to find FindOpenCV.cmake or set OpenCV_DIR to the
  directory containing a CMake configuration file for OpenCV.  The file will
  have one of the following names:

    OpenCVConfig.cmake
    opencv-config.cmake
</code>```

The fact is that I have an environment variable for the path which I use in Visual Studio with no problems. If I don't include OpenCV, then I can configure and generate with no problem, but I need to solve the problem. I don't understand why cmake cannot find the OpenCV path or how to fix it.

I also used the recommendations mentioned in this link:
FindOpenCV.cmake

Does anybody had this problem too?

答:
For me (on Ubuntu), I just run:</p>
```<code>sudo apt-get install libopencv-dev
</code>```

Body:
I wrote a CMakeLists.txt for a project in C++, which uses OpenCV libraries. When I try to create the project using cmake, I get the next configuration problem:

CMake Error at CMakeLists.txt:15 (find_package):
  Could not find module FindOpenCV.cmake or a configuration file for package
  OpenCV.

  Adjust CMAKE_MODULE_PATH to find FindOpenCV.cmake or set OpenCV_DIR to the
  directory containing a CMake configuration file for OpenCV.  The file will
  have one of the following names:

    OpenCVConfig.cmake
    opencv-config.cmake

The fact is that I have an environment variable for the path which I use in Visual Studio with no problems. If I don't include OpenCV, then I can configure and generate with no problem, but I need to solve the problem. I don't understand why cmake cannot find the OpenCV path or how to fix it.

I also used the recommendations mentioned in this link:
FindOpenCV.cmake

Does anybody had this problem too?

Body:
For me (on Ubuntu), I just run:

sudo apt-get install libopencv-dev


问:
grep -P no longer works. How can I rewrite my searches?
It looks like the new version of OS X no longer supports grep -P and as such has made some of my scripts stop working, for example:

```<code>var1=`grep -o -P '(?<=<st:italic>).*(?=</italic>)' file.txt`
</code>```

I need to capture grep's result to a variable and I need to use zero-width assertions, as well as \K:

```<code>var2=`grep -P -o '(property:)\K.*\d+(?=end)' file.txt`
</code>```

Any alternatives would be greatly appreciated.

答:
Some more options, these also set correct exit status:

equivalent to grep -P PATTERN FILE :

perl -e'while(<>){if( (m!PATTERN!) ){$ok++;print}};if(!($ok)){exit 1}' FILE

equivalent to grep -P -i PATTERN FILE :

perl -e'while(<>){if( (m!PATTERN!i) ){$ok++;print}};if(!($ok)){exit 1}' FILE

equivalent to grep -v -P PATTERN FILE :

perl -e'while(<>){if( !(m!PATTERN!) ){$ok++;print}};if(!($ok)){exit 1}' FILE

For a more cleaner solution use this gist - implemented switches are: -A , -B , -v , -P , -i : https://gist.github.com/torson/bd6931bda0035c4884b2a8c4c64a33b2

Body:
It looks like the new version of OS X no longer supports grep -P and as such has made some of my scripts stop working, for example:

var1=`grep -o -P '(?<=<st:italic>).*(?=</italic>)' file.txt`

I need to capture grep's result to a variable and I need to use zero-width assertions, as well as \K:

var2=`grep -P -o '(property:)\K.*\d+(?=end)' file.txt`

Any alternatives would be greatly appreciated.


问:
javascript sum values from two different functions
I'm trying to create a calculator, I've managed to get the values from a google Sheets doc when I console.log from within the function. I'm now trying to combine those figures to get a total price. I'm getting a NAN error.

I'm new to Javascript so I could be missing something simple but I have tried and tried and I can't figure it out.

I simply want to add the hourly rate and the mileage together to get 25.00 and then convert it to a UK currency.

```<code>      function showHourlyRate(qty) {
        var oneFunc = qty
        console.log(oneFunc) //result is 5.00
        return oneFunc
      };

      function showMileageRate(qty) {
        var twoFunc = qty
        console.log(twoFunc) //result is 20.00
        return twoFunc
      };

      function combinedTotal(){
        var addTogether = showHourlyRate() + showMileageRate();
        alert(addTogether); // gives NAN
        return addTogether;
      }
</code>```

UPDATE:

Excuse me if my terminology is not correct.

I've updated my question as the answers still didn't work for me which make me think I've done something early on so...

This is a google apps script.

I have a functions.gs, within this file I get the spreadsheet and sheet needed. I then get the range of columns and filter the results to match my word. Once it finds a match, get the next column which has a price. I then return that.

Here's that part: (I've only added the hourly rate one as the mileage one is the same but with the names changed)

```<code>function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? "No Match" : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

</code>```

My next file is the index.html. I first load the function on initial load, I then get the hourly rate using the function afterSidebar Loads which then uses the showHourlyRate function.

Thats how I get my 20.00 or 5.00 figure

here's the html file:

```<code>      var arrayOfArrays;

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      }

      function showHourlyRate(qty) {
        var oneFunc = hourlyRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(oneFunc) //result is 0.55
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(twoFunc) //result is 22.64
        return twoFunc
      };

      function combinedTotal(){
      }
</code>```

I hope this makes more sense and thank you all for answering.

UPDATE 2:

So it turns out that the following code works in the functions.gs file but not in the index.html file

```<code>function combinedTotal(){
        var addTogether = Number(getHourlyRate()) + Number(getMileageRate());
        console.log(addTogether);
        return addTogether;
      }
</code>```

I changed the functions names to match the ones in the functions.gs file.

What am I not understanding?

答:
You didn't specify the inputs for your showHourlyRate and showMileageRage functions.

You put:

```<code>function combinedTotal(){
    var addTogether = showHourlyRate() + showMileageRate();
    alert(addTogether); // gives NAN
    return addTogether;
}
</code>```

You can have:

```<code>function combinedTotal(hourlyRate, mileageRate){
    var addTogether = showHourlyRate(hourlyRate) + showMileageRate(mileageRate);
    alert(addTogether);
    return addTogether;
}
</code>```

Body:
I'm trying to create a calculator, I've managed to get the values from a google Sheets doc when I console.log from within the function. I'm now trying to combine those figures to get a total price. I'm getting a NAN error.

I'm new to Javascript so I could be missing something simple but I have tried and tried and I can't figure it out.

I simply want to add the hourly rate and the mileage together to get 25.00 and then convert it to a UK currency.

      function showHourlyRate(qty) {
        var oneFunc = qty
        console.log(oneFunc) //result is 5.00
        return oneFunc
      };

      function showMileageRate(qty) {
        var twoFunc = qty
        console.log(twoFunc) //result is 20.00
        return twoFunc
      };

      function combinedTotal(){
        var addTogether = showHourlyRate() + showMileageRate();
        alert(addTogether); // gives NAN
        return addTogether;
      }

UPDATE:

Excuse me if my terminology is not correct.

I've updated my question as the answers still didn't work for me which make me think I've done something early on so...

This is a google apps script.

I have a functions.gs, within this file I get the spreadsheet and sheet needed. I then get the range of columns and filter the results to match my word. Once it finds a match, get the next column which has a price. I then return that.

Here's that part: (I've only added the hourly rate one as the mileage one is the same but with the names changed)

function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? "No Match" : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

My next file is the index.html. I first load the function on initial load, I then get the hourly rate using the function afterSidebar Loads which then uses the showHourlyRate function.

Thats how I get my 20.00 or 5.00 figure

here's the html file:

      var arrayOfArrays;

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      }

      function showHourlyRate(qty) {
        var oneFunc = hourlyRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(oneFunc) //result is 0.55
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(twoFunc) //result is 22.64
        return twoFunc
      };

      function combinedTotal(){
      }

I hope this makes more sense and thank you all for answering.

UPDATE 2:

So it turns out that the following code works in the functions.gs file but not in the index.html file

function combinedTotal(){
        var addTogether = Number(getHourlyRate()) + Number(getMileageRate());
        console.log(addTogether);
        return addTogether;
      }

I changed the functions names to match the ones in the functions.gs file.

What am I not understanding?

Body:
You didn't specify the inputs for your showHourlyRate and showMileageRage functions.

You put:

function combinedTotal(){
    var addTogether = showHourlyRate() + showMileageRate();
    alert(addTogether); // gives NAN
    return addTogether;
}

You can have:

function combinedTotal(hourlyRate, mileageRate){
    var addTogether = showHourlyRate(hourlyRate) + showMileageRate(mileageRate);
    alert(addTogether);
    return addTogether;
}


问:
Rails: How can I remove default version of bundler?
I tried to change default bundle version but it getting updated with 2 default version. How can I modify to single default?

```<code>$ gem list bundler

*** LOCAL GEMS ***

bundler (2.0.1, default: 1.16.6, default: 1.16.2)
</code>```

If I do gem uninstall not removing defaults,

```<code>$ gem uninstall bundler
Successfully uninstalled bundler-2.0.1

$ gem list bundle

*** LOCAL GEMS ***

bundler (default: 1.16.6, default: 1.16.2)
</code>```

How can I set (like the below) default as single version?

```<code>bundler (2.0.1, default: 1.16.6)
</code>```

答:
As @theist points out, after Ruby 2.6 bundler became a default gem. So depending on your version of Ruby, you will have a different version of bundler included. You can see the list here.

But what has not been explained in the answers so far is that you can control which version of bundler is used by editing your Gemfile.lock and specifying the version you want to use on the very last line of the file, where it says:

```<code>BUNDLED WITH
   2.2.33
</code>```

This feels completely backwards since Gemfile.lock is supposed to be generated automatically by bundler, but that is the state of things at this point.

So, let's explain it all with an example. Let's say I am using Ruby 3.0.3. This version of Ruby comes with bundler 2.2.32. But my hosting company, Heroku, is using bundler 2.2.33. Since I want my dev environment to use the same bundler version as my production environment, I want to use 2.2.33.

So the first thing to do is gem install bundler -v "2.2.33". Then change the very bottom line of Gemfile.lock to say that it was bundled with 2.2.33 like:

```<code>BUNDLED WITH
   2.2.33
</code>```

Now when you run bundle install it will use bundler 2.2.33.

Body:
I tried to change default bundle version but it getting updated with 2 default version. How can I modify to single default?

$ gem list bundler

*** LOCAL GEMS ***

bundler (2.0.1, default: 1.16.6, default: 1.16.2)

If I do gem uninstall not removing defaults,

$ gem uninstall bundler
Successfully uninstalled bundler-2.0.1

$ gem list bundle

*** LOCAL GEMS ***

bundler (default: 1.16.6, default: 1.16.2)

How can I set (like the below) default as single version?

bundler (2.0.1, default: 1.16.6)

Body:
As @theist points out, after Ruby 2.6 bundler became a default gem. So depending on your version of Ruby, you will have a different version of bundler included. You can see the list here.

But what has not been explained in the answers so far is that you can control which version of bundler is used by editing your Gemfile.lock and specifying the version you want to use on the very last line of the file, where it says:

BUNDLED WITH
   2.2.33

This feels completely backwards since Gemfile.lock is supposed to be generated automatically by bundler, but that is the state of things at this point.

So, let's explain it all with an example. Let's say I am using Ruby 3.0.3. This version of Ruby comes with bundler 2.2.32. But my hosting company, Heroku, is using bundler 2.2.33. Since I want my dev environment to use the same bundler version as my production environment, I want to use 2.2.33.

So the first thing to do is gem install bundler -v "2.2.33". Then change the very bottom line of Gemfile.lock to say that it was bundled with 2.2.33 like:

BUNDLED WITH
   2.2.33

Now when you run bundle install it will use bundler 2.2.33.


问:
Mysql: Select all values alphabetically between two strings in a table
Okay let's say I have this in my table:

id
name

1
tom

2
anna

3
beatrice

4
robert

5
xavier

6
zoe

7
eustace

How can I select all ids of the names that are alphabetically sorted?

Say, select * from myTable where name "between" 'beatrice' and 'tom' order by name;

Should give me :

id
name

3
beatrice

7
eustace

4
robert

1
tom

Because in alphabetical order, those are in between 'beatrice' and 'tom'.

答:
Since these are strings, try this:

```<code>SELECT id
FROM tableName
WHERE nameField >= 'Landon' and nameField <= 'Peter'
ORDER BY nameField;
</code>```

If you want to use the full name (first and last), you can try with that too.

Body:
Since these are strings, try this:

SELECT id
FROM tableName
WHERE nameField >= 'Landon' and nameField <= 'Peter'
ORDER BY nameField;

If you want to use the full name (first and last), you can try with that too.


问:
Forking actions/checkout@v2 at organization level to be used repo's github actions

Problem:

Inherently, github actions has no information about the code within the repo it's being run in. To rid that problem, there is the actions/checkout workflow that is the defacto start of most workflows.

Our enterprise account got locked down to only local actions only:

Because of this, we are not able to use the actions/checkout@v2 at the start of our workflow, thus rendering our Github Actions useless.

Proposed Solution

Fork the actions/checkout repo as a submodule of a repo and use that reference in my code like so:

steps:
  - uses: <enterprise_name>/<repo_name>/checkout@main
```
<p>When running this action as a test, I get this error message:</p>
```Error: Can't find 'action.yml', 'action.yaml' or 'Dockerfile' under
'/home/runner/work/_actions/<enterprise_name>/<repo_name>/main/checkout'.
Did you forget to run actions/checkout before running your local action?
```

So my question:

Is there a way to run a forked or local version of actions/checkout? The above example is telling me, I can't run a local version of actions/checkout because I have clone the repo which is ironic error.

答:
You need to push the actions/checkout repo into an internal or public repo on your enterprise. Then update your workflow to reference organization/repo@2 instead.

After forking the actions/checkout repo to my jessehouwing-actions this would result in the following update of the YAML:

```<code>steps:
  # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
  - uses: actions/checkout@v3
</code>```

Would become:

```<code>steps:
  # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
  - uses: jessehouwing-actions/checkout@v3
</code>```

Don't use submodules.

Body:
Problem:

Inherently, github actions has no information about the code within the repo it's being run in. To rid that problem, there is the actions/checkout workflow that is the defacto start of most workflows.

Our enterprise account got locked down to only local actions only:

Because of this, we are not able to use the actions/checkout@v2 at the start of our workflow, thus rendering our Github Actions useless.

Proposed Solution

Fork the actions/checkout repo as a submodule of a repo and use that reference in my code like so:

steps:
  - uses: <enterprise_name>/<repo_name>/checkout@main

When running this action as a test, I get this error message:

Error: Can't find 'action.yml', 'action.yaml' or 'Dockerfile' under
'/home/runner/work/_actions/<enterprise_name>/<repo_name>/main/checkout'.
Did you forget to run actions/checkout before running your local action?

So my question:

Is there a way to run a forked or local version of actions/checkout? The above example is telling me, I can't run a local version of actions/checkout because I have clone the repo which is ironic error.

Body:
You need to push the actions/checkout repo into an internal or public repo on your enterprise. Then update your workflow to reference organization/repo@2 instead.

After forking the actions/checkout repo to my jessehouwing-actions this would result in the following update of the YAML:

steps:
  # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
  - uses: actions/checkout@v3

Would become:

steps:
  # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
  - uses: jessehouwing-actions/checkout@v3

Don't use submodules.


答:
You need to add the params to the called functions on the 3rd function after if you are getting a NaN error probably because you are using strings or other type of value from the doc, you cloud use something like this</p>
```<code>function showHourlyRate(qty) {
  return parseFloat(qty)
};

function showMileageRate(qty) {
  return parseFloat(qty)
};

function combinedTotal(hourlyRate, mileageRate){
  let addTogether = showHourlyRate(hourlyRate) + showMileageRate(mileageRate);
    console.log(addTogether)
  return addTogether;
}

combinedTotal(1,"22")
</code>```

Title: javascript sum values from two different functions

Body:
You need to add the params to the called functions on the 3rd function after if you are getting a NaN error probably because you are using strings or other type of value from the doc, you cloud use something like this

function showHourlyRate(qty) {
  return parseFloat(qty)
};

function showMileageRate(qty) {
  return parseFloat(qty)
};

function combinedTotal(hourlyRate, mileageRate){
  let addTogether = showHourlyRate(hourlyRate) + showMileageRate(mileageRate);
    console.log(addTogether)
  return addTogether;
}

combinedTotal(1,"22")


问:
Sending and Receiving arrays via Sockets
Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. Hope I explained the problem as clearly as possible. I would appreciate the help!</p>

```<code># Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()
</code>```

答:
You're trying to send a python object through a socket, it is normal that it doesn't work, you can't send objects in a socket, objects are not data, they are the representation of some data in a given programming language. You need to "translate" your object to data and re-create the object from the data on the other socket's side. One way to do this would be with the pickle module.

On the client side, you "pickle" the object:

```<code>data = pickle.dumps(my_array)
</code>```

And on the server side, you "unpickle" the received data:

```<code>my_array = pickle.loads(received_data)
</code>```

Body:
Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. Hope I explained the problem as clearly as possible. I would appreciate the help!

# Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()

Body:
You're trying to send a python object through a socket, it is normal that it doesn't work, you can't send objects in a socket, objects are not data, they are the representation of some data in a given programming language. You need to "translate" your object to data and re-create the object from the data on the other socket's side. One way to do this would be with the pickle module.

On the client side, you "pickle" the object:

data = pickle.dumps(my_array)

And on the server side, you "unpickle" the received data:

my_array = pickle.loads(received_data)


问:
How would I use .split() to split a string by \n instead of .split() reading \n as a new line
I'm trying to split up a string inside of a list into a list, and the string contains \n as a character.
Whenever I use .split("\n"), its of course splitting the string at a new line, but I need it to split at the character \n. Is there anyway to make .split() interpret it this way?

Example:

```<code>#original list
['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']
</code>```

what id like to create with .split() function:

```<code>[ [SK Telecom CO. Ltd. ADR] , [SKM] , [12/31/2021] , [1.49], [N/A], [N/A] ]
</code>```

if you have any idea on how to help i'd be very grateful, thanks!

答:
what about:</p>
```<code>a= ['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']
print(a[0].strip('\n').split('\n'))
</code>```

Body:
I'm trying to split up a string inside of a list into a list, and the string contains \n as a character.
Whenever I use .split("\n"), its of course splitting the string at a new line, but I need it to split at the character \n. Is there anyway to make .split() interpret it this way?

Example:

#original list
['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']

what id like to create with .split() function:

[ [SK Telecom CO. Ltd. ADR] , [SKM] , [12/31/2021] , [1.49], [N/A], [N/A] ]

if you have any idea on how to help i'd be very grateful, thanks!

Body:
what about:

a= ['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']
print(a[0].strip('\n').split('\n'))


问:
Django: exists() using queryset cache
Does django's QuerySet.exists() method use the queryset's cache if called twice?
For example

# this makes a call to db
queryset.exists()
# > true

# does it make a call to the db or reuse some cached result?
queryset.exists()
# > true
```

I know that len(queryset) won't make a call to the db if it has previously been evaluated. Is it the same with exists?

答:
If you use .exists() twice, it will make two queries, the queryset will not cache the outcome of the .exists() call.

If you however plan to enumerate over the queryset, you can check the truthiness of the queryset with:

```<code>if queryset:
    # not empty
    pass
else:
    # empty
    pass
</code>```

This will make a query and load the records into the cache of the queryset, so later enumerating over the queryset, applying len(…), etc. will not trigger a new query.

This however should be avoided if you are only interested to check if an item exists, for the same reason you should use .count() [Django-doc] over len(…) if you are only interested in the number of records: by using len(…) you load the records into memory, which is more expensive than making a SELECT COUNT(*) query.

Title: Django: exists() using queryset cache

Body:
Does django's QuerySet.exists() method use the queryset's cache if called twice?
For example

# this makes a call to db
queryset.exists()
# > true

# does it make a call to the db or reuse some cached result?
queryset.exists()
# > true

I know that len(queryset) won't make a call to the db if it has previously been evaluated. Is it the same with exists?

Body:
If you use .exists() twice, it will make two queries, the queryset will not cache the outcome of the .exists() call.

If you however plan to enumerate over the queryset, you can check the truthiness of the queryset with:

if queryset:
    # not empty
    pass
else:
    # empty
    pass

This will make a query and load the records into the cache of the queryset, so later enumerating over the queryset, applying len(…), etc. will not trigger a new query.

This however should be avoided if you are only interested to check if an item exists, for the same reason you should use .count() [Django-doc] over len(…) if you are only interested in the number of records: by using len(…) you load the records into memory, which is more expensive than making a SELECT COUNT(*) query.