问:
Threejs mtl loader unfaithful material colors
I created a MTL loader to load: Mtl file, Obj file, and all its materials.

All this files are requested from a server, and looking at the responses, they all have the right colors and textures.

The thing is, when all the files get rendered, the materials itself gets darker and the colors are not faithful with the materials I’m loading.

OBS: I’ve already tested this files on Sketchfab and it rendered correctly, so i’m hoping someone can help me to find what i’m doing wrong. I can post more code if necessary.

import * as THREE from 'three';

export function makeDirectionalLight() {
    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(100, 100, 0);

    return directionalLight;
}```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import * as THREE from 'three';

export function makeAmbientLight() {
    return new THREE.AmbientLight(0xffffff, 0.9);
}</code>```

import * as THREE from 'three';

export function makeRenderer() {
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor('#000', 0.1);
    renderer.outputEncoding =  THREE.sRGBEncoding;

    return renderer;
}```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { makeObjLoader } from '../factories';
import { domManager } from '../singletons/DomManager';
import { FileUtil } from '../utils/FileUtil';
import { UrlUtil } from '../utils/UrlUtil';

export class MtlRemoteStrategy {
    constructor(scene, files = [], loader) {
        this.scene = scene;
        this.files = files;
        this.loader = loader;
    }

    load() {
        const mtlObjectUrl = UrlUtil.getRemoteObjectUrl(FileUtil.getFileByText(this.files, '.mtl'))
        const objObjectUrl = UrlUtil.getRemoteObjectUrl(FileUtil.getFileByText(this.files, '.obj'))

        this.loader.load(mtlObjectUrl, (materials) => {
            materials.preload();

            makeObjLoader()
                .setMaterials(materials)
                .load(objObjectUrl, (model) => {
                    model.position.set(0, 0, 0);
                    this.scene.add(model);
                });
        });
    }
}</code>```

Actual render:

Render tested on Sketchfab:

Body:
I created a MTL loader to load: Mtl file, Obj file, and all its materials.

All this files are requested from a server, and looking at the responses, they all have the right colors and textures.

The thing is, when all the files get rendered, the materials itself gets darker and the colors are not faithful with the materials I’m loading.

OBS: I’ve already tested this files on Sketchfab and it rendered correctly, so i’m hoping someone can help me to find what i’m doing wrong. I can post more code if necessary.

import * as THREE from 'three';

export function makeDirectionalLight() {
    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(100, 100, 0);

    return directionalLight;
}

import * as THREE from 'three';

export function makeAmbientLight() {
    return new THREE.AmbientLight(0xffffff, 0.9);
}

import * as THREE from 'three';

export function makeRenderer() {
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor('#000', 0.1);
    renderer.outputEncoding =  THREE.sRGBEncoding;

    return renderer;
}

import { makeObjLoader } from '../factories';
import { domManager } from '../singletons/DomManager';
import { FileUtil } from '../utils/FileUtil';
import { UrlUtil } from '../utils/UrlUtil';

export class MtlRemoteStrategy {
    constructor(scene, files = [], loader) {
        this.scene = scene;
        this.files = files;
        this.loader = loader;
    }

    load() {
        const mtlObjectUrl = UrlUtil.getRemoteObjectUrl(FileUtil.getFileByText(this.files, '.mtl'))
        const objObjectUrl = UrlUtil.getRemoteObjectUrl(FileUtil.getFileByText(this.files, '.obj'))

        this.loader.load(mtlObjectUrl, (materials) => {
            materials.preload();

            makeObjLoader()
                .setMaterials(materials)
                .load(objObjectUrl, (model) => {
                    model.position.set(0, 0, 0);
                    this.scene.add(model);
                });
        });
    }
}

Actual render:

Render tested on Sketchfab:


来源: stackexchange

问:
ReferenceError: AudioContext is not defined is appearing in my Jest Suite
I get this error ReferenceError: AudioContext is not defined in all of my Jest tests. I don't use it in my test cases -- 100% sure. But I noticed one of the external libraries is using it (library is proprietary and not in npm). But that library is not even part of any test files. Does anyone have an idea how to circumvent this annoying issue?

ContentLicense: CC BY-SA 4.0


问:
Pointer doesn't point to the correct location, after parsing it as an argument
```<code>internal unsafe struct Array<T>
{
    public int Length;

    internal nuint* ptr;

    public Array(int capacity)
    {
        ptr = (nuint*)Marshal.AllocHGlobal(capacity * sizeof(nuint)); // allocates memory on heap
        Length = capacity;
    }

    public T this[int index]
    {
        get
        {
            if (index > Length || index < 0)
                throw new ArgumentOutOfRangeException(nameof(index));
            nuint PointerToT = ptr[index]; // gets pointer to type
            byte TFirstByte = *(byte*)PointerToT; // gets the first byte of the type
            return Unsafe.As<byte, T>(ref TFirstByte); // converts byte to type

        }
        set
        {
            if (index > Length || index < 0)
                throw new ArgumentOutOfRangeException(nameof(index));
            void* valueAsPtr = Unsafe.AsPointer(ref value); // gets pointer, but gets the wrong address
            ptr[index] = (nuint)valueAsPtr; // sets pointer at index
        }
    }
}
</code>```

what I'm trying to do is make my own sort of array, but when I try to get the pointer to the memory address of the value that I'm setting, I get the pointer location of the parameter: 'value' but not the actual value. Is there a way to get the memory address of the value before it has been parsed as an argument.

```<code>Array<int> myArray = new(1);
int v = 21;
myArray[0] = v;

int* ptr = &v;
</code>```

this is how I'm trying to use it but the address that the 'ptr' variable gets is not the same as the address that it has in the setter. I have used other data types like strings, but those have the same issue.

```<code>Console.WriteLine(myArray[0])
</code>```

and once i try to get the value, it tries to read the memory of the 'value' parameter which was in the setter, but this is not available anymore.

Body:
internal unsafe struct Array<T>
{
    public int Length;

    internal nuint* ptr;

    public Array(int capacity)
    {
        ptr = (nuint*)Marshal.AllocHGlobal(capacity * sizeof(nuint)); // allocates memory on heap
        Length = capacity;
    }

    public T this[int index]
    {
        get
        {
            if (index > Length || index < 0)
                throw new ArgumentOutOfRangeException(nameof(index));
            nuint PointerToT = ptr[index]; // gets pointer to type
            byte TFirstByte = *(byte*)PointerToT; // gets the first byte of the type
            return Unsafe.As<byte, T>(ref TFirstByte); // converts byte to type

        }
        set
        {
            if (index > Length || index < 0)
                throw new ArgumentOutOfRangeException(nameof(index));
            void* valueAsPtr = Unsafe.AsPointer(ref value); // gets pointer, but gets the wrong address
            ptr[index] = (nuint)valueAsPtr; // sets pointer at index
        }
    }
}

what I'm trying to do is make my own sort of array, but when I try to get the pointer to the memory address of the value that I'm setting, I get the pointer location of the parameter: 'value' but not the actual value. Is there a way to get the memory address of the value before it has been parsed as an argument.

Array<int> myArray = new(1);
int v = 21;
myArray[0] = v;

int* ptr = &v;

this is how I'm trying to use it but the address that the 'ptr' variable gets is not the same as the address that it has in the setter. I have used other data types like strings, but those have the same issue.

Console.WriteLine(myArray[0])

and once i try to get the value, it tries to read the memory of the 'value' parameter which was in the setter, but this is not available anymore.


问:
Rstudio update cause Rcpp fail to compile
I recently updated my Rstudio to V2022.07.2+576, but found Rcpp can no longer compile code.

```<code>library(Rcpp)
cppFunction('int add(int x, int y, int z) {
  int sum = x + y + z;
  return sum;
}')
</code>```

, which give me error message like:

```<code>clang-12: warning: include path for libstdc++ headers not found; pass '-stdlib=libc++' on the command line to use the libc++ standard library instead [-Wstdlibcxx-not-found]
In file included from file7898532e8a3d.cpp:1:
In file included from /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include/Rcpp.h:27:
In file included from /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include/RcppCommon.h:30:
In file included from /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include/Rcpp/r/headers.h:62:
/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include/Rcpp/platform/compiler.h:100:10: fatal error: 'cmath' file not found
#include <cmath>
         ^~~~~~~
1 error generated.
make: *** [/Library/Frameworks/R.framework/Resources/etc/Makeconf:176: file7898532e8a3d.o] Error 1
clang++ -arch arm64 -std=gnu++14 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include" -I"/private/var/folders/0l/_zb89yxd4qs6g7t3dx2t__k80000gr/T/RtmpPHmvlY/sourceCpp-aarch64-apple-darwin20-1.0.9" -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c file7898532e8a3d.cpp -o file7898532e8a3d.o
 Error in sourceCpp(code = code, env = env, rebuild = rebuild, cacheDir = cacheDir, :
Error 1 occurred building shared library.
</code>```

I tried to reinstall R/Rstudio, and update Xcode, but had no good luck. Here is my sessioninfo

```<code>R version 4.2.2 (2022-10-31)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Big Sur 11.4

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] Rcpp_1.0.9        MASS_7.3-58.1     doParallel_1.0.17 iterators_1.0.14  foreach_1.5.2

loaded via a namespace (and not attached):
 [1] xfun_0.31              tidyselect_1.1.2       purrr_0.3.4            splines_4.2.2          operator.tools_1.6.3
 [6] lattice_0.20-45        vctrs_0.4.1            generics_0.1.3         htmltools_0.5.3        GWASExactHW_1.01
[11] stats4_4.2.2           yaml_2.3.5             mgcv_1.8-41            utf8_1.2.2             rlang_1.0.4
[16] pillar_1.8.0           glue_1.6.2             withr_2.5.0            DBI_1.1.3              BiocGenerics_0.42.0
[21] gdsfmt_1.32.0          GenomeInfoDbData_1.2.8 lifecycle_1.0.1        zlibbioc_1.42.0        Biostrings_2.64.0
[26] codetools_0.2-18       evaluate_0.15          Biobase_2.56.0         knitr_1.39             SeqArray_1.36.2
[31] IRanges_2.30.0         fastmap_1.1.0          GenomeInfoDb_1.32.2    fansi_1.0.3            broom_1.0.0
[36] backports_1.4.1        S4Vectors_0.34.0       XVector_0.36.0         digest_0.6.29          formula.tools_1.7.1
[41] dplyr_1.0.9            GenomicRanges_1.48.0   grid_4.2.2             cli_3.3.0              tools_4.2.2
[46] bitops_1.0-7           magrittr_2.0.3         RCurl_1.98-1.7         tibble_3.1.8           mice_3.14.0
[51] crayon_1.5.1           tidyr_1.2.0            pkgconfig_2.0.3        Matrix_1.5-1           data.table_1.14.2
[56] assertthat_0.2.1       rmarkdown_2.14         rstudioapi_0.13        logistf_1.24.1         R6_2.5.1
[61] SeqVarTools_1.34.0     nlme_3.1-160           compiler_4.2.2
</code>```

Body:
I recently updated my Rstudio to V2022.07.2+576, but found Rcpp can no longer compile code.

library(Rcpp)
cppFunction('int add(int x, int y, int z) {
  int sum = x + y + z;
  return sum;
}')

, which give me error message like:

clang-12: warning: include path for libstdc++ headers not found; pass '-stdlib=libc++' on the command line to use the libc++ standard library instead [-Wstdlibcxx-not-found]
In file included from file7898532e8a3d.cpp:1:
In file included from /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include/Rcpp.h:27:
In file included from /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include/RcppCommon.h:30:
In file included from /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include/Rcpp/r/headers.h:62:
/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include/Rcpp/platform/compiler.h:100:10: fatal error: 'cmath' file not found
#include <cmath>
         ^~~~~~~
1 error generated.
make: *** [/Library/Frameworks/R.framework/Resources/etc/Makeconf:176: file7898532e8a3d.o] Error 1
clang++ -arch arm64 -std=gnu++14 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/Rcpp/include" -I"/private/var/folders/0l/_zb89yxd4qs6g7t3dx2t__k80000gr/T/RtmpPHmvlY/sourceCpp-aarch64-apple-darwin20-1.0.9" -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c file7898532e8a3d.cpp -o file7898532e8a3d.o
 Error in sourceCpp(code = code, env = env, rebuild = rebuild, cacheDir = cacheDir, :
Error 1 occurred building shared library.

I tried to reinstall R/Rstudio, and update Xcode, but had no good luck. Here is my sessioninfo

R version 4.2.2 (2022-10-31)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Big Sur 11.4

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] Rcpp_1.0.9        MASS_7.3-58.1     doParallel_1.0.17 iterators_1.0.14  foreach_1.5.2

loaded via a namespace (and not attached):
 [1] xfun_0.31              tidyselect_1.1.2       purrr_0.3.4            splines_4.2.2          operator.tools_1.6.3
 [6] lattice_0.20-45        vctrs_0.4.1            generics_0.1.3         htmltools_0.5.3        GWASExactHW_1.01
[11] stats4_4.2.2           yaml_2.3.5             mgcv_1.8-41            utf8_1.2.2             rlang_1.0.4
[16] pillar_1.8.0           glue_1.6.2             withr_2.5.0            DBI_1.1.3              BiocGenerics_0.42.0
[21] gdsfmt_1.32.0          GenomeInfoDbData_1.2.8 lifecycle_1.0.1        zlibbioc_1.42.0        Biostrings_2.64.0
[26] codetools_0.2-18       evaluate_0.15          Biobase_2.56.0         knitr_1.39             SeqArray_1.36.2
[31] IRanges_2.30.0         fastmap_1.1.0          GenomeInfoDb_1.32.2    fansi_1.0.3            broom_1.0.0
[36] backports_1.4.1        S4Vectors_0.34.0       XVector_0.36.0         digest_0.6.29          formula.tools_1.7.1
[41] dplyr_1.0.9            GenomicRanges_1.48.0   grid_4.2.2             cli_3.3.0              tools_4.2.2
[46] bitops_1.0-7           magrittr_2.0.3         RCurl_1.98-1.7         tibble_3.1.8           mice_3.14.0
[51] crayon_1.5.1           tidyr_1.2.0            pkgconfig_2.0.3        Matrix_1.5-1           data.table_1.14.2
[56] assertthat_0.2.1       rmarkdown_2.14         rstudioapi_0.13        logistf_1.24.1         R6_2.5.1
[61] SeqVarTools_1.34.0     nlme_3.1-160           compiler_4.2.2


问:
Work with Stellar Network : How can I check the balance for each account using node.js and mongo.db
``I workk with stellar network , I create an account with stellar laboratry and node.js,in the begin I save the data in Json file and everything works perfectly  but now I want to save it into  the database, the signup function work correctly but when I try to check the balance account I am bloked and I have Errors
So my question : I want to use the publickey from the user_account in the database and check the balance using Stellar Horizen

How can I do it ?``

enter image description here

This is the data for the user when he sign up

**SignUp function **

```<code></code>```
```<code>const userModel= require('../models/user.model')
const { errorsSignUp,errorsSignIn } = require('../utils/errors')
const stellar = require("stellar-sdk");

module.exports.signUp= async(req,res)={
const {pseudo,email,password}= req.body
try{
const pair = stellar.Keypair.random();
const userData= await userModel.create(
{
pseudo,
email,
password,
publicKey: pair.publicKey(),
secret:pair.secret(),
})

      // await userData.save()
        res.send(userData)
        res.status(201).json({userData:userData._id})`

}
catch(err){
const errors= errorsSignUp(err)
res.status(200).send({errors})
}
}

</code>```
```<code></code>```

Check balance function

```<code></code>```
```<code>const stellar= require('stellar-sdk')
const accounts= require("./accounts")
const util = require("util")
//const userModel = require('../models/user.model')

// function without mongodb
// saving data in file.json
var server= new stellar.Server("https://horizon-testnet.stellar.org")

const checkAccount= async accounts={
const AccountsBalance= await Promise.all(
accounts.map(async account= await server.loadAccount(account.publicKey)))

return AccountsBalance.map(({id,balances})=({
id,
balances,

    }))

}

checkAccount(accounts)
.then(account=
console.log(util.inspect(account,false, null))

    )

.catch(error={
console.log(error)
})
</code>```
```<code></code>```

Body:
``I workk with stellar network , I create an account with stellar laboratry and node.js,in the begin I save the data in Json file and everything works perfectly  but now I want to save it into  the database, the signup function work correctly but when I try to check the balance account I am bloked and I have Errors
So my question : I want to use the publickey from the user_account in the database and check the balance using Stellar Horizen

How can I do it ?``

enter image description here

This is the data for the user when he sign up

**SignUp function **

const userModel= require('../models/user.model')
const { errorsSignUp,errorsSignIn } = require('../utils/errors')
const stellar = require("stellar-sdk");

module.exports.signUp= async(req,res)={
const {pseudo,email,password}= req.body
try{
const pair = stellar.Keypair.random();
const userData= await userModel.create(
{
pseudo,
email,
password,
publicKey: pair.publicKey(),
secret:pair.secret(),
})

      // await userData.save()
        res.send(userData)
        res.status(201).json({userData:userData._id})`

}
catch(err){
const errors= errorsSignUp(err)
res.status(200).send({errors})
}
}

Check balance function

const stellar= require('stellar-sdk')
const accounts= require("./accounts")
const util = require("util")
//const userModel = require('../models/user.model')

// function without mongodb
// saving data in file.json
var server= new stellar.Server("https://horizon-testnet.stellar.org")

const checkAccount= async accounts={
const AccountsBalance= await Promise.all(
accounts.map(async account= await server.loadAccount(account.publicKey)))

return AccountsBalance.map(({id,balances})=({
id,
balances,

    }))

}

checkAccount(accounts)
.then(account=
console.log(util.inspect(account,false, null))

    )

.catch(error={
console.log(error)
})


问:
Sonar scanner runs more sub-modules than needed
When I run sonar-scanner on C project, it analyzes my submodules, but it also includes a "parent" configuration. What I mean:

sonar-project.properties

```<code>sonar.host.url=<host>
sonar.login=<token>
sonar.projectKey=PROJECT1
sonar.qualitygate.wait=true
sonar.sourceEncoding=UTF-8
sonar.scm.provider=git
sonar.verbose=true

sonar.modules=module1,module2

sonar.language=C
# if I enable below 3 lines it won't crash
#sonar.sources=.
#sonar.cfamily.build-wrapper-output=code_coverage_results
#sonar.cfamily.gcov.reportsPath=code_coverage_results

module1.sonar.projectName=Module1
module1.sonar.projectBaseDir=./module1
module1.sonar.sources=src
module1.sonar.tests=tests
module1.sonar.cfamily.build-wrapper-output=../code_coverage_results
module1.sonar.cfamily.gcov.reportsPath=../code_coverage_results
module1.sonar.exclusions=**/*.py,src/http-parser/**,obj/**,bin/**

module2.sonar.projectName=Module2
module2.sonar.projectBaseDir=./module2
module2.sonar.sources=src
module2.sonar.tests=tests
module2.sonar.cfamily.build-wrapper-output=../code_coverage_results
module2.sonar.cfamily.gcov.reportsPath=../code_coverage_results

sonar.cfamily.threads=10
sonar.cfamily.cache.enabled=true
sonar.cfamily.cache.path=sonar.cfamily.cache
sonar.scm.exclusions.disabled=true
</code>```

code_coverage_results is a common folder for both submodules, basically can be separated.

What I see when run sonar-scanner -X:

```<code>------------- Run sensors on module Module1
... <analyzing> ...

------------- Run sensors on module Module2
... <analyzing> ...

------------- Run sensors on module PROJECT1
17:39:47.092 INFO: Sensor CFamily [cpp]
17:39:47.093 INFO: CFamily plugin version: 6.32.0.44918
17:39:47.093 ERROR:

he only way to get an accurate analysis of C/C++/Objective-C files is by using the SonarSource build-wrapper and setting the property "sonar.cfamily.build-wrapper-output" or by using Clang Compilation Database and setting the property "sonar.cfamily.compile-commands". None of these two options were specified.

If you don't want to analyze C/C++/Objective-C files, then prevent them from being analyzed by setting the following properties:

    sonar.c.file.suffixes=-
    sonar.cpp.file.suffixes=-
    sonar.objc.file.suffixes=-

    at com.sonar.cpp.plugin.CFamilySensor.process(CFamilySensor.java:236)
    at com.sonar.cpp.plugin.CFamilySensor.execute(CFamilySensor.java:186)
    at org.sonar.scanner.sensor.AbstractSensorWrapper.analyse(AbstractSensorWrapper.java:64)
    at org.sonar.scanner.sensor.ModuleSensorsExecutor.execute(ModuleSensorsExecutor.java:85)
    at org.sonar.scanner.sensor.ModuleSensorsExecutor.execute(ModuleSensorsExecutor.java:62)
    at org.sonar.scanner.scan.SpringModuleScanContainer.doAfterStart(SpringModuleScanContainer.java:81)
    at org.sonar.core.platform.SpringComponentContainer.startComponents(SpringComponentContainer.java:188)
    at org.sonar.core.platform.SpringComponentContainer.execute(SpringComponentContainer.java:167)
    at org.sonar.scanner.scan.SpringProjectScanContainer.scan(SpringProjectScanContainer.java:392)
</code>```

When I uncomment the lines:

```<code>sonar.sources=.
sonar.cfamily.build-wrapper-output=code_coverage_results
sonar.cfamily.gcov.reportsPath=code_coverage_results
</code>```

I am getting the error like:

```<code>File module2/src/Source.c can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files
</code>```

That is why I have to put

```<code>sonar.exclusions=**
</code>```

in the beginning.

The question is: why it tries to analyze three modules instead of two?

I have the next structure:

```<code>root folder
   Module1
   Module2
   CommonSources
   *.sh, *.py files
   sonar-project.properties
</code>```

Thanks.

Body:
When I run sonar-scanner on C project, it analyzes my submodules, but it also includes a "parent" configuration. What I mean:

sonar-project.properties

sonar.host.url=<host>
sonar.login=<token>
sonar.projectKey=PROJECT1
sonar.qualitygate.wait=true
sonar.sourceEncoding=UTF-8
sonar.scm.provider=git
sonar.verbose=true

sonar.modules=module1,module2

sonar.language=C
# if I enable below 3 lines it won't crash
#sonar.sources=.
#sonar.cfamily.build-wrapper-output=code_coverage_results
#sonar.cfamily.gcov.reportsPath=code_coverage_results

module1.sonar.projectName=Module1
module1.sonar.projectBaseDir=./module1
module1.sonar.sources=src
module1.sonar.tests=tests
module1.sonar.cfamily.build-wrapper-output=../code_coverage_results
module1.sonar.cfamily.gcov.reportsPath=../code_coverage_results
module1.sonar.exclusions=**/*.py,src/http-parser/**,obj/**,bin/**

module2.sonar.projectName=Module2
module2.sonar.projectBaseDir=./module2
module2.sonar.sources=src
module2.sonar.tests=tests
module2.sonar.cfamily.build-wrapper-output=../code_coverage_results
module2.sonar.cfamily.gcov.reportsPath=../code_coverage_results

sonar.cfamily.threads=10
sonar.cfamily.cache.enabled=true
sonar.cfamily.cache.path=sonar.cfamily.cache
sonar.scm.exclusions.disabled=true

code_coverage_results is a common folder for both submodules, basically can be separated.

What I see when run sonar-scanner -X:

------------- Run sensors on module Module1
... <analyzing> ...

------------- Run sensors on module Module2
... <analyzing> ...

------------- Run sensors on module PROJECT1
17:39:47.092 INFO: Sensor CFamily [cpp]
17:39:47.093 INFO: CFamily plugin version: 6.32.0.44918
17:39:47.093 ERROR:

he only way to get an accurate analysis of C/C++/Objective-C files is by using the SonarSource build-wrapper and setting the property "sonar.cfamily.build-wrapper-output" or by using Clang Compilation Database and setting the property "sonar.cfamily.compile-commands". None of these two options were specified.

If you don't want to analyze C/C++/Objective-C files, then prevent them from being analyzed by setting the following properties:

    sonar.c.file.suffixes=-
    sonar.cpp.file.suffixes=-
    sonar.objc.file.suffixes=-

    at com.sonar.cpp.plugin.CFamilySensor.process(CFamilySensor.java:236)
    at com.sonar.cpp.plugin.CFamilySensor.execute(CFamilySensor.java:186)
    at org.sonar.scanner.sensor.AbstractSensorWrapper.analyse(AbstractSensorWrapper.java:64)
    at org.sonar.scanner.sensor.ModuleSensorsExecutor.execute(ModuleSensorsExecutor.java:85)
    at org.sonar.scanner.sensor.ModuleSensorsExecutor.execute(ModuleSensorsExecutor.java:62)
    at org.sonar.scanner.scan.SpringModuleScanContainer.doAfterStart(SpringModuleScanContainer.java:81)
    at org.sonar.core.platform.SpringComponentContainer.startComponents(SpringComponentContainer.java:188)
    at org.sonar.core.platform.SpringComponentContainer.execute(SpringComponentContainer.java:167)
    at org.sonar.scanner.scan.SpringProjectScanContainer.scan(SpringProjectScanContainer.java:392)

When I uncomment the lines:

sonar.sources=.
sonar.cfamily.build-wrapper-output=code_coverage_results
sonar.cfamily.gcov.reportsPath=code_coverage_results

I am getting the error like:

File module2/src/Source.c can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files

That is why I have to put

sonar.exclusions=**

in the beginning.

The question is: why it tries to analyze three modules instead of two?

I have the next structure:

root folder
   Module1
   Module2
   CommonSources
   *.sh, *.py files
   sonar-project.properties

Thanks.


问:
Discrepancy in rich results in Google's rich results testing tool vs Google Search Console
I've a added structured data to articles on my website, and for some reason Google's Rich Results test recognizes the JSON LD structure I have in place as valid, but the same article that I do a live test of in search console does not detect any rich results (screenshots attached below). Has anyone had this issue come up before, and if so is there a way to have search console recognize the structured data and ultimately have Google crawl and index the rich results?


问:
How to sequentially execute functions in React?
I am trying to upload images to firebase storage and then when uploads finish, execute a try/catch block of codes with addDoc() command to create a doc inside fb database. The sample coding is as follows:

```<code>const abc = () => {

  array.map(() => {
    return uploadFilesToFb()
  })

  // then, when the above function finishes
  createDocInFb()
}
</code>```

I heard about Promises, but is there any other way of doing this? I mean, in firebase there are .then functions but since I have a mapping I couldn't put addDoc() after .then of uploadFilesToFb(). If only alternative is promises, how can I achieve that with promises?

Body:
I am trying to upload images to firebase storage and then when uploads finish, execute a try/catch block of codes with addDoc() command to create a doc inside fb database. The sample coding is as follows:

const abc = () => {

  array.map(() => {
    return uploadFilesToFb()
  })

  // then, when the above function finishes
  createDocInFb()
}

I heard about Promises, but is there any other way of doing this? I mean, in firebase there are .then functions but since I have a mapping I couldn't put addDoc() after .then of uploadFilesToFb(). If only alternative is promises, how can I achieve that with promises?


问:
fitting a data set with a multimodal Gaussian function in python
I'm trying to use the function curve_fit to find a multimodal Gaussian function that has "n" relative maximus that fits a data set.

My idea, once you know the value of n, is create 3 arrays A, M, and C n-size, then create a function which its arguments are x and the 3 arrays, finally use the function curve_fit to get the value of the constants that fits the data set. in this case our data set is Y

import numpy as np
from scipy.optimize import curve_fit

X=np.array(range(1,501)/100)
n=3

A=np.array([1,1,1], float)
M=np.array([1,2,3], float)
C=np.array([.5,.5,.5], float)

def MultiGauss(x, a, b, c):
    p = a.size
    r=0
    for i in range(p):
        r =r+ a[i]*(math.exp(((x-b[i])**2)/(2*(c[i]**2))))

    return r

Y=MultiGauss(X,A,M,C)
popt,_=curve_fit(MultiGauss, X, Y)
```


问:
How i can open server to internet with noip
I was setup an webserver for some testing with friends, i was using noip, i have open ports on my router but... the server isn't accessible from internet it is listening on 0.0.0.0 (apache2 is the server) what can i do?? i have probe everything i know but nothing was success

i tried all, i dont know what i need to do to that be accessible from internet

i need to the server be accessible from internet i have been open the ports on my router and change listening address to 0.0.0.0


问:
How to use progress bar using Cryptostream directly not with FileStream to Increase the speed of the Encryption
I want to use  CryptoStream  with Progress bar directly when Encrypt some file.

Because, when i loop using fileStream.Read to increment the value for Pogress bar and write the file it takes a time, especially when the file is more than 2 MB.

This is my code with speed encryption without using filestream but no progress bar (i don't know where to put the progress valse change)

```<code> public  byte[] AES_Encrypt(byte[] fileContent, byte[] mtpass, string ifile)
 {
     byte[] salt_Bytes = new byte[] {10, 20, 30, 40, 50, 60, 70, 80};
     RijndaelManaged AES = new RijndaelManaged();
     AES.KeySize = 256;
     AES.BlockSize = 128;
     var key = new Rfc2898DeriveBytes(mtpass, salt_Bytes, 1000);
     AES.Key = key.GetBytes(AES.KeySize / 8);
     AES.IV = key.GetBytes(AES.BlockSize / 8);
     AES.Mode = CipherMode.CBC;
     AES.Padding = PaddingMode.Zeros;
 //SPEED INCRYPTION WITHOUT PROGRESS BAR

     MemoryStream mem = new MemoryStream();
     CryptoStream fich_crypt_mem = new CryptoStream(mem, AES.CreateEncryptor(),CryptoStreamMode.Write);

 //MAYBE HERE TO ADD THE CODE FOR CHANGE THE VALUE FOR PROGRESS BAR
     fich_crypt_mem.Write(fileContent, 0, fileContent.Length);

     fich_crypt_mem.Close();
     return  mem.ToArray();
 }
</code>```

And this is the code: using fileStream and Progress bar work fine, but slow encryption:

```<code>public  byte[] AES_Encrypt(byte[] fileContent, byte[] mtpass, string ifile)
{
//AES KEY GENERATION(SAME)

MemoryStream mem = new MemoryStream();
CryptoStream fich_crypt_mem = new CryptoStream(mem, AES.CreateEncryptor(), CryptoStreamMode.Write);

// USING FileStream TO CHANGE THE VALUE OF PROGRESS BAR AND WRITE THE ENCRYPT FILE
FileStream fsIn = new FileStream(ifile, FileMode.Open);

int data;
double counter = 1;

while ((data = fsIn.ReadByte()) != -1) //Loop FileStream.Read
  {
    fich_crypt_mem.WriteByte((byte)data);

    //progressbar using BackgroundWorker
    myBgWorker.ReportProgress((int)((counter / fsIn.Length) * 100));

    counter++;
  }
fsIn.Close();
fich_crypt_mem.Close();
return mem.ToArray();
}
</code>```

Thanks, and sorry for my English is not good.

progress bar with CryptoStream

Body:
I want to use  CryptoStream  with Progress bar directly when Encrypt some file.

Because, when i loop using fileStream.Read to increment the value for Pogress bar and write the file it takes a time, especially when the file is more than 2 MB.

This is my code with speed encryption without using filestream but no progress bar (i don't know where to put the progress valse change)

 public  byte[] AES_Encrypt(byte[] fileContent, byte[] mtpass, string ifile)
 {
     byte[] salt_Bytes = new byte[] {10, 20, 30, 40, 50, 60, 70, 80};
     RijndaelManaged AES = new RijndaelManaged();
     AES.KeySize = 256;
     AES.BlockSize = 128;
     var key = new Rfc2898DeriveBytes(mtpass, salt_Bytes, 1000);
     AES.Key = key.GetBytes(AES.KeySize / 8);
     AES.IV = key.GetBytes(AES.BlockSize / 8);
     AES.Mode = CipherMode.CBC;
     AES.Padding = PaddingMode.Zeros;
 //SPEED INCRYPTION WITHOUT PROGRESS BAR

     MemoryStream mem = new MemoryStream();
     CryptoStream fich_crypt_mem = new CryptoStream(mem, AES.CreateEncryptor(),CryptoStreamMode.Write);

 //MAYBE HERE TO ADD THE CODE FOR CHANGE THE VALUE FOR PROGRESS BAR
     fich_crypt_mem.Write(fileContent, 0, fileContent.Length);

     fich_crypt_mem.Close();
     return  mem.ToArray();
 }

And this is the code: using fileStream and Progress bar work fine, but slow encryption:

public  byte[] AES_Encrypt(byte[] fileContent, byte[] mtpass, string ifile)
{
//AES KEY GENERATION(SAME)

MemoryStream mem = new MemoryStream();
CryptoStream fich_crypt_mem = new CryptoStream(mem, AES.CreateEncryptor(), CryptoStreamMode.Write);

// USING FileStream TO CHANGE THE VALUE OF PROGRESS BAR AND WRITE THE ENCRYPT FILE
FileStream fsIn = new FileStream(ifile, FileMode.Open);

int data;
double counter = 1;

while ((data = fsIn.ReadByte()) != -1) //Loop FileStream.Read
  {
    fich_crypt_mem.WriteByte((byte)data);

    //progressbar using BackgroundWorker
    myBgWorker.ReportProgress((int)((counter / fsIn.Length) * 100));

    counter++;
  }
fsIn.Close();
fich_crypt_mem.Close();
return mem.ToArray();
}

Thanks, and sorry for my English is not good.

progress bar with CryptoStream


问:
How can we decide which patterns (isResume check or LiveData) we should use, when updating UI from background thread?
When we are updating UI from user thread, it is important for us to check for isResume(), to ensure the Fragment's UI is still valid.

Using isResume check when updating UI

```<code>getCommonExecutor().execute(() -> {
    // Run in user thread.

    runInUiThread(() -> {
        if (!isResumed()) {
            return;
        }

        // Update fragment UI...
    });
});

private static final ExecutorService commonExecutor = Executors.newSingleThreadExecutor();

public static ExecutorService getCommonExecutor() {
    return commonExecutor;
}

public static void runInUiThread(Runnable runnable) {
    if (isUiThread()) {
        runnable.run();
    } else {
        // non-UI thread.
        runInNextUiThread(runnable);
    }
}

public static void runInNextUiThread(Runnable runnable) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(runnable::run);
}
</code>```

However, using LiveData is able to achieve similar purpose as well.

Using LiveData when updating UI

```<code>SingleLiveEvent<...> liveEvent = new SingleLiveEvent<>();

liveEvent.observe(viewLifecycleOwner, {
    // Update fragment UI...
})

getCommonExecutor().execute(() -> {
    // Run in user thread.
    liveEvent.post(...);
});
</code>```

I was wondering, what is the pro and con for each methodology? How can we decide which we should use?

Body:
When we are updating UI from user thread, it is important for us to check for isResume(), to ensure the Fragment's UI is still valid.

Using isResume check when updating UI

getCommonExecutor().execute(() -> {
    // Run in user thread.

    runInUiThread(() -> {
        if (!isResumed()) {
            return;
        }

        // Update fragment UI...
    });
});

private static final ExecutorService commonExecutor = Executors.newSingleThreadExecutor();

public static ExecutorService getCommonExecutor() {
    return commonExecutor;
}

public static void runInUiThread(Runnable runnable) {
    if (isUiThread()) {
        runnable.run();
    } else {
        // non-UI thread.
        runInNextUiThread(runnable);
    }
}

public static void runInNextUiThread(Runnable runnable) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(runnable::run);
}

However, using LiveData is able to achieve similar purpose as well.

Using LiveData when updating UI

SingleLiveEvent<...> liveEvent = new SingleLiveEvent<>();

liveEvent.observe(viewLifecycleOwner, {
    // Update fragment UI...
})

getCommonExecutor().execute(() -> {
    // Run in user thread.
    liveEvent.post(...);
});

I was wondering, what is the pro and con for each methodology? How can we decide which we should use?


问:
Access to fetch at * from origin * has been blocked by CORS policy, even though CORS policy explicitly allows it
I am performing a graphql query from my client to my server and am getting the following error in the browser:

```<code>Access to fetch at 'https://my-server.com/graphql' from origin 'https://my-client.com' has been blocked by CORS policy:
  Response to preflight request doesn't pass access control check:
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code>```

I once got this same error in the past which is why I added the following to the express middleware on the server which solved it:

  const app = express();
  app.use(cors({
    origin: ['http://localhost:3000', 'https://studio.apollographql.com', "https://my-client.com"],
    credentials: true
  }))
```
<p>However without any changes that I can reasonably trace back to this issue the error is occurring again. The strange thing if I run the client and server on my local machine (on localhost:3000 and localhost:4000 respectively) the error does not happen.</p>
<hr />
<p>Edit:</p>
<p>On the client I use a library called GraphQL Code Generator to generate hooks which execute the relevant queries. One of them is for instance this one:</p>
<pre class="lang-js prettyprint-override"><code>export function useUsersQuery(baseOptions?: Apollo.QueryHookOptions<UsersQuery, UsersQueryVariables>) {
        const options = {...defaultOptions, ...baseOptions}
        return Apollo.useQuery<UsersQuery, UsersQueryVariables>(UsersDocument, options);
      }
</code>```

And to execute the query: const { data, loading, error } = useUsersQuery()

I am using the following package versions

```<code>apollo-server-express@3.11.1
express@4.18.2
cors@2.8.5
</code>```

Body:
I am performing a graphql query from my client to my server and am getting the following error in the browser:

Access to fetch at 'https://my-server.com/graphql' from origin 'https://my-client.com' has been blocked by CORS policy:
  Response to preflight request doesn't pass access control check:
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I once got this same error in the past which is why I added the following to the express middleware on the server which solved it:

  const app = express();
  app.use(cors({
    origin: ['http://localhost:3000', 'https://studio.apollographql.com', "https://my-client.com"],
    credentials: true
  }))

However without any changes that I can reasonably trace back to this issue the error is occurring again. The strange thing if I run the client and server on my local machine (on localhost:3000 and localhost:4000 respectively) the error does not happen.

Edit:

On the client I use a library called GraphQL Code Generator to generate hooks which execute the relevant queries. One of them is for instance this one:

export function useUsersQuery(baseOptions?: Apollo.QueryHookOptions<UsersQuery, UsersQueryVariables>) {
        const options = {...defaultOptions, ...baseOptions}
        return Apollo.useQuery<UsersQuery, UsersQueryVariables>(UsersDocument, options);
      }

And to execute the query: const { data, loading, error } = useUsersQuery()

I am using the following package versions

apollo-server-express@3.11.1
express@4.18.2
cors@2.8.5


问:
Preserving original colour spaces with FFmpeg
I'm trying to implement some logic in my FFmpeg scripts to make sure that a video's colourspace is always preserved when upscaling. Just setting the metadata seems to be enough to do this, but the hard part is figuring out which metadata is needed, especially when the colourspace and related colour data reads as unknown, as is so often the case with many of my source videos.

As I understand it, two things determine a video's original colourspace: whether a video is standard or high definition, and if it's standard definition, whether it's NTSC or PAL/SECAM. Based on this, I came up with the following logic to check the height of a video and set colourspace according to it:

```<code>height=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of default=nw=1:nk=1 "$1" | tr -d $'\r')
colour_space=$(ffprobe -v error -select_streams v:0 -show_entries stream=color_space -of default=nw=1:nk=1 "$1" | tr -d $'\r')

# If input is standard definition and colourspace is BT601 (NTSC)
if [[ $height -lt 720 && $colour_space == "smpte170m" ]]; then
colour_metadata="-colorspace smpte170m -color_trc smpte170m -color_primaries smpte170m" # set metadata to BT601 (NTSC)
# If input is standard definition and colourspace is BT601 (PAL and SECAM) or unknown
elif [[ $height -lt 720 && ($colour_space == "bt470bg" || $colour_space == "unknown") ]]; then
colour_metadata="-colorspace bt470bg -color_trc gamma28 -color_primaries bt470bg" # set metadata to superior/more common PAL/SECAM
elif [[ $height -ge 720 ]]; then # If input is high definition
colour_metadata="-colorspace bt709 -color_trc bt709 -color_primaries bt709" # set metadata to BT.709
else echo "Unrecognised colorspace $color_space detected, leaving colour untouched"
fi
</code>```

Is this approach likely to work for the majority of videos? Is there anything wrong with it that can be improved, or is it completely flawed for some reason that I'm missing?

Body:
I'm trying to implement some logic in my FFmpeg scripts to make sure that a video's colourspace is always preserved when upscaling. Just setting the metadata seems to be enough to do this, but the hard part is figuring out which metadata is needed, especially when the colourspace and related colour data reads as unknown, as is so often the case with many of my source videos.

As I understand it, two things determine a video's original colourspace: whether a video is standard or high definition, and if it's standard definition, whether it's NTSC or PAL/SECAM. Based on this, I came up with the following logic to check the height of a video and set colourspace according to it:

height=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of default=nw=1:nk=1 "$1" | tr -d $'\r')
colour_space=$(ffprobe -v error -select_streams v:0 -show_entries stream=color_space -of default=nw=1:nk=1 "$1" | tr -d $'\r')

# If input is standard definition and colourspace is BT601 (NTSC)
if [[ $height -lt 720 && $colour_space == "smpte170m" ]]; then
colour_metadata="-colorspace smpte170m -color_trc smpte170m -color_primaries smpte170m" # set metadata to BT601 (NTSC)
# If input is standard definition and colourspace is BT601 (PAL and SECAM) or unknown
elif [[ $height -lt 720 && ($colour_space == "bt470bg" || $colour_space == "unknown") ]]; then
colour_metadata="-colorspace bt470bg -color_trc gamma28 -color_primaries bt470bg" # set metadata to superior/more common PAL/SECAM
elif [[ $height -ge 720 ]]; then # If input is high definition
colour_metadata="-colorspace bt709 -color_trc bt709 -color_primaries bt709" # set metadata to BT.709
else echo "Unrecognised colorspace $color_space detected, leaving colour untouched"
fi

Is this approach likely to work for the majority of videos? Is there anything wrong with it that can be improved, or is it completely flawed for some reason that I'm missing?


问:
How do I copy all tables from one database to another in MySQL for C++
I want to copy all tables and data in those tables from one database to another in C++ code (not cmd). I want all data to be pasted in my new MySQL database which I connected with a server using their quickstart guide.

The code I found was:

```<code>CREATE DATABASE copy_of_db;
create table copy_of_db.table LIKE source_db.table;

If you want to copy data too:
INSERT INTO copy_of_db.table SELECT * FROM source_db.table;
</code>```

This isn’t efficient because I have to do this for every table, data and so on. I have to keep reusing this command and I want to do it all at once. I want to copy all data and tables from one database to another. Can someone help me?

Body:
I want to copy all tables and data in those tables from one database to another in C++ code (not cmd). I want all data to be pasted in my new MySQL database which I connected with a server using their quickstart guide.

The code I found was:

CREATE DATABASE copy_of_db;
create table copy_of_db.table LIKE source_db.table;

If you want to copy data too:
INSERT INTO copy_of_db.table SELECT * FROM source_db.table;

This isn’t efficient because I have to do this for every table, data and so on. I have to keep reusing this command and I want to do it all at once. I want to copy all data and tables from one database to another. Can someone help me?


问:
Calculating Time of Use value for solar panels?
I am trying to apply Time of Use metering rates to calculate the dollar value of the energy produced by a solar panel array.  (San Diego Gas and Electric's EV-TOU-5 rate, in particular).  The value changes according to the time of day, day of week, and holidays during the year. This will be part of a larger model that factors in savings from EV charging at off-peak rates after midnight, etc.  So just displaying kwh/month misses the full picture, which I'm trying to model.

Rather than jump into coding this from scratch with PVLIB, I would appreciate any pointers to existing software.


问:
WITH SCHEMABINDING on Azure SQL Server Views
I am trying to speed up an Azure SQL Database View and I have read that I should start by using

WITH SCHEMABINDING, however I always get the same error:

Parse error at line: 1, column: 28: Incorrect syntax near 'SCHEMABINDING'. I get the same error on both views below.

We store our data in Azure Data Warehouse ( which I think is called now Azure Synapse Analytics) and I am wondering if this is some sort of limitation that exists and I am unaware of.

I have created non clustered indexes on the tables the view reads and they seem to speed it up, however I am also a bit unsure on that one. I do not know if they automatically kick in or if I need to type WITH (NOEXPAND).

Thanks

CREATE VIEW dbo.vKey1 with SCHEMABINDING AS SELECT KeyUser, Name FROM dbo.Test

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[email campaigns data test]
with SCHEMABINDING
AS SELECT j.emailname AS 'Email Name',j.emailsubject AS 'Email Subject',COALESCE(l.centre_name,'Non Centre Specific Campaign') AS Centre,j.Category,s.JobId,s.BatchId,s.eventdate_utc As 'Sent Date',COUNT(s.subscriberkey) AS 'Sends',COUNT(b.subscriberkey) as 'Bounce',COUNT(o.subscriberkey) as 'Open',COUNT(c.subscriberkey) as 'Click'
FROM salesforce_marketing_cloud.sent s
JOIN [salesforce_marketing_cloud].[job] j on j.jobid=s.jobid
LEFT JOIN salesforce_marketing_cloud.bounce b on s.jobid=b.jobid AND s.listid=b.listid AND s.batchid=b.batchid AND s.subscriberkey=b.subscriberkey
LEFT JOIN salesforce_marketing_cloud.opens o on s.jobid=o.jobid AND s.listid=o.listid AND s.batchid=o.batchid AND s.subscriberkey=o.subscriberkey
LEFT JOIN salesforce_marketing_cloud.click c on o.jobid=c.jobid AND o.listid=c.listid AND o.batchid=c.batchid AND o.subscriberkey=c.subscriberkey
LEFT JOIN salesforce_marketing_cloud.location mcl on j.fromname=mcl.fromname
LEFT JOIN [location].[location] l ON l.salesforce_marketing_cloud_location_id = mcl.id AND l.[type] = 'Centre'
WHERE s.eventdate_utc>='1/03/2020'
AND (o.IsUnique=1 OR o.IsUnique is Null) AND (c.IsUnique=1 OR c.IsUnique is Null)
GROUP BY j.emailname,j.emailsubject,COALESCE(l.centre_name,'Non Centre Specific Campaign'),j.Category,s.JobId,s.BatchId,s.eventdate_utc;
GO


问:
Azure: How do I restrict Azure so that high-impact changes are allowed only from a specific subnet?
How do I restrict Azure so that high-impact changes are allowed only from a specific subnet?

For example, any changes to the VNET / SubNet / Firewall / Gateway / Bastion / Defender / Sentinel should only be made from a specific subnet part of the Hub-VNET.


问:
{status: false, message: Not Authorized, date: null}
I get this in my flutter app, I send the token but still get this error message and everything is supposed to be alright</p>
```<code>void changeFavourites(int productId) {
    DioHelper.postData(
      url: favourite,
      data: {"product_id": productId},
      lang: "en",
      token: token,
    ).then((value) {
      changeFavouritesmodel = ChangeFavouritesmodel.fromJson(value.data);
      print(value.data);
      print(token);
      emit(ShopChangeFavouritesSuccessState());
    }).catchError((error) {
      emit(ShopChangeFavouritesErrorState());
    });
  }

</code>```

Body:
I get this in my flutter app, I send the token but still get this error message and everything is supposed to be alright

void changeFavourites(int productId) {
    DioHelper.postData(
      url: favourite,
      data: {"product_id": productId},
      lang: "en",
      token: token,
    ).then((value) {
      changeFavouritesmodel = ChangeFavouritesmodel.fromJson(value.data);
      print(value.data);
      print(token);
      emit(ShopChangeFavouritesSuccessState());
    }).catchError((error) {
      emit(ShopChangeFavouritesErrorState());
    });
  }


问:
Is there a way to have Parcel inline my Vue SFC CSS into a style tag in the html head?
I am using Google Apps Script and Google Sites to serve a web-app and I would like to take full advantage of the Vue Single File Components. However, in order to use CSS stylesheets you need/ to inline them.

Normally with a hand crafted CSS file I inline it as follows in the head tag of the html template:

```

*With a minimal Vue application, (single component with a p tag and a style setting the text colour to red)

When I run a parcel build ./index.html it creates the HTML with the JS file, but a separate CSS file is also created and not in-lined.

Can I get Parcel to inline the separate CSS file into the head of the HTML file?

Body:
I am using Google Apps Script and Google Sites to serve a web-app and I would like to take full advantage of the Vue Single File Components. However, in order to use CSS stylesheets you need/ to inline them.

Normally with a hand crafted CSS file I inline it as follows in the head tag of the html template:

*With a minimal Vue application, (single component with a p tag and a style setting the text colour to red)

When I run a parcel build ./index.html it creates the HTML with the JS file, but a separate CSS file is also created and not in-lined.

Can I get Parcel to inline the separate CSS file into the head of the HTML file?


问:
Is it possible to use OpenCV Sift for manuallly selected keypoints which are the vertices of bounding boxes?
I have a sequence of camera images overlapping each other, and I did an object detection by Faster RCNN deep network, which resulted in bounding boxes per image per each object, and I am going to do triangulation to convert bounding boxes vertices(2D pixel coordinates) to 3D coordinates in the world coordinate system. So, I need to do matching to find corresponding bounding boxes vertices over the images. Is it possible to use Sift matching to run "only" corresponding bounding boxes vertices in images overlapping? Moreover, is there any other way except matching to find corresponding bounding boxes over the images?

Below is a sample code that reproduces my method

```<code>#bounding box top left pixel coordinate for image 0 and image 1
bbox0 = [2337.07139369, 1132.20814732]
bbox1 = [2078.25994001, 1559.14941406]

#make key points for bbox0 and bbox1 using below code
key_points = cv2.KeyPoint(bbox[0], bbox[1], 1)]

#create a sift descriptor object
sift = cv2.SIFT_create()

#img0, and img1 RGB images read using cv2, and
#convert to gray images using cv2, #images shape : (4096, 3008)

#compute sift key points descriptors per each image
kp, des = sift.compute(image, key_points)
</code>```

Body:
I have a sequence of camera images overlapping each other, and I did an object detection by Faster RCNN deep network, which resulted in bounding boxes per image per each object, and I am going to do triangulation to convert bounding boxes vertices(2D pixel coordinates) to 3D coordinates in the world coordinate system. So, I need to do matching to find corresponding bounding boxes vertices over the images. Is it possible to use Sift matching to run "only" corresponding bounding boxes vertices in images overlapping? Moreover, is there any other way except matching to find corresponding bounding boxes over the images?

Below is a sample code that reproduces my method

#bounding box top left pixel coordinate for image 0 and image 1
bbox0 = [2337.07139369, 1132.20814732]
bbox1 = [2078.25994001, 1559.14941406]

#make key points for bbox0 and bbox1 using below code
key_points = cv2.KeyPoint(bbox[0], bbox[1], 1)]

#create a sift descriptor object
sift = cv2.SIFT_create()

#img0, and img1 RGB images read using cv2, and
#convert to gray images using cv2, #images shape : (4096, 3008)

#compute sift key points descriptors per each image
kp, des = sift.compute(image, key_points)


问:
Just started learning type script. I have written simple program below. Instead of "Hi shri vishnu" as output I'm getting Hi ${fstname} ${lstname}
```<code>let found: boolean = true;
let grade: number = 88.9;
let fstname: String = 'shri';
let lstname: String = 'vishnu';

console.log(found);
console.log(grade);
console.log('Hi ${fstname} ${lstname}');
</code>```

can anyone help why i am getting like this. The color of this part ${fstname} ${lstname} should actually be blue. but it is orange(same as contents in inverted commasthis is the image)

Body:
let found: boolean = true;
let grade: number = 88.9;
let fstname: String = 'shri';
let lstname: String = 'vishnu';

console.log(found);
console.log(grade);
console.log('Hi ${fstname} ${lstname}');

can anyone help why i am getting like this. The color of this part ${fstname} ${lstname} should actually be blue. but it is orange(same as contents in inverted commasthis is the image)


问:
How to inherit from an x64 windows form that references classes built for x64 platform in Visual Studio
I'm using Visual Studio 2015 professional, and my issue is similar to https://developercommunity.visualstudio.com/t/vs2019-winforms-designer-inherited-forms-issue/513785 . However, I cannot use the workaround in the thread because I'm referencing another class built only for x64 platforms in the parent form.

If I switch to "AnyCPU" platform, the compiler would complain about not able to find the x64 assembly.

If I switch back to "x64" platform, the compiler would complain about not able to load the parent form class.

Any ideas or this is just impossible to achieve in Visual Studio?


问:
How to manually select a database when updating a model using DRF viewset
I'm trying to manually select the db with using() it works fine when retrieving the data, but for  when i try to update the object, the is_valid() method in the serializer uses the default database and ignores the using().

Expected behaviour is to use the same queryset when updating object

What actually happened is it uses the default database and not the manually selected DB in the queryset

I tried the below code

```<code>class TestViewSet(
    mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet
):

    serializer_class = TestSerializer

    def get_queryset(self):
        return Test.objects.using(self.user.name).all()
</code>```

Body:
I'm trying to manually select the db with using() it works fine when retrieving the data, but for  when i try to update the object, the is_valid() method in the serializer uses the default database and ignores the using().

Expected behaviour is to use the same queryset when updating object

What actually happened is it uses the default database and not the manually selected DB in the queryset

I tried the below code

class TestViewSet(
    mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet
):

    serializer_class = TestSerializer

    def get_queryset(self):
        return Test.objects.using(self.user.name).all()


问:
when i do calculation num1 + num 2 anwser is coming num1+num2undefind on screen

(function () {
    let screen = document.querySelector('.screen');
    let buttons = document.querySelectorAll('.btn');
    let clear = document.querySelector('.btn-clear');
    let equal = document.querySelector('.btn-equal');

    buttons.forEach(function (button) {
        button.addEventListener('click', function (e) {
            let value = e.target.dataset.num;
            screen.value += value;
        });
    });

    equal.addEventListener('click', function () {
        if (screen.value == '') {
            screen.value = "Please Enter Value";
        } else {
            let answer = eval(screen.value)
            screen.value = answer;
        }

    });

})();
```

when i  do calculation num1 + num 2 anwser is coming num1+num2undefind on screen
but answer should be like num1 + num 2 = answer

Body:
(function () {
    let screen = document.querySelector('.screen');
    let buttons = document.querySelectorAll('.btn');
    let clear = document.querySelector('.btn-clear');
    let equal = document.querySelector('.btn-equal');

    buttons.forEach(function (button) {
        button.addEventListener('click', function (e) {
            let value = e.target.dataset.num;
            screen.value += value;
        });
    });

    equal.addEventListener('click', function () {
        if (screen.value == '') {
            screen.value = "Please Enter Value";
        } else {
            let answer = eval(screen.value)
            screen.value = answer;
        }

    });

})();

when i  do calculation num1 + num 2 anwser is coming num1+num2undefind on screen
but answer should be like num1 + num 2 = answer


问:
How to enable referential integrity of many to one relationship before persistence
my App should model a statemachine.
For this I have the Entities Statemachine and State. A statemachine may have many States. A state belongs to only statemachine.

I established a bidirectional relation by adding  a @ManyToOne Annotation in class State
and a @OneToMany Annotation in class Statemachine.

Both classes have Id with

```<code>@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
</code>```

In class Statemachine I have Method addState(State aState)
Within this method I make sure that the reference to the Statemachine in the State Object is set.

```<code>public void addState(State aState) {
    aState.setStatemachineid(this.getId());
    states.add(aState);
}
</code>```

This works fine, as long as the statemachine has been saved before and a valid id is present,
but something like this would not work.

```<code>@Test
void addStateToStatemachineTest() {

    StateMachine sm = new StateMachine();

    sm.addState(new State("StartState", "This is the Start State of the Machine" ));

    smRepo.save(sm);

}
</code>```

I assume that there is a common pattern for this problem.

Body:
my App should model a statemachine.
For this I have the Entities Statemachine and State. A statemachine may have many States. A state belongs to only statemachine.

I established a bidirectional relation by adding  a @ManyToOne Annotation in class State
and a @OneToMany Annotation in class Statemachine.

Both classes have Id with

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

In class Statemachine I have Method addState(State aState)
Within this method I make sure that the reference to the Statemachine in the State Object is set.

public void addState(State aState) {
    aState.setStatemachineid(this.getId());
    states.add(aState);
}

This works fine, as long as the statemachine has been saved before and a valid id is present,
but something like this would not work.

@Test
void addStateToStatemachineTest() {

    StateMachine sm = new StateMachine();

    sm.addState(new State("StartState", "This is the Start State of the Machine" ));

    smRepo.save(sm);

}

I assume that there is a common pattern for this problem.


问:
Why is sum of series coming as fractional and less than the actual values in graphite
I am creating a dashboard using metrics in graphite. I have tried consolidatedBy to get all the metrics. The metric values looks correct and are of the range of 1000s.

The graphite query for the same is

```<code>consolidateBy(monitors.x.y.z.client_metrics.k.*.*.*.*.*.response_codes.*.count, 'sum')
</code>```

I want to get the total number of requests, which would be sum of all this series.
So, I tried the sum function but it is giving the sum around 1-12, which is actually less than the actual values.

The query is

```<code>sum(consolidateBy(monitors.x.y.z.client_metrics.k.*.*.*.*.*.response_codes.*.count, 'sum'))
</code>```

This query also gives the same result

```<code>sum(monitors.x.y.z.client_metrics.k.*.*.*.*.*.response_codes.*.count)
</code>```

My questions are:

Why is the sum of series giving point's value less than the actual values ?

I just want to calculate the total number of requests. If there is an easier solution. Can you please specify it.

Body:
I am creating a dashboard using metrics in graphite. I have tried consolidatedBy to get all the metrics. The metric values looks correct and are of the range of 1000s.

The graphite query for the same is

consolidateBy(monitors.x.y.z.client_metrics.k.*.*.*.*.*.response_codes.*.count, 'sum')

I want to get the total number of requests, which would be sum of all this series.
So, I tried the sum function but it is giving the sum around 1-12, which is actually less than the actual values.

The query is

sum(consolidateBy(monitors.x.y.z.client_metrics.k.*.*.*.*.*.response_codes.*.count, 'sum'))

This query also gives the same result

sum(monitors.x.y.z.client_metrics.k.*.*.*.*.*.response_codes.*.count)

My questions are:

Why is the sum of series giving point's value less than the actual values ?

I just want to calculate the total number of requests. If there is an easier solution. Can you please specify it.


问:
React state causing weird behavior on conditional disable attribute on button when backspacing an input within a field
I have just started using react and created a basic form which consists 3 fields (username, password and a submit button). I am only using reducers and state within this component and while testing out my validation I picked up that the button enabled property as a reverse reaction if I enter a correct email, backspace the '@' character and enter the '@' character back. What should happen is if the entered email doesn't include an '@' I set formIsValid property to false and if it does then I set it to true which enable the login button. I have a hunch that maybe the component isn't re-rendering but I have no idea on how to prove this nor fix this.

Screenshot of validation fails but button is still enabled

adding the '@' in email now disables button

This only occurs if I type something and then start backspacing and re-entering into the field, If I go in the order of filling in the email and then filling in the password as needed then is works as it should

Component :

```<code>import React,
// eslint-disable-next-line
{ useEffect, useState, useReducer } from 'react';

import Card from '../UI/Card/Card';
import classes from './Login.module.css';
import Button from '../UI/Button/Button';

const emailReducer = (state, action) => {
  if(action.type === 'USER_INPUT') {
    return {value: action.val, isValid: action.val.includes('@') };
  }
  if (action.type === 'INPUT_BLUR') {
    return {value: state.value, isValid: state.value.includes('@') };
  }
  return { value: '', isValid: false }
};

const passwordReducer = (state, action) => {
  if(action.type === 'USER_INPUT') {
    return {value: action.val, isValid: action.val.trim().length > 6}
  }
  if(action.type === 'INPUT_BLUR') {
    return {value: state.value, isValid: state.value.trim().length > 6}
  }
};

const Login = (props) => {
  // const [enteredEmail, setEnteredEmail] = useState('');
  // const [emailIsValid, setEmailIsValid] = useState();
  const [formIsValid, setFormIsValid] = useState(false);

  const [emailState, dispatchEmail] = useReducer(emailReducer, {value: '', isValid: null});
  const [passwordState, dispatchPassword] = useReducer(passwordReducer, {value: '', isValid: null})

  const emailChangeHandler = (event) => {
    dispatchEmail({type: 'USER_INPUT', val: event.target.value});

    setFormIsValid(
      emailState.isValid && passwordState.isValid
    );
  };

  // useEffect(() => {
  //   const identifier = setTimeout(() => {
  //     setFormIsValid(
  //       enteredEmail.includes('@') && enteredPassword.trim().length > 6
  //     );
  //   }, 500);

  //   return () => {
  //     console.log('CLEANUP');
  //     clearTimeout(identifier);
  //   };
  // }, [enteredEmail, enteredPassword]);

  const passwordChangeHandler = (event) => {
    dispatchPassword({type: 'USER_INPUT', val: event.target.value});

    setFormIsValid(
      passwordState.isValid && emailState.isValid
    );
  };

  const validateEmailHandler = () => {
    dispatchEmail({type: 'INPUT_BLUR'});
  };

  const validatePasswordHandler = () => {
    dispatchPassword({type: 'INPUT_BLUR'})
  };

  const submitHandler = (event) => {
    event.preventDefault();
    props.onLogin(emailState.value, passwordState.value);
  };

  return (
    <Card className={classes.login}>
      <form onSubmit={submitHandler}>
        <div
          className={`${classes.control} ${emailState.isValid === false ? classes.invalid : ''
            }`}
        >
          <label htmlFor="email">E-Mail</label>
          <input
            type="email"
            id="email"
            value={emailState.value}
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />
        </div>
        <div
          className={`${classes.control} ${passwordState.isValid === false ? classes.invalid : ''
            }`}
        >
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            value={passwordState.value}
            onChange={passwordChangeHandler}
            onBlur={validatePasswordHandler}
          />
        </div>
        <div className={classes.actions}>
          <Button type="submit" className={classes.btn} disabled={!formIsValid}>
            Login
          </Button>
        </div>
      </form>
    </Card>
  );
};

export default Login;
</code>```

The above code has 2 reducers, 1 for email state and 1 for password state

stateObject:

```<code>{
   value: '',
   isValid: false
}
</code>```

I am using the useState hook to only manage if the entire form is valid which is basically determined by emailState.IsValid && passwordState.IsValid

Also I am listening for onchange events on both input fields which executes my reducer functions for their respective state

I tried removing the expression that uses the reducer state and went with

event.target.value.includes('@') && passwordState.isValid thinking that maybe the reducer state is not updating in time before my component renders but that did not work. Any help pointing me to where the problem is and what is causing this would be really appreciated, thanks in advance

Body:
I have just started using react and created a basic form which consists 3 fields (username, password and a submit button). I am only using reducers and state within this component and while testing out my validation I picked up that the button enabled property as a reverse reaction if I enter a correct email, backspace the '@' character and enter the '@' character back. What should happen is if the entered email doesn't include an '@' I set formIsValid property to false and if it does then I set it to true which enable the login button. I have a hunch that maybe the component isn't re-rendering but I have no idea on how to prove this nor fix this.

Screenshot of validation fails but button is still enabled

adding the '@' in email now disables button

This only occurs if I type something and then start backspacing and re-entering into the field, If I go in the order of filling in the email and then filling in the password as needed then is works as it should

Component :

import React,
// eslint-disable-next-line
{ useEffect, useState, useReducer } from 'react';

import Card from '../UI/Card/Card';
import classes from './Login.module.css';
import Button from '../UI/Button/Button';

const emailReducer = (state, action) => {
  if(action.type === 'USER_INPUT') {
    return {value: action.val, isValid: action.val.includes('@') };
  }
  if (action.type === 'INPUT_BLUR') {
    return {value: state.value, isValid: state.value.includes('@') };
  }
  return { value: '', isValid: false }
};

const passwordReducer = (state, action) => {
  if(action.type === 'USER_INPUT') {
    return {value: action.val, isValid: action.val.trim().length > 6}
  }
  if(action.type === 'INPUT_BLUR') {
    return {value: state.value, isValid: state.value.trim().length > 6}
  }
};

const Login = (props) => {
  // const [enteredEmail, setEnteredEmail] = useState('');
  // const [emailIsValid, setEmailIsValid] = useState();
  const [formIsValid, setFormIsValid] = useState(false);

  const [emailState, dispatchEmail] = useReducer(emailReducer, {value: '', isValid: null});
  const [passwordState, dispatchPassword] = useReducer(passwordReducer, {value: '', isValid: null})

  const emailChangeHandler = (event) => {
    dispatchEmail({type: 'USER_INPUT', val: event.target.value});

    setFormIsValid(
      emailState.isValid && passwordState.isValid
    );
  };

  // useEffect(() => {
  //   const identifier = setTimeout(() => {
  //     setFormIsValid(
  //       enteredEmail.includes('@') && enteredPassword.trim().length > 6
  //     );
  //   }, 500);

  //   return () => {
  //     console.log('CLEANUP');
  //     clearTimeout(identifier);
  //   };
  // }, [enteredEmail, enteredPassword]);

  const passwordChangeHandler = (event) => {
    dispatchPassword({type: 'USER_INPUT', val: event.target.value});

    setFormIsValid(
      passwordState.isValid && emailState.isValid
    );
  };

  const validateEmailHandler = () => {
    dispatchEmail({type: 'INPUT_BLUR'});
  };

  const validatePasswordHandler = () => {
    dispatchPassword({type: 'INPUT_BLUR'})
  };

  const submitHandler = (event) => {
    event.preventDefault();
    props.onLogin(emailState.value, passwordState.value);
  };

  return (
    <Card className={classes.login}>
      <form onSubmit={submitHandler}>

          E-Mail
          <input
            type="email"
            id="email"
            value={emailState.value}
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />

          Password
          <input
            type="password"
            id="password"
            value={passwordState.value}
            onChange={passwordChangeHandler}
            onBlur={validatePasswordHandler}
          />

          <Button type="submit" className={classes.btn} disabled={!formIsValid}>
            Login
          </Button>

      </form>
    </Card>
  );
};

export default Login;

The above code has 2 reducers, 1 for email state and 1 for password state

stateObject:

{
   value: '',
   isValid: false
}

I am using the useState hook to only manage if the entire form is valid which is basically determined by emailState.IsValid && passwordState.IsValid

Also I am listening for onchange events on both input fields which executes my reducer functions for their respective state

I tried removing the expression that uses the reducer state and went with

event.target.value.includes('@') && passwordState.isValid thinking that maybe the reducer state is not updating in time before my component renders but that did not work. Any help pointing me to where the problem is and what is causing this would be really appreciated, thanks in advance


问:
TeamCity Error - Unable to collect Changes
I am getting an error in TeamCity When making a new private build. It is not picking up any changes.

The error is Failed to collect changes, error: git -c core.askpass=D:\TeamCity\install\temp\pass802548814093469879.bat -c credential.helper= ls-remote origin command failed.
exit code: 128
stderr: fatal: unable to access 'http://gitserver.xyz.com/pureohs/abc-def/': Failed to connect to gitserver.abcdef.com port 80 after 31 ms: Address already in use, VCS root: "git :: XYZ Template" {instance id=2027, parent internal id=183, parent id=GitABCXYZTemplate, description: "http://gitserver.xyz.com/abcdef/abc-def#master"}

i tried deleting the git cache, but this is not solving the problem. Please help me with the issue.

So i am trying to create a private build and get rid of this error.


问:
Possible to apply ETL and linking processes to a variable collection of files in a Sharepoint folder?
Every month I have to manually export 40+ reports (excel files generally) into a SharePoint folder. I want to create a power query in Excel to link all the reports (based on a common field in all reports) and include only 2-3 columns of data from each report.

How can I use ETL in Power Query to create queries that can apply to new reports each month, without having to redo the queries each month for the new reports?


问:
PendingIntent Broadcast is always running after upgrading to API 31
The BroadcastReceiver was working perfectly in targetSdkVersion 30. After upgrading to 31, I added PendingIntent.FLAG_MUTABLE then the Broadcast is always running even though I change the CODE and it can't be cancelled.

Code:

```<code>    Intent myIntent = new Intent(mContext, FetchDataReceiver.class);

    final int isAlarmUpFlag = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ?
            PendingIntent.FLAG_NO_CREATE | PendingIntent.FLAG_MUTABLE: PendingIntent.FLAG_NO_CREATE;
    boolean isAlarmUp = (PendingIntent.getBroadcast(mContext, MY_CODE,
            myIntent,  isAlarmUpFlag) != null);
</code>```

isAlarmUp is always TRUE.

Body:
The BroadcastReceiver was working perfectly in targetSdkVersion 30. After upgrading to 31, I added PendingIntent.FLAG_MUTABLE then the Broadcast is always running even though I change the CODE and it can't be cancelled.

Code:

    Intent myIntent = new Intent(mContext, FetchDataReceiver.class);

    final int isAlarmUpFlag = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ?
            PendingIntent.FLAG_NO_CREATE | PendingIntent.FLAG_MUTABLE: PendingIntent.FLAG_NO_CREATE;
    boolean isAlarmUp = (PendingIntent.getBroadcast(mContext, MY_CODE,
            myIntent,  isAlarmUpFlag) != null);

isAlarmUp is always TRUE.