问:
why is my int() conversion looking so weird?
I'm trying to take a number and divide it by 100 to get 1%, but when i tried to convert it to integer using the int(), it's giving me some weird output. i have no clue what i'm doing wrong here.

```<code>totalsupply = 1000000000000000000000000000000
onepercent = int((totalsupply/100))

print(totalsupply)
print(onepercent)
</code>```

the output is coming out as such:

```<code>1000000000000000000000000000000
9999999999999999583119736832
[Finished in 68ms]
</code>```

I was expecting the onepercent to be this: 10000000000000000000000000000.

答:
According to this post, python tries to convert the number to a float on a division. However, floats are limited to 1.7976931348623157e+308. A workaround is to use the // operator which returns an int from the division, so for your example:

```<code>totalsupply = 1000000000000000000000000000000
onepercent = totalsupply//100

print(totalsupply)
print(onepercent)
</code>```

Body:
I'm trying to take a number and divide it by 100 to get 1%, but when i tried to convert it to integer using the int(), it's giving me some weird output. i have no clue what i'm doing wrong here.

totalsupply = 1000000000000000000000000000000
onepercent = int((totalsupply/100))

print(totalsupply)
print(onepercent)

the output is coming out as such:

1000000000000000000000000000000
9999999999999999583119736832
[Finished in 68ms]

I was expecting the onepercent to be this: 10000000000000000000000000000.

Body:
According to this post, python tries to convert the number to a float on a division. However, floats are limited to 1.7976931348623157e+308. A workaround is to use the // operator which returns an int from the division, so for your example:

totalsupply = 1000000000000000000000000000000
onepercent = totalsupply//100

print(totalsupply)
print(onepercent)


来源: stackexchange

问:
How to aggregate related object counts in a view effectively?
Imagine this scenario:

I have three tables in my database: Products, Users and Likes, the latter representing a relation between a Product and a User. Now I have a query, which joins Products with the Likes table, counting how many Likes a Product got.

In fact, I need the information about the count much more often than the actual users and I want to use the query above as part of a greater query in a view. Is it possible to optimize the query or the view so that MySQL somehow caches the result of the count query above?

答:
You shouldn't need a join to count the likes for a product.

```<code>SELECT product, count(*)
FROM likes
GROUP BY product;
</code>```

Should be ripping fast if you use a WHERE clause.

ContentLicense: CC BY-SA 3.0

Body:
You shouldn't need a join to count the likes for a product.

SELECT product, count(*)
FROM likes
GROUP BY product;

Should be ripping fast if you use a WHERE clause.


问:
How to set build name (Build.BuildNumber) in an Azure DevOps Build Pipeline template?
I need to create several build definitions, which will all perform the exact same steps. What changes are only triggers and a few parameters, basically. I therefore based them all on a template that does all the heavy lifting. That works fine.

However, I need to customise the value of $(Build.BuildNumber) for several reasons, some aesthetic, some practical. According to Configure run or build numbers, all I have to do is set the name property in a YAML definition.

All my definitions should have the same name format, so I wanted to define it in the template directly. But setting a top-level name property in the template results in error message :

/templates/default-build.yml (Line: 5, Col: 1): Unexpected value 'name'

Setting the property in the individual definitions works as expected, but won't "scale" as a solution.

The individual definitions look like this:

```<code>trigger:
- master

extends:
  template: ../templates/default-build.yml
  parameters:
    solution: '**/ASolution.sln'
</code>```

The template looks like this:

```<code>parameters:
- name: solution
  type: string
  default: ''

name: $(Build.DefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)  # Trying to set Build.BuildNumber

variables:
  solution: ${{ parameters.solution }}
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

stages:
- stage: build_solution
  jobs:
    - job:
      steps:
        - task: VSBuild@1
          displayName: 'Build solution $(solution)'
          inputs:
            solution: $(solution)
            platform: '$(BuildPlatform)'
            configuration: '$(BuildConfiguration)'

        - task: PublishBuildArtifacts@1
          displayName: 'Publish Artifact'
          inputs:
            PathtoPublish: '$(build.artifactstagingdirectory)'
            ArtifactName: '$(Build.BuildNumber)'
</code>```

Am I missing something? Or is setting this particular property in a template just not (currently) supported?

答:
You can do this in a Powershell task that calls the ##vso[build.updatebuildnumber] 'command'.

https://learn.microsoft.com/en-us/azure/devops/pipelines/scripts/logging-commands?view=azure-devops&tabs=bash#updatebuildnumber-override-the-automatically-generated-build-number

The task can also be defined as a template like so:

```<code>steps:

- task: PowerShell@2
  displayName: 'Create version number'
  name: 'CreateVersionNumber'
  inputs:
    targetType: 'inline'
    script: |
        $newVersion = "MyVersion $(Build.BuildId)"

        Write-Host "New version is $($newVersion)"

        [string] $buildName = "$($newVersion)"
        Write-Host "Setting the name of the build to '$buildName'."
        Write-Host "##vso[build.updatebuildnumber]$buildName"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to create several build definitions, which will all perform the exact same steps. What changes are only triggers and a few parameters, basically. I therefore based them all on a template that does all the heavy lifting. That works fine.

However, I need to customise the value of $(Build.BuildNumber) for several reasons, some aesthetic, some practical. According to Configure run or build numbers, all I have to do is set the name property in a YAML definition.

All my definitions should have the same name format, so I wanted to define it in the template directly. But setting a top-level name property in the template results in error message :

/templates/default-build.yml (Line: 5, Col: 1): Unexpected value 'name'

Setting the property in the individual definitions works as expected, but won't "scale" as a solution.

The individual definitions look like this:

trigger:
- master

extends:
  template: ../templates/default-build.yml
  parameters:
    solution: '**/ASolution.sln'

The template looks like this:

parameters:
- name: solution
  type: string
  default: ''

name: $(Build.DefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)  # Trying to set Build.BuildNumber

variables:
  solution: ${{ parameters.solution }}
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

stages:
- stage: build_solution
  jobs:
    - job:
      steps:
        - task: VSBuild@1
          displayName: 'Build solution $(solution)'
          inputs:
            solution: $(solution)
            platform: '$(BuildPlatform)'
            configuration: '$(BuildConfiguration)'

        - task: PublishBuildArtifacts@1
          displayName: 'Publish Artifact'
          inputs:
            PathtoPublish: '$(build.artifactstagingdirectory)'
            ArtifactName: '$(Build.BuildNumber)'

Am I missing something? Or is setting this particular property in a template just not (currently) supported?

Body:
You can do this in a Powershell task that calls the ##vso[build.updatebuildnumber] 'command'.

https://learn.microsoft.com/en-us/azure/devops/pipelines/scripts/logging-commands?view=azure-devops&tabs=bash#updatebuildnumber-override-the-automatically-generated-build-number

The task can also be defined as a template like so:

steps:

- task: PowerShell@2
  displayName: 'Create version number'
  name: 'CreateVersionNumber'
  inputs:
    targetType: 'inline'
    script: |
        $newVersion = "MyVersion $(Build.BuildId)"

        Write-Host "New version is $($newVersion)"

        [string] $buildName = "$($newVersion)"
        Write-Host "Setting the name of the build to '$buildName'."
        Write-Host "##vso[build.updatebuildnumber]$buildName"


问:
Export data from always open, live-updating Excel document every 10 seconds
Is it possible to export data from an Excel document that is always open and constantly updating its values? This can be through any means(SQL, python, excel macro, text document). The Excel document was setup by a third party vendor that pumps their live data into the Excel document.

The main problem I'm running into is the fact that the document is never being saved. Meaning, the data is being refreshed on Excel but never actually being "saved" on the local drive. Therefore the only data I actually have access to is the last time the "save" button was pressed on the Excel document. Closing the document is not really an option because this will prevent it from updating altogether. Manually pressing the save button is not feasible either as the data is live.

What I have tried so far;

Using an SQL server agent job. The server agent job however is not able to access a file that is open.

Programmatically opening the file and accessing its contents through a C# console application. This is where the 'last saved' problem described above is prevalent.

Setting Excel to save the document every 10 seconds through its autosave settings (This only modifies the save timer on the "recovery" information not the actual information being stored on the drive).

答:
python with xlwings?

use xlwings to read your live data into a dataframe and then python-export that dataframe out into whatever---


问:
Duplicated function in mint contract / solidity
i have differents parts of code to call a mint function.

the parts are this

2 modifiers

```<code>modifier mintCompliance(uint256 _mintAmount) {
    require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
    require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
    _;
  }

    modifier mintCompliancePresale(uint256 _mintAmount) {
    require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
    require(supply.current() + _mintAmount <= maxPresaleSupply, "Max supply exceeded!");
    _;
  }
</code>```

One is for normal mint, and the other one is for presale minting only.

And that connects with my mint functions.

```<code>function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
      require(!paused, "The contract is paused!");
      require(msg.value >= cost * _mintAmount, "Insufficient funds!");

    if (msg.sender != owner()) {
        if(onlyWhitelisted == true) {
            require(isWhitelisted(msg.sender), "user is not whitelisted");
    }
    require(msg.value >= cost * _mintAmount, "insufficient funds");
    }

    _mintLoop(msg.sender, _mintAmount);
}

    function presaleMint(uint256 _mintAmount) public payable mintCompliancePresale(_mintAmount) {
      require(!paused, "The contract is paused!");
      require(msg.value >= cost * _mintAmount, "Insufficient funds!");

    if (msg.sender != owner()) {
        if(onlyWhitelisted == true) {
            require(isWhitelisted(msg.sender), "user is not whitelisted");
    }
    require(msg.value >= cost * _mintAmount, "insufficient funds");
    }

    _mintLoop(msg.sender, _mintAmount);
}
</code>```

2 functions, one for normal mint and another one for presale minting.

and that connects with my mint loop

```<code> function _mintLoop(address _receiver, uint256 _mintAmount) internal {
    for (uint256 i = 0; i < _mintAmount; i++) {
      supply.increment();
      _safeMint(_receiver, supply.current());
    }
  }
</code>```

Now, my question is how can i improve the 2 modifiers and 2 mint functions in just 1 modifier and 1 minting function? Is it possible to do?

I dont think 2 modifiers and 2 minting functions have sense. It works, but i think there is an error inside it.

答:
you can create bool presale
and make an if inside the modifier, the function will be unique since both function are the same:

```<code>modifier mintCompliance(uint256 _mintAmount) {
    if(!presale){
      require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
      require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
      _;
    }else{
      require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
      require(supply.current() + _mintAmount <= maxPresaleSupply, "Max supply exceeded!");
      _;
    }
  }
</code>```

and function:

```<code>function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
      require(!paused, "The contract is paused!");
      require(msg.value >= cost * _mintAmount, "Insufficient funds!");

    if (msg.sender != owner()) {
        if(onlyWhitelisted == true) {
            require(isWhitelisted(msg.sender), "user is not whitelisted");
    }
    require(msg.value >= cost * _mintAmount, "insufficient funds");
    }

    _mintLoop(msg.sender, _mintAmount);
}
</code>```

NOTE
If you're using Pausable.sol by openzeppelin you can do:

```<code>function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) whenNotPaused {}
</code>```

and delete:

```<code>require(!paused, "The contract is paused!");
</code>```

Body:
i have differents parts of code to call a mint function.

the parts are this

2 modifiers

modifier mintCompliance(uint256 _mintAmount) {
    require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
    require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
    _;
  }

    modifier mintCompliancePresale(uint256 _mintAmount) {
    require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
    require(supply.current() + _mintAmount <= maxPresaleSupply, "Max supply exceeded!");
    _;
  }

One is for normal mint, and the other one is for presale minting only.

And that connects with my mint functions.

function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
      require(!paused, "The contract is paused!");
      require(msg.value >= cost * _mintAmount, "Insufficient funds!");

    if (msg.sender != owner()) {
        if(onlyWhitelisted == true) {
            require(isWhitelisted(msg.sender), "user is not whitelisted");
    }
    require(msg.value >= cost * _mintAmount, "insufficient funds");
    }

    _mintLoop(msg.sender, _mintAmount);
}

    function presaleMint(uint256 _mintAmount) public payable mintCompliancePresale(_mintAmount) {
      require(!paused, "The contract is paused!");
      require(msg.value >= cost * _mintAmount, "Insufficient funds!");

    if (msg.sender != owner()) {
        if(onlyWhitelisted == true) {
            require(isWhitelisted(msg.sender), "user is not whitelisted");
    }
    require(msg.value >= cost * _mintAmount, "insufficient funds");
    }

    _mintLoop(msg.sender, _mintAmount);
}

2 functions, one for normal mint and another one for presale minting.

and that connects with my mint loop

 function _mintLoop(address _receiver, uint256 _mintAmount) internal {
    for (uint256 i = 0; i < _mintAmount; i++) {
      supply.increment();
      _safeMint(_receiver, supply.current());
    }
  }

Now, my question is how can i improve the 2 modifiers and 2 mint functions in just 1 modifier and 1 minting function? Is it possible to do?

I dont think 2 modifiers and 2 minting functions have sense. It works, but i think there is an error inside it.

Body:
you can create bool presale
and make an if inside the modifier, the function will be unique since both function are the same:

modifier mintCompliance(uint256 _mintAmount) {
    if(!presale){
      require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
      require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
      _;
    }else{
      require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
      require(supply.current() + _mintAmount <= maxPresaleSupply, "Max supply exceeded!");
      _;
    }
  }

and function:

function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
      require(!paused, "The contract is paused!");
      require(msg.value >= cost * _mintAmount, "Insufficient funds!");

    if (msg.sender != owner()) {
        if(onlyWhitelisted == true) {
            require(isWhitelisted(msg.sender), "user is not whitelisted");
    }
    require(msg.value >= cost * _mintAmount, "insufficient funds");
    }

    _mintLoop(msg.sender, _mintAmount);
}

NOTE
If you're using Pausable.sol by openzeppelin you can do:

function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) whenNotPaused {}

and delete:

require(!paused, "The contract is paused!");


问:
Better way of converting to lowercase only if it is of type string
I need to sort a table that has columns of varying data types. The problem with sorting the strings is that they are case sensitive. The original code is

```<code>const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => row.data[col])
        : descend((row) => row.data[col])
)
</code>```

and I updated it to the following which works

```<code>const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
        : descend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
)
</code>```

Is there a better way to do this?

答:
If you want to avoid repeating yourself on the sorting you can isolate the typecheck function:

```<code>const stringCheck = (row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col]
</code>```

and then:

```<code>const Details = sortWith(
    sortDir === 'ASC'
        ? ascend(stringCheck)
        : descend(stringCheck)
)
</code>```

Body:
I need to sort a table that has columns of varying data types. The problem with sorting the strings is that they are case sensitive. The original code is

const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => row.data[col])
        : descend((row) => row.data[col])
)

and I updated it to the following which works

const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
        : descend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
)

Is there a better way to do this?

Body:
If you want to avoid repeating yourself on the sorting you can isolate the typecheck function:

const stringCheck = (row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col]

and then:

const Details = sortWith(
    sortDir === 'ASC'
        ? ascend(stringCheck)
        : descend(stringCheck)
)


问:
Multiply numbers for loop java returning 0
I'm trying to take a number(n) and multiply it by every number before it, enter 4 you get (1x2x3x4) = 24. My code returns a 0. I have an addition just like this that works. Any ideas?</p>
```<code>public static int multiplyTooNum()
    {
        Scanner myIn = new Scanner(System.in);
        int n;

        System.out.println("Please enter a number");
        n = myIn.nextInt();
        myIn.nextLine();
        int sum = 0;

        for (int i=0; i<n; i++)
        {
            sum = sum * i;
        }

        int result = sum*n;
        System.out.println(result);
        myIn.close();
        return result;
    }
</code>```

答:
```<code>    for (int i=0; i<n; i++)
    {
        sum = sum * i;
    }
</code>```

Issue is in this part, you start i from 0, so each time the sum get's 0 and it will be multiplied again. I suggest you to learn debugging and step over in loops to pinpoint the issues.

Body:
I'm trying to take a number(n) and multiply it by every number before it, enter 4 you get (1x2x3x4) = 24. My code returns a 0. I have an addition just like this that works. Any ideas?

public static int multiplyTooNum()
    {
        Scanner myIn = new Scanner(System.in);
        int n;

        System.out.println("Please enter a number");
        n = myIn.nextInt();
        myIn.nextLine();
        int sum = 0;

        for (int i=0; i<n; i++)
        {
            sum = sum * i;
        }

        int result = sum*n;
        System.out.println(result);
        myIn.close();
        return result;
    }

Body:
    for (int i=0; i<n; i++)
    {
        sum = sum * i;
    }

Issue is in this part, you start i from 0, so each time the sum get's 0 and it will be multiplied again. I suggest you to learn debugging and step over in loops to pinpoint the issues.


问:
Why transition does not work in my Vue components?
I am building a Vue app. I have two components that are related to each other. One of them is called loginRegister.vue and the code of that is here:

loginRegister.vue:

<template>
<BaseModal idBtn = "regis" btnOneText="Cancel" :btnTwoText="button2Text['register']" v-show="showModal1" @close="showModal1 = false" @submitForm="registerUser(regLogPara['register'])" :popoverVue = "showToolTip.register">

  <transition name="fade">

Create Your Account

you succeed

there is an error!

  </transition>
</BaseModal>
</template>

```
</div>
</div>
</p>
<p>The other one called <code>BaseModal.vue</code> and the code of that is here:</p>
<blockquote>
<p>BaseModal.vue:</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
  <div class="modal-overlay container-fluid p-0">
    <div class="row align-items-center justify-content-center" @click.self="$emit('close')">
      <div class="col-md-6">
        <div class="card">
          <div class="card-body">
            <!-- text and other html comes here in the slot -->
            <!-- ############## -->
            <!-- this is the slot part -->
            <!-- ############## -->
            <slot></slot>
            <div class="card-footer d-flex justify-content-around align-items-center">
              <base-button
              large
              v-if="btnOneText"
              kind = "btn-secondary"
              :textBtn = "btnOneText"
              @click="$emit('close')"
              >
              </base-button>

              <base-button
              large
              v-if="btnTwoText"
              kind = "btn-secondary"
              :textBtn = "btnTwoText"
              @click="popoverFunc"
              @blur="popoverDisable"
              :id="idBtn"
              >
              </base-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BaseButton from './BaseButton.vue';
import bootstrap from "bootstrap/dist/js/bootstrap.bundle.min.js";

export default {
  // $emit('submitForm'),
  name: "BaseModal",
  props: {
    btnOneText: {
      type: String
    },
    btnTwoText: {
      type: String
    },
    popoverVue: {
      type: Boolean
    },
    idBtn: {
      type: String
    }
  },
  computed: {
    popOverData: function () {
      return this.popoverVue;
    },
    popVar: function() {
      return new bootstrap.Popover(document.getElementById(this.idBtn), {
            trigger: "manual",
            title: "Notice:",
            content: "Please fill all fields in the correct way to submit your information!",
            customClass: "myPopover",
            placement: "top"
          })
    }
  },
  data() {
      return {
          showPopOver: false
      }
  },
  emits: ["close", "submitForm"],
  components: {
    BaseButton
  },
  watch: {
    popOverData: function (newState, oldState) {
      if(newState === true) {
        this.showPopOver = true;
        this.popoverFinal();
      } else {
        this.showPopOver = false;
        this.popoverFinal();
      }
    }
  },
  methods: {
    popoverFunc: function() {
      this.$emit('submitForm');
      if (this.popOverData) {
        this.showPopOver = true;
        this.popoverFinal();
      }
    },
    popoverDisable: function() {
      console.log("popoverDisable");
      this.showPopOver = false;
      this.popoverFinal();
    },
    popoverFinal: function() {
      console.log(this.showPopOver);
      /* this function is responsible for showing and hiding the popover according to "showPopOver" data */
      if (this.showPopOver) {
        this.popVar.show();
      } else {
        this.popVar.hide();
      }
    }
  }

};
</script>

<style scoped src="../assets/css/compoStyles/baseModal.css"></style></code>```

There are some codes that are not related to this question and also I tried to simplify the codes and clarify the parts that are related to transition and slot in my components code.

Although the codes may seem long or complicated, the goal that I want to reach is simple. I want to submit a register form in a modal component. Actually the user in my app clicks on register button and then the BaseModal.vue component is shown. In that case the register form (that for simplicity I substitute that with a h4 tag) is the default thing that user could see. After submitting the form according that the process is successful or there is an error, I want to show a message to the user and change the text of button from submit to try again if there is an error. After that when the user clicks try again button the form (h4 tag) must be fade in again. So I tried the v-if/v-else-if/v-else structure of Vue in my loginRegister.vue component. The code that I used in transition part is similar to the code that Vue documentation is used, But the transition does not work correctly. In my local development environment, the h4 tag disappears smoothly and then no message is shown, after clicking try again the h4 tag fade in again. Also in the console I could see this warning:

```<code>[Vue warn]: <transition> can only be used on a single element or component. Use <transition-group> for lists.
  at <BaseTransition mode=undefined appear=false persisted=false  ... >
  at <Transition name="fade" >
  at <BaseModal idBtn="regis" btnOneText="Cancel" btnTwoText="Try again"  ... >
  at <LoginRegister>
  at <App>
</code>```

But I don't think that is related to my issue, because I did not use transition on multi elements in my app. So could anyone please help me that what is wrong in my codes?

答: It seems like you want baseModal.vue to be inside loginRegister.vue and the baseModal to have some kind of transition whenever some state changes? Try changing <transition></transition> into <transition-group></transition-group>

Body:
I am building a Vue app. I have two components that are related to each other. One of them is called loginRegister.vue and the code of that is here:

loginRegister.vue:

<template>
<BaseModal idBtn = "regis" btnOneText="Cancel" :btnTwoText="button2Text['register']" v-show="showModal1" @close="showModal1 = false" @submitForm="registerUser(regLogPara['register'])" :popoverVue = "showToolTip.register">

  <transition name="fade">

Create Your Account

you succeed

there is an error!

  </transition>
</BaseModal>
</template>

The other one called BaseModal.vue and the code of that is here:

BaseModal.vue:

<template>

            <slot></slot>

              <base-button
              large
              v-if="btnOneText"
              kind = "btn-secondary"
              :textBtn = "btnOneText"
              @click="$emit('close')"
              >
              </base-button>

              <base-button
              large
              v-if="btnTwoText"
              kind = "btn-secondary"
              :textBtn = "btnTwoText"
              @click="popoverFunc"
              @blur="popoverDisable"
              :id="idBtn"
              >
              </base-button>

</template>

There are some codes that are not related to this question and also I tried to simplify the codes and clarify the parts that are related to transition and slot in my components code.

Although the codes may seem long or complicated, the goal that I want to reach is simple. I want to submit a register form in a modal component. Actually the user in my app clicks on register button and then the BaseModal.vue component is shown. In that case the register form (that for simplicity I substitute that with a h4 tag) is the default thing that user could see. After submitting the form according that the process is successful or there is an error, I want to show a message to the user and change the text of button from submit to try again if there is an error. After that when the user clicks try again button the form (h4 tag) must be fade in again. So I tried the v-if/v-else-if/v-else structure of Vue in my loginRegister.vue component. The code that I used in transition part is similar to the code that Vue documentation is used, But the transition does not work correctly. In my local development environment, the h4 tag disappears smoothly and then no message is shown, after clicking try again the h4 tag fade in again. Also in the console I could see this warning:

[Vue warn]: <transition> can only be used on a single element or component. Use <transition-group> for lists.
  at <BaseTransition mode=undefined appear=false persisted=false  ... >
  at <Transition name="fade" >
  at <BaseModal idBtn="regis" btnOneText="Cancel" btnTwoText="Try again"  ... >
  at <LoginRegister>
  at <App>

But I don't think that is related to my issue, because I did not use transition on multi elements in my app. So could anyone please help me that what is wrong in my codes?


问:
How to set android layout height to x% of its parent height?
I would like to create this simple layout:

I wrote this:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/purple_200">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.3"
        android:background="@color/black" />

</LinearLayout>
</code>```

But doing so I don't see any black view appearing. What am I missing?

答:
There is a new way called ConstraintLayout which is preferred. You can use layout_constraintHeight_percent property of it.

Example

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purple_200"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Output:

Body:
I would like to create this simple layout:

I wrote this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/purple_200">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.3"
        android:background="@color/black" />

</LinearLayout>

But doing so I don't see any black view appearing. What am I missing?

Body:
There is a new way called ConstraintLayout which is preferred. You can use layout_constraintHeight_percent property of it.

Example

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purple_200"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output:


问:
Setup vite --template react and eslint (airbnb)
I'm trying to configure a project using vite.js and airbnb eslint setup.
I would like a "create-react-app"-kind of workflow where the linting is made every time the server starts/restarts, but I'm having a lot of trouble in doing so. To make things work I followed this video in particular: https://www.youtube.com/watch?v=cSl12yjFgDo. They use @rollup/plugin-eslint to achieve linting on every server restart, with the option { enforce: "pre" }, but it's absolutely not working for me. I have 200+ linting errors from files internal to vite.
This is my vite.config.js:

```<code>import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import eslint from '@rollup/plugin-eslint';

export default defineConfig({
  plugins: [react(), { ...eslint(), enforce: 'pre' }],
});
</code>```

This my .eslintrc.js

```<code>module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ['airbnb', 'airbnb/hooks'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: [],
  rules: {},
};
</code>```

As you can see it's all very minimal at the moment.
Can you please point me towards the right direction?

答:
I would suggest using vite-plugin-eslint plugin to run eslint on vite server restart.
Here a example config which is working fine here on a vite react ts project.

vite.config.ts

```<code>import { defineConfig } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import eslint from 'vite-plugin-eslint';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [eslint(), reactRefresh()],
});
</code>```

package.json

```<code>{
  "name": "vitetest",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },
  "dependencies": {
    "@vitejs/plugin-react-refresh": "^1.3.6",
    "react": "^17.0.0",
    "react-dom": "^17.0.0",
    "vite-plugin-eslint": "^1.3.0"
  },
  "devDependencies": {
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@typescript-eslint/eslint-plugin": "^5.10.2",
    "@typescript-eslint/parser": "^5.10.2",
    "@vitejs/plugin-react": "^1.0.0",
    "eslint": "^8.8.0",
    "eslint-plugin-react": "^7.28.0",
    "typescript": "^4.3.2",
    "vite": "^2.6.4"
  }
}
</code>```

.eslintrc.json

```<code>{
    "root": true,
    "env": {
      "node": true,
      "browser": true
    },
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
      "ecmaVersion": 2021,
      "sourceType": "module",
      "ecmaFeatures": {
        "jsx": true
      }
    },
    "extends": [
      "plugin:react/recommended",
      "plugin:@typescript-eslint/recommended"    ],
      "rules": {
        // suppress errors for missing 'import React' in files
       "react/react-in-jsx-scope": "off",
       "semi": [2, "always"]
      }
  }
</code>```

Body:
I'm trying to configure a project using vite.js and airbnb eslint setup.
I would like a "create-react-app"-kind of workflow where the linting is made every time the server starts/restarts, but I'm having a lot of trouble in doing so. To make things work I followed this video in particular: https://www.youtube.com/watch?v=cSl12yjFgDo. They use @rollup/plugin-eslint to achieve linting on every server restart, with the option { enforce: "pre" }, but it's absolutely not working for me. I have 200+ linting errors from files internal to vite.
This is my vite.config.js:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import eslint from '@rollup/plugin-eslint';

export default defineConfig({
  plugins: [react(), { ...eslint(), enforce: 'pre' }],
});

This my .eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ['airbnb', 'airbnb/hooks'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: [],
  rules: {},
};

As you can see it's all very minimal at the moment.
Can you please point me towards the right direction?

Body:
I would suggest using vite-plugin-eslint plugin to run eslint on vite server restart.
Here a example config which is working fine here on a vite react ts project.

vite.config.ts

import { defineConfig } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import eslint from 'vite-plugin-eslint';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [eslint(), reactRefresh()],
});

package.json

{
  "name": "vitetest",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },
  "dependencies": {
    "@vitejs/plugin-react-refresh": "^1.3.6",
    "react": "^17.0.0",
    "react-dom": "^17.0.0",
    "vite-plugin-eslint": "^1.3.0"
  },
  "devDependencies": {
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@typescript-eslint/eslint-plugin": "^5.10.2",
    "@typescript-eslint/parser": "^5.10.2",
    "@vitejs/plugin-react": "^1.0.0",
    "eslint": "^8.8.0",
    "eslint-plugin-react": "^7.28.0",
    "typescript": "^4.3.2",
    "vite": "^2.6.4"
  }
}

.eslintrc.json

{
    "root": true,
    "env": {
      "node": true,
      "browser": true
    },
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
      "ecmaVersion": 2021,
      "sourceType": "module",
      "ecmaFeatures": {
        "jsx": true
      }
    },
    "extends": [
      "plugin:react/recommended",
      "plugin:@typescript-eslint/recommended"    ],
      "rules": {
        // suppress errors for missing 'import React' in files
       "react/react-in-jsx-scope": "off",
       "semi": [2, "always"]
      }
  }


问:
Very basic JSON question
I have this JSON data:

```<code>var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];
</code>```

How can I loop through all the objects inside people and output their names along with their ages like so:

```<code>John 25
Jame 49
followed by the rest...
</code>```

答:
I'd use forEach:

```<code>people.forEach(function(person) {
    console.log(person.name, person.age)
});
</code>```

Title: Very basic JSON question

Body:
I have this JSON data:

var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

How can I loop through all the objects inside people and output their names along with their ages like so:

John 25
Jame 49
followed by the rest...

Body:
I'd use forEach:

people.forEach(function(person) {
    console.log(person.name, person.age)
});


问:
zip the files and folders inside a parent directory without including the parent directory + Amazon Linux
Is there a Linux command to zip the files and folders inside a parent directory without including the parent directory.
From all the solutions that I tried, the parent directory also is getting zipped</p>

答:
Move into the folder, then zip :

```<code>cd my-folder
zip -r ../my-archive.zip *
</code>```

Dirty, but effective

Or, in a more fancy way, using tar:

```<code>tar czf my-archive.tar.gz -C /path/to/my-foder/ ./
</code>```

Body:
Move into the folder, then zip :

cd my-folder
zip -r ../my-archive.zip *

Dirty, but effective

Or, in a more fancy way, using tar:

tar czf my-archive.tar.gz -C /path/to/my-foder/ ./


问:
if condition is not working in django post request
I'm check null values from the request but creating record on null after put the condition in views you can check my code.

```<code>if request.method == 'POST':
    category_id = request.POST['category_id ']
    text1       = request.POST['text1']
    text2       = request.POST['text2']
    text3       = request.POST['text3']

    product = Product(category_id=category_id, text=text1)
    product.save()

    if text2 is not None:
        product = Product(category_id=category_id, text=text2)
        product.save()

    if text3 is not None:
        product = Product(category_id=category_id, text=text3)
        product.save()
</code>```

The text2 and text3 I'm sending null but creating in the database I'm not understanding why these are creating. Thanks

答: I might be inclined to use if len(text2) > 0: or just if text2.  You might be getting empty strings "" in the POST data so your tests are always True.

Body:
I'm check null values from the request but creating record on null after put the condition in views you can check my code.

if request.method == 'POST':
    category_id = request.POST['category_id ']
    text1       = request.POST['text1']
    text2       = request.POST['text2']
    text3       = request.POST['text3']

    product = Product(category_id=category_id, text=text1)
    product.save()

    if text2 is not None:
        product = Product(category_id=category_id, text=text2)
        product.save()

    if text3 is not None:
        product = Product(category_id=category_id, text=text3)
        product.save()

The text2 and text3 I'm sending null but creating in the database I'm not understanding why these are creating. Thanks


问:
selecting a specific container without a class
I'm having problems with my coding-challange where im not allowed to use :nth-child, +, ~ or the data-target in the css. I also cannot edit the HTML. Is there any solution to get the second element in the
 without the syntax above?
Thanks for the help

```<code><article id="task-2">
        <div class="marble"></div>
        <section>
          <div class="marble"></div>
          <div class="marble" data-target></div>
        </section>
        <div class="marble"></div>
      </article>
</code>```

答:
Since you can't use nth-child, the closest to it that you can select is nth-of-type, so you can do the following:

section div {
  height: 30px;
  border: solid 1px yellow;
}
section div:nth-of-type(2) {
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article id="task-2">
        <div class="marble"></div>
        <section>
          <div class="marble"></div>
          <div class="marble" data-target></div>
        </section>
        <div class="marble"></div>
      </article></code>```

Read more about this selector here:
https://www.w3schools.com/cssref/sel_nth-of-type.asp

Body:
Since you can't use nth-child, the closest to it that you can select is nth-of-type, so you can do the following:

section div {
  height: 30px;
  border: solid 1px yellow;
}
section div:nth-of-type(2) {
  background-color: blue;
}

<article id="task-2">
        <div class="marble"></div>
        <section>
          <div class="marble"></div>
          <div class="marble" data-target></div>
        </section>
        <div class="marble"></div>
      </article>

Read more about this selector here:
https://www.w3schools.com/cssref/sel_nth-of-type.asp


问:
Inserting an HTML fragment into a WPF FlowDocument
I'm dynamically building a WPF FlowDocument from a datasource.  One of the data elements is a fragment of HTML - I need to figure out a way to parse that and insert it into my FlowDocument.

I've found HTMLToXAMLConverter which will return a XAML representation of the HTML, but I'm still not sure how to best go about instantiating that XAML fragment so I can insert it into my FlowDocument.

答:
Had same problem, but had to solve databinding problems as well

Had a convector that created XAML from string and vice-verse.

OwnerDisplayName: Jason

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Daniil Harik


答:
Here is an example using jquery:

```<code>var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

jQuery.each(people, function(index, person){
console.log([person.name, person.age].join(" ")) ;
});
</code>```

Output:

```<code>John 25
Jane 49
Jim 31
Julie 39
Joe 19
Jack 48
</code>```

Title: Very basic JSON question

Body:
Here is an example using jquery:

var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

jQuery.each(people, function(index, person){
console.log([person.name, person.age].join(" ")) ;
});

Output:

John 25
Jane 49
Jim 31
Julie 39
Joe 19
Jack 48


问:
Passing dependencies the "right way"
When injecting dependencies into a constructor, I'm not quite sure if it breaks SOLID if I do the following:

public MyClass(IConfiguration configuration)
{
    _port = configuration.GetValue("Port");
}
```
<p>instead of passing the pure value like so:</p>
<pre class="lang-cs prettyprint-override"><code>public MyClass(int port)
{
    _port = port;
}
</code>```

The first one seems to be some kind of a Service Locator.

Question here is: Is it okay to pass complex dependencies just to retrieve a single value the class actually relies on?

To me it doesn't look that wrong, but it unnecessarily hides the real dependency which could  get passed much easier.

答:
From perspective of the SOLID principles, I see no clear violation:

Single Responsibility: Whether or not you inject port or IConfiguration doesn't change the number of responsibilities that MyClass has.

Open/Closed: This principle is about preventing sweeping changes. I don't see how injecting port would prevent sweeping changes compared to injecting IConfiguration.

Liskov Substitution: This principle is about letting derivatives behave as their base class specification. Injection of IConfiguration has no impact on LSP.

Interface Segregation: This principle pushes towards the use of narrow interfaces. This is a bit more tricky, and a closer inspection of the code might be needed to see whether IConfiguration is wide and violates ISP. From just this code, however, I would say there is no ISP problem.

Dependency Inversion: This principle states that we should program to abstractions, and -almost as importantly- it states that the client should own the abstraction. In case IConfiguration is a framework-defined abstraction, we might consider this code to violate the DIP. But it's not always possible or feasible to remove all dependencies to framework abstractions, so we should be pragmatic. Whether or not it is pragmatic to take a dependency on IConfiguration is impossible to say in your case.

There is, however, other guidance besides the SOLID principles that might help us out here:

The injection constructor's body should be simple: When it comes to DI, the rule is that an Injection Constructor should do no more than receiving the dependencies. It should not use it. The MyClass constructor, however, is using IConfiguration inside the constructor.

The injection constructor's definition should be minimal: An injection constructor should only be provided with just the dependencies it requires to function. It's a sort of an ISP for constructors and relates to Nikola’s 4th law of IoC. In this case you are providing an interface (IConfiguration) with broad capabilities. In your question you are referring to the Service Locator anti-pattern in this regards. Although injecting IConfiguration can certainly not be regarded as a Service Locator, from loading configuration values, IConfiguration as similar capabilities. It's better to narrow this down and be as explicit as possible and int port is much more explicit compared to IConfiguration.

So with all that in place, let me try to answer your question:

Is it okay to pass complex dependencies just to retrieve a single value the class actually relies on?

Considering the guidance on DI above, I would say that it is better to either inject int port, or a typed configuration class that wraps int port, that is specific to MyClass; e.g. MyClassSettings:

public MyClass(MyClassSettings settings)
{
    _settings = settings;
}
```

Both convey the same amount of information, but the latter is less ambiguous, as int could mean anything, while MyClassSettings is very precise and easily resolved from a DI Container.

Title: Passing dependencies the "right way"

Body:
When injecting dependencies into a constructor, I'm not quite sure if it breaks SOLID if I do the following:

public MyClass(IConfiguration configuration)
{
    _port = configuration.GetValue("Port");
}

instead of passing the pure value like so:

public MyClass(int port)
{
    _port = port;
}

The first one seems to be some kind of a Service Locator.

Question here is: Is it okay to pass complex dependencies just to retrieve a single value the class actually relies on?

To me it doesn't look that wrong, but it unnecessarily hides the real dependency which could  get passed much easier.

Body:
From perspective of the SOLID principles, I see no clear violation:

Single Responsibility: Whether or not you inject port or IConfiguration doesn't change the number of responsibilities that MyClass has.

Open/Closed: This principle is about preventing sweeping changes. I don't see how injecting port would prevent sweeping changes compared to injecting IConfiguration.

Liskov Substitution: This principle is about letting derivatives behave as their base class specification. Injection of IConfiguration has no impact on LSP.

Interface Segregation: This principle pushes towards the use of narrow interfaces. This is a bit more tricky, and a closer inspection of the code might be needed to see whether IConfiguration is wide and violates ISP. From just this code, however, I would say there is no ISP problem.

Dependency Inversion: This principle states that we should program to abstractions, and -almost as importantly- it states that the client should own the abstraction. In case IConfiguration is a framework-defined abstraction, we might consider this code to violate the DIP. But it's not always possible or feasible to remove all dependencies to framework abstractions, so we should be pragmatic. Whether or not it is pragmatic to take a dependency on IConfiguration is impossible to say in your case.

There is, however, other guidance besides the SOLID principles that might help us out here:

The injection constructor's body should be simple: When it comes to DI, the rule is that an Injection Constructor should do no more than receiving the dependencies. It should not use it. The MyClass constructor, however, is using IConfiguration inside the constructor.

The injection constructor's definition should be minimal: An injection constructor should only be provided with just the dependencies it requires to function. It's a sort of an ISP for constructors and relates to Nikola’s 4th law of IoC. In this case you are providing an interface (IConfiguration) with broad capabilities. In your question you are referring to the Service Locator anti-pattern in this regards. Although injecting IConfiguration can certainly not be regarded as a Service Locator, from loading configuration values, IConfiguration as similar capabilities. It's better to narrow this down and be as explicit as possible and int port is much more explicit compared to IConfiguration.

So with all that in place, let me try to answer your question:

Is it okay to pass complex dependencies just to retrieve a single value the class actually relies on?

Considering the guidance on DI above, I would say that it is better to either inject int port, or a typed configuration class that wraps int port, that is specific to MyClass; e.g. MyClassSettings:

public MyClass(MyClassSettings settings)
{
    _settings = settings;
}

Both convey the same amount of information, but the latter is less ambiguous, as int could mean anything, while MyClassSettings is very precise and easily resolved from a DI Container.


问:
Thread Synchronization C# - I want to execute one process ( async) and then after execute another process(async)
I have two process write and read. I want to complete write process asynchronously using 10 threads and after all thread complete writing. I want to start 5 threads for Reading Process. How to check writing all threads finished its task so that I can signal main thread to start reading process asynchronously by using 5 threads.</p>
```<code>    public static void MainThread()
    {

        new Thread(() => WriterThread(10)).Start();
        a_ResetEvent.WaitOne();
        new Thread(() => ReadWorkerThread(5)).Start();

    }

    public static void WriterThread(int _noThread)
    {
        Thread t = null;

        for (int i = 0; i < _noThread; i++)
        {
          t =  new Thread(() => Write());
          t.Start();
        }

        if(t.ThreadState != ThreadState.Running)
        a_ResetEvent.Set();
    }

    public static void ReadWorkerThread(int _noThread)
    {
        for (int i = 0; i < _noThread; i++)
        {
            new Thread(() => Read()).Start();
        }
    }

    public static void Write()
    {
        Console.WriteLine($"Writing Thread- {Thread.CurrentThread.ManagedThreadId}");
        Thread.Sleep(5000);
        Console.WriteLine($"Writing Completed Thread -{Thread.CurrentThread.ManagedThreadId}");

    }

    public static void Read()
    {
        Console.WriteLine($"Reading Thread - {Thread.CurrentThread.ManagedThreadId}");
        Thread.Sleep(1000);
        Console.WriteLine($"Reading Completed Thread - {Thread.CurrentThread.ManagedThreadId}");
    }
</code>```

答:
The simplest option would be to use Parallel.For loops.

But without more information it is difficult to tell if this is a good idea or not. IO operations typically do not benefit much from parallelism, and running things in parallel requires your program to be thread safe, and that may make your program more complicated, or risks introducing bugs.

Body:
I have two process write and read. I want to complete write process asynchronously using 10 threads and after all thread complete writing. I want to start 5 threads for Reading Process. How to check writing all threads finished its task so that I can signal main thread to start reading process asynchronously by using 5 threads.

    public static void MainThread()
    {

        new Thread(() => WriterThread(10)).Start();
        a_ResetEvent.WaitOne();
        new Thread(() => ReadWorkerThread(5)).Start();

    }

    public static void WriterThread(int _noThread)
    {
        Thread t = null;

        for (int i = 0; i < _noThread; i++)
        {
          t =  new Thread(() => Write());
          t.Start();
        }

        if(t.ThreadState != ThreadState.Running)
        a_ResetEvent.Set();
    }

    public static void ReadWorkerThread(int _noThread)
    {
        for (int i = 0; i < _noThread; i++)
        {
            new Thread(() => Read()).Start();
        }
    }

    public static void Write()
    {
        Console.WriteLine($"Writing Thread- {Thread.CurrentThread.ManagedThreadId}");
        Thread.Sleep(5000);
        Console.WriteLine($"Writing Completed Thread -{Thread.CurrentThread.ManagedThreadId}");

    }

    public static void Read()
    {
        Console.WriteLine($"Reading Thread - {Thread.CurrentThread.ManagedThreadId}");
        Thread.Sleep(1000);
        Console.WriteLine($"Reading Completed Thread - {Thread.CurrentThread.ManagedThreadId}");
    }


问:
How to change the limitrequestfieldsize in Apache 2.4.2
I'm working with Apache 2.4.2 and I need to change the LimitRequestFieldSize. supposedly (according to some Google researchs) that can be done in the httpd.conf file but I cant find that LimitRequestFieldSize neither the httpd.conf or any file within the Apache. Have any idea how I can do it?</p>

答:
This issue can be solved by updating the directive LimitRequestFieldSize either in the apache httpd.conf or in the virtual hosts.

How to add the prop in the virtual host

```<code><VirtualHost 10.10.50.50:80>
    ServerName www.mysite.com

    LimitRequestFieldSize 16384

    RewriteEngine On
    ...
    ...
</VirtualHost>
</code>```

How to add in the httpd.conf which is inside , apache2/conf/httpd.conf

LimitRequestFieldSize 16384

But even after doing this i am still getting bad request error.

Body:
This issue can be solved by updating the directive LimitRequestFieldSize either in the apache httpd.conf or in the virtual hosts.

How to add the prop in the virtual host

<VirtualHost 10.10.50.50:80>
    ServerName www.mysite.com

    LimitRequestFieldSize 16384

    RewriteEngine On
    ...
    ...
</VirtualHost>

How to add in the httpd.conf which is inside , apache2/conf/httpd.conf

LimitRequestFieldSize 16384

But even after doing this i am still getting bad request error.


答:
In multiplication, the accumulated variable is not called sum. It is called product. The word sum is only used in the context of addition.

Now, on with your problem:

If you remember your elementary school mathematics, anything multiplied by zero gives zero.

That's why you are receiving a zero in the end.

So, in order to fix this, you have to initialize your product with 1 instead of 0, and then make your for loop start counting from index 1 instead of 0.

Title: Multiply numbers for loop java returning 0

Body:
I'm trying to take a number(n) and multiply it by every number before it, enter 4 you get (1x2x3x4) = 24. My code returns a 0. I have an addition just like this that works. Any ideas?

public static int multiplyTooNum()
    {
        Scanner myIn = new Scanner(System.in);
        int n;

        System.out.println("Please enter a number");
        n = myIn.nextInt();
        myIn.nextLine();
        int sum = 0;

        for (int i=0; i<n; i++)
        {
            sum = sum * i;
        }

        int result = sum*n;
        System.out.println(result);
        myIn.close();
        return result;
    }


问:
can I get an entity type using only a guid
I have a process that one of the params been used is a record's guid of a specific entity (always salesorder for example). Now I've been asked to support an other entity (case for example) but I don't want to pass a new param (entity type), I want to use the record's guid to get the entity type, is there an option to get entity type only by guid (c#)</p>

答:
It's not possible to get directly the entity type (or Entity Name if you prefer) from the Guid inside a Dynamics CRM / 365 CE / Dataverse instance.

You can eventually do a try/catch (like a service.Retrieve to salesorder and if fails try against incident) but is an approach I would not suggest if you have other options available.


问:
jQuery css left/right chosen by array
How would I go about doing something like this:

```<code>var positionY = ['left','right'],
    x = Math.ceil(Math.random()*2);

$('#foo').css({positionY[x]: 200});
</code>```

Is it even possible?

Reason being I want to randomise the left/right.

I'm really wanting to use the brackets in the css function, any ideas?

EDIT --

```<code>$('#foo').animate({
   positionX[1]: 300,
   positionY[1]: 300
}, 300);
</code>```

That's the sort of thing I'm after, any ideas?

答:
This should work:

```<code>var positionY = ['left', 'right'];
var randomNumber = Math.floor(Math.random() * positionY.length);

var cssStyle = {};
cssStyle[positionY[randomNumber]] = 200;

$('#foo').css(cssStyle);
</code>```

Actually, I forgot jQuery css() also takes name/value pair, so the following works too:

```<code>var positionY = ['left', 'right'];
var randomNumber = Math.floor(Math.random() * positionY.length);

$('#foo').css(positionY[randomNumber], 200);
</code>```

Title: jQuery css left/right chosen by array

Body:
How would I go about doing something like this:

var positionY = ['left','right'],
    x = Math.ceil(Math.random()*2);

$('#foo').css({positionY[x]: 200});

Is it even possible?

Reason being I want to randomise the left/right.

I'm really wanting to use the brackets in the css function, any ideas?

EDIT --

$('#foo').animate({
   positionX[1]: 300,
   positionY[1]: 300
}, 300);

That's the sort of thing I'm after, any ideas?

Body:
This should work:

var positionY = ['left', 'right'];
var randomNumber = Math.floor(Math.random() * positionY.length);

var cssStyle = {};
cssStyle[positionY[randomNumber]] = 200;

$('#foo').css(cssStyle);

Actually, I forgot jQuery css() also takes name/value pair, so the following works too:

var positionY = ['left', 'right'];
var randomNumber = Math.floor(Math.random() * positionY.length);

$('#foo').css(positionY[randomNumber], 200);


问:
How can I complete the pre departure confirmation of react components (including class components and function components)？
I have searched the answer of this question for many times, and I know this can be solved by the Prompt comnponent in react-router v4. But I use the version 6.x of it. What is the substitution of the component Prompt in v6?

答:
There is no substitution so far: prompt-is-not-currently-supported. Prompt and usePrompt where present up to v6.0.0-beta.6 but were removed in the stable v6 release.

The general advice is to remain on v5 if you really need this feature or re-design your user experience without blocking behaviour.


问:
Git login in eclipse not possible
I want to import a project from an existing git repository in Eclipse via URI. The Problem is that my git password and user are not accepted. I double checked username and password multiple times but nothing happens.

Anyone an idea why this happens?

答:
I encountered the same problem while pushing to GitHub.
The error was Can't connect to any repository: https://github.com/~ (https://github.com/~: not authorized) Seem the error relates to Eclipse not getting authorized.
Instead I turned to Git bash and it worked. I recommend using Git Bash.

Title: Git login in eclipse not possible


问:
JS: adding styles to a div through object.value results in nothing
```<code>let styles1 = {
    margin1: '50px',
    borderRadius1: '20px',
    borderStyle1: 'solid',
    borderWidth1: '10px',
    borderColor1: '#81ecec'
}

let elem = document.createElement('div');
elem.style.margin = styles1.margin1.value + 'px';
elem.style.borderRadius = styles1.borderRadius1.value + 'px';
elem.style.borderStyle = styles1.borderStyle1.value;
elem.style.borderWidth = styles1.borderWidth1.value + 'px';
elem.style.borderColor = styles1.borderColor1.value;
document.body.appendChild(elem);
</code>```

The other part of the code(not mentioned) works perfectly, but for some reason none of the border styles work(and without any errors?). Anyone got any ideas?

答:
There are some things going wrong in your code. When you reference a key in an object like styles1.margin1 it already returns "50px". So there is no need to add a .value. Meaning that you do not need to append a "px" at the end of each style assignment.
This should do the trick:

```<code>let elem = document.createElement('div');
elem.style.margin = styles1.margin1;
elem.style.borderRadius = styles1.borderRadius1;
elem.style.borderStyle = styles1.borderStyle1;
elem.style.borderWidth = styles1.borderWidth1;
elem.style.borderColor = styles1.borderColor1;
document.body.appendChild(elem);
</code>```

Body:
let styles1 = {
    margin1: '50px',
    borderRadius1: '20px',
    borderStyle1: 'solid',
    borderWidth1: '10px',
    borderColor1: '#81ecec'
}

let elem = document.createElement('div');
elem.style.margin = styles1.margin1.value + 'px';
elem.style.borderRadius = styles1.borderRadius1.value + 'px';
elem.style.borderStyle = styles1.borderStyle1.value;
elem.style.borderWidth = styles1.borderWidth1.value + 'px';
elem.style.borderColor = styles1.borderColor1.value;
document.body.appendChild(elem);

The other part of the code(not mentioned) works perfectly, but for some reason none of the border styles work(and without any errors?). Anyone got any ideas?

Body:
There are some things going wrong in your code. When you reference a key in an object like styles1.margin1 it already returns "50px". So there is no need to add a .value. Meaning that you do not need to append a "px" at the end of each style assignment.
This should do the trick:

let elem = document.createElement('div');
elem.style.margin = styles1.margin1;
elem.style.borderRadius = styles1.borderRadius1;
elem.style.borderStyle = styles1.borderStyle1;
elem.style.borderWidth = styles1.borderWidth1;
elem.style.borderColor = styles1.borderColor1;
document.body.appendChild(elem);


问:
Why does QWebFrame::evalutateJavaScript do nothing in this case?
I'm calling QWebFrame::evaluateJavaScript in one place in my code and it has no effect. However, if I replace this call with the setTimer(0) call and will call the original function when this timer times out it works. How do I know if it works or not? The JavaScript code which is evaluated in my case calls one JavaScript function which in turn makes AJAX call. This AJAX call in turn makes QNetworkAccessManager used by QWebFrame create and send a QNetworkRequest. There is no request being created when I call QWebFrame::evalutateJavaScript directly from my code, however. That's what I mean when I say it does not work in the first scenario.

It looks like something is preventing QtWebKit and//or QNetworkAccessManager from carrying out their job after evaluateJavaScript is called. I suspect it has something to do with events and the main (gui) event loop. Any ideas?

答: Do you called evaluateJavaScript before the signal loadFinished was emitted?</p>


问:
How to disable inversify auto-recognition of controller
I want to have two servers, living in the same source tree.  one of the app servers carry a lot of functionality, the other one is more narrowly focused. There are common classes to both and really need to share some source between the two servers.

This doesn't work as inversify/Express is looking through code for its @controller decorator.  As soon as it sees that starts to pull in a lot of dependencies because of dependency injection.

How do we disable/manually enable this auto-recognition of the controller in inversify/Express?

答:
Instead of using the @controller decorator, you can use the function

controller(path, middleware)(SomeClass); to manually create a controller


问:
Slack view_submission Payload block_ids
I'm trying to get the submitted data from a slack modal payload (using Integromat) but I'm unable to match the fields as the field names (block_ids) and random and change on each submission.

Not sure where to start, is there something on the Slack side I can do to stop this or how can I handle this in Integromat?

Payload below:

```<code>{
   "blocks":[
      {
         "type":"header",
         "block_id":"GH6Wh",
         "text":{
            "type":"plain_text",
            "text":"AHome",
            "emoji":true
         }
      },
      {
         "type":"input",
         "block_id":"ayv5",
         "label":{
            "type":"plain_text",
            "text":"Project Title",
            "emoji":true
         },
         "optional":false,
         "dispatch_action":false,
         "element":{
            "type":"plain_text_input",
            "action_id":"field_project_title",
            "dispatch_action_config":{
               "trigger_actions_on":[
                  "on_enter_pressed"
               ]
            }
         }
      },
      {
         "type":"input",
         "block_id":"4Tf7",
         "label":{
            "type":"plain_text",
            "text":"Client Project Contacts",
            "emoji":true
         },
         "optional":false,
         "dispatch_action":false,
         "element":{
            "type":"multi_static_select",
            "action_id":"client_project_contacts",
            "placeholder":{
               "type":"plain_text",
               "text":"Select",
               "emoji":true
            },
            "options":[
               {
                  "text":{
                     "type":"plain_text",
                     "text":"jennifer",
                     "emoji":true
                  },
                  "value":"47dht5f-1942-4448-9842-20fef64dcd67"
               }
            ]
         }
      },
      {
         "type":"divider",
         "block_id":"a=6G"
      },
      {
         "type":"section",
         "block_id":"qtq0W",
         "text":{
            "type":"mrkdwn",
            "text":"Project Start",
            "verbatim":false
         },
         "accessory":{
            "type":"datepicker",
            "action_id":"field_project_start_date",
            "initial_date":"2022-01-19",
            "placeholder":{
               "type":"plain_text",
               "text":"Select a date",
               "emoji":true
            }
         }
      },
      {
         "type":"section",
         "block_id":"4YOTI",
         "text":{
            "type":"mrkdwn",
            "text":"Project Finish",
            "verbatim":false
         },
         "accessory":{
            "type":"datepicker",
            "action_id":"field_project_end_date",
            "initial_date":"2022-03-19",
            "placeholder":{
               "type":"plain_text",
               "text":"Select a date",
               "emoji":true
            }
         }
      },
      {
         "type":"divider",
         "block_id":"MZU"
      },
      {
         "type":"input",
         "block_id":"v09",
         "label":{
            "type":"plain_text",
            "text":"Project Manager",
            "emoji":true
         },
         "optional":false,
         "dispatch_action":false,
         "element":{
            "type":"static_select",
            "action_id":"field_project_managers",
            "placeholder":{
               "type":"plain_text",
               "text":"Select",
               "emoji":true
            },
            "options":[
               {
                  "text":{
                     "type":"plain_text",
                     "text":"Eric ",
                     "emoji":true
                  },
                  "value":"b85ba51b-2346-481f-98a8-2b94fh994575"
               }
            ]
         }
      },
      {
         "type":"input",
         "block_id":"gxN9",
         "label":{
            "type":"plain_text",
            "text":"Project Team",
            "emoji":true
         },
         "optional":false,
         "dispatch_action":false,
         "element":{
            "type":"multi_static_select",
            "action_id":"field_project_team",
            "placeholder":{
               "type":"plain_text",
               "text":"Select",
               "emoji":true
            },
            "options":[

            ]
         }
      },
      {
         "type":"divider",
         "block_id":"CU1k"
      },
      {
         "type":"input",
         "block_id":"ows",
         "label":{
            "type":"plain_text",
            "text":"Setup apps",
            "emoji":true
         },
         "optional":true,
         "dispatch_action":false,
         "element":{
            "type":"checkboxes",
            "action_id":"setup_apps",
            "options":[
               {
                  "text":{
                     "type":"plain_text",
                     "text":"Harvest",
                     "emoji":true
                  },
                  "value":"setup_harvest"
               },
               {
                  "text":{
                     "type":"plain_text",
                     "text":"Dropbox Project Folder",
                     "emoji":true
                  },
                  "value":"setup_dropbox"
               }
            ]
         }
      },
      {
         "type":"divider",
         "block_id":"Eov"
      }
   ],
   "private_metadata":"",
   "callback_id":"_project_setup_form_submit",
   "state":{
      "values":{
         "ayv5":{
            "field_project_title":{
               "type":"plain_text_input",
               "value":"cvgf"
            }
         },
         "4Tf7":{
            "client_project_contacts":{
               "type":"multi_static_select",
               "selected_options":[
                  {
                     "text":{
                        "type":"plain_text",
                        "text":"Jennifer",
                        "emoji":true
                     },
                     "value":"04a96f00-c84d-403c-992f-28fgh34b7ade"
                  }
               ]
            }
         },
         "qtq0W":{
            "field_project_start_date":{
               "type":"datepicker",
               "selected_date":"2022-01-19"
            }
         },
         "4YOTI":{
            "field_project_end_date":{
               "type":"datepicker",
               "selected_date":"2022-03-19"
            }
         },
         "v09":{
            "field_project_managers":{
               "type":"static_select",
               "selected_option":{
                  "text":{
                     "type":"plain_text",
                     "text":"Eric",
                     "emoji":true
                  },
                  "value":"b85ba51b-2346-481f-9sa8-2b9468994575"
               }
            }
         },
         "gxN9":{
            "field_project_team":{
               "type":"multi_static_select",
               "selected_options":[
                  {
                     "text":{
                        "type":"plain_text",
                        "text":"Elliot",
                        "emoji":true
                     },
                     "value":"94c4b483-fbg8-4211-971d-38cf615fdc5e"
                  }
               ]
            }
         },
         "ows":{
            "setup_apps":{
               "type":"checkboxes",
               "selected_options":[
                  {
                     "text":{
                        "type":"plain_text",
                        "text":"Harvest",
                        "emoji":true
                     },
                     "value":"setup_harvest"
                  }
               ]
            }
         }
      }
   }
}
</code>```

答:
When creating a view, you can (but aren't required to) specify a "block_id" as a property for each block. When an ID isn't provided, it seems to be randomly-generated each time.

Example:

```<code>{
  "type": "modal",
  "callback_id": "modal-identifier",
  "title": {
    "type": "plain_text",
    "text": "Just a modal"
  },
  "blocks": [
    {
      "type": "section",
      "block_id": "section-identifier",
      "text": {
        "type": "mrkdwn",
        "text": "*Welcome* to ~my~ Block Kit _modal_!"
      },
      "accessory": {
        "type": "button",
        "block_id": "just-a-button",
        "text": {
          "type": "plain_text",
          "text": "Just a button",
        },
        "action_id": "button-identifier",
      }
    }
  ],
}
</code>```

Source, and I added a second "block_id" for the button.

Title: Slack view_submission Payload block_ids

Body:
I'm trying to get the submitted data from a slack modal payload (using Integromat) but I'm unable to match the fields as the field names (block_ids) and random and change on each submission.

Not sure where to start, is there something on the Slack side I can do to stop this or how can I handle this in Integromat?

Payload below:

{
   "blocks":[
      {
         "type":"header",
         "block_id":"GH6Wh",
         "text":{
            "type":"plain_text",
            "text":"AHome",
            "emoji":true
         }
      },
      {
         "type":"input",
         "block_id":"ayv5",
         "label":{
            "type":"plain_text",
            "text":"Project Title",
            "emoji":true
         },
         "optional":false,
         "dispatch_action":false,
         "element":{
            "type":"plain_text_input",
            "action_id":"field_project_title",
            "dispatch_action_config":{
               "trigger_actions_on":[
                  "on_enter_pressed"
               ]
            }
         }
      },
      {
         "type":"input",
         "block_id":"4Tf7",
         "label":{
            "type":"plain_text",
            "text":"Client Project Contacts",
            "emoji":true
         },
         "optional":false,
         "dispatch_action":false,
         "element":{
            "type":"multi_static_select",
            "action_id":"client_project_contacts",
            "placeholder":{
               "type":"plain_text",
               "text":"Select",
               "emoji":true
            },
            "options":[
               {
                  "text":{
                     "type":"plain_text",
                     "text":"jennifer",
                     "emoji":true
                  },
                  "value":"47dht5f-1942-4448-9842-20fef64dcd67"
               }
            ]
         }
      },
      {
         "type":"divider",
         "block_id":"a=6G"
      },
      {
         "type":"section",
         "block_id":"qtq0W",
         "text":{
            "type":"mrkdwn",
            "text":"Project Start",
            "verbatim":false
         },
         "accessory":{
            "type":"datepicker",
            "action_id":"field_project_start_date",
            "initial_date":"2022-01-19",
            "placeholder":{
               "type":"plain_text",
               "text":"Select a date",
               "emoji":true
            }
         }
      },
      {
         "type":"section",
         "block_id":"4YOTI",
         "text":{
            "type":"mrkdwn",
            "text":"Project Finish",
            "verbatim":false
         },
         "accessory":{
            "type":"datepicker",
            "action_id":"field_project_end_date",
            "initial_date":"2022-03-19",
            "placeholder":{
               "type":"plain_text",
               "text":"Select a date",
               "emoji":true
            }
         }
      },
      {
         "type":"divider",
         "block_id":"MZU"
      },
      {
         "type":"input",
         "block_id":"v09",
         "label":{
            "type":"plain_text",
            "text":"Project Manager",
            "emoji":true
         },
         "optional":false,
         "dispatch_action":false,
         "element":{
            "type":"static_select",
            "action_id":"field_project_managers",
            "placeholder":{
               "type":"plain_text",
               "text":"Select",
               "emoji":true
            },
            "options":[
               {
                  "text":{
                     "type":"plain_text",
                     "text":"Eric ",
                     "emoji":true
                  },
                  "value":"b85ba51b-2346-481f-98a8-2b94fh994575"
               }
            ]
         }
      },
      {
         "type":"input",
         "block_id":"gxN9",
         "label":{
            "type":"plain_text",
            "text":"Project Team",
            "emoji":true
         },
         "optional":false,
         "dispatch_action":false,
         "element":{
            "type":"multi_static_select",
            "action_id":"field_project_team",
            "placeholder":{
               "type":"plain_text",
               "text":"Select",
               "emoji":true
            },
            "options":[

            ]
         }
      },
      {
         "type":"divider",
         "block_id":"CU1k"
      },
      {
         "type":"input",
         "block_id":"ows",
         "label":{
            "type":"plain_text",
            "text":"Setup apps",
            "emoji":true
         },
         "optional":true,
         "dispatch_action":false,
         "element":{
            "type":"checkboxes",
            "action_id":"setup_apps",
            "options":[
               {
                  "text":{
                     "type":"plain_text",
                     "text":"Harvest",
                     "emoji":true
                  },
                  "value":"setup_harvest"
               },
               {
                  "text":{
                     "type":"plain_text",
                     "text":"Dropbox Project Folder",
                     "emoji":true
                  },
                  "value":"setup_dropbox"
               }
            ]
         }
      },
      {
         "type":"divider",
         "block_id":"Eov"
      }
   ],
   "private_metadata":"",
   "callback_id":"_project_setup_form_submit",
   "state":{
      "values":{
         "ayv5":{
            "field_project_title":{
               "type":"plain_text_input",
               "value":"cvgf"
            }
         },
         "4Tf7":{
            "client_project_contacts":{
               "type":"multi_static_select",
               "selected_options":[
                  {
                     "text":{
                        "type":"plain_text",
                        "text":"Jennifer",
                        "emoji":true
                     },
                     "value":"04a96f00-c84d-403c-992f-28fgh34b7ade"
                  }
               ]
            }
         },
         "qtq0W":{
            "field_project_start_date":{
               "type":"datepicker",
               "selected_date":"2022-01-19"
            }
         },
         "4YOTI":{
            "field_project_end_date":{
               "type":"datepicker",
               "selected_date":"2022-03-19"
            }
         },
         "v09":{
            "field_project_managers":{
               "type":"static_select",
               "selected_option":{
                  "text":{
                     "type":"plain_text",
                     "text":"Eric",
                     "emoji":true
                  },
                  "value":"b85ba51b-2346-481f-9sa8-2b9468994575"
               }
            }
         },
         "gxN9":{
            "field_project_team":{
               "type":"multi_static_select",
               "selected_options":[
                  {
                     "text":{
                        "type":"plain_text",
                        "text":"Elliot",
                        "emoji":true
                     },
                     "value":"94c4b483-fbg8-4211-971d-38cf615fdc5e"
                  }
               ]
            }
         },
         "ows":{
            "setup_apps":{
               "type":"checkboxes",
               "selected_options":[
                  {
                     "text":{
                        "type":"plain_text",
                        "text":"Harvest",
                        "emoji":true
                     },
                     "value":"setup_harvest"
                  }
               ]
            }
         }
      }
   }
}

Body:
When creating a view, you can (but aren't required to) specify a "block_id" as a property for each block. When an ID isn't provided, it seems to be randomly-generated each time.

Example:

{
  "type": "modal",
  "callback_id": "modal-identifier",
  "title": {
    "type": "plain_text",
    "text": "Just a modal"
  },
  "blocks": [
    {
      "type": "section",
      "block_id": "section-identifier",
      "text": {
        "type": "mrkdwn",
        "text": "*Welcome* to ~my~ Block Kit _modal_!"
      },
      "accessory": {
        "type": "button",
        "block_id": "just-a-button",
        "text": {
          "type": "plain_text",
          "text": "Just a button",
        },
        "action_id": "button-identifier",
      }
    }
  ],
}

Source, and I added a second "block_id" for the button.


问:
Remove characters from the last column of a list of data frame
I have a list listDF of 30 data frames (~1000 rows X 3 columns). In the last column of each one, I have a composite character as shown below :

```<code>Date        Origin              Chemical
28/10/2012  Artificial nuclides Cs-137__Sea
28/10/2012  Natural nuclides    Ra-226__Clouds
28/10/2012  Natural nuclides    Ra-228__Sands
28/10/2012  Natural nuclides    Th-228__Sea
28/10/2012  Artificial nuclides Cs-137__Rocks
</code>```

For the last column of each df, how can I simply remove "__Sea", "__Clouds"... and just keep the chemical name ?

答:
This may also be done with trimws from base R

```<code>listDF <- lapply(listDF, transform,
      Chemical = trimws(Chemical, whitespace = "__.*"))
</code>```

Or in tidyverse

```<code>library(stringr)
library(purrr)
library(dplyr)
listDF <- map(listDF, mutate, Chemical = str_remove(Chemical, "__.*"))
</code>```

Body:
I have a list listDF of 30 data frames (~1000 rows X 3 columns). In the last column of each one, I have a composite character as shown below :

Date        Origin              Chemical
28/10/2012  Artificial nuclides Cs-137__Sea
28/10/2012  Natural nuclides    Ra-226__Clouds
28/10/2012  Natural nuclides    Ra-228__Sands
28/10/2012  Natural nuclides    Th-228__Sea
28/10/2012  Artificial nuclides Cs-137__Rocks

For the last column of each df, how can I simply remove "__Sea", "__Clouds"... and just keep the chemical name ?

Body:
This may also be done with trimws from base R

listDF <- lapply(listDF, transform,
      Chemical = trimws(Chemical, whitespace = "__.*"))

Or in tidyverse

library(stringr)
library(purrr)
library(dplyr)
listDF <- map(listDF, mutate, Chemical = str_remove(Chemical, "__.*"))


问:
Git: Pushing to a branch that has changes that aren't local
I am trying to push to a repo that some merged in changes not in my local.

```<code>error: failed to push some refs to 'git@git.corp.myrepo'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
</code>```

I remember using in the past a way to pull using rebase to resolve this easily where it would pull and also merge your commits.

What is the best way to resolve this?

答:
It looks like someone push new commits to the remote repository after you cloned it

to solve the issue you need to pull the commits made by others by using git pull , and then solve any conflicts if they appear, and only then you can push your changes to the remote repository

another way is to force the push by git push -f , but this is not recommended as it will throw conflict for others

Body:
I am trying to push to a repo that some merged in changes not in my local.

error: failed to push some refs to 'git@git.corp.myrepo'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing

I remember using in the past a way to pull using rebase to resolve this easily where it would pull and also merge your commits.

What is the best way to resolve this?


问:
Deleting html element from webview in flutter
I tried to remove element dynamically but the removed element still shows up on screen, and is removed when clicked on the element.

here is the code i used

```<code> onPageFinished: (url){
        removeAds(url);
      },
 void removeAds(String url){
      print("asdjkhjahsdk");
      //_controller.loadUrl('javascript: var ad= document.getElementById("_b04pct_2709847"); ad.parentNode.removeChild(ad);');
      _controller.evaluateJavascript('var ad= document.getElementById("_b04pct_2709847"); ad.parentNode.removeChild(ad);');

  }
</code>```

答:
Since webview_flutter 3.0.0    this is how I do this

with as a future that is  controller = Completer<WebViewController>();

```<code>onProgress: (progress) {

        if (progress > 30) {
          //remove the element with class name
          controller.future.then((webviewController) => webviewController
              .runJavascript(
                  'document.getElementsByClassName("td-header-template-wrap")[0].remove();')
              .then(
                  (value) => debugPrint('Page finished running Javascript'))
              .catchError((onError) => debugPrint('$onError')));
        }
      },
</code>```

I do it in onProgress because I want the javascript to run once and only once before the full page loading completes. This can also be done in onPageFinished. Sometimes the tag doesn't exist before the javascript is run which is why it's preferred to do this in onPageFinished.

Body:
I tried to remove element dynamically but the removed element still shows up on screen, and is removed when clicked on the element.

here is the code i used

 onPageFinished: (url){
        removeAds(url);
      },
 void removeAds(String url){
      print("asdjkhjahsdk");
      //_controller.loadUrl('javascript: var ad= document.getElementById("_b04pct_2709847"); ad.parentNode.removeChild(ad);');
      _controller.evaluateJavascript('var ad= document.getElementById("_b04pct_2709847"); ad.parentNode.removeChild(ad);');

  }

Body:
Since webview_flutter 3.0.0    this is how I do this

with as a future that is  controller = Completer<WebViewController>();

onProgress: (progress) {

        if (progress > 30) {
          //remove the element with class name
          controller.future.then((webviewController) => webviewController
              .runJavascript(
                  'document.getElementsByClassName("td-header-template-wrap")[0].remove();')
              .then(
                  (value) => debugPrint('Page finished running Javascript'))
              .catchError((onError) => debugPrint('$onError')));
        }
      },

I do it in onProgress because I want the javascript to run once and only once before the full page loading completes. This can also be done in onPageFinished. Sometimes the tag doesn't exist before the javascript is run which is why it's preferred to do this in onPageFinished.


问:
git pull without remotely compressing objects
I have a repository full of zip files, re-compressing theses files will be a waste of time.

I've tried to set core.compression = 0 on the remote and the local copy without success

```<code>git config core.compression 0
git config core.loosecompression 0
</code>```

git pull still do

```<code>remote: Counting objects: 23, done.
remote: Compressing objects: ...
</code>```

答: The compressing object line means it is do the packing  work.  That include diffing the trees and stuff.   It is not "compressing" in the sense of core.compression.

Body:
I have a repository full of zip files, re-compressing theses files will be a waste of time.

I've tried to set core.compression = 0 on the remote and the local copy without success

git config core.compression 0
git config core.loosecompression 0

git pull still do

remote: Counting objects: 23, done.
remote: Compressing objects: ...


问:
Combine 3 grayscale images to 1 natural color image in Python
I am dealing with a dataset on Kaggle.com:
https://www.kaggle.com/sorour/38cloud-cloud-segmentation-in-satellite-images
And what I'm trying to do is combine 3 grayscale image represent 3 channels (R, G, B) to one natural color image. So here is what I've tried:

```<code>r_np = np.array(cv2.imread(red, 0))
g_np = np.array(cv2.imread(green, 0))
b_np = np.array(cv2.imread(blue, 0))

# Add the channels to the final image
final_img = np.dstack([b_np, g_np, r_np]).astype(np.uint8)

# Directory to save
final_img_dir = store_directory + "\\" + "img" + image_id

# Save the needed multi channel image
cv2.imwrite(final_img_dir, final_img)
</code>```

And its output is a still a grayscale image. My image format is .TIF.
Thank you in advance!

答:
You have several problems in your code:

Firstly, you need to import modules:

```<code>import numpy as np
import cv2
</code>```

Secondly, you are using ugly, manifest constants instead of the nice, legible, maintainable ones that OpenCV provides for free and also you are needlessly wrapping the Numpy array you get from cv2.imread() into a Numpy array.

Finally, you are not checking for errors.

So, rather than:

```<code>r_np = np.array(cv2.imread(red, 0))
</code>```

consider:

```<code>r_np = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
assert r_np is not None, "ERROR: Error reading red image"
</code>```

Body:
I am dealing with a dataset on Kaggle.com:
https://www.kaggle.com/sorour/38cloud-cloud-segmentation-in-satellite-images
And what I'm trying to do is combine 3 grayscale image represent 3 channels (R, G, B) to one natural color image. So here is what I've tried:

r_np = np.array(cv2.imread(red, 0))
g_np = np.array(cv2.imread(green, 0))
b_np = np.array(cv2.imread(blue, 0))

# Add the channels to the final image
final_img = np.dstack([b_np, g_np, r_np]).astype(np.uint8)

# Directory to save
final_img_dir = store_directory + "\\" + "img" + image_id

# Save the needed multi channel image
cv2.imwrite(final_img_dir, final_img)

And its output is a still a grayscale image. My image format is .TIF.
Thank you in advance!

Body:
You have several problems in your code:

Firstly, you need to import modules:

import numpy as np
import cv2

Secondly, you are using ugly, manifest constants instead of the nice, legible, maintainable ones that OpenCV provides for free and also you are needlessly wrapping the Numpy array you get from cv2.imread() into a Numpy array.

Finally, you are not checking for errors.

So, rather than:

r_np = np.array(cv2.imread(red, 0))

consider:

r_np = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
assert r_np is not None, "ERROR: Error reading red image"