问:
Vite.js Dynamic Image Loading Fails In Production
I have a problem in importing dynamic assets in production mode. When I ran the development environment everything works fine and the assets loads...but when I build the Vue.js application, assets won't load and I gets below error:
TypeError: URL constructor: ../../../assets/images/name.png is not a valid URL.
how can I fix this issue?

Vue Example

```
<pre class="lang-js prettyprint-override"><code>function findImageFromNumber(number: string) {
  const name = identify(number).english;
  const path = new URL('../../../assets/images/banks/' + name + '.png', import.meta.url);
  return path.href
}
</code>```

Vite.js Config

export default defineConfig({
  root: './',
  resolve: {
    alias: {
      '/@/': path.resolve(__dirname, 'src')
    },
  },
  publicDir: 'assets',
  mode: 'production',
  build: {
    outDir: 'dist',
    sourcemap: true,
    target: ['es2019', 'safari11', 'firefox60', 'chrome61', 'node12'],
    chunkSizeWarningLimit: 500,
    minify: false,
    emptyOutDir: true,
    assetsInlineLimit: 2048,
    rollupOptions: {
      output: {
        entryFileNames: `assets/[name].js`,
        chunkFileNames: `assets/[name].js`,
        assetFileNames: `assets/[name].[ext]`,
        manualChunks(id) {
          if (id.includes('vue')) {
            return 'react';
          } else if (id.includes('node_modules')) {
            return 'vendor';
          }
        },
      },
    }
  },
  plugins: [
    vue(),
    legacy({
      polyfills: ['es.promise.finally', 'es/map', 'es/set'],
      modernPolyfills: ['es.promise.finally']
    })
  ],
})
```

Note: Everything works fine in development and it only fails in production...

答: Assets is your public dir. Should it just be /assets/images/banks, according to the docs?

Body:
I have a problem in importing dynamic assets in production mode. When I ran the development environment everything works fine and the assets loads...but when I build the Vue.js application, assets won't load and I gets below error:
TypeError: URL constructor: ../../../assets/images/name.png is not a valid URL.
how can I fix this issue?

Vue Example

function findImageFromNumber(number: string) {
  const name = identify(number).english;
  const path = new URL('../../../assets/images/banks/' + name + '.png', import.meta.url);
  return path.href
}

Vite.js Config

export default defineConfig({
  root: './',
  resolve: {
    alias: {
      '/@/': path.resolve(__dirname, 'src')
    },
  },
  publicDir: 'assets',
  mode: 'production',
  build: {
    outDir: 'dist',
    sourcemap: true,
    target: ['es2019', 'safari11', 'firefox60', 'chrome61', 'node12'],
    chunkSizeWarningLimit: 500,
    minify: false,
    emptyOutDir: true,
    assetsInlineLimit: 2048,
    rollupOptions: {
      output: {
        entryFileNames: `assets/[name].js`,
        chunkFileNames: `assets/[name].js`,
        assetFileNames: `assets/[name].[ext]`,
        manualChunks(id) {
          if (id.includes('vue')) {
            return 'react';
          } else if (id.includes('node_modules')) {
            return 'vendor';
          }
        },
      },
    }
  },
  plugins: [
    vue(),
    legacy({
      polyfills: ['es.promise.finally', 'es/map', 'es/set'],
      modernPolyfills: ['es.promise.finally']
    })
  ],
})

Note: Everything works fine in development and it only fails in production...


来源: stackexchange

问:
How to use Future<string> in a dataTable in flutter
i have two future methods

```<code>Future<List> getTrns(String token,int page,) async {

final response = await
http.get(Uri.parse("api1/?params" ),
    headers:{
      ....
    });
final String t = response.body;
List list =jsonDecode(t)['data'];
return list;

}

Future<String> getstate(String code,String token,DateTime now) async {
DateTime start_date = new DateTime(now.year, now.month, now.day);
 String stat='';

final response = await
http.get(Uri.parse("api2/?params" ),
   headers:{
     ...
   });
final String t = response.body;
 List l = jsonDecode(t)['data'];

if(l.length == 0){
   stat = "absent";
}else {
   stat = "present";
}

return stat;

}
</code>```

this first methode will get the list of employee while the second one will use each employee code to find their state from another api.. the two functions are working fine but displaying them in an Datatable gave me an error of

```<code> Instance of future<string>
</code>```

Only in the stat cell while other cells are working fine
here's how i built the table

```<code> body: Column( children: <Widget>[
        FutureBuilder<List>(
        future: getTrns(widget.token,widget.page),
        builder: (ctx,ss){
          if(ss.hasError){
            print("error");
          }
          if(ss.hasData){
            datalist=ss.data!;

            return SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    child: _createDataTable(),

                )
            );
          }else {
            return Center(child: CircularProgressIndicator());
          }
        }
      ),

      MaterialButton(onPressed: () {
        widget.page = widget.page+1;
        print(widget.page);
      },
        child: Text("Next"),
        color: Colors.blue,)
       ]
       )
       )
      );
      }

  DataTable _createDataTable() {
    return DataTable(columns: _createColumns(), rows: _createRows());
  }
  List<DataColumn> _createColumns() {
    return [
      DataColumn(label: Text('ID')),
      DataColumn(label: Text('Full Name')),
      DataColumn(label: Text('State'))
    ];
  }
  List<DataRow> _createRows() {
    return datalist
        .map((list) => DataRow(cells: [
      DataCell(
          Text(list['emp_code'].toString()),
           onTap: (){
             Navigator.of(context).push(
                 MaterialPageRoute(builder: (BuildContext context)=>Details(token: w idget.token, emp:list['emp_code'].toString())
            ));
      }
 ),
 DataCell(
     Text(list['first_name'].toString()+" "+list['last_name'].toString()),
     onTap: (){
     Navigator.of(context).push(
     MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
     ));
     }
 ),
 DataCell(Text( getstate(list['emp_code'], widget.token, widget.now).toString() ),
 onTap: (){
   Navigator.of(context).push(
       MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
       ));
 }
 )
    ]))
        .toList();
  }

 }
</code>```

this is the result
table screenshot

Edit1:  new cell code cell code
the error is random, sometimes in first celland sometimes in a different one
first result
another result

答:
You will need another FutureBuilder around getstate just as you did with getTrns.

Your code already demonstrates that you know how to use one, so I will not bore you with it.

If you need a refresher: What is a Future and how do I use it?

You may want to put your Future, into a variable instead of directly refering to them in your FutureBuilders though, because you want to keep the same Future (or rather it's probably already existing result) when the user trigger a rebuild that has nothing to do with your data, for example by tilting the screen of their device or changing the size of their browser or desktop window.

ContentLicense: CC BY-SA 4.0

Body:
i have two future methods

Future<List> getTrns(String token,int page,) async {

final response = await
http.get(Uri.parse("api1/?params" ),
    headers:{
      ....
    });
final String t = response.body;
List list =jsonDecode(t)['data'];
return list;

}

Future<String> getstate(String code,String token,DateTime now) async {
DateTime start_date = new DateTime(now.year, now.month, now.day);
 String stat='';

final response = await
http.get(Uri.parse("api2/?params" ),
   headers:{
     ...
   });
final String t = response.body;
 List l = jsonDecode(t)['data'];

if(l.length == 0){
   stat = "absent";
}else {
   stat = "present";
}

return stat;

}

this first methode will get the list of employee while the second one will use each employee code to find their state from another api.. the two functions are working fine but displaying them in an Datatable gave me an error of

 Instance of future<string>

Only in the stat cell while other cells are working fine
here's how i built the table

 body: Column( children: <Widget>[
        FutureBuilder<List>(
        future: getTrns(widget.token,widget.page),
        builder: (ctx,ss){
          if(ss.hasError){
            print("error");
          }
          if(ss.hasData){
            datalist=ss.data!;

            return SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    child: _createDataTable(),

                )
            );
          }else {
            return Center(child: CircularProgressIndicator());
          }
        }
      ),

      MaterialButton(onPressed: () {
        widget.page = widget.page+1;
        print(widget.page);
      },
        child: Text("Next"),
        color: Colors.blue,)
       ]
       )
       )
      );
      }

  DataTable _createDataTable() {
    return DataTable(columns: _createColumns(), rows: _createRows());
  }
  List<DataColumn> _createColumns() {
    return [
      DataColumn(label: Text('ID')),
      DataColumn(label: Text('Full Name')),
      DataColumn(label: Text('State'))
    ];
  }
  List<DataRow> _createRows() {
    return datalist
        .map((list) => DataRow(cells: [
      DataCell(
          Text(list['emp_code'].toString()),
           onTap: (){
             Navigator.of(context).push(
                 MaterialPageRoute(builder: (BuildContext context)=>Details(token: w idget.token, emp:list['emp_code'].toString())
            ));
      }
 ),
 DataCell(
     Text(list['first_name'].toString()+" "+list['last_name'].toString()),
     onTap: (){
     Navigator.of(context).push(
     MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
     ));
     }
 ),
 DataCell(Text( getstate(list['emp_code'], widget.token, widget.now).toString() ),
 onTap: (){
   Navigator.of(context).push(
       MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
       ));
 }
 )
    ]))
        .toList();
  }

 }

this is the result
table screenshot

Edit1:  new cell code cell code
the error is random, sometimes in first celland sometimes in a different one
first result
another result


问:
How can I group by index with index +1 in Pandas
```<code>df = pd.DataFrame({'index': [1, 2, 3, 69, 70, 71, 458, 459, 460],
                   'Animals': ['alligator', 'bee', 'falcon', 'lion',
                   'monkey', 'parrot', 'shark', 'whale', 'zebra'],})
df
</code>```

Here is my DataFrame. I would like to groupby "index" column where first 3 animals which have index 1, 2, 3 goes to one group. The animals with numbers 69, 70, 71 goes to next group and so on.

In the end I would like to have 3 groups made by consecutive values in index column.

The good thing is the numbers in column index are always +1 and then a gap larger than 1 but never just +1

It should be exist some function for that I believe.

答:
IIUC, you want to group rows depending on whether difference is 1 or not right?. You can use diff + ne + cumsum to create different groups, groupby these groups and use agg to create lists:

```<code>out = df.groupby(df['index'].diff().ne(1).cumsum()).agg(list).reset_index(drop=True)
</code>```

Output:

```<code>             index                   Animals
0        [1, 2, 3]  [alligator, bee, falcon]
1     [69, 70, 71]    [lion, monkey, parrot]
2  [458, 459, 460]     [shark, whale, zebra]
</code>```

Body:
df = pd.DataFrame({'index': [1, 2, 3, 69, 70, 71, 458, 459, 460],
                   'Animals': ['alligator', 'bee', 'falcon', 'lion',
                   'monkey', 'parrot', 'shark', 'whale', 'zebra'],})
df

Here is my DataFrame. I would like to groupby "index" column where first 3 animals which have index 1, 2, 3 goes to one group. The animals with numbers 69, 70, 71 goes to next group and so on.

In the end I would like to have 3 groups made by consecutive values in index column.

The good thing is the numbers in column index are always +1 and then a gap larger than 1 but never just +1

It should be exist some function for that I believe.

Body:
IIUC, you want to group rows depending on whether difference is 1 or not right?. You can use diff + ne + cumsum to create different groups, groupby these groups and use agg to create lists:

out = df.groupby(df['index'].diff().ne(1).cumsum()).agg(list).reset_index(drop=True)

Output:

             index                   Animals
0        [1, 2, 3]  [alligator, bee, falcon]
1     [69, 70, 71]    [lion, monkey, parrot]
2  [458, 459, 460]     [shark, whale, zebra]


问:
Missing CFBundleIconName in Xcode9 iOS11 app release
I'm struggling to release a new version of our app using Xcode 9 built with iOS 11 SDK. Archiving and uploading the binary goes well without any issue. The build appears in iTunes Connect under Activity as 'processing' and it gets disappear and I get the following email back.

Dear developer,

We have discovered one or more issues with your recent delivery for
  "". To process your delivery, the following issues must be
  corrected: Missing Info.plist value - A value for the Info.plist key
  CFBundleIconName is missing in the bundle ''. Apps that
  provide icons in the asset catalog must also provide this Info.plist
  key. For more information see
  http://help.apple.com/xcode/mac/current/#/dev10510b1f7. Once these
  issues have been corrected, you can then redeliver the corrected
  binary. Regards, The App Store team

The link gives some info about asset bundles. I tried setting a CFBundleIconName key to project name or an image file name and submitted the app again. However, I still get the same email as above.

Any suggestion of help would be highly appreciated.

答: If you are still facing with the issue and you are using XCode 13, maybe the solution is to remove the info.plist key. I explain more here: https://stackoverflow.com/a/71016589/15860448

ContentLicense: CC BY-SA 3.0


问:
parse a binary decision tree and find all path by inversing the rule of the decision tree traversing to the right
the decision tree rule right now that I am having

```<code>{
  "id": -1,
  "rule": "TOTAL_REVENUE <= 300",
  "left": {
        "id": "0",
        "rule": "TOTAL_DATA_DUR <= 39.5794",

        "left": {
          "id": "1",
          "rule": "TOTAL_DATA_DUR <= 0.7408",

          "left": null,
          "right": {
            "id": "3",
            "rule": "TOTAL_PACKAGE_REVENUE <= 15.1350",

            "left": {
              "id": "4",
              "rule": "TOTAL_PACKAGE_REVENUE_14DAYS <= 12.5000",

              "left": null,
              "right": {
                "id": "6",

                "value": 84.62

              }
            },
            "right": null
          }
        },
        "right": {
          "id": "8",
          "rule": "TOTAL_DATA_DUR <= 301.6211",

          "left": null,
          "right": {
            "id": "10",
            "rule": "TOTAL_DATA_DUR <= 6898.9146",

            "left": {
              "id": "11",
              "rule": "TOTAL_PACKAGE_REVENUE <= 14.5000",

              "left": null,
              "right": {
                "id": "13",
                "rule": "TOTAL_PACKAGE_REVENUE <= 16.0000",

                "left": {
                  "id": "14",

                  "value": 84.96

                },
                "right": {
                  "id": "15",
                  "rule": "TOTAL_PACKAGE_REVENUE <= 19.5000",
                  "left": null,
                  "right": {
                    "id": "17",

                    "value": 70.8

                  }
                }
              }
            },
            "right": null
          }
        }
      }
}
</code>```

the output that I am trying to get is

```<code>path1 -> TOTAL_REVENUE <= 300 and TOTAL_DATA_DUR <= 39.5794 TOTAL_DATA_DUR > 0.7408 and TOTAL_PACKAGE_REVENUE <= 15.1350 and TOTAL_PACKAGE_REVENUE_14DAYS > 12.5000
</code>```

here you can see TOTAL_DATA_DUR > 0.7408 and TOTAL_PACKAGE_REVENUE_14DAYS > 12.5000 is being reversed as it is traversing through the right the rest of the condition is <=  because its going through left

```<code>path2 -> TOTAL_REVENUE <= 300 and TOTAL_DATA_DUR > 39.5794 and TOTAL_DATA_DUR >  301.6211 and TOTAL_DATA_DUR <= 6898.9146 and TOTAL_PACKAGE_REVENUE > 14.5000 and TOTAL_PACKAGE_REVENUE <= 16.0000

path3 -> TOTAL_REVENUE <= 300 and TOTAL_DATA_DUR > 39.5794 and TOTAL_DATA_DUR >  301.6211 and TOTAL_DATA_DUR <= 6898.9146 and TOTAL_PACKAGE_REVENUE > 14.5000 and TOTAL_PACKAGE_REVENUE > 16.0000 and TOTAL_PACKAGE_REVENUE > 19.5000
</code>```

I am fairly new to coding
how will I get the required output using recursion

the code that I am working on right now

```<code>from collections import deque
import json
def isLeaf1(node):
    return node.get('left') is None and node.get('right') is None

all_paths = []

def printRootToLeafPaths1(node, path, node_type=None):
    # base case
    if node is None:

        return

    # include the current node to the path
    if node.get('rule') is not None:
        path.append(node.get('rule'))

    # if a leaf node is found, print the path
    if isLeaf1(node):
        all_paths.append(list(path))

    # recur for the left and right subtree
    printRootToLeafPaths1(node.get('left'), path, 'left')
    printRootToLeafPaths1(node.get('right'), path, 'right')

    # backtrack: remove the current node after the left, and right subtree are done
    path.pop()

# The main function to print paths from the root node to every leaf node
def printRootToLeafPath1(root):
    # list to store root-to-leaf path
    path = deque()
    printRootToLeafPaths1(root, path)

json_rule ='{"id":-1,"rule":"TOTAL_REVENUE <= 300","left":{"id":"0","rule":"TOTAL_DATA_DUR <= 39.5794","left":{"id":"1","rule":"TOTAL_DATA_DUR <= 0.7408","left":null,"right":{"id":"3","rule":"TOTAL_PACKAGE_REVENUE <= 15.1350","left":{"id":"4","rule":"TOTAL_PACKAGE_REVENUE_14DAYS <= 12.5000","left":null,"right":{"id":"6","value":84.62}},"right":null}},"right":{"id":"8","rule":"TOTAL_DATA_DUR <= 301.6211","left":null,"right":{"id":"10","rule":"TOTAL_DATA_DUR <= 6898.9146","left":{"id":"11","rule":"TOTAL_PACKAGE_REVENUE <= 14.5000","left":null,"right":{"id":"13","rule":"TOTAL_PACKAGE_REVENUE <= 16.0000","left":{"id":"14","value":84.96},"right":{"id":"15","rule":"TOTAL_PACKAGE_REVENUE <= 19.5000","impurity":"0.47643265235457066","samples":"304","left":null,"right":{"id":"17","value":70.8}}}},"right":null}}}}'

printRootToLeafPath1(json.loads(json_rule))
</code>```

can anyone tell me what changes should I make in this code in order to obtains the output paths ?

答:
Some remarks:

Instead of printing in the recursive function, yield. That way, the caller can decide what they do with the paths: print them, or something else.

It is bad practice to use a global variable and let the function mutate that variable all_paths. Instead aim to make the function "pure", so it does not need that and can produce the paths through yielding them (or returning them).

The pop() call is unconditional, while the append() call is conditional. This looks as it there is a possibility to pop something when it was not appended in the same function, so it will be error prone. There is a better way to do recursion -- next point:

Instead of passing a partial path to the recursive call, let the recursive call give the paths it has found "as if" it was the root, and then prefix the current node's rule to it. This is the better practice for recursion.

Apparently, when there is no "rule" key in the node, it is a leaf-node. In that case it is not needed to look for left/right anymore, as it is understood that a node has either a "rule" key and children, or has no "rule" key and no children. In the case of a leaf, just yield an empty path which the caller can extend.

There is no logic in your code that negates a rule. For that you can use list of pairs that maps each operator to its opposite. And if none of those match the rule, then just apply a default not (rule) format. This logic assumes that a rule uses just one operator.

Your algorithm makes no use of the "value" properties in the leaves of the tree. I think you will need to use that information at some point, but I will ignore it for now.

Here is a possible implementation, taking the above points into account:

```<code>def negate(rule):
    mapper = (("<=", ">"), (">=", "<"), (">", "<="), ("<", ">="))
    for operator, negated in mapper:
        if operator in rule:
            return rule.replace(operator, negated)
    return "not (" + rule + ")"  # Default when operator not recognised

def nodeToLeafPaths(node):
    if not node:  # base case: nothing in this direction
        return
    rule = node.get('rule')
    if rule is None:  # base case: a leaf with a value
        yield []  # empty path
        return

    negated_rule = negate(rule)
    for path in nodeToLeafPaths(node.get('left')):
        yield [rule, *path]  # Extend path with current rule
    for path in nodeToLeafPaths(node.get('right')):
        yield [negated_rule, *path]

# Transform paths (lists) to AND-rules (strings):
def rootToLeafConjugations(root):
    return [" AND ".join(path) for path in nodeToLeafPaths(root)]
</code>```

The main driver code could look like this:

```<code>import json

json_rule ='{"id":-1,"rule":"TOTAL_REVENUE <= 300","left":{"id":"0","rule":"TOTAL_DATA_DUR <= 39.5794","left":{"id":"1","rule":"TOTAL_DATA_DUR <= 0.7408","left":null,"right":{"id":"3","rule":"TOTAL_PACKAGE_REVENUE <= 15.1350","left":{"id":"4","rule":"TOTAL_PACKAGE_REVENUE_14DAYS <= 12.5000","left":null,"right":{"id":"6","value":84.62}},"right":null}},"right":{"id":"8","rule":"TOTAL_DATA_DUR <= 301.6211","left":null,"right":{"id":"10","rule":"TOTAL_DATA_DUR <= 6898.9146","left":{"id":"11","rule":"TOTAL_PACKAGE_REVENUE <= 14.5000","left":null,"right":{"id":"13","rule":"TOTAL_PACKAGE_REVENUE <= 16.0000","left":{"id":"14","value":84.96},"right":{"id":"15","rule":"TOTAL_PACKAGE_REVENUE <= 19.5000","impurity":"0.47643265235457066","samples":"304","left":null,"right":{"id":"17","value":70.8}}}},"right":null}}}}'

for rule in rootToLeafConjugations(json.loads(json_rule)):
    print(rule)
</code>```

Body:
the decision tree rule right now that I am having

{
  "id": -1,
  "rule": "TOTAL_REVENUE <= 300",
  "left": {
        "id": "0",
        "rule": "TOTAL_DATA_DUR <= 39.5794",

        "left": {
          "id": "1",
          "rule": "TOTAL_DATA_DUR <= 0.7408",

          "left": null,
          "right": {
            "id": "3",
            "rule": "TOTAL_PACKAGE_REVENUE <= 15.1350",

            "left": {
              "id": "4",
              "rule": "TOTAL_PACKAGE_REVENUE_14DAYS <= 12.5000",

              "left": null,
              "right": {
                "id": "6",

                "value": 84.62

              }
            },
            "right": null
          }
        },
        "right": {
          "id": "8",
          "rule": "TOTAL_DATA_DUR <= 301.6211",

          "left": null,
          "right": {
            "id": "10",
            "rule": "TOTAL_DATA_DUR <= 6898.9146",

            "left": {
              "id": "11",
              "rule": "TOTAL_PACKAGE_REVENUE <= 14.5000",

              "left": null,
              "right": {
                "id": "13",
                "rule": "TOTAL_PACKAGE_REVENUE <= 16.0000",

                "left": {
                  "id": "14",

                  "value": 84.96

                },
                "right": {
                  "id": "15",
                  "rule": "TOTAL_PACKAGE_REVENUE <= 19.5000",
                  "left": null,
                  "right": {
                    "id": "17",

                    "value": 70.8

                  }
                }
              }
            },
            "right": null
          }
        }
      }
}

the output that I am trying to get is

path1 -> TOTAL_REVENUE <= 300 and TOTAL_DATA_DUR <= 39.5794 TOTAL_DATA_DUR > 0.7408 and TOTAL_PACKAGE_REVENUE <= 15.1350 and TOTAL_PACKAGE_REVENUE_14DAYS > 12.5000

here you can see TOTAL_DATA_DUR > 0.7408 and TOTAL_PACKAGE_REVENUE_14DAYS > 12.5000 is being reversed as it is traversing through the right the rest of the condition is <=  because its going through left

path2 -> TOTAL_REVENUE <= 300 and TOTAL_DATA_DUR > 39.5794 and TOTAL_DATA_DUR >  301.6211 and TOTAL_DATA_DUR <= 6898.9146 and TOTAL_PACKAGE_REVENUE > 14.5000 and TOTAL_PACKAGE_REVENUE <= 16.0000

path3 -> TOTAL_REVENUE <= 300 and TOTAL_DATA_DUR > 39.5794 and TOTAL_DATA_DUR >  301.6211 and TOTAL_DATA_DUR <= 6898.9146 and TOTAL_PACKAGE_REVENUE > 14.5000 and TOTAL_PACKAGE_REVENUE > 16.0000 and TOTAL_PACKAGE_REVENUE > 19.5000

I am fairly new to coding
how will I get the required output using recursion

the code that I am working on right now

from collections import deque
import json
def isLeaf1(node):
    return node.get('left') is None and node.get('right') is None

all_paths = []

def printRootToLeafPaths1(node, path, node_type=None):
    # base case
    if node is None:

        return

    # include the current node to the path
    if node.get('rule') is not None:
        path.append(node.get('rule'))

    # if a leaf node is found, print the path
    if isLeaf1(node):
        all_paths.append(list(path))

    # recur for the left and right subtree
    printRootToLeafPaths1(node.get('left'), path, 'left')
    printRootToLeafPaths1(node.get('right'), path, 'right')

    # backtrack: remove the current node after the left, and right subtree are done
    path.pop()

# The main function to print paths from the root node to every leaf node
def printRootToLeafPath1(root):
    # list to store root-to-leaf path
    path = deque()
    printRootToLeafPaths1(root, path)

json_rule ='{"id":-1,"rule":"TOTAL_REVENUE <= 300","left":{"id":"0","rule":"TOTAL_DATA_DUR <= 39.5794","left":{"id":"1","rule":"TOTAL_DATA_DUR <= 0.7408","left":null,"right":{"id":"3","rule":"TOTAL_PACKAGE_REVENUE <= 15.1350","left":{"id":"4","rule":"TOTAL_PACKAGE_REVENUE_14DAYS <= 12.5000","left":null,"right":{"id":"6","value":84.62}},"right":null}},"right":{"id":"8","rule":"TOTAL_DATA_DUR <= 301.6211","left":null,"right":{"id":"10","rule":"TOTAL_DATA_DUR <= 6898.9146","left":{"id":"11","rule":"TOTAL_PACKAGE_REVENUE <= 14.5000","left":null,"right":{"id":"13","rule":"TOTAL_PACKAGE_REVENUE <= 16.0000","left":{"id":"14","value":84.96},"right":{"id":"15","rule":"TOTAL_PACKAGE_REVENUE <= 19.5000","impurity":"0.47643265235457066","samples":"304","left":null,"right":{"id":"17","value":70.8}}}},"right":null}}}}'

printRootToLeafPath1(json.loads(json_rule))

can anyone tell me what changes should I make in this code in order to obtains the output paths ?

Body:
Some remarks:

Instead of printing in the recursive function, yield. That way, the caller can decide what they do with the paths: print them, or something else.

It is bad practice to use a global variable and let the function mutate that variable all_paths. Instead aim to make the function "pure", so it does not need that and can produce the paths through yielding them (or returning them).

The pop() call is unconditional, while the append() call is conditional. This looks as it there is a possibility to pop something when it was not appended in the same function, so it will be error prone. There is a better way to do recursion -- next point:

Instead of passing a partial path to the recursive call, let the recursive call give the paths it has found "as if" it was the root, and then prefix the current node's rule to it. This is the better practice for recursion.

Apparently, when there is no "rule" key in the node, it is a leaf-node. In that case it is not needed to look for left/right anymore, as it is understood that a node has either a "rule" key and children, or has no "rule" key and no children. In the case of a leaf, just yield an empty path which the caller can extend.

There is no logic in your code that negates a rule. For that you can use list of pairs that maps each operator to its opposite. And if none of those match the rule, then just apply a default not (rule) format. This logic assumes that a rule uses just one operator.

Your algorithm makes no use of the "value" properties in the leaves of the tree. I think you will need to use that information at some point, but I will ignore it for now.

Here is a possible implementation, taking the above points into account:

def negate(rule):
    mapper = (("<=", ">"), (">=", "<"), (">", "<="), ("<", ">="))
    for operator, negated in mapper:
        if operator in rule:
            return rule.replace(operator, negated)
    return "not (" + rule + ")"  # Default when operator not recognised

def nodeToLeafPaths(node):
    if not node:  # base case: nothing in this direction
        return
    rule = node.get('rule')
    if rule is None:  # base case: a leaf with a value
        yield []  # empty path
        return

    negated_rule = negate(rule)
    for path in nodeToLeafPaths(node.get('left')):
        yield [rule, *path]  # Extend path with current rule
    for path in nodeToLeafPaths(node.get('right')):
        yield [negated_rule, *path]

# Transform paths (lists) to AND-rules (strings):
def rootToLeafConjugations(root):
    return [" AND ".join(path) for path in nodeToLeafPaths(root)]

The main driver code could look like this:

import json

json_rule ='{"id":-1,"rule":"TOTAL_REVENUE <= 300","left":{"id":"0","rule":"TOTAL_DATA_DUR <= 39.5794","left":{"id":"1","rule":"TOTAL_DATA_DUR <= 0.7408","left":null,"right":{"id":"3","rule":"TOTAL_PACKAGE_REVENUE <= 15.1350","left":{"id":"4","rule":"TOTAL_PACKAGE_REVENUE_14DAYS <= 12.5000","left":null,"right":{"id":"6","value":84.62}},"right":null}},"right":{"id":"8","rule":"TOTAL_DATA_DUR <= 301.6211","left":null,"right":{"id":"10","rule":"TOTAL_DATA_DUR <= 6898.9146","left":{"id":"11","rule":"TOTAL_PACKAGE_REVENUE <= 14.5000","left":null,"right":{"id":"13","rule":"TOTAL_PACKAGE_REVENUE <= 16.0000","left":{"id":"14","value":84.96},"right":{"id":"15","rule":"TOTAL_PACKAGE_REVENUE <= 19.5000","impurity":"0.47643265235457066","samples":"304","left":null,"right":{"id":"17","value":70.8}}}},"right":null}}}}'

for rule in rootToLeafConjugations(json.loads(json_rule)):
    print(rule)


问:
refactor cferror tag to application.cfc's onError()
How to translate

```<code><cferror type="EXCEPTION" template="ErrorTemplate.cfm">
</code>```

to an onError() function for Application.cfc?  Notice that cferror create a var error struct for the template.  Is there a quick and easy way to create the same error struct?  How to pass that into ErrorTemplate.cfm using <cfinclude>?

I know onRequest() shares the variable scope with the target page, but does onError share variables scope too?  If not, what shall I do? Stick it to the Form scope?

Thank you

答:
According to http://livedocs.adobe.com/coldfusion/8/htmldocs/appFramework_15.html

Consider replacing cferror tags with an onError event method. If you
  do not do so, put the cferror tags in the CFC initialization code.

According to http://www.coldfusionjedi.com/index.cfm/2007/12/5/The-Complete-Guide-to-Adding-Error-Handling-to-Your-ColdFusion-Application

What if you are using Application.cfc? Well one thing to remember is
  that you can just as easily put CFERROR tags inside your
  Application.cfc file. That is allowed, and I've done that before.

Body:
How to translate

<cferror type="EXCEPTION" template="ErrorTemplate.cfm">

to an onError() function for Application.cfc?  Notice that cferror create a var error struct for the template.  Is there a quick and easy way to create the same error struct?  How to pass that into ErrorTemplate.cfm using <cfinclude>?

I know onRequest() shares the variable scope with the target page, but does onError share variables scope too?  If not, what shall I do? Stick it to the Form scope?

Thank you


问:
Subsetting data coming from database
I have a model which collects data in my ASP.NET MVC app:

```<code>namespace myapp.Models
{
    [Table("mytable")]
    public partial class mytbl
    {
        // column specifications
    }
}
</code>```

but this model takes all rows of the selected table. I want to add some filter rules. In an SQL query it's look so;

```<code>SELECT *
FROM mytable
WHERE mycol = 2 OR mycol = 3
</code>```

in above example I typed 2 and 3 by hand but I have a text file toshow.txt (located at wwwroot) the contents of the toshow.txt file is;

```<code>2
3
</code>```

How can I subset the data according to the text file ?

I'm not super familiar with ASP.NET MVC app development. Sorry if my question doesn't make sense.

Thanks in advance.

答:
You'll need to

read the file

convert strings read from the file to int values

filter the data in the database

The below should at least get you started:

```<code>// get filename and read the file
string fileName = Path.Combine(_env.WebRootPath, "toshow.txt");
string[] lines = File.ReadAllLines(fileName);

// parse values in file to List<int>
List<int> filter = lines.Select(line => int.Parse(line)).ToList();
// could also be written lines.Select(int.Parse)

// filter your DB
var filteredResult = _context.MyTable.Where(x => filter.Contains(x.MyCol));
</code>```

Where _env is an IWebHostingEnvironment and WebRootPath maps to the wwwroot directory. You may need to use ContentRootPath instead if you're using IHostingEnvironment. More details can be found in Static files in Asp.Net Core.

The above will filter MyCol on the values in the file.

You'll also need to perform your own error checking and validation if, for example, the file doesn't contain values which are convertible to ints.

Title: Subsetting data coming from database

Body:
I have a model which collects data in my ASP.NET MVC app:

namespace myapp.Models
{
    [Table("mytable")]
    public partial class mytbl
    {
        // column specifications
    }
}

but this model takes all rows of the selected table. I want to add some filter rules. In an SQL query it's look so;

SELECT *
FROM mytable
WHERE mycol = 2 OR mycol = 3

in above example I typed 2 and 3 by hand but I have a text file toshow.txt (located at wwwroot) the contents of the toshow.txt file is;

2
3

How can I subset the data according to the text file ?

I'm not super familiar with ASP.NET MVC app development. Sorry if my question doesn't make sense.

Thanks in advance.

Body:
You'll need to

read the file

convert strings read from the file to int values

filter the data in the database

The below should at least get you started:

// get filename and read the file
string fileName = Path.Combine(_env.WebRootPath, "toshow.txt");
string[] lines = File.ReadAllLines(fileName);

// parse values in file to List<int>
List<int> filter = lines.Select(line => int.Parse(line)).ToList();
// could also be written lines.Select(int.Parse)

// filter your DB
var filteredResult = _context.MyTable.Where(x => filter.Contains(x.MyCol));

Where _env is an IWebHostingEnvironment and WebRootPath maps to the wwwroot directory. You may need to use ContentRootPath instead if you're using IHostingEnvironment. More details can be found in Static files in Asp.Net Core.

The above will filter MyCol on the values in the file.

You'll also need to perform your own error checking and validation if, for example, the file doesn't contain values which are convertible to ints.


问:
What is the use of Docker Desktop?
As a technology, we understand the docker creates virtualization and there is a docker hub, where Docker images are stored.
To explain in simple words, what purpose does docker desktop serve?
Or why do I need to install Docker Desktop App to use Docker

If we need to use docker on linux server, do we need to install Docker Desktop there as well or there is some other way?

答:
Docker as technology can only be run on Linux OS.

Docker Desktop does 2 things.

creates Linux VM on your host OS (Windows / Mac)

forwards docker-cli commands from the host OS to created Linux VM --> due to this the containers are created on Linux VM, and on the surface it appears to be working on Windows/Mac

Thus we are able to run and use docker-cli on Windows/Mac even though these OS's do not support docker images/containers.

Title: What is the use of Docker Desktop?


问:
Make random curvy lines or segments for paths on Canvas
Here is the code that I tried:

```<code>var myPath = new Path();
myPath.strokeColor = 'red';
myPath.strokeWidth = 5;
myPath.dashArray = [20, 5];
myPath.add(new Point(1800, 120));

function onFrame(event) {
    if(event.count%10 == 0) {
        var angle = Math.random(0, 1)*Math.PI;
        var all_points = myPath.segments.length;
        var last_point = myPath.segments[all_points - 1];
        myPath.add(new Point(last_point.point.x + 40*Math.cos(angle*(180 / Math.PI)), last_point.point.y + 40*Math.sin(angle*(180 / Math.PI))));
        myPath.smooth({type: 'geometric', factor: 2});
    }
}
</code>```

I was thinking this would choose a random angle between 0 and Math.PI and then plot the points from the last point. However, it just draws a line at 45 degree going back and forth. I did a console.log() for the angle and it is always something random between 0 and Math.PI.

I want to achieve something similar to this: https://codepen.io/speaud/pen/ExxzrL

Here is what I have so far. My idea was to get a random angle and then gets sin and cosine values for that angle and add them to the last point in the path. This would move the path randomly in a certain direction.

I was hoping that it would create nice curvy non-intersecting paths but the path goes over the same place multiple times also making it smooth with the smooth() function changes its previous course a little.

答: Math.cos and Math.sin get angle in radians but in your code you convert them to degrees

Body:
Here is the code that I tried:

var myPath = new Path();
myPath.strokeColor = 'red';
myPath.strokeWidth = 5;
myPath.dashArray = [20, 5];
myPath.add(new Point(1800, 120));

function onFrame(event) {
    if(event.count%10 == 0) {
        var angle = Math.random(0, 1)*Math.PI;
        var all_points = myPath.segments.length;
        var last_point = myPath.segments[all_points - 1];
        myPath.add(new Point(last_point.point.x + 40*Math.cos(angle*(180 / Math.PI)), last_point.point.y + 40*Math.sin(angle*(180 / Math.PI))));
        myPath.smooth({type: 'geometric', factor: 2});
    }
}

I was thinking this would choose a random angle between 0 and Math.PI and then plot the points from the last point. However, it just draws a line at 45 degree going back and forth. I did a console.log() for the angle and it is always something random between 0 and Math.PI.

I want to achieve something similar to this: https://codepen.io/speaud/pen/ExxzrL

Here is what I have so far. My idea was to get a random angle and then gets sin and cosine values for that angle and add them to the last point in the path. This would move the path randomly in a certain direction.

I was hoping that it would create nice curvy non-intersecting paths but the path goes over the same place multiple times also making it smooth with the smooth() function changes its previous course a little.


问:
Tools to help reverse engineer binary file formats
What tools are available to aid in decoding unknown binary data formats?

I know Hex Workshop and 010 Editor both support structures. These are okay to a limited extent for a known fixed format but get difficult to use with anything more complicated, especially for unknown formats. I guess I'm looking at a module for a scripting language or a scriptable GUI tool.

For example, I'd like to be able to find a structure within a block of data from limited known information, perhaps a magic number. Once I've found a structure, then follow known length and offset words to find other structures. Then repeat this recursively and iteratively where it makes sense.

In my dreams, perhaps even automatically identify possible offsets and lengths based on what I've already told the system!

答: Kaitai is an open-source language for describing binary structures in data streams. It comes with a translator that can output parsing code for many programming languages, for inclusion in your own program code.</p>

OwnerDisplayName: Mat

ContentLicense: CC BY-SA 2.5


问:
No such method memberName when building InvokeRequest for lambda function
I'm trying to create a request, in java, to call a lambda function locally.
When creating the request:

```<code>InvokeRequest request = InvokeRequest.builder()
                .functionName("examplelambda")
                .payload(SdkBytes.fromUtf8String("{\n" +
                        " \"Hello \": \"Paris\",\n" +
                        " \"countryCode\": \"FR\"\n" +
                        "}")).build();
</code>```

it gives an error like this:

```<code>java.lang.NoSuchMethodError: software.amazon.awssdk.core.SdkField$Builder.memberName(Ljava/lang/String;)Lsoftware/amazon/awssdk/core/SdkField$Builder;
</code>```

I'm using

```<code><dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-core</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>lambda</artifactId>
            <version>2.17.124</version>
        </dependency>
</code>```

How to solve it?

答:
I solved by downgrading software.amazon.awssdk.lambda dependency to 2.5.10</p>
```<code><dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>lambda</artifactId>
            <version>2.5.10</version>
</dependency>
</code>```

Body:
I'm trying to create a request, in java, to call a lambda function locally.
When creating the request:

InvokeRequest request = InvokeRequest.builder()
                .functionName("examplelambda")
                .payload(SdkBytes.fromUtf8String("{\n" +
                        " \"Hello \": \"Paris\",\n" +
                        " \"countryCode\": \"FR\"\n" +
                        "}")).build();

it gives an error like this:

java.lang.NoSuchMethodError: software.amazon.awssdk.core.SdkField$Builder.memberName(Ljava/lang/String;)Lsoftware/amazon/awssdk/core/SdkField$Builder;

I'm using

<dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-core</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>lambda</artifactId>
            <version>2.17.124</version>
        </dependency>

How to solve it?

Body:
I solved by downgrading software.amazon.awssdk.lambda dependency to 2.5.10

<dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>lambda</artifactId>
            <version>2.5.10</version>
</dependency>


问:
angular this.formGroup.get('elemName').value returns a weird json object
I have the following code in my project (the problem shows up in the tipoDoc variable):

```<code>this.formGroup = this.fb.group({
      valutazioneNuovoDoc: [false],
      tipoDoc : new FormControl(2),
      note: ['']
    });

this.fileTypeOptions = this.fileTypeOptions || [
  { label: "Carta di identita", value: "CI" },
  { label: "Dichiarazione dei redditi", value: "DR" },
  { label: "Certificazione unica", value: "CU" },
  { label: "Foto tessera", value: "FT" }
]
</code>```

Then in my .html component

```<code><div>
      <div class="peav-upload-file-type col-6 form-group">
      <p-dropdown [options]="fileTypeOptions" formControlName="tipoDoc" optionLabel="label" optionValue="value"></p-dropdown>
    </div>
</code>```

My problem: whenever i try to access the selected value of this p-dropdown, as follows:

```<code>console.log('tipoDoc.value: ' + JSON.stringify(this.formGroup.get('tipoDoc').value) );
</code>```

i get this json object, instead of a fileTypeOptions value:

```<code>tipoDoc.value: {"validator":null,"asyncValidator":null,"pristine":true,"touched":false,"_onDisabledChange":[],"_onChange":[],"_pendingValue":2,"value":2,"status":"VALID","errors":null,"valueChanges":{"_isScalar":false,"observers":[],"closed":false,"isStopped":false,"hasError":false,"thrownError":null,"__isAsync":false},"statusChanges":{"_isScalar":false,"observers":[],"closed":false,"isStopped":false,"hasError":false,"thrownError":null,"__isAsync":false}}
</code>```

The weird thing is that this happens only the first time, after selecting any item from the menu. If after the first choice i change my selection it then starts to work correctly.

Thanks in advance.

答:
the issue here is that your'e initializing tipodoc with formControl as default value, then when you select a value from list it's being overridden and hence the issue is gone.
try to init the formGroup this way -</p>
```<code>this.formGroup = this.fb.group({
      valutazioneNuovoDoc: [false],
      tipoDoc : [2],
      note: ['']
    });
</code>```

Body:
I have the following code in my project (the problem shows up in the tipoDoc variable):

this.formGroup = this.fb.group({
      valutazioneNuovoDoc: [false],
      tipoDoc : new FormControl(2),
      note: ['']
    });

this.fileTypeOptions = this.fileTypeOptions || [
  { label: "Carta di identita", value: "CI" },
  { label: "Dichiarazione dei redditi", value: "DR" },
  { label: "Certificazione unica", value: "CU" },
  { label: "Foto tessera", value: "FT" }
]

Then in my .html component

My problem: whenever i try to access the selected value of this p-dropdown, as follows:

console.log('tipoDoc.value: ' + JSON.stringify(this.formGroup.get('tipoDoc').value) );

i get this json object, instead of a fileTypeOptions value:

tipoDoc.value: {"validator":null,"asyncValidator":null,"pristine":true,"touched":false,"_onDisabledChange":[],"_onChange":[],"_pendingValue":2,"value":2,"status":"VALID","errors":null,"valueChanges":{"_isScalar":false,"observers":[],"closed":false,"isStopped":false,"hasError":false,"thrownError":null,"__isAsync":false},"statusChanges":{"_isScalar":false,"observers":[],"closed":false,"isStopped":false,"hasError":false,"thrownError":null,"__isAsync":false}}

The weird thing is that this happens only the first time, after selecting any item from the menu. If after the first choice i change my selection it then starts to work correctly.

Thanks in advance.

Body:
the issue here is that your'e initializing tipodoc with formControl as default value, then when you select a value from list it's being overridden and hence the issue is gone.
try to init the formGroup this way -

this.formGroup = this.fb.group({
      valutazioneNuovoDoc: [false],
      tipoDoc : [2],
      note: ['']
    });


问:
Limit the list of objects sql
I am new to SQL (using SQLiteStudio) and I wrote such a query to calculate. List of municipalities where the number of sales increased by at least 20% between the first and second quarters of 2020. I'm trying to set a limit using HAVING but it doesn't work. Any help would really help. Thanks!

```<code>    SELECT commune, p.date_1,d.date_2,
    (((d.date_2)*100/(p.date_1)-100)) as "Sales"
    FROM pr_semestr p, dx_semestre d
    WHERE p.commune=d.commune
    HAVING ( (d.date_2)*100/(p.date_1)-100) > '20'
</code>```

Data Sample:

commune
date_1
date_2
Sales

ABBEVILLE
2
9
350

ACHERES
5
13
160

ACIGNE
11
8
-28

AGEN
1
1
0

AIGUES-VIVES
15
17
13

答:
Yes, I changed using a WHERE clause, also added one parenthesis and deleted quotes. And also changed on JOIN ON. It worked!</p>
```<code>    FROM pr_semestr p JOIN dx_semestre d ON p.commune=d.commune
    WHERE (((d.date_2)*100/(p.date_1)-100)) > 20
</code>```

Title: Limit the list of objects sql

Body:
I am new to SQL (using SQLiteStudio) and I wrote such a query to calculate. List of municipalities where the number of sales increased by at least 20% between the first and second quarters of 2020. I'm trying to set a limit using HAVING but it doesn't work. Any help would really help. Thanks!

    SELECT commune, p.date_1,d.date_2,
    (((d.date_2)*100/(p.date_1)-100)) as "Sales"
    FROM pr_semestr p, dx_semestre d
    WHERE p.commune=d.commune
    HAVING ( (d.date_2)*100/(p.date_1)-100) > '20'

Data Sample:

commune
date_1
date_2
Sales

ABBEVILLE
2
9
350

ACHERES
5
13
160

ACIGNE
11
8
-28

AGEN
1
1
0

AIGUES-VIVES
15
17
13

Body:
Yes, I changed using a WHERE clause, also added one parenthesis and deleted quotes. And also changed on JOIN ON. It worked!

    FROM pr_semestr p JOIN dx_semestre d ON p.commune=d.commune
    WHERE (((d.date_2)*100/(p.date_1)-100)) > 20


问:
"At least one signature is invalid" After adding stamp in Signed PDF
I need to add stamp or image annotation in a signed PDF but it gives me an "invalid signature" error and, after moving this annotation, it gives me an "at least one signature required validating" error. How can I solve this?

I also found a solution but for text annotation in this question.
It worked fine with text annotation but I cannot do the same for the stamp.

```<code>iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@"D:\\11.jpg");
float w = 100;
float h = 100;
iTextSharp.text.Rectangle location = new iTextSharp.text.Rectangle(36, 770 - h, 36 + w, 770);

PdfAnnotation stamp = PdfAnnotation.CreateStamp(stamper.Writer, location, null, "ITEXT");
img.SetAbsolutePosition(0, 0);
PdfContentByte cb = stamper.GetOverContent(1);
PdfAppearance app = cb.CreateAppearance(100, 100);
app.AddImage(img);
stamp.SetAppearance(PdfName.N, app);
stamper.AddAnnotation(stamp, 1);
</code>```

答:
This

```<code>PdfContentByte cb = stamper.GetOverContent(1);
</code>```

is the line causing the invalidation of the signature.

Calling stamper.GetOverContent (or stamper.GetUnderContent) already prepares the page contents for the addition of new content. This preparation already is considered a change of page content. As page content changes to a signed PDF are forbidden, this invalidates the signature.

You only use this PdfContentByte cb to create a PdfAppearance for your stamp annotation:

```<code>PdfAppearance app = cb.CreateAppearance(100, 100);
</code>```

Fortunately you don't need cb to create a PdfAppearance, there also is a static PdfAppearance method to do so. Thus, simply replace

```<code>PdfContentByte cb = stamper.GetOverContent(1);
PdfAppearance app = cb.CreateAppearance(100, 100);
</code>```

by

```<code>PdfAppearance app = PdfAppearance.CreateAppearance(stamper.Writer, 100, 100);
</code>```

Body:
I need to add stamp or image annotation in a signed PDF but it gives me an "invalid signature" error and, after moving this annotation, it gives me an "at least one signature required validating" error. How can I solve this?

I also found a solution but for text annotation in this question.
It worked fine with text annotation but I cannot do the same for the stamp.

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@"D:\\11.jpg");
float w = 100;
float h = 100;
iTextSharp.text.Rectangle location = new iTextSharp.text.Rectangle(36, 770 - h, 36 + w, 770);

PdfAnnotation stamp = PdfAnnotation.CreateStamp(stamper.Writer, location, null, "ITEXT");
img.SetAbsolutePosition(0, 0);
PdfContentByte cb = stamper.GetOverContent(1);
PdfAppearance app = cb.CreateAppearance(100, 100);
app.AddImage(img);
stamp.SetAppearance(PdfName.N, app);
stamper.AddAnnotation(stamp, 1);

Body:
This

PdfContentByte cb = stamper.GetOverContent(1);

is the line causing the invalidation of the signature.

Calling stamper.GetOverContent (or stamper.GetUnderContent) already prepares the page contents for the addition of new content. This preparation already is considered a change of page content. As page content changes to a signed PDF are forbidden, this invalidates the signature.

You only use this PdfContentByte cb to create a PdfAppearance for your stamp annotation:

PdfAppearance app = cb.CreateAppearance(100, 100);

Fortunately you don't need cb to create a PdfAppearance, there also is a static PdfAppearance method to do so. Thus, simply replace

PdfContentByte cb = stamper.GetOverContent(1);
PdfAppearance app = cb.CreateAppearance(100, 100);

by

PdfAppearance app = PdfAppearance.CreateAppearance(stamper.Writer, 100, 100);


问:
I need a function like countif in PostgreSQL
I have this table like this

```<code>Status    Last_update_time
4      | 2/2/2021, 11:03
5      | 2/2/2021, 12:04
4      | 24/2/2021, 12:36
4      | 20/2/2021, 17:33
5      | 13/2/2021, 10:57
</code>```

I already write a SQL like this

```<code>Select date_trunc('week', CAST(kyc.last_update_time as timestamp )) AS "week",
       Count(status)
From KYC
Where kyc.status = 4
  and (kyc.last_update_time >= date_trunc('week', CURRENT_TIMESTAMP - interval '3 week')
       and kyc.last_update_time < date_trunc('week', CURRENT_TIMESTAMP))
Group by 1
</code>```

So it will count for me all status 4 for each week in last 3 week

But now I want to change that I can count 4 and 5. And when I visualization, I will have 2 columns, 1 for status 4, 1 for status 5

My expected output SQL like this

```<code>Select date_trunc('week', CAST(kyc.last_update_time as timestamp )) AS "week",
       Count(if(kyc.status = 4,kyc.used_id,null) as XTTC
       Count(if(kyc.status = 5,kyc.used_id,null) as XTTB
From KYC

Where (kyc.last_update_time >= date_trunc('week', CURRENT_TIMESTAMP - interval '3 week')
       and kyc.last_update_time < date_trunc('week', CURRENT_TIMESTAMP))
Group by 1
</code>```

Is there any function like countif in excel that can help me with this

Thank you

答:
As @a_horse_with_no_name suggests you can use conditional aggregation with filter as a very capable alternative of countif in order to achieve this.

select date_trunc('week', last_update_time::timestamp) as "week",
       count(*) filter (where status = 4) as "XTTC",
       count(*) filter (where status = 5) as "XTTB"
from kyc
where last_update_time >= date_trunc('week', CURRENT_TIMESTAMP - interval '3 weeks')
  and last_update_time <  date_trunc('week', CURRENT_TIMESTAMP)
group by 1;
```

Body:
I have this table like this

Status    Last_update_time
4      | 2/2/2021, 11:03
5      | 2/2/2021, 12:04
4      | 24/2/2021, 12:36
4      | 20/2/2021, 17:33
5      | 13/2/2021, 10:57

I already write a SQL like this

Select date_trunc('week', CAST(kyc.last_update_time as timestamp )) AS "week",
       Count(status)
From KYC
Where kyc.status = 4
  and (kyc.last_update_time >= date_trunc('week', CURRENT_TIMESTAMP - interval '3 week')
       and kyc.last_update_time < date_trunc('week', CURRENT_TIMESTAMP))
Group by 1

So it will count for me all status 4 for each week in last 3 week

But now I want to change that I can count 4 and 5. And when I visualization, I will have 2 columns, 1 for status 4, 1 for status 5

My expected output SQL like this

Select date_trunc('week', CAST(kyc.last_update_time as timestamp )) AS "week",
       Count(if(kyc.status = 4,kyc.used_id,null) as XTTC
       Count(if(kyc.status = 5,kyc.used_id,null) as XTTB
From KYC

Where (kyc.last_update_time >= date_trunc('week', CURRENT_TIMESTAMP - interval '3 week')
       and kyc.last_update_time < date_trunc('week', CURRENT_TIMESTAMP))
Group by 1

Is there any function like countif in excel that can help me with this

Thank you


问:
Good way on creating C# validation class
I have a functionality that upload a file, validate it, save it to database and so on.

All of these actions are on some different classes and methods. But, if something goes wrong in any of these methods, I want to inform these errors to my front-end.

Is there a good way to manage this, let's call, "Error Class"?

Thanks!

答:
Well lets say, your sequence of processing a file is

Upload

Validate

Save

Return with success result/error.

Now, in all these sequence if its same all the time, then you could just go for exception throwing mechanism and collect it at the front end. May be you could throw with an Error ID.


问:
How is this function dealing into 2 lists?
The purpose of this self created function is to take in a list, and output 2 lists, they are to ne inserted into the lists alternating. SO [4,5,1,6,7,8] will be dealt into 2 lists like ([4,1,7],[5,6,8])

```<code>deal :: [a] -> ([a],[a])
deal [] = ([],[])
deal [x] = ([x],[])
deal (x:xs) = let (ys,zs) = deal xs
              in (x:zs, ys)
</code>```

this is the function. Im not understanding what is happening with let (ys,zs) = deal xs, i know its basically creating a placeholder for 2 lists but can someone walk me through the recursion thats taking place.

答:
By definition,

```<code>deal [8] = ([8], [])
</code>```

Now:

```<code>deal [7,8]
= deal (7:[8])
= let (ys,zs) = deal [8]
  in (7:zs, ys)
-- from the recursion we discover ys=[8], zs=[]
= (7:[], [8])
= ([7], [8])
</code>```

Again:

```<code>deal [6,7,8]
= deal (6:[7,8])
= let (ys,zs) = deal [7,8]
  in (6:zs, ys)
-- from the recursion we discover ys=[7], zs=[8]
= (6:[8], [7])
= ([6,8], [7])
</code>```

And so on. Every time we recurse, we swap the previous result pair and  prepend an item to the first component. Because of the swaps, it's like adding an element to the first component, then to the second one, then again to the first, and so on, alternating. This splits the list in half, roughly speaking.

Body:
The purpose of this self created function is to take in a list, and output 2 lists, they are to ne inserted into the lists alternating. SO [4,5,1,6,7,8] will be dealt into 2 lists like ([4,1,7],[5,6,8])

deal :: [a] -> ([a],[a])
deal [] = ([],[])
deal [x] = ([x],[])
deal (x:xs) = let (ys,zs) = deal xs
              in (x:zs, ys)

this is the function. Im not understanding what is happening with let (ys,zs) = deal xs, i know its basically creating a placeholder for 2 lists but can someone walk me through the recursion thats taking place.

Body:
By definition,

deal [8] = ([8], [])

Now:

deal [7,8]
= deal (7:[8])
= let (ys,zs) = deal [8]
  in (7:zs, ys)
-- from the recursion we discover ys=[8], zs=[]
= (7:[], [8])
= ([7], [8])

Again:

deal [6,7,8]
= deal (6:[7,8])
= let (ys,zs) = deal [7,8]
  in (6:zs, ys)
-- from the recursion we discover ys=[7], zs=[8]
= (6:[8], [7])
= ([6,8], [7])

And so on. Every time we recurse, we swap the previous result pair and  prepend an item to the first component. Because of the swaps, it's like adding an element to the first component, then to the second one, then again to the first, and so on, alternating. This splits the list in half, roughly speaking.


问:
JMeter JSR223 script - how do we load multiple groovy files?
I want to structure my code well to use in JMeter, so I plan to have the groovy scripts in separate groovy files. The JSR223 script can load the script file and execute it. So far so good.

The groovy scripts will get complex, so I want to split the files into multiple files and use them. For e.g. have a file utils.groovy with content

```<code>public class SharedStore {
    // Initializes the store to store all information about all the data being worked upon
    def initializeStore() {
        HashMap allStore = new HashMap();
        // def props = org.apache.jmeter.util.JMeterUtils.getJMeterProperties()
        props.put("${storeHashSet}", allStore);
    }
</code>```

This class will grow with more methods and will be used by all scripts invoked from JMeter. There will be other similar classes.

One JMeter sampler called InitializeEnvironment.groovy wants to use this method thus:

```<code>evaluate(new File("<<path>>/Utils.groovy"));  // This line is an attempt to include utils.groovy
var shr = new SharedStore().initializeStore();
</code>```

The above attempt to include groovy file is based on this discussion - https://stackoverflow.com/a/9154553 (and I have tried other options from that discussion to no avail)

Using the above option throws the error:

```<code>Script70.groovy: 2: unable to resolve class SharedStore
 @ line 2, column 11.
   var shr = new SharedStore().initializeStore();
</code>```

I would prefer to wrap things utility methods a class but I can live with having keep methods in global space.
If I do manage to load the additional file like in this - https://stackoverflow.com/a/15904699 - suggestion, without using "class" and have groovy wrap it up in a class for me, props are not available in utils.groovy unless I include the line def props = org.apache.jmeter.util.JMeterUtils.getJMeterProperties() and even then ${storeHashSet} cannot be used

```<code>No such property: storeHashSet for class: SharedStore
</code>```

I want to be able to decompose the scripts into more manageable files, and be able to access JMeter variables and structures in these files.

Any advise on how I can do that in JMeter?

答:
The most straightforward solution would be:

Compiling these individual files into classes

Packaging them into .jar (this one you can skip)

Putting the .jar or (class files if you skipped step 2) in the JMeter Classpath

Using the .jar file in your JSR223 Test Elements

Body:
I want to structure my code well to use in JMeter, so I plan to have the groovy scripts in separate groovy files. The JSR223 script can load the script file and execute it. So far so good.

The groovy scripts will get complex, so I want to split the files into multiple files and use them. For e.g. have a file utils.groovy with content

public class SharedStore {
    // Initializes the store to store all information about all the data being worked upon
    def initializeStore() {
        HashMap allStore = new HashMap();
        // def props = org.apache.jmeter.util.JMeterUtils.getJMeterProperties()
        props.put("${storeHashSet}", allStore);
    }

This class will grow with more methods and will be used by all scripts invoked from JMeter. There will be other similar classes.

One JMeter sampler called InitializeEnvironment.groovy wants to use this method thus:

evaluate(new File("<<path>>/Utils.groovy"));  // This line is an attempt to include utils.groovy
var shr = new SharedStore().initializeStore();

The above attempt to include groovy file is based on this discussion - https://stackoverflow.com/a/9154553 (and I have tried other options from that discussion to no avail)

Using the above option throws the error:

Script70.groovy: 2: unable to resolve class SharedStore
 @ line 2, column 11.
   var shr = new SharedStore().initializeStore();

I would prefer to wrap things utility methods a class but I can live with having keep methods in global space.
If I do manage to load the additional file like in this - https://stackoverflow.com/a/15904699 - suggestion, without using "class" and have groovy wrap it up in a class for me, props are not available in utils.groovy unless I include the line def props = org.apache.jmeter.util.JMeterUtils.getJMeterProperties() and even then ${storeHashSet} cannot be used

No such property: storeHashSet for class: SharedStore

I want to be able to decompose the scripts into more manageable files, and be able to access JMeter variables and structures in these files.

Any advise on how I can do that in JMeter?


问:
Google Plus and OpenSocial
It appears Google Plus is mainly written using Java on the server side. So I wonder if it will be compatible with the existing OpenSocial APIs Google has created with MySpace.
It could easily be done using Apache Shindig, the reference OpenSocial implementation for Java.

Does anyone has information about that?

答:
Yes, it runs on open social.

Watch the requests in your browser and you will see something like this:

```<code>https://r3101-dot-latest-dot-project-slingshot-gp.appspot.com/
?loadFrom=ES
&jsh=r;gc/[OBSCURED]#id=gameIframe
&parent=https://upt14k1i2veesusrda9nfotcrbp9d7p5-a-oz-opensocial.googleusercontent.com
&rpctoken= [OBSCURED]
&_methods=_ready,_close,_open,_resizeMe
</code>```

the domain ...opensocial.googleusercontent.com seems to make it pretty obvious whats going on here, no?

Title: Google Plus and OpenSocial

Body:
Yes, it runs on open social.

Watch the requests in your browser and you will see something like this:

https://r3101-dot-latest-dot-project-slingshot-gp.appspot.com/
?loadFrom=ES
&jsh=r;gc/[OBSCURED]#id=gameIframe
&parent=https://upt14k1i2veesusrda9nfotcrbp9d7p5-a-oz-opensocial.googleusercontent.com
&rpctoken= [OBSCURED]
&_methods=_ready,_close,_open,_resizeMe

the domain ...opensocial.googleusercontent.com seems to make it pretty obvious whats going on here, no?


问:
Convert Dataframe of itemsets to asymmetric binary attribute
I have a dataframe of itemsets and I want to change to asymmetric binary attributes for each item

I have managed to do this but with a very lengthy process; creating a new list for each row in df and iterating through to check for each items.

```<code>list1= list(shopping.loc[0])
list2= list(shopping.loc[1])
list3= list(shopping.loc[2])
list4= list(shopping.loc[3])
list5= list(shopping.loc[4])
list6= list(shopping.loc[5])
list7= list(shopping.loc[6])
list8= list(shopping.loc[7])

list9= list(shopping.loc[8])
list10= list(shopping.loc[9])

ref= ['Milk', 'Burgers', 'Buns', 'Ketchup', 'Coals', 'Beer']

def item_in_list(shop, ref):
    there= []
    for item in ref:
        if item in shop: there.append(1)
        else: there.append(0)
    return there

nl1 = item_in_list(list1, ref)
nl2 = item_in_list(list2, ref)
nl3 = item_in_list(list3, ref)
nl4 = item_in_list(list4, ref)
nl5 = item_in_list(list5, ref)
nl6 = item_in_list(list6, ref)
nl7 = item_in_list(list7, ref)
nl8 = item_in_list(list8, ref)
nl9 = item_in_list(list9, ref)
nl10 = item_in_list(list10, ref)

shop_bin= pd.DataFrame(np.array([nl1, nl2, nl3, nl4, nl5, nl6, nl7, nl8, nl9, nl10 ]),
                   columns=['Milk', 'Burgers', 'Buns', 'Ketchup', 'Coals', 'Beer'])
</code>```

And then combining these lists into a new df to produce the df below

End Result

There must be a better way to do this to get to same result?

答:
We can use:</p>
```<code>#assert len(ref) == shopping.shape[1]
shop_bin = shopping.eq(ref, axis=1).astype(int).set_axis(ref, axis=1)
</code>```

Body:
I have a dataframe of itemsets and I want to change to asymmetric binary attributes for each item

I have managed to do this but with a very lengthy process; creating a new list for each row in df and iterating through to check for each items.

list1= list(shopping.loc[0])
list2= list(shopping.loc[1])
list3= list(shopping.loc[2])
list4= list(shopping.loc[3])
list5= list(shopping.loc[4])
list6= list(shopping.loc[5])
list7= list(shopping.loc[6])
list8= list(shopping.loc[7])

list9= list(shopping.loc[8])
list10= list(shopping.loc[9])

ref= ['Milk', 'Burgers', 'Buns', 'Ketchup', 'Coals', 'Beer']

def item_in_list(shop, ref):
    there= []
    for item in ref:
        if item in shop: there.append(1)
        else: there.append(0)
    return there

nl1 = item_in_list(list1, ref)
nl2 = item_in_list(list2, ref)
nl3 = item_in_list(list3, ref)
nl4 = item_in_list(list4, ref)
nl5 = item_in_list(list5, ref)
nl6 = item_in_list(list6, ref)
nl7 = item_in_list(list7, ref)
nl8 = item_in_list(list8, ref)
nl9 = item_in_list(list9, ref)
nl10 = item_in_list(list10, ref)

shop_bin= pd.DataFrame(np.array([nl1, nl2, nl3, nl4, nl5, nl6, nl7, nl8, nl9, nl10 ]),
                   columns=['Milk', 'Burgers', 'Buns', 'Ketchup', 'Coals', 'Beer'])

And then combining these lists into a new df to produce the df below

End Result

There must be a better way to do this to get to same result?

Body:
We can use:

#assert len(ref) == shopping.shape[1]
shop_bin = shopping.eq(ref, axis=1).astype(int).set_axis(ref, axis=1)


问:
I am trying to use the TextInputLayout for my register screen however it does not show any hints that I have in the Edit text
The button that is also included here does not show up along with a check box for terms and conditions and all other UI elements. Does it have to do anything with the Text Input Layout or something else?

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.RegisterActivity">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar_register_activity"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <com.example.pcwares.utils.pcwarestextviewbold
    android:id="@+id/tv_title"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:paddingStart="@dimen/toolbar_title_paddingStart"
    android:paddingEnd="0dp"
        android:text="@string/create_account"
    android:textColor="@color/black"
    android:textSize="@dimen/toolbar_title_text_size" />

</androidx.appcompat.widget.Toolbar>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/toolbar_register_activity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_first_name"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/hint_first_name"
            android:textColorHint="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="parent">

            <com.example.pcwares.utils.pcwaresedittext
                android:id="@+id/et_first_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:padding="@dimen/et_padding"
                android:textColor="@color/black"
                android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_last_name"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="25dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/hint_last_name"
            android:textColorHint="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_first_name">

        <com.example.pcwares.utils.pcwaresedittext
            android:id="@+id/et_last_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:padding="@dimen/et_padding"
            android:textColor="@color/black"
            android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_email"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="25dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/et_hint_email_id"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_last_name">

            <com.example.pcwares.utils.pcwaresedittext
                android:id="@+id/et_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:padding="@dimen/et_padding"
                android:textColor="@color/black"
                android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_password"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="25dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/et_hint_password"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_email">

            <com.example.pcwares.utils.pcwaresedittext
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:padding="@dimen/et_padding"
                android:textColor="@color/black"
                android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_confirm_password"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="25dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/et_hint_confirm_password"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_password">

            <com.example.pcwares.utils.pcwaresedittext
                android:id="@+id/et_confirm_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:padding="@dimen/et_padding"
                android:textColor="@color/black"
                android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <LinearLayout
            android:id="@+id/ll_terms_and_cond"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_confirm_password">

            <androidx.appcompat.widget.AppCompatCheckBox
                android:id="@+id/cb_terms_and_cond"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                tools:checked="false" />

            <com.example.pcwares.utils.pcwarestextview
                android:id="@+id/tv_terms_and_cond"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/txt_terms_condition_marginStart"
                android:text="@string/terms_and_cond"
                android:textColor="@color/black"
                android:textSize="@dimen/txt_terms_and_condition_textSize" />
        </LinearLayout>

        <com.example.pcwares.utils.pcwaresbutton
            android:id="@+id/btn_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginStart="16dp"
            android:layout_marginTop="30dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/btn_bkg"
            android:foreground="?attr/selectableItemBackground"
            android:gravity="center"
            android:paddingTop="@dimen/btn_padding"
            android:paddingBottom="@dimen/btn_padding"
            android:text="@string/btn_lbl_register"
            android:textColor="@color/black"
            android:textSize="@dimen/btn_textSize"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/ll_terms_and_cond" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btn_register">

            <com.example.pcwares.utils.pcwarestextview
                android:id="@+id/tv_already_have_acc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="@dimen/clickable_text_view_padding"
                android:text="@string/have_account"
                android:textColor="@color/black"
                android:textSize="@dimen/lbl_text_view_textSize"/>

            <com.example.pcwares.utils.pcwarestextviewbold
                android:id="@+id/tv_login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:foreground="?attr/selectableItemBackground"
                android:padding="@dimen/clickable_text_view_padding"
                android:text="@string/login"
                android:textColor="@color/black"
                android:textSize="@dimen/lbl_text_view_textSize"/>

        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>
</code>```

</androidx.constraintlayout.widget.ConstraintLayout>

Additional image that shows the design https://imgur.com/a/Ed6oo3m

答:
TextInputLayout will work good if you use TextInputEditText as inside element, we dont see your custom view pcwaresedittext implementation.

Please, check: https://developer.android.com/reference/com/google/android/material/textfield/TextInputEditText

Also my recomendation is to not use custom views if possible, if you need to adjust look of element, use Styles

Body:
The button that is also included here does not show up along with a check box for terms and conditions and all other UI elements. Does it have to do anything with the Text Input Layout or something else?

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.RegisterActivity">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar_register_activity"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <com.example.pcwares.utils.pcwarestextviewbold
    android:id="@+id/tv_title"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:paddingStart="@dimen/toolbar_title_paddingStart"
    android:paddingEnd="0dp"
        android:text="@string/create_account"
    android:textColor="@color/black"
    android:textSize="@dimen/toolbar_title_text_size" />

</androidx.appcompat.widget.Toolbar>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/toolbar_register_activity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_first_name"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/hint_first_name"
            android:textColorHint="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="parent">

            <com.example.pcwares.utils.pcwaresedittext
                android:id="@+id/et_first_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:padding="@dimen/et_padding"
                android:textColor="@color/black"
                android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_last_name"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="25dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/hint_last_name"
            android:textColorHint="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_first_name">

        <com.example.pcwares.utils.pcwaresedittext
            android:id="@+id/et_last_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:padding="@dimen/et_padding"
            android:textColor="@color/black"
            android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_email"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="25dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/et_hint_email_id"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_last_name">

            <com.example.pcwares.utils.pcwaresedittext
                android:id="@+id/et_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:padding="@dimen/et_padding"
                android:textColor="@color/black"
                android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_password"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="25dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/et_hint_password"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_email">

            <com.example.pcwares.utils.pcwaresedittext
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:padding="@dimen/et_padding"
                android:textColor="@color/black"
                android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_confirm_password"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="25dp"
            android:layout_marginEnd="16dp"
            android:hint="@string/et_hint_confirm_password"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_password">

            <com.example.pcwares.utils.pcwaresedittext
                android:id="@+id/et_confirm_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:padding="@dimen/et_padding"
                android:textColor="@color/black"
                android:textSize="@dimen/et_textSize"/>

        </com.google.android.material.textfield.TextInputLayout>

        <LinearLayout
            android:id="@+id/ll_terms_and_cond"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/til_confirm_password">

            <androidx.appcompat.widget.AppCompatCheckBox
                android:id="@+id/cb_terms_and_cond"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                tools:checked="false" />

            <com.example.pcwares.utils.pcwarestextview
                android:id="@+id/tv_terms_and_cond"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/txt_terms_condition_marginStart"
                android:text="@string/terms_and_cond"
                android:textColor="@color/black"
                android:textSize="@dimen/txt_terms_and_condition_textSize" />
        </LinearLayout>

        <com.example.pcwares.utils.pcwaresbutton
            android:id="@+id/btn_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginStart="16dp"
            android:layout_marginTop="30dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/btn_bkg"
            android:foreground="?attr/selectableItemBackground"
            android:gravity="center"
            android:paddingTop="@dimen/btn_padding"
            android:paddingBottom="@dimen/btn_padding"
            android:text="@string/btn_lbl_register"
            android:textColor="@color/black"
            android:textSize="@dimen/btn_textSize"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/ll_terms_and_cond" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btn_register">

            <com.example.pcwares.utils.pcwarestextview
                android:id="@+id/tv_already_have_acc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="@dimen/clickable_text_view_padding"
                android:text="@string/have_account"
                android:textColor="@color/black"
                android:textSize="@dimen/lbl_text_view_textSize"/>

            <com.example.pcwares.utils.pcwarestextviewbold
                android:id="@+id/tv_login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:foreground="?attr/selectableItemBackground"
                android:padding="@dimen/clickable_text_view_padding"
                android:text="@string/login"
                android:textColor="@color/black"
                android:textSize="@dimen/lbl_text_view_textSize"/>

        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

Additional image that shows the design https://imgur.com/a/Ed6oo3m