问:
Find the smallest positive integer that does not occur in a given sequence
I was trying to solve this problem:

Write a function:

```<code>class Solution { public int solution(int[] A); }
</code>```

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

```<code>Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.
</code>```

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

        for (int i = 0; i < N; i++) {

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

        for (int i = 0; i < N; i++) {

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

```

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

答:
Ruby 2.2 solution. Total score 77% due to somewhat weak performance.</p>
```<code>def solution(a)
  positive_sorted = a.uniq.sort.select {|i| i > 0 }
  return 1 if (positive_sorted.empty? || positive_sorted.first > 1)

  positive_sorted.each do |i|
    res = i + 1
    next if positive_sorted.include?(res)
    return res
  end
end
</code>```

Body:
I was trying to solve this problem:

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

        for (int i = 0; i < N; i++) {

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

        for (int i = 0; i < N; i++) {

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

Body:
Ruby 2.2 solution. Total score 77% due to somewhat weak performance.

def solution(a)
  positive_sorted = a.uniq.sort.select {|i| i > 0 }
  return 1 if (positive_sorted.empty? || positive_sorted.first > 1)

  positive_sorted.each do |i|
    res = i + 1
    next if positive_sorted.include?(res)
    return res
  end
end


来源: stackexchange

问:
How get nft-tokens of a contract which are available in a wallet address by web3
I have a NFTs-Contract address on ethereum. I want to know a wallet address have which token of my contract. How can I get list of tokenId which are in a wallet address by web3?

```<code>const Web3 = require("web3");const provider = "https://lively-withered-grass.quiknode.pro"
const Web3Client = new Web3(new Web3.providers.HttpProvider(provider));
const minABI = [
    {
        constant: true,
        inputs: [{name: "_owner", type: "address"}],
        name: "balanceOf",
        outputs: [{name: "balance", type: "uint256"}],
        type: "function",
    },
];
const tokenAddress = "0x0d8775f648430679a709e98d2b0cb6250d2887ef";
const walletAddress = "0x1cf56Fd8e1567f8d663e54050d7e44643aF970Ce";
const contract = new Web3Client.eth.Contract(minABI, tokenAddress);
async function getBalance() {
    const result = await contract.methods.balanceOf(walletAddress).call();
    const format = Web3Client.utils.fromWei(result); // 29803630.997051883414242659
    console.log(format);
}
getBalance();
</code>```

I am able to know that in a wallet address whether or not any my token but it doesn't give me any information about which token are existed in wallet.

Do you have any solution?

答:
you must be use from etherscan.io service's(API's)

for your problem you can use this and parse information till get access your request

https://docs.etherscan.io/api-endpoints/accounts#get-a-list-of-erc721-token-transfer-events-by-address

ContentLicense: CC BY-SA 4.0

Body:
I have a NFTs-Contract address on ethereum. I want to know a wallet address have which token of my contract. How can I get list of tokenId which are in a wallet address by web3?

const Web3 = require("web3");const provider = "https://lively-withered-grass.quiknode.pro"
const Web3Client = new Web3(new Web3.providers.HttpProvider(provider));
const minABI = [
    {
        constant: true,
        inputs: [{name: "_owner", type: "address"}],
        name: "balanceOf",
        outputs: [{name: "balance", type: "uint256"}],
        type: "function",
    },
];
const tokenAddress = "0x0d8775f648430679a709e98d2b0cb6250d2887ef";
const walletAddress = "0x1cf56Fd8e1567f8d663e54050d7e44643aF970Ce";
const contract = new Web3Client.eth.Contract(minABI, tokenAddress);
async function getBalance() {
    const result = await contract.methods.balanceOf(walletAddress).call();
    const format = Web3Client.utils.fromWei(result); // 29803630.997051883414242659
    console.log(format);
}
getBalance();

I am able to know that in a wallet address whether or not any my token but it doesn't give me any information about which token are existed in wallet.

Do you have any solution?


问:
depth-first algorithm in python does not work
I have some project which I decide to do in Python. In brief: I have list of lists. Each of them also have lists, sometimes one-element, sometimes more. It looks like this:

```<code>rules=[
[[1],[2],[3,4,5],[4],[5],[7]]
[[1],[8],[3,7,8],[3],[45],[12]]
[[31],[12],[43,24,57],[47],[2],[43]]
]
</code>```

The point is to compare values from numpy array to values from this rules (elements of rules table). We are comparing some [x][y] point to first element (e.g. 1 in first element), then, if it is true, value [x-1][j] from array with second from list and so on. Five first comparisons must be true to change value of [x][y] point. I've wrote sth like this (main function is SimulateLoop, order are switched because simulate2 function was written after second one):

```<code>def simulate2(self, i, j, w, rule):
        data = Data(rule)
        if w.world[i][j] in data.c:
            if w.world[i-1][j] in data.n:
                if w.world[i][j+1] in data.e:
                    if w.world[i+1][j] in data.s:
                        if w.world[i][j-1] in data.w:
                            w.world[i][j] = data.cc[0]
                        else: return
                    else: return
                else: return
            else: return
        else: return

def SimulateLoop(self,w):
    for z in range(w.steps):
            for i in range(2,w.x-1):
                for j in range(2,w.y-1):
                    for rule in w.rules:
                        self.simulate2(i,j,w,rule)
</code>```

Data class:

```<code>class Data:
    def __init__(self, rule):
        self.c = rule[0]
        self.n = rule[1]
        self.e = rule[2]
        self.s = rule[3]
        self.w = rule[4]
        self.cc = rule[5]
</code>```

NumPy array is a object from World class. Rules is list as described above, parsed by function obtained from another program (GPL License).

To be honest it seems to work fine, but it does not. I was trying other possibilities, without luck. It is working, interpreter doesn't return any errors, but somehow values in array changing wrong. Rules are good because it was provided by program from which I've obtained parser for it (GPL license).

Maybe it will be helpful - it is Perrier's Loop, modified Langton's loop (artificial life).

Will be very thankful for any help!
)

答:
I am not familiar with Perrier's Loop, but if you code something like famous "game life" you would have done simple mistake: store the next generation in the same array thus corrupting it.

Normally you store the next generation in temporary array and do copy/swap after the sweep, like in this sketch:

```<code>def do_step_in_game_life(world):
    next_gen = zeros(world.shape)    # <<< Tmp array here
    Nx, Ny = world.shape
    for i in range(1, Nx-1):
        for j in range(1, Ny-1):
            neighbours = sum(world[i-1:i+2, j-1:j+2]) - world[i,j]
            if neighbours < 3:
                next_gen[i,j] = 0
            elif ...
    world[:,:] = next_gen[:,:]       # <<< Saving computed next generation
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have some project which I decide to do in Python. In brief: I have list of lists. Each of them also have lists, sometimes one-element, sometimes more. It looks like this:

rules=[
[[1],[2],[3,4,5],[4],[5],[7]]
[[1],[8],[3,7,8],[3],[45],[12]]
[[31],[12],[43,24,57],[47],[2],[43]]
]

The point is to compare values from numpy array to values from this rules (elements of rules table). We are comparing some [x][y] point to first element (e.g. 1 in first element), then, if it is true, value [x-1][j] from array with second from list and so on. Five first comparisons must be true to change value of [x][y] point. I've wrote sth like this (main function is SimulateLoop, order are switched because simulate2 function was written after second one):

def simulate2(self, i, j, w, rule):
        data = Data(rule)
        if w.world[i][j] in data.c:
            if w.world[i-1][j] in data.n:
                if w.world[i][j+1] in data.e:
                    if w.world[i+1][j] in data.s:
                        if w.world[i][j-1] in data.w:
                            w.world[i][j] = data.cc[0]
                        else: return
                    else: return
                else: return
            else: return
        else: return

def SimulateLoop(self,w):
    for z in range(w.steps):
            for i in range(2,w.x-1):
                for j in range(2,w.y-1):
                    for rule in w.rules:
                        self.simulate2(i,j,w,rule)

Data class:

class Data:
    def __init__(self, rule):
        self.c = rule[0]
        self.n = rule[1]
        self.e = rule[2]
        self.s = rule[3]
        self.w = rule[4]
        self.cc = rule[5]

NumPy array is a object from World class. Rules is list as described above, parsed by function obtained from another program (GPL License).

To be honest it seems to work fine, but it does not. I was trying other possibilities, without luck. It is working, interpreter doesn't return any errors, but somehow values in array changing wrong. Rules are good because it was provided by program from which I've obtained parser for it (GPL license).

Maybe it will be helpful - it is Perrier's Loop, modified Langton's loop (artificial life).

Will be very thankful for any help!
)

Body:
I am not familiar with Perrier's Loop, but if you code something like famous "game life" you would have done simple mistake: store the next generation in the same array thus corrupting it.

Normally you store the next generation in temporary array and do copy/swap after the sweep, like in this sketch:

def do_step_in_game_life(world):
    next_gen = zeros(world.shape)    # <<< Tmp array here
    Nx, Ny = world.shape
    for i in range(1, Nx-1):
        for j in range(1, Ny-1):
            neighbours = sum(world[i-1:i+2, j-1:j+2]) - world[i,j]
            if neighbours < 3:
                next_gen[i,j] = 0
            elif ...
    world[:,:] = next_gen[:,:]       # <<< Saving computed next generation

ContentLicense: CC BY-SA 3.0


问:
Table not loading on power bi desktop
I am getting the following error when i am trying to load a table from hive in power bi desktop.

"OLE DB or ODBC error: [DataSource.Error] ERROR [HY000] [Hortonworks][Hardy] (35) Error from server: error code: '0' error message: 'Invalid OperationHandle: OperationHandle [opType=EXECUTE_STATEMENT, getHandleIdentifier()=e3ffaec5-d446-4a22-adc5-a859d2abfd2a]"

答:
I was got this error until ago.

Because my systems have -Power BI and Windows Server- different formats. I could fix it going to Control Panel > Region > Formats > English
(United States)

Other case you can check column types. If you are doing type
conversion, you should check the data content or Dax function.

Title: Table not loading on power bi desktop


问:
Keyboard pushes FooterView up when its opening < TextView > Swift
I have a problem that I couldn't find any appropriate solution.
I have a tableView with custom cells which holds a textView inside.
also I have a blank grey footer for the section.
whenever I click on the textView and the keyboard pops up the footer in that section goes up and hides behind the textView field.

I don't know how to make that footer sticky so it won't move when the keyboard pops.
if anyone have a solution it will be great!
thank you!

```<code>    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    if section == 0 {
        let footerView = UIView()
        footerView.backgroundColor = .red
            return footerView
    }else {
        return UIView()
    }
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 8
}
</code>```

答:
Set your tableView as grouped give height to the tableview footer and tableView Header in the tableview header,footer height functions.

If you are not using tableview header the set the height of the header to .leastNormalMagnitude .

This is the way to make the tableView Footer Static.

Body:
I have a problem that I couldn't find any appropriate solution.
I have a tableView with custom cells which holds a textView inside.
also I have a blank grey footer for the section.
whenever I click on the textView and the keyboard pops up the footer in that section goes up and hides behind the textView field.

I don't know how to make that footer sticky so it won't move when the keyboard pops.
if anyone have a solution it will be great!
thank you!

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    if section == 0 {
        let footerView = UIView()
        footerView.backgroundColor = .red
            return footerView
    }else {
        return UIView()
    }
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 8
}


问:
How to use va_arg to modify the value of a variadic parameter in C

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

void tag_log(const char *format, ...) {
    va_list ap;
    va_start(ap, format);
    for (int i = 0; i < 4; i++) {
        va_arg(ap, int) += 100; // is wrong?
    }
    va_end(ap);
    va_start(ap, format);
    vprintf(format, ap);
    va_end(ap);
}

int main() {
    tag_log("%d, %d, %d, %d\n", 1, 2, 3, 4);
}
```

Since va_arg returns an rvalue, the content cannot be modified. How to modify the content of the variable parameter?

Expected output: 101, 102, 103, 104

thanks!!!

How should i do?

答:
Assume that you call:

```<code>int main() {
    tag_log("%d, %s, %d, %d\n", 1, "My precious values", 3, 4);
}
</code>```

How will you deal with that in your tag_log()?  are you going to reinterpret the pointer passed to the string literal and adding 100 to it?

The answer to this question is "you cannot",

```<code>        va_arg(ap, int) += 100; // is wrong?
</code>```

is equivalent to an rvalue  (the result of a function value or a macro call, converted to a type specified in the second parameter to the macro call), so you cannot change it.  An rvalue is just a value, without any reference to where it is stored.  This is how parameters are passed to functions, and how values are returned from functions, but while explicit parameter declarations result in local variables (that can be used as lvalues and modified), the expression returned by the va_arg() macro is an rvalue, and so, you cannot change it (as you cannot change in a program the literal value 3)  The situation is the same as if you had:

```<code>#define PARAMETER 3
</code>```

and you say

```<code>    PARAMETER = 5;
</code>```

(well, not exactly the same... but the effect is the same)
even the statemente looks like a variable assignment, you have an rvalue (3) being assigned another rvalue(5), in something like

```<code>    3 = 5;
</code>```

Can you do this?  nope.

But you have a solution... just create a local variable and assign it the value returned by va_arg.

```<code>    int var = va_arg(ap, int);
    var += 100;  // this is not wrong anymore.
</code>```

or use the rvalue in the expression you want:

```<code>    whatever_int_variable = va_arg(ap, int) + 100;  // this is also valid.
</code>```

If you consider that the "%s, %s, %s, %s\n" literal string should always be fixed, then it should be better for you to do:

```<code>#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

void tag_log(int a, int b, int c, int d) {
   printf("%d, %d, %d, %d\n", a, b, c, d);
}

int main() {
    tag_log(1, 2, 3, 4);
}
</code>```

but I imagine that what you want to do is to be as general as printf is, making all possible format strings.... then you need to dig into the body of printf and see how it solves each of the format specifiers and do the same in your function.  You cand divide the work, by selecting all the format specifiers, and divide the string literal into places where literal strings are printed only, and separate all the format specifiers to individually call printf with each parameter, but the sample code you specified is not well specified, so I think is no worth considering to add 100 to break the string parameter to separate the literal formats from the format specifiers and add 100 to all the integer parameters, or to add 100.0 to the double, what should we do with the string literals, or with the booleans?

Body:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

void tag_log(const char *format, ...) {
    va_list ap;
    va_start(ap, format);
    for (int i = 0; i < 4; i++) {
        va_arg(ap, int) += 100; // is wrong?
    }
    va_end(ap);
    va_start(ap, format);
    vprintf(format, ap);
    va_end(ap);
}

int main() {
    tag_log("%d, %d, %d, %d\n", 1, 2, 3, 4);
}

Since va_arg returns an rvalue, the content cannot be modified. How to modify the content of the variable parameter?

Expected output: 101, 102, 103, 104

thanks!!!

How should i do?

Body:
Assume that you call:

int main() {
    tag_log("%d, %s, %d, %d\n", 1, "My precious values", 3, 4);
}

How will you deal with that in your tag_log()?  are you going to reinterpret the pointer passed to the string literal and adding 100 to it?

The answer to this question is "you cannot",

        va_arg(ap, int) += 100; // is wrong?

is equivalent to an rvalue  (the result of a function value or a macro call, converted to a type specified in the second parameter to the macro call), so you cannot change it.  An rvalue is just a value, without any reference to where it is stored.  This is how parameters are passed to functions, and how values are returned from functions, but while explicit parameter declarations result in local variables (that can be used as lvalues and modified), the expression returned by the va_arg() macro is an rvalue, and so, you cannot change it (as you cannot change in a program the literal value 3)  The situation is the same as if you had:

#define PARAMETER 3

and you say

    PARAMETER = 5;

(well, not exactly the same... but the effect is the same)
even the statemente looks like a variable assignment, you have an rvalue (3) being assigned another rvalue(5), in something like

    3 = 5;

Can you do this?  nope.

But you have a solution... just create a local variable and assign it the value returned by va_arg.

    int var = va_arg(ap, int);
    var += 100;  // this is not wrong anymore.

or use the rvalue in the expression you want:

    whatever_int_variable = va_arg(ap, int) + 100;  // this is also valid.

If you consider that the "%s, %s, %s, %s\n" literal string should always be fixed, then it should be better for you to do:

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

void tag_log(int a, int b, int c, int d) {
   printf("%d, %d, %d, %d\n", a, b, c, d);
}

int main() {
    tag_log(1, 2, 3, 4);
}

but I imagine that what you want to do is to be as general as printf is, making all possible format strings.... then you need to dig into the body of printf and see how it solves each of the format specifiers and do the same in your function.  You cand divide the work, by selecting all the format specifiers, and divide the string literal into places where literal strings are printed only, and separate all the format specifiers to individually call printf with each parameter, but the sample code you specified is not well specified, so I think is no worth considering to add 100 to break the string parameter to separate the literal formats from the format specifiers and add 100 to all the integer parameters, or to add 100.0 to the double, what should we do with the string literals, or with the booleans?


问:
Deserialize anonym JSON array into Model with List C#
I have JSON like

```<code>[
  {
    "Id":"1"
  },
  {
    "Id":"2"
  }
]
</code>```

And I have models

```<code>public class ModelList
{
   public List<Model> Models {get; set;}
}

public class Model
{
   public string Id {get; set;}
}
</code>```

Can I Deserialize this json to ModelList like:

```<code>var model = JsonConvert.DeserializeObject<ModelList>(strJson); - This code throw error

var model = JsonConvert.DeserializeObject<List<Model>>(strJson); - This works fine, but I need to deserialize into my model, not List
</code>```

In other words, I need to bind the array that comes to me in json to the model property

答:
try this

```<code>ModelList modelList =  new ModelList{
 Models=JsonConvert.DeserializeObject<List<Model>>(strJson)
};
</code>```

or you can use a model constructor

```<code>ModelList modelList = new ModelList (JsonConvert.DeserializeObject<List<Model>>(strJson));

public class ModelList
{
   public List<Model> Models {get; set;}

    public ModelList(List<Model> models)
   {
      Models=models;
   }
}
</code>```

or you will have to correct your json according to a ModelList

```<code> {"Models": [
  {
    "Id":"1"
  },
  {
    "Id":"2"
  }
]}
</code>```

and then

```<code>ModelList modelList = JsonConvert.DeserializeObject<ModelList>(strJson);
</code>```

Body:
I have JSON like

[
  {
    "Id":"1"
  },
  {
    "Id":"2"
  }
]

And I have models

public class ModelList
{
   public List<Model> Models {get; set;}
}

public class Model
{
   public string Id {get; set;}
}

Can I Deserialize this json to ModelList like:

var model = JsonConvert.DeserializeObject<ModelList>(strJson); - This code throw error

var model = JsonConvert.DeserializeObject<List<Model>>(strJson); - This works fine, but I need to deserialize into my model, not List

In other words, I need to bind the array that comes to me in json to the model property

Body:
try this

ModelList modelList =  new ModelList{
 Models=JsonConvert.DeserializeObject<List<Model>>(strJson)
};

or you can use a model constructor

ModelList modelList = new ModelList (JsonConvert.DeserializeObject<List<Model>>(strJson));

public class ModelList
{
   public List<Model> Models {get; set;}

    public ModelList(List<Model> models)
   {
      Models=models;
   }
}

or you will have to correct your json according to a ModelList

 {"Models": [
  {
    "Id":"1"
  },
  {
    "Id":"2"
  }
]}

and then

ModelList modelList = JsonConvert.DeserializeObject<ModelList>(strJson);


问:
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError
I have an error message:

```<code>ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(MarketModule)
[IndiceService -> IndiceService -> IndiceService -> IndiceService -> IndiceService]:
NullInjectorError: No provider for IndiceService! NullInjectorError:
R3InjectorError(MarketModule)[IndiceService -> IndiceService
</code>```

Error in the console

the indice.service.ts file is presented like this:

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { IndiceResponse } from './folder/indice.response';

@Injectable()

export class IndiceService {

  private readonly api: string = environment.api;

  constructor(private http: HttpClient) { }

  getIndices(): Observable<IndiceResponse> {
    return this.http.post<IndiceResponse>(this.api + `/AZEMONDL`, {
      FILTRE: {
        LASTACTIF_CODE: "1W"
      }
    });
  }

}
</code>```

indice.component.ts file

```<code>import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Subject, takeUntil } from 'rxjs';
import { CreateDateTimePipe } from 'src/app/shared/pipes/create-date-time.pipe';
import { Indice } from './folder/indice';
import { IndiceService } from './indice.service';

@Component({
  selector: 'app-indice',
  templateUrl: './indice.component.html',
  styleUrls: ['./indice.component.css']
})
export class IndiceComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject<void>();

  indices: Indice[] = [];
  selectedIndex: string = '';

  indiceDatas: any;

  constructor(
    private service: IndiceService,
    private router: Router,
    private createDateTimePipe: CreateDateTimePipe) { }

  ngOnInit(): void {
    this.getIndices();
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
</code>```

I also have a strange message for the Router:

```<code>Property 'router' is declared but its value is never read.
</code>```

Error Visual Studio Code

indice.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { RouterModule } from '@angular/router';
import { PipesModule } from 'src/app/shared/pipes/pipes.module';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule,
    PipesModule,
  ]
})

export class IndiceModule { }
</code>```

I don't know where these problems come from? Thank you for your help.

答:
```<code>@Injectable({
    providedIn: "root"
})
export class IndiceService {
</code>```

Body:
I have an error message:

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(MarketModule)
[IndiceService -> IndiceService -> IndiceService -> IndiceService -> IndiceService]:
NullInjectorError: No provider for IndiceService! NullInjectorError:
R3InjectorError(MarketModule)[IndiceService -> IndiceService

Error in the console

the indice.service.ts file is presented like this:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { IndiceResponse } from './folder/indice.response';

@Injectable()

export class IndiceService {

  private readonly api: string = environment.api;

  constructor(private http: HttpClient) { }

  getIndices(): Observable<IndiceResponse> {
    return this.http.post<IndiceResponse>(this.api + `/AZEMONDL`, {
      FILTRE: {
        LASTACTIF_CODE: "1W"
      }
    });
  }

}

indice.component.ts file

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Subject, takeUntil } from 'rxjs';
import { CreateDateTimePipe } from 'src/app/shared/pipes/create-date-time.pipe';
import { Indice } from './folder/indice';
import { IndiceService } from './indice.service';

@Component({
  selector: 'app-indice',
  templateUrl: './indice.component.html',
  styleUrls: ['./indice.component.css']
})
export class IndiceComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject<void>();

  indices: Indice[] = [];
  selectedIndex: string = '';

  indiceDatas: any;

  constructor(
    private service: IndiceService,
    private router: Router,
    private createDateTimePipe: CreateDateTimePipe) { }

  ngOnInit(): void {
    this.getIndices();
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

I also have a strange message for the Router:

Property 'router' is declared but its value is never read.

Error Visual Studio Code

indice.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { RouterModule } from '@angular/router';
import { PipesModule } from 'src/app/shared/pipes/pipes.module';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule,
    PipesModule,
  ]
})

export class IndiceModule { }

I don't know where these problems come from? Thank you for your help.


问:
How to detect the last insert ID within a transaction in Yii using DAO?
That's the source code, I need to detect the ID (see the marked position between the two queries below).

```<code>$connection = Yii::app()->db;
$transaction=$connection->beginTransaction();
try {

    $q = "INSERT INTO `someTable1` .... ";
    $connection->createCommand($q)->execute(); // Single Row Inserted

    // HERE!! How to get the last insert ID from query above

    $q = "INSERT INTO `someTable2` ....
          WHERE id = LAST_INSERT_ID_FROM_FIRST_QUERY ";
    $connection->createCommand($q)->execute();

    $transaction->commit();

} catch (Exception $e) {
    // react on exception
    $trans->rollback();
}
</code>```

What would be the most suitable way to do that?

答:
For anyone yet interested:

ActiveRecord in saveMethod does this like

```<code>\Yii::$app->db->schema->insert($tableName, $values)
</code>```

It results like

```<code>["id" => 1]
</code>```

Schema in it's way does this:

```<code>public function insert($table, $columns)
{
    $command = $this->db->createCommand()->insert($table, $columns);
    if (!$command->execute()) {
        return false;
    }
    $tableSchema = $this->getTableSchema($table);
    $result = [];
    foreach ($tableSchema->primaryKey as $name) {
        if ($tableSchema->columns[$name]->autoIncrement) {
            $result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
            break;
        }

        $result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
    }

    return $result;
}
</code>```

I suggest rather use schema->insert. It supports composite identifiers and uses sequence name for fetching last ID

Body:
That's the source code, I need to detect the ID (see the marked position between the two queries below).

$connection = Yii::app()->db;
$transaction=$connection->beginTransaction();
try {

    $q = "INSERT INTO `someTable1` .... ";
    $connection->createCommand($q)->execute(); // Single Row Inserted

    // HERE!! How to get the last insert ID from query above

    $q = "INSERT INTO `someTable2` ....
          WHERE id = LAST_INSERT_ID_FROM_FIRST_QUERY ";
    $connection->createCommand($q)->execute();

    $transaction->commit();

} catch (Exception $e) {
    // react on exception
    $trans->rollback();
}

What would be the most suitable way to do that?

Body:
For anyone yet interested:

ActiveRecord in saveMethod does this like

\Yii::$app->db->schema->insert($tableName, $values)

It results like

["id" => 1]

Schema in it's way does this:

public function insert($table, $columns)
{
    $command = $this->db->createCommand()->insert($table, $columns);
    if (!$command->execute()) {
        return false;
    }
    $tableSchema = $this->getTableSchema($table);
    $result = [];
    foreach ($tableSchema->primaryKey as $name) {
        if ($tableSchema->columns[$name]->autoIncrement) {
            $result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
            break;
        }

        $result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
    }

    return $result;
}

I suggest rather use schema->insert. It supports composite identifiers and uses sequence name for fetching last ID


问:
insert into new column values generated from trigger
I want to create a trigger which generates an 18 digit code based on the value of several other columns in the table.

R-MU-WEST-RJS-9697 So basically my last 4 digit code is the STORE_CODE based on which I want to compare and insert that 18 digit code against it the column named as CODE_18DIGIT

Below is the select statement that generates the code

```<code>SELECT    'R-'
  || CASE
         WHEN INSTR (TRIM (r.state), ' ') > 1
         THEN
                SUBSTR (r.state, 1, 1)
             || SUBSTR (r.state, INSTR (r.state, ' ') + 1, 1)
         ELSE
             UPPER (SUBSTR (r.state, 1, 2))
     END
  || '-'
  || UPPER (SUBSTR (r.zone_name, 1, 4))
  || '-'
  || r.format_code
  || '-'
  || SUBSTR (r.store_code, 1, 4)
FROM tbl_rrsoc_store_info  r
WHERE r.ISACTIVE = 'Y';
</code>```

and the table description of tbl_rrsoc_store_info is below

```<code>Name                        Null     Type
--------------------------- -------- --------------
RRSOC_ID                    NOT NULL NUMBER
STORE_CODE                  NOT NULL NVARCHAR2(55)
STATE                                NVARCHAR2(55)
CITY                                 NVARCHAR2(55)
CODE_18DIGIT                         NVARCHAR2(18)
</code>```

答:
Architecturally, this is not a particularly good design.  You're violating basic rules of normalization by storing redundant data.  It would be much less objectionable to just create a view that computes the code or to add a computed column to the table instead.  But it sounds like you have decided that you want to use the trigger-based solution.

For simplicity, I'd create a function (note that the code you posted references multiple columns that don't exist in the table definition you posted.  My guess is that the columns exist and were omitted from your table definition but maybe you changed the column names in either your query or your table definition and didn't change them in the other).

```<code>create or replace function make_18digit_code(
  p_state tbl_rrsoc_store_info.state%type,
  p_zone_name tbl_rrsoc_store_info.zone_name%type, -- Note that your table definition doesn't include this column
  p_format_code tbl_rrsoc_store_info.format_code%type, -- Or this column
  p_store_code tbl_rrsoc_store_info.store_code%type
)
  return tbl_rrsoc_store_info.code_18digit%type
is
begin
  return 'R-'  ||
         CASE
         WHEN INSTR (TRIM (p_state), ' ') > 1
         THEN
                SUBSTR (p_state, 1, 1)
             || SUBSTR (p_state, INSTR (p_state, ' ') + 1, 1)
         ELSE
             UPPER (SUBSTR (p_state, 1, 2))
     END
  || '-'
  || UPPER (SUBSTR (p_zone_name, 1, 4))
  || '-'
  || p_format_code
  || '-'
  || SUBSTR (p_store_code, 1, 4);
end;
</code>```

Then you can simply call the function in the trigger

```<code>create or replace trigger trg_generate_code
  before insert or update on tbl_rrsoc_store_info
  for each row
begin
  :new.code_18digit := make_18digit_code( :new.state,
                                          :new.zoe_name,
                                          :new.format_code,
                                          :new.store_code );
end;
</code>```

Body:
I want to create a trigger which generates an 18 digit code based on the value of several other columns in the table.

R-MU-WEST-RJS-9697 So basically my last 4 digit code is the STORE_CODE based on which I want to compare and insert that 18 digit code against it the column named as CODE_18DIGIT

Below is the select statement that generates the code

SELECT    'R-'
  || CASE
         WHEN INSTR (TRIM (r.state), ' ') > 1
         THEN
                SUBSTR (r.state, 1, 1)
             || SUBSTR (r.state, INSTR (r.state, ' ') + 1, 1)
         ELSE
             UPPER (SUBSTR (r.state, 1, 2))
     END
  || '-'
  || UPPER (SUBSTR (r.zone_name, 1, 4))
  || '-'
  || r.format_code
  || '-'
  || SUBSTR (r.store_code, 1, 4)
FROM tbl_rrsoc_store_info  r
WHERE r.ISACTIVE = 'Y';

and the table description of tbl_rrsoc_store_info is below

Name                        Null     Type
--------------------------- -------- --------------
RRSOC_ID                    NOT NULL NUMBER
STORE_CODE                  NOT NULL NVARCHAR2(55)
STATE                                NVARCHAR2(55)
CITY                                 NVARCHAR2(55)
CODE_18DIGIT                         NVARCHAR2(18)

Body:
Architecturally, this is not a particularly good design.  You're violating basic rules of normalization by storing redundant data.  It would be much less objectionable to just create a view that computes the code or to add a computed column to the table instead.  But it sounds like you have decided that you want to use the trigger-based solution.

For simplicity, I'd create a function (note that the code you posted references multiple columns that don't exist in the table definition you posted.  My guess is that the columns exist and were omitted from your table definition but maybe you changed the column names in either your query or your table definition and didn't change them in the other).

create or replace function make_18digit_code(
  p_state tbl_rrsoc_store_info.state%type,
  p_zone_name tbl_rrsoc_store_info.zone_name%type, -- Note that your table definition doesn't include this column
  p_format_code tbl_rrsoc_store_info.format_code%type, -- Or this column
  p_store_code tbl_rrsoc_store_info.store_code%type
)
  return tbl_rrsoc_store_info.code_18digit%type
is
begin
  return 'R-'  ||
         CASE
         WHEN INSTR (TRIM (p_state), ' ') > 1
         THEN
                SUBSTR (p_state, 1, 1)
             || SUBSTR (p_state, INSTR (p_state, ' ') + 1, 1)
         ELSE
             UPPER (SUBSTR (p_state, 1, 2))
     END
  || '-'
  || UPPER (SUBSTR (p_zone_name, 1, 4))
  || '-'
  || p_format_code
  || '-'
  || SUBSTR (p_store_code, 1, 4);
end;

Then you can simply call the function in the trigger

create or replace trigger trg_generate_code
  before insert or update on tbl_rrsoc_store_info
  for each row
begin
  :new.code_18digit := make_18digit_code( :new.state,
                                          :new.zoe_name,
                                          :new.format_code,
                                          :new.store_code );
end;


答:
The issue you are getting is because Angular doesn't know about the IndiceService yet.

You either have to define it at the root level:

```<code>@Injectable({
  providedIn:'root'
})

export class IndiceService {...}
</code>```

Or in your IndiceModule inside providers array:

```<code>@NgModule({
  ...
  providers:[IndiceService]; //Add it to the import also above
})

export class IndiceModule { }
</code>```

The difference between the 2 is with 'root' level service, its single instance will be created & shared throughout the application. While adding it in the providers array, its instance will be shared within this module only.

Property 'router' is declared but its value is never read.

This error is generated by the Typescript compiler because you have injected Router in your IndiceComponent, but it is not used. So, it warns you to remove it if it is not used.

Title: ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError

Body:
The issue you are getting is because Angular doesn't know about the IndiceService yet.

You either have to define it at the root level:

@Injectable({
  providedIn:'root'
})

export class IndiceService {...}

Or in your IndiceModule inside providers array:

@NgModule({
  ...
  providers:[IndiceService]; //Add it to the import also above
})

export class IndiceModule { }

The difference between the 2 is with 'root' level service, its single instance will be created & shared throughout the application. While adding it in the providers array, its instance will be shared within this module only.

Property 'router' is declared but its value is never read.

This error is generated by the Typescript compiler because you have injected Router in your IndiceComponent, but it is not used. So, it warns you to remove it if it is not used.


问:
How to get specific values from a dictionary using list comprehension and modify them?
Can someone help and kindly advise how Can I get specific values from this dictionary (Using list comprehension) and

square the values only,

change every string value, so it starts with upper case?

```<code>items_list = {'a': 3, 'b':6, 'c': 'short', 'h': 'example', 'p': 77}
</code>```

So, the output needs to be:

```<code>9, 36, 5929
Short, Example
</code>```

答:
(Python):

items_list = {'a': 3, 'b': 6, 'c': 'short', 'h': 'example', 'p': 77}

lst = [v ** 2 if isinstance(v, (int, float)) else v.capitalize() for v in
       items_list.values()]

print(lst)
```
<p>output:</p>
<pre class="lang-none prettyprint-override"><code>[9, 36, 'Short', 'Example', 5929]
</code>```

The exact output that you showed can not be produced using single list comprehension, because the iteration is in order.

Body:
Can someone help and kindly advise how Can I get specific values from this dictionary (Using list comprehension) and

square the values only,

change every string value, so it starts with upper case?

items_list = {'a': 3, 'b':6, 'c': 'short', 'h': 'example', 'p': 77}

So, the output needs to be:

9, 36, 5929
Short, Example

Body:
(Python):

items_list = {'a': 3, 'b': 6, 'c': 'short', 'h': 'example', 'p': 77}

lst = [v ** 2 if isinstance(v, (int, float)) else v.capitalize() for v in
       items_list.values()]

print(lst)

output:

[9, 36, 'Short', 'Example', 5929]

The exact output that you showed can not be produced using single list comprehension, because the iteration is in order.


问:
Puppeteer failed to render emojis when running in Ubuntu
I have a script that uses puppeteer to take screenshot of DOM components and outputs an image. Everything works fine on MacOS but when I run this on Ubuntu the emojis become a rectangle. Does anyone know why is this happening?

MacOS: (where you can see a rocket emoji)

Ubuntu: (emoji becomes a rectangle)

答:
If you happen to be using chrome-aws-lambda (i.e.: using a cloud function to execute Puppeteer), you can load the font right after instantiating the browser:

const chromium = require('chrome-aws-lambda');

const browser = // ...
await chromium.font('https://raw.githack.com/googlei18n/noto-emoji/master/fonts/NotoColorEmoji.ttf');
```

However, note that the font is almost 10 MB. If instead of taking a screenshot you are generating a PDF, the output file size will increase significantly.

Body:
If you happen to be using chrome-aws-lambda (i.e.: using a cloud function to execute Puppeteer), you can load the font right after instantiating the browser:

const chromium = require('chrome-aws-lambda');

const browser = // ...
await chromium.font('https://raw.githack.com/googlei18n/noto-emoji/master/fonts/NotoColorEmoji.ttf');

However, note that the font is almost 10 MB. If instead of taking a screenshot you are generating a PDF, the output file size will increase significantly.


问:
Flutter and Android release aab 'android:exported = true' not working
I tried to upload the AAB file to the play console but giving the uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without 'android:exported' property set. This file can't be installed on Android 12 or higher. See: developer.android.com/about/versions/12/behavior-changes-12#exported error. I set the exported= true property to the activity too. And also add the android:exported="true" tools:node="merge".

I made the changes in the manifest as per suggestions then also getting same issue.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.example.example">

        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.INTERNET"/>

        <application
            android:label="Demo"
            android:icon="@mipmap/ic_launcher_foreground">
            <activity
                android:name=".MainActivity"
                android:launchMode="singleTop"
                android:theme="@style/LaunchTheme"
                android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
                android:hardwareAccelerated="true"
                android:windowSoftInputMode="adjustResize"
                android:exported="true"
                tools:node="merge"
                >

                <meta-data
                    android:name="io.flutter.embedding.android.NormalTheme"
                    android:resource="@style/NormalTheme"
                    />

                <meta-data
                    android:name="io.flutter.embedding.android.SplashScreenDrawable"
                    android:resource="@drawable/launch_background"
                    />

                <meta-data
                    android:name="com.google.firebase.messaging.default_notification_channel_id"
                    android:value="demo"/>
                <intent-filter>
                    <action android:name="FLUTTER_NOTIFICATION_CLICK"/>
                    <category android:name="android.intent.category.DEFAULT"/>
                </intent-filter>

                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>

            <meta-data
                android:name="flutterEmbedding"
                android:value="2"
                />

            <meta-data
                android:name="com.facebook.sdk.ApplicationId"
                android:value="@string/facebook_app_id" />
        </application>
</manifest>
```

答: I globally search all the exported value set manifest files. In between them I just change the value in manifest file of firebase messaging . I set all android:exported="true" in freebase messaging manifest</p>


问:
Why is the SVG of my raster plot so blurry?
I'm trying to print a raster visualisation. It renders fine in RStudio, but when I save it using the base svg device it comes out super blurry - as though each square of the raster is a massive pixel and they've been interpolated at some stage in the process.

Here's a reprex:

## libraries / set up
require(dplyr)
require(ggplot2)

set.seed(11)

## Generate data
### Make 100 random(ish) pairings of eye and hair colour to visualise
possibleEye <- c("green", "green", "green",
                          "blue", "blue", "brown", "hazel")
possibleHair <- c("blonde", "blonde", "brown",
                  "gray", "gray", "gray", "ginger")
eyeColours <- sample(possibleEye, 100, replace = TRUE)
hairColours <- sample(possibleHair, 100, replace = TRUE)

plotData <- tibble(
  eye.colour = factor(eyeColours),
  hair.colour = factor(hairColours)
)

### Count the occurrences of each combination
plotData <-
  plotData |>
  group_by(hair.colour, eye.colour) |>
  count()

## Plot raster

rasterPlot <-
  ggplot(plotData, aes(x = eye.colour, y = hair.colour, fill = n)) +
  geom_raster()

rasterPlot
```
<p><img src="https://i.imgur.com/R4rjHG7.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code>## save SVG file

svg("my-raster.svg")
print(rasterPlot)
dev.off()
#> png
#>   2
</code>```

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

But this is what my SVG looks like:

Why is that happening? How can I stop it from happening?

It's not a fault with the software I'm using to view the SVG, because it looks the same when viewed in either Inkscape or Google Chrome.

Here's my R.Version():

```<code>$platform
[1] "x86_64-w64-mingw32"

...

$version.string
[1] "R version 4.1.1 (2021-08-10)"

$nickname
[1] "Kick Things"
</code>```

答:
The geom_raster is being interpreted as a low-res raster, so it seems that the svg device is attempting to interpolate it (you will see the same image in the plotting window if you use geom_raster(interpolate = TRUE)). One way round this is to use geom_tile instead:

rasterPlot <-
  ggplot(plotData, aes(x = eye.colour, y = hair.colour, fill = n)) +
  geom_tile(colour = NA, height = 1.01, width = 1.01)

svg("my-raster.svg")
print(rasterPlot)
dev.off()
```
<p><img src="https://i.stack.imgur.com/S8lLS.png" alt="enter image description here" /></p>
<p>Alternatively, you can keep the geom_raster and use <code>ggsave</code> (you need to have the svglite package installed for this)</p>
<pre class="lang-r prettyprint-override"><code>rasterPlot <-
  ggplot(plotData, aes(x = eye.colour, y = hair.colour, fill = n)) +
  geom_raster()

ggsave("my_svg.svg", rasterPlot, device = "svg")
</code>```

Body:
I'm trying to print a raster visualisation. It renders fine in RStudio, but when I save it using the base svg device it comes out super blurry - as though each square of the raster is a massive pixel and they've been interpolated at some stage in the process.

Here's a reprex:

## libraries / set up
require(dplyr)
require(ggplot2)

set.seed(11)

## Generate data
### Make 100 random(ish) pairings of eye and hair colour to visualise
possibleEye <- c("green", "green", "green",
                          "blue", "blue", "brown", "hazel")
possibleHair <- c("blonde", "blonde", "brown",
                  "gray", "gray", "gray", "ginger")
eyeColours <- sample(possibleEye, 100, replace = TRUE)
hairColours <- sample(possibleHair, 100, replace = TRUE)

plotData <- tibble(
  eye.colour = factor(eyeColours),
  hair.colour = factor(hairColours)
)

### Count the occurrences of each combination
plotData <-
  plotData |>
  group_by(hair.colour, eye.colour) |>
  count()

## Plot raster

rasterPlot <-
  ggplot(plotData, aes(x = eye.colour, y = hair.colour, fill = n)) +
  geom_raster()

rasterPlot

## save SVG file

svg("my-raster.svg")
print(rasterPlot)
dev.off()
#> png
#>   2

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

But this is what my SVG looks like:

Why is that happening? How can I stop it from happening?

It's not a fault with the software I'm using to view the SVG, because it looks the same when viewed in either Inkscape or Google Chrome.

Here's my R.Version():

$platform
[1] "x86_64-w64-mingw32"

...

$version.string
[1] "R version 4.1.1 (2021-08-10)"

$nickname
[1] "Kick Things"

Body:
The geom_raster is being interpreted as a low-res raster, so it seems that the svg device is attempting to interpolate it (you will see the same image in the plotting window if you use geom_raster(interpolate = TRUE)). One way round this is to use geom_tile instead:

rasterPlot <-
  ggplot(plotData, aes(x = eye.colour, y = hair.colour, fill = n)) +
  geom_tile(colour = NA, height = 1.01, width = 1.01)

svg("my-raster.svg")
print(rasterPlot)
dev.off()

Alternatively, you can keep the geom_raster and use ggsave (you need to have the svglite package installed for this)

rasterPlot <-
  ggplot(plotData, aes(x = eye.colour, y = hair.colour, fill = n)) +
  geom_raster()

ggsave("my_svg.svg", rasterPlot, device = "svg")


问:
How do I add two numbers and them multiply it with the 3rd number and show the total in a disabled input in a html form with javascript?
```<code>This is the html code:
</code>```

the id's are : num1, num2, num3 and the total input is "total"
I want the calc function to be (num1+num2)*num3

```<code><div class="row">
    <div class="col">
    <label> Tarif Colet</label>
      <input type="num1" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()"  value="0" id="tarifcolet" id="num1"  class="form-control" placeholder="Tarif Colet">

    </div>
<div class="col">
      <label>Alte Taxe</label>
      <input type="num2" value="0" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()" id="num2"  class="form-control" placeholder="Alte Taxe">
    </div>
<div class="col">
    <label>Tva</label>
      <input type="percent" name="num3" id="num3" value="19%"  class="form-control" placeholder="TVA">
</div>
    <div class="col">
    <label>Total</label>
      <input type="number" name="total" disabled="disabled" id="total" class="form-control" placeholder="total">
    </div>
</code>```

答:
You can assign a value to a disabled input box using the same property you read:

```<code>function calculare() {
  var num1 = parseFloat(document.getElementById('num1').value);
    var num2 = parseFloat(document.getElementById('num2').value);
    var num3 = parseFloat(document.getElementById('num3').value);
    document.getElementById("total").value = ((num1 + num2) * num3/100).toFixed(2);
}
</code>```

Fiddle here: https://jsfiddle.net/9s1d2nac/1/

(In the fiddle I fixed the duplicate inputs you've assigned to the first input, leaving only "num1" as the id.)

Body:
This is the html code:

the id's are : num1, num2, num3 and the total input is "total"
I want the calc function to be (num1+num2)*num3

     Tarif Colet
      <input type="num1" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()"  value="0" id="tarifcolet" id="num1"  class="form-control" placeholder="Tarif Colet">

      Alte Taxe
      <input type="num2" value="0" onfocus="calculare()" onkeyup="calculare()" onclick="calculare()" onblur="calculare()" id="num2"  class="form-control" placeholder="Alte Taxe">

    Tva
      <input type="percent" name="num3" id="num3" value="19%"  class="form-control" placeholder="TVA">

    Total
      <input type="number" name="total" disabled="disabled" id="total" class="form-control" placeholder="total">

Body:
You can assign a value to a disabled input box using the same property you read:

function calculare() {
  var num1 = parseFloat(document.getElementById('num1').value);
    var num2 = parseFloat(document.getElementById('num2').value);
    var num3 = parseFloat(document.getElementById('num3').value);
    document.getElementById("total").value = ((num1 + num2) * num3/100).toFixed(2);
}

Fiddle here: https://jsfiddle.net/9s1d2nac/1/

(In the fiddle I fixed the duplicate inputs you've assigned to the first input, leaving only "num1" as the id.)


问:
Is it possible to trigger an Airflow 2 dag from an Airflow 1 dag, and viceversa?
We are doing a migration between new and old Airflow and we were trying to implement a trigger from Airflow1 to Airflow2(and vice-versa), is it possible?</p>

答:
Since running Airflow 1 code in an Airflow 2 instance will likely result in errors, I assume you intend to have two Airflow instances? One running Airflow 1, and one running Airflow 2, where the Airflow 2 DAGs trigger Airflow 1 DAGs?

To trigger a DAG externally, such as another Airflow instance, you can use the REST API or CLI to trigger DAGs:

CLI (docs):

airflow dags trigger DAG_ID
# For example:
airflow dags trigger mydag-airflow1
```
<p>REST API (docs):</p>
<pre class="lang-sh prettyprint-override"><code>curl -X POST http://localhost:8080/api/v1/dags/mydag-airflow1/dagRuns
</code>```

Couple of things to note:

REST API and CLI were rewritten in Airflow 2. If you intend to trigger from Airflow 1 to 2, you must look up the respective command for the old REST API/CLI.

Maintaining codebases for different versions can quickly become messy. I'd advise to stick to one Airflow version.

Body:
Since running Airflow 1 code in an Airflow 2 instance will likely result in errors, I assume you intend to have two Airflow instances? One running Airflow 1, and one running Airflow 2, where the Airflow 2 DAGs trigger Airflow 1 DAGs?

To trigger a DAG externally, such as another Airflow instance, you can use the REST API or CLI to trigger DAGs:

CLI (docs):

airflow dags trigger DAG_ID
# For example:
airflow dags trigger mydag-airflow1

REST API (docs):

curl -X POST http://localhost:8080/api/v1/dags/mydag-airflow1/dagRuns

Couple of things to note:

REST API and CLI were rewritten in Airflow 2. If you intend to trigger from Airflow 1 to 2, you must look up the respective command for the old REST API/CLI.

Maintaining codebases for different versions can quickly become messy. I'd advise to stick to one Airflow version.


问:
Using google drive to upload files
I am using the googledrive package of R to access a shared folder within my Google Drive. However, when I type drive_find() an the name of my folder, an error of permissions appears:

```<code>drive_find(pattern='Github-Colombia Project', type='folder') %>%
</code>```

an the error goes:

```<code>+   drive_reveal("permissions")
Error: Client error: (403) Forbidden
Insufficient Permission: Request had insufficient
authentication scopes.
• domain: global
• reason: insufficientPermissions
• message: Insufficient Permission: Request had
  insufficient authentication scopes.
Run `rlang::last_error()` to see where the error occurred.

</code>```

these is the current status of the folder:

Can you please help me out on this?

答:
At the end I managed to do that by changing the scopes:

```<code>drive_auth(
  email = gargle::gargle_oauth_email(),
  path = NULL,
  scopes = "https://www.googleapis.com/auth/drive",
  cache = gargle::gargle_oauth_cache(),
  use_oob = gargle::gargle_oob_default(),
  token = NULL
)
</code>```

which asks for a novel authentication.

Title: Using google drive to upload files

Body:
I am using the googledrive package of R to access a shared folder within my Google Drive. However, when I type drive_find() an the name of my folder, an error of permissions appears:

drive_find(pattern='Github-Colombia Project', type='folder') %>%

an the error goes:

+   drive_reveal("permissions")
Error: Client error: (403) Forbidden
Insufficient Permission: Request had insufficient
authentication scopes.
• domain: global
• reason: insufficientPermissions
• message: Insufficient Permission: Request had
  insufficient authentication scopes.
Run `rlang::last_error()` to see where the error occurred.

these is the current status of the folder:

Can you please help me out on this?

Body:
At the end I managed to do that by changing the scopes:

drive_auth(
  email = gargle::gargle_oauth_email(),
  path = NULL,
  scopes = "https://www.googleapis.com/auth/drive",
  cache = gargle::gargle_oauth_cache(),
  use_oob = gargle::gargle_oob_default(),
  token = NULL
)

which asks for a novel authentication.


问:
Typing a class component with no props
I am trying to type a class component with no props

```<code>import React, { Component } from "react";

type Props = {};

class MyComponent extends Component<Props> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  render() {
    return <h1>hello</h1>;
  }
}

export default MyComponent;
</code>```

It seems like I just cannot ommit them

```<code>import React, { Component } from 'react';

class ErrorBoundary extends Component {
  constructor() {
    super();
    this.state = { hasError: false };
  }
</code>```

What is the correct way to type a class component with no props?

答:
You can initialize the state like this, avoiding to (manually) overwrite the constructor.

```<code>class ErrorBoundary extends Component {
  state = {
    hasError: false
  }

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

I think that's what you're talking about, not the typings.

Title: Typing a class component with no props

Body:
I am trying to type a class component with no props

import React, { Component } from "react";

type Props = {};

class MyComponent extends Component<Props> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  render() {
    return
hello
;
  }
}

export default MyComponent;

It seems like I just cannot ommit them

import React, { Component } from 'react';

class ErrorBoundary extends Component {
  constructor() {
    super();
    this.state = { hasError: false };
  }

What is the correct way to type a class component with no props?

Body:
You can initialize the state like this, avoiding to (manually) overwrite the constructor.

class ErrorBoundary extends Component {
  state = {
    hasError: false
  }

  render() {
    return <h1>hello</h1>;
  }
}

I think that's what you're talking about, not the typings.


问:
Checking the application loading speed on Android device
I have some web development experiences and today I started learning Flutter.
I made a really basic app, that displays a time in different countries.
It loads very fast, but I want to see how long it takes to open.
I found a lot of tutorials about how to do this but I don't understand them.
I want to compare the results of my app with results of other apps on my phone,
so if you know some apps to test load speed pls send me a link or explain how to do it in another way.</p>

答:
What you're looking for is time to initial display.
Time to initial display

ActivityManager: Displayed com.android.myexample/.StartupTiming: +3s534ms (total +1m22s643ms)

Open your logs and filter by Displayed

I dunno what the flutter counterpart is but since it's an activity you're opening it should be the same.

The other way is using Systrace and Perfetto.

Medium Article on systrace and Perfetto


问:
Does JavaScript provide a history of prior events that occurred?
I was wondering if JavaScript records information about the prior events that occurred so that I could use the information to perform a specific course of action in the current event?

For example, I have an element that has an OnBlur event handler, but I would like to know the event that occurred prior to the OnBlur event that triggered the OnBlur event to occur, such as the user pressing the Tab key, arrow key, or mouse click that moved focus away from the element.

So does JavaScript provide any mechanism to facilitate access to the events history or can people throw ideas to me at good ways of implementing this?

答:
There is nothing native in JS that does this..

You could just listen for the events you are interested in and append them to an array or whatever datastructure is useful to you.  Then reference your own event database as needed.

So something like (JQuery assumed..)

```<code>var eventdb = [];
$(document).bind("click,blur,whatever", function(e) {
  eventdb.push(e);
});
</code>```

Body:
There is nothing native in JS that does this..

You could just listen for the events you are interested in and append them to an array or whatever datastructure is useful to you.  Then reference your own event database as needed.

So something like (JQuery assumed..)

var eventdb = [];
$(document).bind("click,blur,whatever", function(e) {
  eventdb.push(e);
});


问:
how create dynamic textfield and get value from each textfield in jetpack compose?
let say I have this composable function to create outlineTextField

```<code>val valueState = remember { mutableStateOf("") }

myLists.forEach{ item ->
             OutlinedTextField(
                value = valueState.value,
                onValueChange = {
                    valueState.value = it
                }
             )

    }

Button(
    onClick= {
      valueState.value  // want to print each value from OutlinedTextField here..
    }
){
     Text("Click Me")
}
</code>```

Amount of OutlinedTextField will be create based on looping.

Question

how to get value from each textField ?

答:
I think you can use mutableStateListOf

```<code>val myLists = listOf("xx","xx","xxx")
val textFieldInitValues = List(myLists.size){ "" }
val valueStateList = remember { mutableStateListOf<String>().apply { addAll(textFieldInitValues) } }

Column {
    myLists.forEachIndexed { index, item ->
        OutlinedTextField(
            value = valueStateList[index],
            onValueChange = {
                valueStateList[index] = it
            }
        )

    }

    Button(
        onClick = {
            valueStateList.forEach {
                Log.d("Button", it)
            }
        }
    ) {
        Text("Click Me")
    }
}
</code>```

Body:
let say I have this composable function to create outlineTextField

val valueState = remember { mutableStateOf("") }

myLists.forEach{ item ->
             OutlinedTextField(
                value = valueState.value,
                onValueChange = {
                    valueState.value = it
                }
             )

    }

Button(
    onClick= {
      valueState.value  // want to print each value from OutlinedTextField here..
    }
){
     Text("Click Me")
}

Amount of OutlinedTextField will be create based on looping.

Question

how to get value from each textField ?

Body:
I think you can use mutableStateListOf

val myLists = listOf("xx","xx","xxx")
val textFieldInitValues = List(myLists.size){ "" }
val valueStateList = remember { mutableStateListOf<String>().apply { addAll(textFieldInitValues) } }

Column {
    myLists.forEachIndexed { index, item ->
        OutlinedTextField(
            value = valueStateList[index],
            onValueChange = {
                valueStateList[index] = it
            }
        )

    }

    Button(
        onClick = {
            valueStateList.forEach {
                Log.d("Button", it)
            }
        }
    ) {
        Text("Click Me")
    }
}


问:
Why the size of the const char *arr is greater then const char arr[]?
I am using the xc32 compiler for the microchip pic32 microcontroller.

The program memory size (for the startup, vectors and etc..) is 1656 bytes.

```<code>#include <plib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>

//if I use const char array[] for string literal then the size of the program memory increased
//equal to the string length(only 12 bytes)

//const char array[] = "Hello World"; //program mem size(1668 0x684) bytes

//but in this case size increased 28 bytes
//const char *array = "Hello World";  //program mem size(1684 0x694) bytes

int main {

    while(1);
}
</code>```

for optimization purposes:

which one is good(for both speed and size)?

#define STRLIT "HELLO WORLD"

const char *strlit = "HELLO WORLD";

const char arr[] = "HELLO WORLD"

答:
Generally, memory on a MCU is stored like this: What resides in the different memory types of a microcontroller? This means:

The string literal "HELLO WORLD" itself is very likely stored in a .rodata flash ROM section.

When you do const char array[] = "Hello World"; at file scope, the array variable should be allocated in .rodata. So there is no need to allocate the string literal or that would mean redundant allocation.

When you do const char *array then you declare a pointer and it it is not allocated in flash, but in the .data section of RAM. So this will mean RAM and flash consumption both. Please note that this pointer is read/write - you can assign it somewhere else but you can't change the pointed-at contents.

To allocate the pointer in flash ROM, you need to do const char* const array.

As for why you get "28 bytes" of something, I don't know. I haven't used this part but a brief research here claims that it might have Von Neumann characteristics, from the C programmers point of view, even though the core is Harvard. Not sure what that boils down to, but this matters since Harvard architectures might need to execute some support overhead code to access flash ROM data, which in turn leads to slightly larger executable size. You need to disassemble if you want to know the specifics.

Body:
I am using the xc32 compiler for the microchip pic32 microcontroller.

The program memory size (for the startup, vectors and etc..) is 1656 bytes.

#include <plib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>

//if I use const char array[] for string literal then the size of the program memory increased
//equal to the string length(only 12 bytes)

//const char array[] = "Hello World"; //program mem size(1668 0x684) bytes

//but in this case size increased 28 bytes
//const char *array = "Hello World";  //program mem size(1684 0x694) bytes

int main {

    while(1);
}

for optimization purposes:

which one is good(for both speed and size)?

#define STRLIT "HELLO WORLD"

const char *strlit = "HELLO WORLD";

const char arr[] = "HELLO WORLD"


问:
How to create a persistant state for Pinia + Quasar?
I'm using Pinia for state managment, and I want the state to persist when the page is refeshed.

I'm aware of two options:

Use a plugin. Vuex has a vuex-persistedstate plugin for this, and Pinia has a similar plugin but it's still under development.

Use local storage. Luckily Quasar has a LocalStorage plugin which would be nice to use here. But I'm not sure how to integrate it with Pinia, thus the reason for this post.

I found a nice tutorial doing something similar with Pinia + Vueuse.

And I tried adapting it to my needs with Pinia + TypeScript + Quasar LocalStorage Plugin as per below:

```<code>import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
import { LocalStorage } from 'quasar';

type CreateMutable<T> = { -readonly [P in keyof T]: CreateMutable<T[P]> };

export const useUserStore = defineStore('user', {
  state: () => ({
    // user: {} as CreateMutable<User>, // This was my previous non-persistent state
    user: LocalStorage.set('user', {}) as unknown as CreateMutable<User>, // This is my attempt at using LocalStorage persistent state
  }),
  actions: {
    setUser(userData: User) {
      this.user = userData;
    },
    setPhotoURL(photoURLData: string | null) {
      this.user.photoURL = photoURLData;
    },
  },
});
</code>```

Unfortunately it doesn't work.

The state does not persist on page refresh.

Any ideas on how to make this work?

答:
I actually use "vanilla localStorage" and had no issues with that.
I am not a big fan of to much libraries, for simple tasks (although for not using them for complicated tasks).
Whatever, I am a fan of VueUse, too. This function I have not used, but I could imagine.it makes things even easier.

Vanilla localStorage

Set into local storage

localStorage.setItem("myStorageKey", "My persisted values");

Get from local storage

localStorage.getItem("myStorageKey");

State Mutation

Apart from that, I have not tried to set the localStoreage direct into the state. That seems like a red flag to me, as you usually should not directly mutate a state. But I am not sure in this case. I usually prepopulate the state which hard coded data (or just empty) and then I would write an action, which sets the data into the state.

Body:
I'm using Pinia for state managment, and I want the state to persist when the page is refeshed.

I'm aware of two options:

Use a plugin. Vuex has a vuex-persistedstate plugin for this, and Pinia has a similar plugin but it's still under development.

Use local storage. Luckily Quasar has a LocalStorage plugin which would be nice to use here. But I'm not sure how to integrate it with Pinia, thus the reason for this post.

I found a nice tutorial doing something similar with Pinia + Vueuse.

And I tried adapting it to my needs with Pinia + TypeScript + Quasar LocalStorage Plugin as per below:

import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
import { LocalStorage } from 'quasar';

type CreateMutable<T> = { -readonly [P in keyof T]: CreateMutable<T[P]> };

export const useUserStore = defineStore('user', {
  state: () => ({
    // user: {} as CreateMutable<User>, // This was my previous non-persistent state
    user: LocalStorage.set('user', {}) as unknown as CreateMutable<User>, // This is my attempt at using LocalStorage persistent state
  }),
  actions: {
    setUser(userData: User) {
      this.user = userData;
    },
    setPhotoURL(photoURLData: string | null) {
      this.user.photoURL = photoURLData;
    },
  },
});

Unfortunately it doesn't work.

The state does not persist on page refresh.

Any ideas on how to make this work?


问:
Airflow GCSFileTransformOperator source object filename wildcard
I am working on a DAG that should read an xml file, do some transformations to it and land the result as a CSV. For this I am using GCSFileTransformOperator.

Example:

```<code>    xml_to_csv = GCSFileTransformOperator(
    task_id=f'xml_to_csv',
        source_bucket='source_bucket',
        source_object=(
            f'raw/dt=2022-01-19/File_20220119_4302.xml'
        ),
        destination_bucket='destination_bucket',
        destination_object=f'csv_format/dt=2022-01-19/File_20220119_4302.csv',
        transform_script=[
            '/path_to_script/transform_script.py'
        ],
)
</code>```

My problem is that the filename has is ending with a 4 digit number that is different each day (File_20220119_4302). Next day the number will be different.
I can use template for execution date: {{ ds }}, {{ ds_nodash }}, but not sure what to with the number.
I have tried wildcards like File_20220119_*.xml, with no success.

答:
I dig on the operator GCSFileTransformOperator code and I dont think current wildcards will likely work as the current templates are fixed values based on the time of execution as described on templates reference page and the source file will have a totally different filename.

My solution to this will be to have a python operator as an additional step which can find your input file first. Depending on your airflow version you might use TASKFLOW API or XCOM to pass the filename data.

```<code>def look_file(*args, **kwargs):
    # look for file
    return {'file_found': filefounpath}

file_found = PythonOperator(
    task_id='file_searcher',
    python_callable=look_file,
    dag=dag,
)

xml_to_csv = GCSFileTransformOperator(
    task_id=f'xml_to_csv',
        source_bucket='source_bucket',
        source_object=(
            raw/dt=file_found
        ),
        destination_bucket='destination_bucket',
        destination_object=f'csv_format/dt=2022-01-19/File_20220119_4302.csv',
        transform_script=[
            '/path_to_script/transform_script.py'
        ],
)
</code>```

Body:
I am working on a DAG that should read an xml file, do some transformations to it and land the result as a CSV. For this I am using GCSFileTransformOperator.

Example:

    xml_to_csv = GCSFileTransformOperator(
    task_id=f'xml_to_csv',
        source_bucket='source_bucket',
        source_object=(
            f'raw/dt=2022-01-19/File_20220119_4302.xml'
        ),
        destination_bucket='destination_bucket',
        destination_object=f'csv_format/dt=2022-01-19/File_20220119_4302.csv',
        transform_script=[
            '/path_to_script/transform_script.py'
        ],
)

My problem is that the filename has is ending with a 4 digit number that is different each day (File_20220119_4302). Next day the number will be different.
I can use template for execution date: {{ ds }}, {{ ds_nodash }}, but not sure what to with the number.
I have tried wildcards like File_20220119_*.xml, with no success.

Body:
I dig on the operator GCSFileTransformOperator code and I dont think current wildcards will likely work as the current templates are fixed values based on the time of execution as described on templates reference page and the source file will have a totally different filename.

My solution to this will be to have a python operator as an additional step which can find your input file first. Depending on your airflow version you might use TASKFLOW API or XCOM to pass the filename data.

def look_file(*args, **kwargs):
    # look for file
    return {'file_found': filefounpath}

file_found = PythonOperator(
    task_id='file_searcher',
    python_callable=look_file,
    dag=dag,
)

xml_to_csv = GCSFileTransformOperator(
    task_id=f'xml_to_csv',
        source_bucket='source_bucket',
        source_object=(
            raw/dt=file_found
        ),
        destination_bucket='destination_bucket',
        destination_object=f'csv_format/dt=2022-01-19/File_20220119_4302.csv',
        transform_script=[
            '/path_to_script/transform_script.py'
        ],
)


问:
how to make ion-datetime's display the picker in a modal or bottom page slider instead of directly display it
I'm doing an ionic project using Ionic 6 and I need a datetime field in my form.

```<code><ion-content>
  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-item>
          <ion-label>Available From</ion-label>
          <ion-datetime min="1994-03-14" max="2012-12-09" value="2008-09-02"></ion-datetime>
        </ion-item>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>
</code>```

From what I have searched in many sources, it seems like the correct behavior should be button which is when it is clicked will display a slider up from the bottom of the page. The selector displays scrollable columns that can be used to individually specify values for years, months, days, hours, and minutes.

Instead of that, what I get is the picker is displayed instead of button or anything.

Am I missing something? I tried all usage example in the documentation and all of them are displayed like that. Please help.

答:
The ion-datetime has changed in Ionic v6.
To have a text field displaying the date in your form and have the calendar picker in a popup, use it like in the following example (startdate is the date variable):

```<code><ion-row>
   <ion-col>Date:</ion-col>
   <ion-col id="open-date-input" class="ion-text-end" style="margin-right: 10px;">
     <ion-text>{{ startdate|date:'shortDate':undefined:this.translate.currentLang }}</ion-text>
   </ion-col>
   <ion-popover trigger="open-date-input" show-backdrop="false">
     <ng-template>
       <ion-datetime
          #popoverDate
          value="{{startdate}}"
          presentation="date"
          showDefaultButtons=true
          (ionChange)="startdate = popoverDate.value"
        ></ion-datetime>
     </ng-template>
   </ion-popover>
</ion-row>
</code>```

Of course you may omit/replace the date formatting pipe in the ion-text to your needs.

Body:
I'm doing an ionic project using Ionic 6 and I need a datetime field in my form.

<ion-content>
  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-item>
          <ion-label>Available From</ion-label>
          <ion-datetime min="1994-03-14" max="2012-12-09" value="2008-09-02"></ion-datetime>
        </ion-item>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

From what I have searched in many sources, it seems like the correct behavior should be button which is when it is clicked will display a slider up from the bottom of the page. The selector displays scrollable columns that can be used to individually specify values for years, months, days, hours, and minutes.

Instead of that, what I get is the picker is displayed instead of button or anything.

Am I missing something? I tried all usage example in the documentation and all of them are displayed like that. Please help.

Body:
The ion-datetime has changed in Ionic v6.
To have a text field displaying the date in your form and have the calendar picker in a popup, use it like in the following example (startdate is the date variable):

<ion-row>
   <ion-col>Date:</ion-col>
   <ion-col id="open-date-input" class="ion-text-end" style="margin-right: 10px;">
     <ion-text>{{ startdate|date:'shortDate':undefined:this.translate.currentLang }}</ion-text>
   </ion-col>
   <ion-popover trigger="open-date-input" show-backdrop="false">
     <ng-template>
       <ion-datetime
          #popoverDate
          value="{{startdate}}"
          presentation="date"
          showDefaultButtons=true
          (ionChange)="startdate = popoverDate.value"
        ></ion-datetime>
     </ng-template>
   </ion-popover>
</ion-row>

Of course you may omit/replace the date formatting pipe in the ion-text to your needs.


问:
Looping over related (M2M) items in the order specified by the intermediatry relationship
Using the example from the docs:
https://docs.djangoproject.com/en/1.2/topics/db/models/#intermediary-manytomany

I can loop over the groups and show the people in each:

```<code>{% for group in group_list %}
 {{ group.name }}:
 {% for member in group.members.all %}
  {{ member.name }}
 {% endfor %}
{% endfor %}
</code>```

But I can't figure out how to show the members in the order they joined (i.e., by membership.date_joined). Using dictsort after the all like so:

```<code>{% for member in group.members.all|dictsort:"date_joined" %}
</code>```

results in an empty member list. And I've tried using members.through, but can't seem to get any data from that, either.

答:
You can specify the ordering attribute in the model's Meta -- then all queries on that model will be ordered that way by default.

```<code>class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

    class Meta:
        ordering = ['date_joined']
</code>```

Body:
Using the example from the docs:
https://docs.djangoproject.com/en/1.2/topics/db/models/#intermediary-manytomany

I can loop over the groups and show the people in each:

{% for group in group_list %}
 {{ group.name }}:
 {% for member in group.members.all %}
  {{ member.name }}
 {% endfor %}
{% endfor %}

But I can't figure out how to show the members in the order they joined (i.e., by membership.date_joined). Using dictsort after the all like so:

{% for member in group.members.all|dictsort:"date_joined" %}

results in an empty member list. And I've tried using members.through, but can't seem to get any data from that, either.

Body:
You can specify the ordering attribute in the model's Meta -- then all queries on that model will be ordered that way by default.

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

    class Meta:
        ordering = ['date_joined']


问:
Automatic file downloader
I want to download files from a web page that offers public downloads.

I have little experience with the world of web pages, so initially I wrote a simple script using selenium that solves the problem, however I find this way of getting the data too twisted. Therefore, I have tried to download the file via POST requests, investigating a little the "Network" panel of tools I managed to find the request that apparently orders the download.

The button that appears surrounded in the image launches the three requests that appear on the right, except the first time the file is downloaded, one more request appears (this can be seen above the highlighted requests).

However, the response of this request, far from being the content that would allow me to write the desired file, is more like a fragment of html code that corresponds to the content displayed when in the network panel I double click on "downloadDir":

What could I be missing? Does anyone know how to solve the problem or it is not possible by this way?

答:
You should use requests package instead of executing curl or other processes:

```<code>import requests

response = requests.post('https://localhost:4000/bananas/12345.png', data = '[ 1, 2, 3, 4 ]')
data = response.content

</code>```

data contains the downloaded content after that, which you can store to disk for instance:

```<code>with open(path, 'wb') as s:
    s.write(data)
</code>```

Title: Automatic file downloader

Body:
You should use requests package instead of executing curl or other processes:

import requests

response = requests.post('https://localhost:4000/bananas/12345.png', data = '[ 1, 2, 3, 4 ]')
data = response.content

data contains the downloaded content after that, which you can store to disk for instance:

with open(path, 'wb') as s:
    s.write(data)


问:
eclipse 4.14.0 using var keyword in java, made changed to javaSE10 (jdk17), then error on building project
```<code>public static void main(String[] args) {
    var x = 1;
}
</code>```
<p>!ENTRY org.eclipse.core.resources 4 2 2022-02-04 20:07:11.784
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.core.resources".
!STACK 0</p>

答:
Thanks guys.

JDK17 stands for jdk-17.0.1 (I think is the last version)

I installed the last Eclipse Version: 2021-12 (4.22.0)

Now the error was gone. I am a newbie in Java and also Eclipse, I just started to learn now.

I suppose that is a incompatibility JDK 17 and Eclipse 2019.
Now everything OK.
Thanks so much for the help.

Body:
public static void main(String[] args) {
    var x = 1;
}

!ENTRY org.eclipse.core.resources 4 2 2022-02-04 20:07:11.784
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.core.resources".
!STACK 0


问:
VS2008 Setup Project always requires .NET 3.5 at install time but I don't need it!
1, Create and build a default Windows Forms project and look at the project properties. It says that the project is targetting .NET Framework 2.0.

2, Create a Setup project that installs just the single executable from the Windows Forms project.

3, Run that installer and it always says that it needs to install .NET 3.5 SP1 on the machine. But it obviously only really needs 2.0 and so I do not want customers to be forced to install .NET 3.5 when they do not need it. They might already have 2.0 installed and so forcing the upgrade is not desirable!

I have looked at the prerequisites of the setup project and checked the .NET Framework 2.0 entry and all the rest are unchecked. So I cannot find any reason for this strange runtime requirement. Anybody know how to resolve this one?

答:
I eventually found the answer to my own question.

Comparing the projects files using Notepad I noticed that a setup project in VS2008 has an entry that requests version 3.5 and the same section in the VS2005 project was marked as 2.0. What is strange is that the section looks like something you cannot manually alter within the Visual Studio environment and so you are forced to update the project file manually. Anywhere here is the offending area of the project file for those that comes across the same issue...

```<code>"Deployable"
{
    "CustomAction"
    {
    }
    "DefaultFeature"
    {
    "Name" = "8:DefaultFeature"
    "Title" = "8:"
    "Description" = "8:"
    }
    "ExternalPersistence"
    {
        "LaunchCondition"
        {
            "{A06ECF26-33A3-4562-8140-9B0E340D4F24}:_FC497D835F7243569DCCC3E3ACE4196D"
            {
            "Name" = "8:.NET Framework"
            "Message" = "8:[VSDNETMSG]"
            "Version" = "8:3.5.30729"  <--- UPDATE THIS TO 8:2.0.50727
            "AllowLaterVersions" = "11:FALSE"
            "InstallUrl" = "8:http://go.microsoft.com/fwlink/?LinkId=76617"
            }
        }
    }
</code>```

OwnerDisplayName: Phil Wright

Body:
I eventually found the answer to my own question.

Comparing the projects files using Notepad I noticed that a setup project in VS2008 has an entry that requests version 3.5 and the same section in the VS2005 project was marked as 2.0. What is strange is that the section looks like something you cannot manually alter within the Visual Studio environment and so you are forced to update the project file manually. Anywhere here is the offending area of the project file for those that comes across the same issue...

"Deployable"
{
    "CustomAction"
    {
    }
    "DefaultFeature"
    {
    "Name" = "8:DefaultFeature"
    "Title" = "8:"
    "Description" = "8:"
    }
    "ExternalPersistence"
    {
        "LaunchCondition"
        {
            "{A06ECF26-33A3-4562-8140-9B0E340D4F24}:_FC497D835F7243569DCCC3E3ACE4196D"
            {
            "Name" = "8:.NET Framework"
            "Message" = "8:[VSDNETMSG]"
            "Version" = "8:3.5.30729"  <--- UPDATE THIS TO 8:2.0.50727
            "AllowLaterVersions" = "11:FALSE"
            "InstallUrl" = "8:http://go.microsoft.com/fwlink/?LinkId=76617"
            }
        }
    }


问:
On the web, what fonts should I use to create an equivalent experience cross-platform?
Because Linux (and its variants) have a completely different set of fonts than Windows and Mac OS X, is there anyone with any experience of creating cross-platform font families - ideally finding equivalents to the common fonts found on the aforementioned operating systems?

If so, what is the best route to take?

答:
Sitepoint has an excellent article on font stacks:

http://www.sitepoint.com/article/eight-definitive-font-stacks/

OwnerDisplayName: different

OwnerDisplayName: Jeff


问:
Load input file convert to custom array objects in Terraform
I have a situation where I want to load a custom-based file to memory and pass it as array to AWS resource.

Here is my file (this is not JSON)

abc.tmpl

```<code>{
 name="Mark"
 age="20"
},
{
 name="Steve"
 age="25"
}
</code>```

apply the above values to one of the resources in the array below

```<code>module "elb" {
 custome_elb_settings = [
  {
   name="Mark"
   age="20"
  },
  {
   name="Steve"
   age="25"
  }
 ]
}
</code>```

When I tried with template_file it loaded in plain text and loaded as 1 string with \n and escape chars in it.

Is there any way to load as objects from file or else convert string to array in Terraform

Thank you in advance

答:
Declare it as a variable:

```<code>variable "custome_elb_settings" {
  type = list(object({name=string,age=number}))
}

module "elb" {
  custome_elb_settings = var.custome_elb_settings
}
</code>```

Then pass the value in the command line:

```<code>terraform apply -var custome_elb_settings="[ $(cat abc.tmpl) ]"
</code>```

Body:
I have a situation where I want to load a custom-based file to memory and pass it as array to AWS resource.

Here is my file (this is not JSON)

abc.tmpl

{
 name="Mark"
 age="20"
},
{
 name="Steve"
 age="25"
}

apply the above values to one of the resources in the array below

module "elb" {
 custome_elb_settings = [
  {
   name="Mark"
   age="20"
  },
  {
   name="Steve"
   age="25"
  }
 ]
}

When I tried with template_file it loaded in plain text and loaded as 1 string with \n and escape chars in it.

Is there any way to load as objects from file or else convert string to array in Terraform

Thank you in advance

Body:
Declare it as a variable:

variable "custome_elb_settings" {
  type = list(object({name=string,age=number}))
}

module "elb" {
  custome_elb_settings = var.custome_elb_settings
}

Then pass the value in the command line:

terraform apply -var custome_elb_settings="[ $(cat abc.tmpl) ]"


问:
Populate Post Object field with selected value of taxonomy field ACF
I have 2 fields:

type taxonomy called "category"

type post object called "products"

What i want? populate the dropdown of "products" only with the "category" selected.

I'm trying this:

```<code>function filter_product_query( $args, $categorId ) {

    $categorId = get_field('category_v1');

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 3,
        'tax_query'      => array( array(
            'taxonomy'   => 'product_cat',
            'field'      => 'term_id',
            'terms'      => $categorId ,
        ) )
    );
    return $args;

}
add_filter('acf/fields/post_object/query/key=field_61e745e87a5a6', 'filter_product_query', 10, 4);
</code>```

But doesn't work.

Taxonomy field configuration

Post object field configuration

答:
I'm working on this as well.

Now, to start with.  If the function isn't beign called, at all.  Then chances are, you're using the wrong hook.  There is also a hook called

Here are the ones that helped me
https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/

and

https://www.advancedcustomfields.com/resources/acf-fields-taxonomy-result/

There are others.  Pay close attention to the hook text as its probably not a post_object.

If the function you're using is getting called, then you got to follow the steps here as I'm guessing its related to this issue,

https://support.advancedcustomfields.com/forums/topic/send-additional-field-for-ajax-update-event-on-selecttaxonomy/

and possibly this one as well, that references the above.
https://support.advancedcustomfields.com/forums/topic/trouble-with-acffieldspost_objectquery-filter/

Body:
I have 2 fields:

type taxonomy called "category"

type post object called "products"

What i want? populate the dropdown of "products" only with the "category" selected.

I'm trying this:

function filter_product_query( $args, $categorId ) {

    $categorId = get_field('category_v1');

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 3,
        'tax_query'      => array( array(
            'taxonomy'   => 'product_cat',
            'field'      => 'term_id',
            'terms'      => $categorId ,
        ) )
    );
    return $args;

}
add_filter('acf/fields/post_object/query/key=field_61e745e87a5a6', 'filter_product_query', 10, 4);

But doesn't work.

Taxonomy field configuration

Post object field configuration


问:
Convert tailwindcss classes to vanilla css
is there any lib that can take a dom element and return a string with vanilla css, to use inside a webproject?

const styles = TailwindToStyles('
Lorem ipsum
 ')
```
<p>result of styles is</p>
```.bg-teall-100 {
  background-color: #e6fffa;
}
.m-10{
  margin: 40px
}
```

gregor

答:
I was looking for a similar tool that can convert the tailwind class to CSS. I ran into one Reddit Thread. There are various tools listed out there.

The one that is simpler and closer to what I was looking for is this app to convert the tailwind class to CSS.

Here is the GitHub link: https://github.com/Devzstudio/tailwind_to_css

Live demo: https://tailwind-to-css.vercel.app/

FOR REACT NATIVE

Thanks to this packet it is possible to copy the entire tailwind code from react project and paste it as a param of the function tailwind() which returns a react-native stylesheet object.

Here's the doc :
https://github.com/vadimdemedes/tailwind-rn

Body:
is there any lib that can take a dom element and return a string with vanilla css, to use inside a webproject?

const styles = TailwindToStyles('
Lorem ipsum
 ')

result of styles is

.bg-teall-100 {
  background-color: #e6fffa;
}
.m-10{
  margin: 40px
}

gregor


问:
Saving to .msg file in Python, or alternatively, sending mail to the file system
I'm using the emails library to send mail, but I also need to save it as .msg file. I've done some research and also read the msg format specification and stumbled upon this SO answer that shows how to send mail to the file system in C# and I was wondering if it was possible in Python as well.

答:
As per python's official examples - https://docs.python.org/3/library/email.examples.html it is possible to save an email as a .msg file, and then later on load it.</p>
```<code>from email.message import EmailMessage
from email.parser import BytesParser

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
             Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Load local copy of email
with open('outgoing.msg', 'rb') as fp:
    loaded_msg = BytesParser(policy=policy.default).parse(fp)
</code>```

Body:
As per python's official examples - https://docs.python.org/3/library/email.examples.html it is possible to save an email as a .msg file, and then later on load it.

from email.message import EmailMessage
from email.parser import BytesParser

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
             Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Load local copy of email
with open('outgoing.msg', 'rb') as fp:
    loaded_msg = BytesParser(policy=policy.default).parse(fp)


问:
Application failed codesign verification
I know that there are many articles all over the Internet about this, but no matter how hard I try, I can't find an answer to this question:

I want to submit my finished app to the iOS App Store. I just archived my iOS application in Xcode 4, and I clicked the "Validate..." button in the Organiser. When the app is validated, Xcode tells me this:

```<code>Application failed codesign verification. The signature was invalid, or it was
not signed with an Apple submission certificate.
</code>```

I have a distribution profile that I used to codesign in the target app.

I am not using Application Loader because it is telling me that

```<code>Application Loader is currently unavailable... an error occurred talking to the
iTunes store
</code>```

But the question is, what is wrong with my app, and how can I fix it.

Thanks in advance.

答: check 2 things in the build log (detail view), search for "embedded.mobileprovision" to see if it's embedded, and check under "CodeSign" if the certificate is the one that you are using for distribution.</p>

Body:
I know that there are many articles all over the Internet about this, but no matter how hard I try, I can't find an answer to this question:

I want to submit my finished app to the iOS App Store. I just archived my iOS application in Xcode 4, and I clicked the "Validate..." button in the Organiser. When the app is validated, Xcode tells me this:

Application failed codesign verification. The signature was invalid, or it was
not signed with an Apple submission certificate.

I have a distribution profile that I used to codesign in the target app.

I am not using Application Loader because it is telling me that

Application Loader is currently unavailable... an error occurred talking to the
iTunes store

But the question is, what is wrong with my app, and how can I fix it.

Thanks in advance.