问:
Uncaught ReferenceError: require is not defined in Electron Js when using require() in html page
I'm new to Electron Js and I am trying to make a custom titlebar as a project. I made the titlebar in a html page called nav.html and imported it in index.html (the main page)

nav.html :

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Document</title>

    <style>
      * {
        margin: 0;
        padding: 0;
      }
      button {
        margin: 0;
        padding: 0;
        border: none;
        outline: none;
        background-color: transparent;
        height: 35px;
      }
      .header {
        background-color: black;
        color: white;
        overflow: hidden;
      }
#title {
        width: 80%;
        -webkit-app-region: drag;
        -webkit-user-select: none;
        user-select: none;
      }
      svg.restore {
        fill: rgb(255, 255, 255) !important;
        width: 15px;
        height: 15px;
        padding: 10px 14px;
      }
      svg.restore:hover {
        fill: rgb(255, 255, 255) !important;
        background-color: #5e5e5e !important;
      }

      button.minimize {
        padding: 3.5px 16px;
        color: white;
      }
      button.minimize:hover {
        background-color: #5e5e5e !important;
      }

      .maximize {
        cursor: default;
        fill: white;
        padding: 10px 14px;
        height: 15px;
        width: 15px;
        display: none;
      }
      .maximize:hover {
        background-color: #5e5e5e !important;
        color: white;
      }

      button.close {
        padding: 3.3px 14px;
        color: white;
      }
      button.close:hover {
        background-color: red !important;
      }
    </style>
  </head>
  <body>
<div
      class="header"
      style="display: flex; align-items: center; justify-content: space-between;"
    >
      <div id="title"></div>
      <div style="display: flex; align-items: center; justify-content: center;">
        <button
          style="font-size: 25px; cursor: default"
          class="minimize"
          id="minimize"
        >
          -
        </button>
        <button>
          <svg
            width="25px"
            height="25px"
            viewBox="0 0 512 512"
            xmlns="http://www.w3.org/2000/svg"
            style="cursor: default"
            class="restore"
            id="restore"
          >
            <path
              d="M352,153H40.247a24.028,24.028,0,0,0-24,24V458a24.028,24.028,0,0,0,24,24H352a24.028,24.028,0,0,0,24-24V177A24.028,24.028,0,0,0,352,153Zm-8,32v45.22H48.247V185ZM48.247,450V262.22H344V450Z"
              class="ci-primary"
            />
            <path
              d="M472,32H152a24.028,24.028,0,0,0-24,24v65h32V64H464V339.143H408v32h64a24.028,24.028,0,0,0,24-24V56A24.028,24.028,0,0,0,472,32Z"
              class="ci-primary"
            />
          </svg>

          <svg
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            class="maximize"
            id="maximize"
          >
            <path
              d="M896 85.333333H128a42.666667 42.666667 0 0 0-42.666667 42.666667v768a42.666667 42.666667 0 0 0 42.666667 42.666667h768a42.666667 42.666667 0 0 0 42.666667-42.666667V128a42.666667 42.666667 0 0 0-42.666667-42.666667z m-42.666667 768H170.666667V426.666667h682.666666z m0-512H170.666667V170.666667h682.666666z"
            />
          </svg>
        </button>
        <button
          style="font-size: 25px; cursor: default"
          class="close"
          id="close"
        >
          ×
        </button>
      </div>
    </div>
    <script>
      document.getElementById("title").innerHTML = document.title;
      // ipc connection between main.js and nav.html buttons to mainpulate the function of the window asynchronously
      const { ipcRenderer } = require("electron");
      const ipc = ipcRenderer;

      const restore = document.querySelector("#restore");
      const maximize = document.querySelector("#maximize");
      const minimize = document.querySelector("#minimize");
      const closeBtn = document.querySelector("#close");

      // close the window
      closeBtn.onclick = function(){
        ipc.send("closeApp");
        console.log('mama earth');
      }
      restore.onclick = function () {
        maximize.style.display = "block";
        restore.style.display = "none";
      };
      maximize.onclick = function () {
        restore.style.display = "block";
        maximize.style.display = "none";
      };
    </script>
  </body>
</html>

</code>```

I have added inline styles as well as style tag and script tag in the same html document

Problem comes when I am not able to use require('electron') in a script tag. I am trying to make the top window buttons and using the ipcRenderer to process them to main.js.

Main.js :

```<code>const { app, BrowserWindow , ipcMain} = require('electron')
const path = require('path')
const ipc = ipcMain

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 700,
    center: true,
    minHeight: 700,
    minWidth: 1200,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation : true,
      devTools: true,
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  win.loadFile('index.html')

  //close window function
  ipc.on('closeApp', () => {
    console.log('app is closed')
    win.close()
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
</code>```

I have just added the index.html and preload.js for no confussion :

index.html :

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Home</title>

    <link rel="stylesheet" href="style.css" />

    <script src="main.js"></script>

</head>
<body>
    <iframe id="nav-placeholder" src="nav.html" width="100%" style="border: none;height: 35px !important;" loading="eager"></iframe>
    <a href="nav.html">Go to nav page</a>
</body>
</html>
</code>```

Preload.js :

```<code>window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }

    for (const type of ['chrome', 'node', 'electron']) {
      replaceText(`${type}-version`, process.versions[type])
    }
  })
</code>```

I tried using require JS but I had no idea how to do it. If anyone has an answer to it or can guide me through the error it would be highly appreciatable!

Thank you in advance!

答:
You probably read some deprecated articles or forum posts, because calling electron from an HTML file is now an "old way" to use the ipcRenderer.

For security reasons, electron should not be directly accessible from your HTML page. You should only require ipcRenderer from your preload script, where you can put it in a method. Then, you can access your method by sharing it with the contextBridge.

I know this might be confusing at the beginning. You can find a well documented example here about What/How to use the ContextBridge
https://github.com/reZach/secure-electron-template/blob/master/docs/newtoelectron.md

Body:
I'm new to Electron Js and I am trying to make a custom titlebar as a project. I made the titlebar in a html page called nav.html and imported it in index.html (the main page)

nav.html :

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Document</title>

        <button
          style="font-size: 25px; cursor: default"
          class="minimize"
          id="minimize"
        >
          -
        </button>
        <button>
          <svg
            width="25px"
            height="25px"
            viewBox="0 0 512 512"
            xmlns="http://www.w3.org/2000/svg"
            style="cursor: default"
            class="restore"
            id="restore"
          >
            <path
              d="M352,153H40.247a24.028,24.028,0,0,0-24,24V458a24.028,24.028,0,0,0,24,24H352a24.028,24.028,0,0,0,24-24V177A24.028,24.028,0,0,0,352,153Zm-8,32v45.22H48.247V185ZM48.247,450V262.22H344V450Z"
              class="ci-primary"
            />
            <path
              d="M472,32H152a24.028,24.028,0,0,0-24,24v65h32V64H464V339.143H408v32h64a24.028,24.028,0,0,0,24-24V56A24.028,24.028,0,0,0,472,32Z"
              class="ci-primary"
            />
          </svg>

          <svg
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            class="maximize"
            id="maximize"
          >
            <path
              d="M896 85.333333H128a42.666667 42.666667 0 0 0-42.666667 42.666667v768a42.666667 42.666667 0 0 0 42.666667 42.666667h768a42.666667 42.666667 0 0 0 42.666667-42.666667V128a42.666667 42.666667 0 0 0-42.666667-42.666667z m-42.666667 768H170.666667V426.666667h682.666666z m0-512H170.666667V170.666667h682.666666z"
            />
          </svg>
        </button>
        <button
          style="font-size: 25px; cursor: default"
          class="close"
          id="close"
        >
          ×
        </button>

I have added inline styles as well as style tag and script tag in the same html document

Problem comes when I am not able to use require('electron') in a script tag. I am trying to make the top window buttons and using the ipcRenderer to process them to main.js.

Main.js :

const { app, BrowserWindow , ipcMain} = require('electron')
const path = require('path')
const ipc = ipcMain

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 700,
    center: true,
    minHeight: 700,
    minWidth: 1200,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation : true,
      devTools: true,
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  win.loadFile('index.html')

  //close window function
  ipc.on('closeApp', () => {
    console.log('app is closed')
    win.close()
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

I have just added the index.html and preload.js for no confussion :

index.html :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />

    <title>Home</title>

    <link rel="stylesheet" href="style.css" />

    Go to nav page

Preload.js :

window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }

    for (const type of ['chrome', 'node', 'electron']) {
      replaceText(`${type}-version`, process.versions[type])
    }
  })

I tried using require JS but I had no idea how to do it. If anyone has an answer to it or can guide me through the error it would be highly appreciatable!

Thank you in advance!


来源: stackexchange

问:
kendo ui - override k-animation-container style for one dropdown only
I use kendo-ui dropdown.
I add some ovveriding-css, and it works well.

```<code>.k-animation-container {
//this is popup that is html is rendered out of the page element
//so it cannot be selected by id / panaya class / panaya element

.k-popup.k-list-container {
    .k-item,
    .k-item.k-state-selected,
    .k-item.k-state-focused {
        background-color: transparent;
        color: $darken-gray-color;
        margin-left: 0;
        margin-top: 0;
    }
  }
}
</code>```

The problem is, that while each dropdown has other input element instance, the list has one instance that is hidden and when you click any combo - is shown near the currently clicked combo.
What say - when you ovveride the list-container style - dows it for all of the combooxes.
Is there any solution for this issue?

答:
One solution I found was to use

```<code>popup: {
   appendTo: $(some parent with ID)
}
</code>```

This way we can manipulate styling of that particular .k-animation-container.
But this doesn't work on every widget, unfortunately.

ContentLicense: CC BY-SA 4.0

Body:
I use kendo-ui dropdown.
I add some ovveriding-css, and it works well.

.k-animation-container {
//this is popup that is html is rendered out of the page element
//so it cannot be selected by id / panaya class / panaya element

.k-popup.k-list-container {
    .k-item,
    .k-item.k-state-selected,
    .k-item.k-state-focused {
        background-color: transparent;
        color: $darken-gray-color;
        margin-left: 0;
        margin-top: 0;
    }
  }
}

The problem is, that while each dropdown has other input element instance, the list has one instance that is hidden and when you click any combo - is shown near the currently clicked combo.
What say - when you ovveride the list-container style - dows it for all of the combooxes.
Is there any solution for this issue?

Body:
One solution I found was to use

popup: {
   appendTo: $(some parent with ID)
}

This way we can manipulate styling of that particular .k-animation-container.
But this doesn't work on every widget, unfortunately.


问:
How to spot public S3 buckets
I'm trying to list all the buckets with some kind of public access in an account.

The question is: is my rationale correct?

I first checked buckets' access block configuration:

```<code>filtered_buckets = list(filter(lambda item: not list_in_list(exceptions, item['Name']), buckets))
public_buckets = []
public_acl_indicator = ['http://acs.amazonaws.com/groups/global/AllUsers','http://acs.amazonaws.com/groups/global/AuthenticatedUsers']
permissions_to_check = ['READ', 'WRITE']

def check_bucket_access_block():
    for bucket in filtered_buckets:
        try:
            response = s3client.get_public_access_block(Bucket=bucket['Name'])
            for key, value in response['PublicAccessBlockConfiguration'].items():
                logger.info('Bucket: {}, {}: {}'.format(bucket['Name'], key, value))
                if not response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and not response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and bucket['Name'] not in public_buckets:
                    public_buckets.append(bucket['Name'])
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchPublicAccessBlockConfiguration':
                logger.info("Bucket: {} has no Public Access Block Configuration".format(bucket['Name']))
            else:
                logger.info("unexpected error: %s" % (e.response))
</code>```

If any bucket is set to False on both BlockPublicAcls and BlockPublicPolicy, then it IS public. No matter how they configured on Policies and ACLs(correct?).

Then, I proceed to check the buckets' policy status:

```<code> def check_bucket_status():
    try:
        for bucket in filtered_buckets:
            response = s3client.get_bucket_policy_status(Bucket=bucket['Name'])['PolicyStatus']['IsPublic']
            logger.info('Bucket Name: {}, Public: {}'.format(bucket['Name'], response))
            if response == True and bucket['Name'] not in public_buckets:
                public_buckets.append(bucket['Name'])
    except botocore.exceptions.ClientError as e:
        logger.info("unexpected error: %s" % (e.response))
</code>```

If a bucket returns true for isPublic, then it IS public. No matter the previous function result.

In the last step, I check the buckets ACLs for AllUser and AuthenticadedUsers permissions:

```<code>def check_bucket_acl():
    for bucket in filtered_buckets:
        try:
            response = s3client.get_bucket_acl(Bucket=bucket['Name'])
            logger.info('Bucket: {}, ACL: {}'.format(bucket['Name'], response['Grants']))
            for grant in response['Grants']:
                for (key, value) in grant.items():
                    if key == 'Permission' and any(permission in value for permission in permissions_to_check):
                        for (grantee_key, grantee_value) in grant['Grantee'].items():
                            if 'URI' in grantee_key and grant['Grantee']['URI'] in public_acl_indicator:
                                if bucket['Name'] not in public_buckets:
                                    public_buckets.append(bucket['Name'])
        except botocore.exceptions.ClientError as e:
            logger.info("unexpected error: %s" % (e.response))
</code>```

When I print the full result, it outputs some buckets. All of them were caught in the first step:

```<code>check_bucket_access_block()
logger.info('\n')
check_bucket_status()
logger.info('\n')
check_bucket_acl()
logger.info('\n')
logger.info('Public Buckets: {}'.format(public_buckets))
</code>```

Another question: Is it necessary to check the Objects' ACLs after going through all these steps? If yes, why?

答:
If any bucket is set to False on both BlockPublicAcls and
BlockPublicPolicy, then it IS public. No matter how they configured on
Policies and ACLs(correct?).

No that's not correct at all. It just means that the bucket is allowed to have a public Policy/ACL, it doesn't mean that the bucket actually has a public Policy/ACL.

Title: How to spot public S3 buckets

Body:
I'm trying to list all the buckets with some kind of public access in an account.

The question is: is my rationale correct?

I first checked buckets' access block configuration:

filtered_buckets = list(filter(lambda item: not list_in_list(exceptions, item['Name']), buckets))
public_buckets = []
public_acl_indicator = ['http://acs.amazonaws.com/groups/global/AllUsers','http://acs.amazonaws.com/groups/global/AuthenticatedUsers']
permissions_to_check = ['READ', 'WRITE']

def check_bucket_access_block():
    for bucket in filtered_buckets:
        try:
            response = s3client.get_public_access_block(Bucket=bucket['Name'])
            for key, value in response['PublicAccessBlockConfiguration'].items():
                logger.info('Bucket: {}, {}: {}'.format(bucket['Name'], key, value))
                if not response['PublicAccessBlockConfiguration']['BlockPublicAcls'] and not response['PublicAccessBlockConfiguration']['BlockPublicPolicy'] and bucket['Name'] not in public_buckets:
                    public_buckets.append(bucket['Name'])
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchPublicAccessBlockConfiguration':
                logger.info("Bucket: {} has no Public Access Block Configuration".format(bucket['Name']))
            else:
                logger.info("unexpected error: %s" % (e.response))

If any bucket is set to False on both BlockPublicAcls and BlockPublicPolicy, then it IS public. No matter how they configured on Policies and ACLs(correct?).

Then, I proceed to check the buckets' policy status:

 def check_bucket_status():
    try:
        for bucket in filtered_buckets:
            response = s3client.get_bucket_policy_status(Bucket=bucket['Name'])['PolicyStatus']['IsPublic']
            logger.info('Bucket Name: {}, Public: {}'.format(bucket['Name'], response))
            if response == True and bucket['Name'] not in public_buckets:
                public_buckets.append(bucket['Name'])
    except botocore.exceptions.ClientError as e:
        logger.info("unexpected error: %s" % (e.response))

If a bucket returns true for isPublic, then it IS public. No matter the previous function result.

In the last step, I check the buckets ACLs for AllUser and AuthenticadedUsers permissions:

def check_bucket_acl():
    for bucket in filtered_buckets:
        try:
            response = s3client.get_bucket_acl(Bucket=bucket['Name'])
            logger.info('Bucket: {}, ACL: {}'.format(bucket['Name'], response['Grants']))
            for grant in response['Grants']:
                for (key, value) in grant.items():
                    if key == 'Permission' and any(permission in value for permission in permissions_to_check):
                        for (grantee_key, grantee_value) in grant['Grantee'].items():
                            if 'URI' in grantee_key and grant['Grantee']['URI'] in public_acl_indicator:
                                if bucket['Name'] not in public_buckets:
                                    public_buckets.append(bucket['Name'])
        except botocore.exceptions.ClientError as e:
            logger.info("unexpected error: %s" % (e.response))

When I print the full result, it outputs some buckets. All of them were caught in the first step:

check_bucket_access_block()
logger.info('\n')
check_bucket_status()
logger.info('\n')
check_bucket_acl()
logger.info('\n')
logger.info('Public Buckets: {}'.format(public_buckets))

Another question: Is it necessary to check the Objects' ACLs after going through all these steps? If yes, why?


问:
SaxonC 11.1 transform_to_file Produces No Output File
Using SaxonC-HE 11.1 in Python3 to transform XML into a new file appears to produce no file. Here's the py code:

```<code>import os
import saxonc

with saxonc.PySaxonProcessor(license=True) as saxonproc:
   xsltproc = saxonproc.new_xslt30_processor()
   saxonproc.set_cwd(os.getcwd())
   out = xsltproc.transform_to_file(source_file="in.xml", stylesheet_file="test.xsl", output_file="out.xml")
   print(out)
   out_contents = saxonproc.parse_xml(xml_file_name="out.xml")
   print(out_contents)
</code>```

The associated XML file contents are:

in.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<in/>
</code>```

test.xsl

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>
<xsl:output method='xml' indent='yes' />

   <xsl:template match='*'>
      <xsl:message>Here!</xsl:message>
      <out/>
   </xsl:template>
</xsl:stylesheet>
</code>```

The transform_to_file method does… <s>nothing. No output file is created (and I've looked through the entire drive for out.xml!).</s> Correction: it does generate the output file in the root drive location (in this case, D:), despite setting the cwd. The print() commands return NONE in the console.

Note: the xsl:message is just used as a check to verify the transformation is happening, and this does produce the message in my output console. But there is no statement back from SaxonC that any transformation is happening (as does occur with the workaround I have below).

My current workaround is to use the transform_to_string method and then just write the results to an XML file, which appears to work without issues. This gives an output statement in the console from SaxonC: "source in transformFiletoString=in.xml stylsheet=test.xsl" along with my message from the XSLT file.

```<code>import os
import saxonc

with saxonc.PySaxonProcessor(license=True) as saxonproc:
   xsltproc = saxonproc.new_xslt30_processor()
   saxonproc.set_cwd(os.getcwd())
   out = xsltproc.transform_to_string(source_file="in.xml", stylesheet_file="test.xsl")
   with open("out.xml", "w") as f:
     f.write(out)
   print(out)
   out_contents = saxonproc.parse_xml(xml_file_name="out.xml")
   print(out_contents)
</code>```

It's not an impediment to my work, but it sure seems like an unnecessary step when SaxonC apparently should have the ability to write directly to a file. There has to be something simple I'm missing but so far, I simply cannot get transform_to_file to produce any file or output at all.

答:
The cwd just needs to be set before  the xslt processor. The following generates the output file as expected:

```<code>import os
import saxonc

with saxonc.PySaxonProcessor(license=True) as saxonproc:
 saxonproc.set_cwd(os.getcwd()) #set the CWD first
 xsltproc = saxonproc.new_xslt30_processor()
 xsltproc.transform_to_file(source_file="in.xml", stylesheet_file="test.xsl", output_file="out.xml")
 out_contents = saxonproc.parse_xml(xml_file_name="out.xml")
 print(out_contents)
</code>```

Body:
Using SaxonC-HE 11.1 in Python3 to transform XML into a new file appears to produce no file. Here's the py code:

import os
import saxonc

with saxonc.PySaxonProcessor(license=True) as saxonproc:
   xsltproc = saxonproc.new_xslt30_processor()
   saxonproc.set_cwd(os.getcwd())
   out = xsltproc.transform_to_file(source_file="in.xml", stylesheet_file="test.xsl", output_file="out.xml")
   print(out)
   out_contents = saxonproc.parse_xml(xml_file_name="out.xml")
   print(out_contents)

The associated XML file contents are:

in.xml:

<?xml version="1.0" encoding="UTF-8"?>
<in/>

test.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>
<xsl:output method='xml' indent='yes' />

   <xsl:template match='*'>
      <xsl:message>Here!</xsl:message>
      <out/>
   </xsl:template>
</xsl:stylesheet>

The transform_to_file method does… <s>nothing. No output file is created (and I've looked through the entire drive for out.xml!).</s> Correction: it does generate the output file in the root drive location (in this case, D:), despite setting the cwd. The print() commands return NONE in the console.

Note: the xsl:message is just used as a check to verify the transformation is happening, and this does produce the message in my output console. But there is no statement back from SaxonC that any transformation is happening (as does occur with the workaround I have below).

My current workaround is to use the transform_to_string method and then just write the results to an XML file, which appears to work without issues. This gives an output statement in the console from SaxonC: "source in transformFiletoString=in.xml stylsheet=test.xsl" along with my message from the XSLT file.

import os
import saxonc

with saxonc.PySaxonProcessor(license=True) as saxonproc:
   xsltproc = saxonproc.new_xslt30_processor()
   saxonproc.set_cwd(os.getcwd())
   out = xsltproc.transform_to_string(source_file="in.xml", stylesheet_file="test.xsl")
   with open("out.xml", "w") as f:
     f.write(out)
   print(out)
   out_contents = saxonproc.parse_xml(xml_file_name="out.xml")
   print(out_contents)

It's not an impediment to my work, but it sure seems like an unnecessary step when SaxonC apparently should have the ability to write directly to a file. There has to be something simple I'm missing but so far, I simply cannot get transform_to_file to produce any file or output at all.

Body:
The cwd just needs to be set before  the xslt processor. The following generates the output file as expected:

import os
import saxonc

with saxonc.PySaxonProcessor(license=True) as saxonproc:
 saxonproc.set_cwd(os.getcwd()) #set the CWD first
 xsltproc = saxonproc.new_xslt30_processor()
 xsltproc.transform_to_file(source_file="in.xml", stylesheet_file="test.xsl", output_file="out.xml")
 out_contents = saxonproc.parse_xml(xml_file_name="out.xml")
 print(out_contents)


问:
script/command to add extra space before stating of selected/each line in a paragraph
I need to update my cpp source files header by adding extra one space before starting of the below lines in header information -

```<code>This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.
</code>```

Present Header format:

```<code>/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/
</code>```

Expected:

```<code>/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

 This file is an example header file.
 There are 100 files are present with this formats.
 Some files are with proper space before starting of each line in this paragraph.
 How to move each line in this paragraph with single space at start using any script.
 All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/
</code>```

Query:
Is there any command or script available to do that changes.
I have total 270 files with few files with proper space added and majority files with no space added.

答:
Using sed

```<code>$ sed '/^[[:space:]]/ ! s/^/ /' input_file
 /*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

 This file is an example header file.
 There are 100 files are present with this formats.
 Some files are with proper space before starting of each line in this paragraph.
 How to move each line in this paragraph with single space at start using any script.
 All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/
</code>```

Body:
I need to update my cpp source files header by adding extra one space before starting of the below lines in header information -

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

Present Header format:

/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/

Expected:

/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

 This file is an example header file.
 There are 100 files are present with this formats.
 Some files are with proper space before starting of each line in this paragraph.
 How to move each line in this paragraph with single space at start using any script.
 All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/

Query:
Is there any command or script available to do that changes.
I have total 270 files with few files with proper space added and majority files with no space added.

Body:
Using sed

$ sed '/^[[:space:]]/ ! s/^/ /' input_file
 /*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

 This file is an example header file.
 There are 100 files are present with this formats.
 Some files are with proper space before starting of each line in this paragraph.
 How to move each line in this paragraph with single space at start using any script.
 All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/


Title: How to reindex pandas dataframes of different lengths?

Body:
I have a list series of pandas dataframes of different lengths. I need to transform them into the dataframes of the same (maximum) length max_len.

0:
2021-01-20 11:20    4
2021-01-20 11:22    5
2021-01-20 11:23    4
2021-01-20 11:40    3

1:
2021-01-20 11:00    1
2021-01-20 11:22    2
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 10:00    1

2:
2021-01-20 11:20    2
2021-01-20 11:22    5
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 9:00     2

Expected result:

In this example the maximum length is 7. Thus, all dataframes should have the same length:

0:
2021-01-20 11:00    NaN
2021-01-20 11:20    4
2021-01-20 11:22    5
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 9:00     NaN
2021-01-21 10:00    NaN

1:
2021-01-20 11:00    1
2021-01-20 11:20    NaN
2021-01-20 11:22    2
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 9:00     NaN
2021-01-21 10:00    1

2:
2021-01-20 11:00    NaN
2021-01-20 11:20    2
2021-01-20 11:22    5
2021-01-20 11:23    4
2021-01-20 11:40    3
2021-01-21 9:00     2
2021-01-21 10:00    NaN

This is my code:

for i in range(len(series)):
    if len(series[i])!= max_len:
        series[i] = series[i].reindex(longest_series.index)

However, the reindex results in an i-th dataframe with all Nan values. Also, I'm not sure how to retrieve max_len.

How can I have Nan values only in new index values in each dataframe?

Update:

selected_series = []

l = pd.DataFrame([{'2021-01-20 11:20': 4, '2021-01-20 11:22': 5, '2021-01-20 11:23': 4, '2021-01-20 11:40': 3}])
selected_series.append(l)
l = pd.DataFrame([{'2021-01-20 11:00': 1, '2021-01-20 11:22': 2, '2021-01-20 11:23': 4, '2021-01-20 11:40': 3, '2021-01-21 10:00': 1}])
selected_series.append(l)
l = pd.DataFrame([{'2021-01-20 11:20': 2, '2021-01-20 11:22': 5, '2021-01-20 11:23': 4, '2021-01-20 11:40': 3, '2021-01-21 9:00': 2}])
selected_series.append(l)

Body:
you can use pandas.concat on the columns, then split again:

df = pd.concat(selected_series).T
lst = list(zip(*df.iteritems()))[1]

output:

(2021-01-20 11:20    4.0
 2021-01-20 11:22    5.0
 2021-01-20 11:23    4.0
 2021-01-20 11:40    3.0
 2021-01-20 11:00    NaN
 2021-01-21 10:00    NaN
 2021-01-21 9:00     NaN
 Name: 0, dtype: float64,
 2021-01-20 11:20    NaN
 2021-01-20 11:22    2.0
 2021-01-20 11:23    4.0
 2021-01-20 11:40    3.0
 2021-01-20 11:00    1.0
 2021-01-21 10:00    1.0
 2021-01-21 9:00     NaN
 Name: 0, dtype: float64,
 2021-01-20 11:20    2.0
 2021-01-20 11:22    5.0
 2021-01-20 11:23    4.0
 2021-01-20 11:40    3.0
 2021-01-20 11:00    NaN
 2021-01-21 10:00    NaN
 2021-01-21 9:00     2.0
 Name: 0, dtype: float64)


问:
Validate columns in a csv file are present in another csv file JAVA
I have two arrays ArrayList<String> csv1 and ArrayList<String> csv2

csv2 has more columns than csv1 but the goal is to check that all columns in csv1 are present in csv2, regardless of the extra files.

I esstenially want the code to only look at the columns in csv1 and check if they are in csv2 and nothing else.

Currently its giving me a 'false' output because there are extra columns in csv2 so its saying that they do not match.

I have a class called ReadCsvFile that reads csv files from a path

```<code>Public static void main(String[] args) {
ReadCsvFile readFile - new ReadCsvFile();
ArrayList<String> csv1 = (ArrayList<String>) readFile.readcsv1(some parameters here);
ArrayList<String> csv2 = (ArrayList<String>) readFile.readcsv2(some parameters here);
Collections.sort(csv1);
Collections.sort(csv2);
System.out.println(csv1.equals(csv2)); ```

```

答:
You want to know if csv2 containsAll of csv1?
Have you looked at the available Methods that Collection or List offers?</p>

Body:
I have two arrays ArrayList<String> csv1 and ArrayList<String> csv2

csv2 has more columns than csv1 but the goal is to check that all columns in csv1 are present in csv2, regardless of the extra files.

I esstenially want the code to only look at the columns in csv1 and check if they are in csv2 and nothing else.

Currently its giving me a 'false' output because there are extra columns in csv2 so its saying that they do not match.

I have a class called ReadCsvFile that reads csv files from a path

Public static void main(String[] args) {
ReadCsvFile readFile - new ReadCsvFile();
ArrayList<String> csv1 = (ArrayList<String>) readFile.readcsv1(some parameters here);
ArrayList<String> csv2 = (ArrayList<String>) readFile.readcsv2(some parameters here);
Collections.sort(csv1);
Collections.sort(csv2);
System.out.println(csv1.equals(csv2)); ```


问:
Node js Azure media service api filestream not uploading
I am trying to create asset in Azure media services using api v3 from node js.

import {AzureMediaServices, Asset} from "@azure/arm-mediaservices";

const assetName = "English-class";
    const fileName = "/home/raju/work/dynamic-links/sample.mp4";
    const fileSize = fs.statSync(fileName).size;
    const fileStream = fs.createReadStream(fileName);

    console.log("Uploading file to asset: " + assetName + ".. file size: " + fileSize);

    let newAsset = {
        storageAccountName: 'virtualclasses',
        // assetId : "97d52295-0fd7-4bb3-a3bf-edf6236366c9",
        description: "My first asset",
        options: {
            assetName,
            assetDescription: "My first asset",
            encodingType: "None",
            fileSize,
            fileName : 'sample.mp4',
            fileStream: fileStream,
            storageAccountType: "Standard_LRS",
            storageEncryptionFormat: "MP4",
        }
    } as Asset

    const asset = await mediaServicesClient.assets.createOrUpdate(resourceGroup, accountName, assetName, newAsset, {
        requestOptions: {
           onUploadProgress: (progress: any) => {
               console.log(progress);
               console.log(`Uploaded bytes: ${progress.loaded}/${progress.total}`);

           }
        },
        onResponse: (response: any) => {
            console.log(`Response received with status code: ${response.status}`);
            return response;
        },
    });```

But file is not showing in the dashboard. After creating streaming locator, it is always showing Your asset is either empty or not compatible for streaming. Please check your asset.

答:
Have you already walked through some of our Sample applications using the node.js and Typescript SDK here?

https://github.com/Azure-Samples/media-services-v3-node-tutorials/

Try the most basic encoding sample first.
https://github.com/Azure-Samples/media-services-v3-node-tutorials/tree/main/VideoEncoding/Encoding_H264

Body:
I am trying to create asset in Azure media services using api v3 from node js.

import {AzureMediaServices, Asset} from "@azure/arm-mediaservices";

const assetName = "English-class";
    const fileName = "/home/raju/work/dynamic-links/sample.mp4";
    const fileSize = fs.statSync(fileName).size;
    const fileStream = fs.createReadStream(fileName);

    console.log("Uploading file to asset: " + assetName + ".. file size: " + fileSize);

    let newAsset = {
        storageAccountName: 'virtualclasses',
        // assetId : "97d52295-0fd7-4bb3-a3bf-edf6236366c9",
        description: "My first asset",
        options: {
            assetName,
            assetDescription: "My first asset",
            encodingType: "None",
            fileSize,
            fileName : 'sample.mp4',
            fileStream: fileStream,
            storageAccountType: "Standard_LRS",
            storageEncryptionFormat: "MP4",
        }
    } as Asset

    const asset = await mediaServicesClient.assets.createOrUpdate(resourceGroup, accountName, assetName, newAsset, {
        requestOptions: {
           onUploadProgress: (progress: any) => {
               console.log(progress);
               console.log(`Uploaded bytes: ${progress.loaded}/${progress.total}`);

           }
        },
        onResponse: (response: any) => {
            console.log(`Response received with status code: ${response.status}`);
            return response;
        },
    });

But file is not showing in the dashboard. After creating streaming locator, it is always showing Your asset is either empty or not compatible for streaming. Please check your asset.


问:
Jquery tabs using ajax problem
This is the button type.

```<code><input type="button" name="add_person_to_notify" value="Submit" id="add_person_to_notify">
</code>```

this is the script code.

```<code>   <script type="text/javascript">
   $(function(){
           $("#dialog_person_to_notify_form").dialog({
                modal: true,
                width: 'auto',
                autoOpen: false
            });
          $("#add").click(function(){
                $("#dialog_person_to_notify_form").dialog("open");
          });

         $("#add_person_to_notify").click(function(){

                var data = $('#form_person_to_notify').serialize();
                $.post('<?php echo base_url_l(); ?>hr/recruitment_tab/recruitment/person_to_notify_process',data,function(){
                    alert("Person to notify has been added!");
                    $("#dialog_person_to_notify_form").dialog("close");
                    $('#applicant-view-form-tabs').tabs('load',0);
                });
         });
  });
  </script>
</code>```

Now i figured out the problem. once the tab is reloaded, the function happens twice. if the tab is reloaded for the third time. the functions happen three times and so on and so fort. can anyone help me what's the problem? I'm using AJAX for tabs.

Here is how i use the tabs.

```<code>    <div class="wrapper-maint">
    <div id="applicant-view-form-tabs" class="main-tab">
        <ul>
            <li><a href="<?= base_url_l() ?>tab1">Budget Management</a></li>
            <li><a href="<?= base_url_l() ?>tab2">Transactions</a></li>
            <li><a href="<?= base_url_l() ?>tab3">Reports</a></li>
            </ul>
        </div>
</div>
<script type="text/javascript">
$(function(){
    $('#tabs-finance').tabs({

    });
});
</script>
</code>```

Is there anything i should do with my tabs?

答:
I don't see the full picture here but sounds like you need to use unbind:</p>

```<code>$("#add_person_to_notify").unbind('click').click(function(){
 // ...
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jquery tabs using ajax problem

Body:
This is the button type.

<input type="button" name="add_person_to_notify" value="Submit" id="add_person_to_notify">

this is the script code.

Now i figured out the problem. once the tab is reloaded, the function happens twice. if the tab is reloaded for the third time. the functions happen three times and so on and so fort. can anyone help me what's the problem? I'm using AJAX for tabs.

Here is how i use the tabs.

<a href="<?= base_url_l() ?>tab1">Budget Management

<a href="<?= base_url_l() ?>tab2">Transactions

<a href="<?= base_url_l() ?>tab3">Reports

Is there anything i should do with my tabs?

Body:
I don't see the full picture here but sounds like you need to use unbind:

$("#add_person_to_notify").unbind('click').click(function(){
 // ...
});


问:
Filtering associated values in Power BI
Suppose you have a huge dataset with pupils and the classes that they attend. I want to create a filter where, when you filter on pupils, only the classes that they attend are shown. However, I also want to keep the other pupils who attend those indirectly filtered classes.

Example

Dataset:

Pupil ID
Class ID

1
1

1
2

2
1

3
1

3
4

4
4

etc.
etc

So when I filter on Pupil ID = 1, the output should be:

Pupil ID
Class ID

1
1

1
2

2
1

3
1

etc.
etc

My thought process so far is that each class is a group, and each group is overlapping. By choosing a Pupil ID, you indirectly choose a set of groups.

Does anyone have an idea as to how to avoid removing the non-selected pupils within the groups which are indirectly chosen by the selected (filtered) pupil?

Note: I have built the data model so that there are DIM_Pupil and DIM_Class tables.

答:
For the sake of simplicity, let's say that the data from your example above all lives in one table (Table). The problem is, if you're filtering based on Table[Pupil ID], then you're literally telling Power BI that the only thing you want to see is rows with the selected Pupil ID(s).

To work around this, you need to create a new table and associate it in such a way that you can filter how you would like. In your case, create a new table (ex. Filter), which looks the exact same as your original Table. Then, in Power BI's model tab, associate Table[Class ID] to Filter[Class ID] in a many-to-many relationship.

Table

Pupil ID
Class ID

1
1

1
2

2
1

3
1

3
4

4
4

etc.
etc

Filter

Pupil ID
Class ID

1
1

1
2

2
1

3
1

3
4

4
4

etc.
etc

Class ID <--> Class ID

Now all you need to do is display your data using the Table table and filter your data using the Filter[Pupil ID] column. This will give you the result that you want.

Note that this solution will need to be adjusted slightly based on your actual table structure, but the concept remains the same.

Title: Filtering associated values in Power BI


问:
How to seperate Array in Haskell
i just learn about haskell
but i've problem about Type Data, ihave type data like below

```<code>[Test {name = "name1", Address = "Address1", Score = 80},Test {name = "name2", Address = "Address2", Score = 60}]
</code>```

my question is how to seperate to =

```<code>Name  Address  Score Pass
-------------------------
name1 Address1 80    Y
name2 Address2 60    N
</code>```

i've try

```<code>printArray :: [Test] -> IO()
printArray [Test x y z]  = do
                                putStr x
                                putStr (" " ++ y)
                                putStr (" " ++ show z)
                                if z >= 70 then putStrLn " Y"
                                else putStrLn " N"
</code>```

but when i executed i got error : Non-exhaustive patterns in function printArray

Thanks in advance

答:
Split it:

printTest :: Test -> IO()
printTest (Test x y z) = do
  putStr x
  putStr (" " ++ y)
  putStr (" " ++ show z)
  if z >= 60
    then putStrLn " Y"
    else putStrLn " N"

printArray :: [Test] -> IO()
printArray [] = pure ()
printArray (t:ts) = do
    printTest t
    printArray ts
```

Title: How to seperate Array in Haskell

Body:
i just learn about haskell
but i've problem about Type Data, ihave type data like below

[Test {name = "name1", Address = "Address1", Score = 80},Test {name = "name2", Address = "Address2", Score = 60}]

my question is how to seperate to =

Name  Address  Score Pass
-------------------------
name1 Address1 80    Y
name2 Address2 60    N

i've try

printArray :: [Test] -> IO()
printArray [Test x y z]  = do
                                putStr x
                                putStr (" " ++ y)
                                putStr (" " ++ show z)
                                if z >= 70 then putStrLn " Y"
                                else putStrLn " N"

but when i executed i got error : Non-exhaustive patterns in function printArray

Thanks in advance


问:
ProductDetail.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'name')
I'm getting the following error -

ProductDetail.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'name')

```<code>import React from 'react';
import {useParams } from 'react-router-dom';
import products from '../products';

const ProductDetail = () => {

    const { id } = useParams();

    const product = products.find((p) => p._id === Number(id));

    return (
        <div>
            {product.name}
        </div>
    );
}

export default ProductDetail;
</code>```

products.js

```<code>const products = [
  {
    '_id': '1',
    'name': 'Samsubg A001',
    'description':
      'testinggggg',
    'brand': 'Samsung',
    'category': 'Mobile',
    'price': 10,
    'Stock': 20,
    'rating': 4.5,
    'Reviews': 12,
  },
</code>```

答: Are you sure that product variable is not undefined? Seems like you are trying to access to name property inside a undefined variable.

Body:
I'm getting the following error -

ProductDetail.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'name')

import React from 'react';
import {useParams } from 'react-router-dom';
import products from '../products';

const ProductDetail = () => {

    const { id } = useParams();

    const product = products.find((p) => p._id === Number(id));

    return (

            {product.name}

    );
}

export default ProductDetail;

products.js

const products = [
  {
    '_id': '1',
    'name': 'Samsubg A001',
    'description':
      'testinggggg',
    'brand': 'Samsung',
    'category': 'Mobile',
    'price': 10,
    'Stock': 20,
    'rating': 4.5,
    'Reviews': 12,
  },


问:
Indexing into a list of lists with variable depth
Let's say list1 is a list of lists of lists..., and ind = [a_1,...,a_N] is a list of indices, such that list1[a_1][a_2]...[a_n] exists

I want to write a way to access list1[a_1][a_2]...[a_n] for variable depth n

A simple way to achieve this is to use a loop:

```<code>list1 = [1, [2, [3, 7]], [4, [5, [10, [15, 16]], 6]]]
ind = [2, 1, 1]

list2 = list1
for i in ind:
    list2 = list2[i]
</code>```
```<code>>>> list2
[10, [15, 16]]
>>> list1[2][1][1]
[10, [15, 16]]
</code>```

and at the end of the day, list2 contains list1[2][1][1]

I am looking for a way to do that without a loop

答:
Use functools.reduce

```<code>from functools import reduce

ind = [2, 5, 2]
values = [1, 2, [30, 31, 32, 33, 34, [350, 351, 352]]]

result = reduce(lambda res, i: res[i], ind, values)
print(result)  # 352
</code>```

Body:
Let's say list1 is a list of lists of lists..., and ind = [a_1,...,a_N] is a list of indices, such that list1[a_1][a_2]...[a_n] exists

I want to write a way to access list1[a_1][a_2]...[a_n] for variable depth n

A simple way to achieve this is to use a loop:

list1 = [1, [2, [3, 7]], [4, [5, [10, [15, 16]], 6]]]
ind = [2, 1, 1]

list2 = list1
for i in ind:
    list2 = list2[i]

>>> list2
[10, [15, 16]]
>>> list1[2][1][1]
[10, [15, 16]]

and at the end of the day, list2 contains list1[2][1][1]

I am looking for a way to do that without a loop

Body:
Use functools.reduce

from functools import reduce

ind = [2, 5, 2]
values = [1, 2, [30, 31, 32, 33, 34, [350, 351, 352]]]

result = reduce(lambda res, i: res[i], ind, values)
print(result)  # 352


问:
Groovy Swing buider fileChooser
I am trying to use groovy swing builder's fileChooser with no luck.
When I copy the following example from groovy website:

```<code>def openExcelDialog  = SwingBuilder.fileChooser(dialogTitle:"Choose an excel file",
                               id:"openExcelDialog", fileSelectionMode :         JFileChooser.FILES_ONLY,
                               //the file filter must show also directories, in order to be able to look into them
                               fileFilter: [getDescription: {-> "*.xls"}, accept:{file-> file ==~ /.*?\.xls/ || file.isDirectory() }] as FileFilter) {
</code>```

}

But I got an error message:

```<code>groovy.lang.MissingMethodException: No signature of method: static groovy.swing.SwingBuilder.fileChooser() is applicable for argument types: (java.util.LinkedHashMap, ConsoleScript19$_run_closure1) values
</code>```

答:
You can't use the fileChooser like that outside a SwingBuilder.  Instead, you need to just use a normal, non-swingBuilder JFileChooser.  Here's a complete working example:

```<code>import javax.swing.filechooser.FileFilter
import javax.swing.JFileChooser

def openExcelDialog = new JFileChooser(
                            dialogTitle: "Choose an excel file",
                            fileSelectionMode: JFileChooser.FILES_ONLY,
                            //the file filter must show also directories, in order to be able to look into them
                            fileFilter: [getDescription: {-> "*.xls"}, accept:{file-> file ==~ /.*?\.xls/ || file.isDirectory() }] as FileFilter)

openExcelDialog.showOpenDialog()
</code>```

Note that the new JFileChooser just ends with the closing parentheses - there's no trailing closure.

Title: Groovy Swing buider fileChooser

Body:
I am trying to use groovy swing builder's fileChooser with no luck.
When I copy the following example from groovy website:

def openExcelDialog  = SwingBuilder.fileChooser(dialogTitle:"Choose an excel file",
                               id:"openExcelDialog", fileSelectionMode :         JFileChooser.FILES_ONLY,
                               //the file filter must show also directories, in order to be able to look into them
                               fileFilter: [getDescription: {-> "*.xls"}, accept:{file-> file ==~ /.*?\.xls/ || file.isDirectory() }] as FileFilter) {

}

But I got an error message:

groovy.lang.MissingMethodException: No signature of method: static groovy.swing.SwingBuilder.fileChooser() is applicable for argument types: (java.util.LinkedHashMap, ConsoleScript19$_run_closure1) values

Body:
You can't use the fileChooser like that outside a SwingBuilder.  Instead, you need to just use a normal, non-swingBuilder JFileChooser.  Here's a complete working example:

import javax.swing.filechooser.FileFilter
import javax.swing.JFileChooser

def openExcelDialog = new JFileChooser(
                            dialogTitle: "Choose an excel file",
                            fileSelectionMode: JFileChooser.FILES_ONLY,
                            //the file filter must show also directories, in order to be able to look into them
                            fileFilter: [getDescription: {-> "*.xls"}, accept:{file-> file ==~ /.*?\.xls/ || file.isDirectory() }] as FileFilter)

openExcelDialog.showOpenDialog()

Note that the new JFileChooser just ends with the closing parentheses - there's no trailing closure.


问:
How can I access the keys and values of the dictionary that is created by calling constructor __init__() from a function made inside a class?
I have created a class where I've passed an argument dictionary in the constructor. Now I need to make a function inside a class where I could access the information of that created dictionary and print users information. My attempt in doing so generates an error 'dict' object is not callabe.

class User:
    def __init__(self,first_name,last_name,**info):
        info['first_name']=first_name
        info['last_name']=last_name
        self.items=info

    def info_user(self):
            print(self.items)

    def users_information(self):
        print('Users Information:\n')
        for key, values in self.items():
            print(key,":",values)

user_0=User('Sarthak','Banset',address='Kathmandu',sex='Male',qualification='undergrad')
user_0.info_user()
user_0.users_information()
```

答:
The problem is that you named your dict items, while you really want the .items() method of it

for key, value in self.items.items():
    ...
```


答:
The issue is that you have made the confusing choice to call the dictionary attribute "items". With that said, here's a fix to your users_information function.</p>
```<code>def users_information(self):
    print('Users Information:\n')
    for key, values in self.items.items():
        print(key,":",values)
</code>```

Title: How can I access the keys and values of the dictionary that is created by calling constructor __init__() from a function made inside a class?

Body:
I have created a class where I've passed an argument dictionary in the constructor. Now I need to make a function inside a class where I could access the information of that created dictionary and print users information. My attempt in doing so generates an error 'dict' object is not callabe.

class User:
    def __init__(self,first_name,last_name,**info):
        info['first_name']=first_name
        info['last_name']=last_name
        self.items=info

    def info_user(self):
            print(self.items)

    def users_information(self):
        print('Users Information:\n')
        for key, values in self.items():
            print(key,":",values)

user_0=User('Sarthak','Banset',address='Kathmandu',sex='Male',qualification='undergrad')
user_0.info_user()
user_0.users_information()

Body:
The issue is that you have made the confusing choice to call the dictionary attribute "items". With that said, here's a fix to your users_information function.

def users_information(self):
    print('Users Information:\n')
    for key, values in self.items.items():
        print(key,":",values)


问:
Visualisation of intermediate activations in keras: 'History' object has no attribute 'Model'
I have this function to generate a neural network:

```<code>def create_network():
  model = Sequential()

  model.add(Input(shape=(150,150,3)))
  model.add(Conv2D(32, kernel_size=3,strides=(1, 1),activation='relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))

  model.add(Flatten())
  model.add(Dense(512, activation='relu'))

  model.add(Dense(1, activation='relu'))

  model.compile(optimizer = 'rmsprop',
                   loss = 'binary_crossentropy',
                   metrics = ['accuracy'])
  return model
</code>```

and then I call the model:

```<code>network = create_network()
</code>```

Then I find the model:

```<code>def fit_model(X_train, y_train, network=create_network()):
  model = network
  history = model.fit(X_train,
                      y_train,
                      epochs=2,
                      validation_data=(X_test, y_test),
                      batch_size=32,
                      verbose=2
                      )
  return history
</code>```

and call this function:

```<code>model = fit_model(X_train,y_train)
</code>```

I want to visualise the intermediate activations in this model (i.e. every channel in every intermediate activation), for a random image.

So I have this code:

```<code>images = []
for img_path in glob.glob('test_image*.JPEG'):
    image1 = mpimg.imread(img_path)
    open_file = image1 / 255
    resize = cv2.resize(open_file,(150,150))
    print(resize.shape)
    images.append(resize)

plt.figure(figsize=(20,10))
columns = 5
for i, image in enumerate(images):
    plt.subplot(len(images) / columns + 1, columns, i + 1)
    plt.imshow(image)

print(network.summary())

layer_outputs = [layer.output for layer in model.layers[:]]
activation_model = model.Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(np.expand_dims(images[0]), axis=0)
</code>```

When I run this I get the error:

```<code>'History' object has no attribute 'layers'
</code>```

So then I thought ok I'm meant to run this on the network architecture with the layers itself, and not the model that's been fit, so I changed the last three lines to:

```<code>layer_outputs = [layer.output for layer in network.layers[:]]
activation_model = network.Model(inputs=network.input, outputs=layer_outputs)
activations = activation_model.predict(np.expand_dims(images[0]), axis=0)
</code>```

And I get:

```<code>AttributeError: 'Sequential' object has no attribute 'Model'
</code>```

Then I thought maybe initially I should be reading in the layers into layer_outputs, but then using the model in the activation_model:

```<code>layer_outputs = [layer.output for layer in network.layers[:]]
activation_model = model.Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(np.expand_dims(images[0]), axis=0)
</code>```

But I get:

```<code>'History' object has no attribute 'Model'
</code>```

Could someone show me where I'm going wrong to visualise my intermediate activations?

答:
The problem is that model.fit actually returns a history object and not your model itself. Check the docs:

A History object. Its History.history attribute is a record of
training loss values and metrics values at successive epochs, as well
as validation loss values and validation metrics values

It does not have any layers etc. Try something like this:

import tensorflow as tf

def create_network():
  model = tf.keras.Sequential()
  model.add(tf.keras.layers.Conv2D(32, kernel_size=3,strides=(1, 1),activation='relu'))
  model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))

  model.add(tf.keras.layers.Flatten())
  model.add(tf.keras.layers.Dense(512, activation='relu'))

  model.add(tf.keras.layers.Dense(1, activation='relu'))

  model.compile(optimizer = 'rmsprop',
                   loss = 'binary_crossentropy',
                   metrics = ['accuracy'])
  return model

def fit_model(network=create_network()):
  model = network
  history = model.fit(tf.random.normal((50, 150, 150, 3)),
                      tf.random.normal((50, 1)),
                      epochs=2,
                      validation_data=(tf.random.normal((50, 150, 150, 3)), tf.random.normal((50, 1))),
                      batch_size=32,
                      verbose=2
                      )
  return history, model

history, model = fit_model()
layer_outputs = [layer.output for layer in model.layers[:]]
activation_model = tf.keras.Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(tf.random.normal((1, 150, 150, 3)))
```

Body:
I have this function to generate a neural network:

def create_network():
  model = Sequential()

  model.add(Input(shape=(150,150,3)))
  model.add(Conv2D(32, kernel_size=3,strides=(1, 1),activation='relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))

  model.add(Flatten())
  model.add(Dense(512, activation='relu'))

  model.add(Dense(1, activation='relu'))

  model.compile(optimizer = 'rmsprop',
                   loss = 'binary_crossentropy',
                   metrics = ['accuracy'])
  return model

and then I call the model:

network = create_network()

Then I find the model:

def fit_model(X_train, y_train, network=create_network()):
  model = network
  history = model.fit(X_train,
                      y_train,
                      epochs=2,
                      validation_data=(X_test, y_test),
                      batch_size=32,
                      verbose=2
                      )
  return history

and call this function:

model = fit_model(X_train,y_train)

I want to visualise the intermediate activations in this model (i.e. every channel in every intermediate activation), for a random image.

So I have this code:

images = []
for img_path in glob.glob('test_image*.JPEG'):
    image1 = mpimg.imread(img_path)
    open_file = image1 / 255
    resize = cv2.resize(open_file,(150,150))
    print(resize.shape)
    images.append(resize)

plt.figure(figsize=(20,10))
columns = 5
for i, image in enumerate(images):
    plt.subplot(len(images) / columns + 1, columns, i + 1)
    plt.imshow(image)

print(network.summary())

layer_outputs = [layer.output for layer in model.layers[:]]
activation_model = model.Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(np.expand_dims(images[0]), axis=0)

When I run this I get the error:

'History' object has no attribute 'layers'

So then I thought ok I'm meant to run this on the network architecture with the layers itself, and not the model that's been fit, so I changed the last three lines to:

layer_outputs = [layer.output for layer in network.layers[:]]
activation_model = network.Model(inputs=network.input, outputs=layer_outputs)
activations = activation_model.predict(np.expand_dims(images[0]), axis=0)

And I get:

AttributeError: 'Sequential' object has no attribute 'Model'

Then I thought maybe initially I should be reading in the layers into layer_outputs, but then using the model in the activation_model:

layer_outputs = [layer.output for layer in network.layers[:]]
activation_model = model.Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(np.expand_dims(images[0]), axis=0)

But I get:

'History' object has no attribute 'Model'

Could someone show me where I'm going wrong to visualise my intermediate activations?


问:
Karate js file: org.graalvm.polyglot.PolyglotException: Cannot read the array length because "src" is null
I'm using this util feature:

```<code>Feature: Set headers
  Scenario:
    * def authToken = call read('classpath:basic-auth.js') api.credentials
</code>```

With the javascript basic-auth.js:

```<code>function auth(credentials){
    var temp = credentials.username + ':' + credentials.password;
    var Base64 = Java.type('java.util.Base64');
    var encoded = Base64.getEncoder().encodeToString(temp.bytes);
    return 'Basic ' + encoded;
}
</code>```

That worked fine until I update the Karate version to 1.2.0.RC4 and Java version to 17. Now I'm getting the following exception while running the tests:

```<code>org.graalvm.polyglot.PolyglotException: Cannot read the array length because "src" is null
 - java.base/java.util.Base64$Encoder.encode(Base64.java:291)
 - java.base/java.util.Base64$Encoder.encodeToString(Base64.java:345)
 - <js>.auth(Unnamed:4)
</code>```

Thanks in advance!

答:
I fix it replacing:

```<code>var encoded = Base64.getEncoder().encodeToString(temp.bytes);
</code>```

with:

```<code>var encoded = Base64.getEncoder().encodeToString(temp.getBytes());
</code>```

Maybe someone can help me explaining why this works now.

Body:
I'm using this util feature:

Feature: Set headers
  Scenario:
    * def authToken = call read('classpath:basic-auth.js') api.credentials

With the javascript basic-auth.js:

function auth(credentials){
    var temp = credentials.username + ':' + credentials.password;
    var Base64 = Java.type('java.util.Base64');
    var encoded = Base64.getEncoder().encodeToString(temp.bytes);
    return 'Basic ' + encoded;
}

That worked fine until I update the Karate version to 1.2.0.RC4 and Java version to 17. Now I'm getting the following exception while running the tests:

org.graalvm.polyglot.PolyglotException: Cannot read the array length because "src" is null
 - java.base/java.util.Base64$Encoder.encode(Base64.java:291)
 - java.base/java.util.Base64$Encoder.encodeToString(Base64.java:345)
 - <js>.auth(Unnamed:4)

Thanks in advance!

Body:
I fix it replacing:

var encoded = Base64.getEncoder().encodeToString(temp.bytes);

with:

var encoded = Base64.getEncoder().encodeToString(temp.getBytes());

Maybe someone can help me explaining why this works now.


问:
Create PDF with (resized) PNG images using Pycairo - rescaling Surface issue
I have som PNG image links that I want to download, "convert to thumbnails" and save to PDF using Python and Cairo.

Now, I have a working code, but I don't know how to control image size on paper. Is there a way to resize a PyCairo Surface to the dimensions I want (which happens to be smaller than the original)? I want the original pixels to be "shrinked" to a higher resolution (on paper).

Also, I tried Image.rescale() function from PIL, but it gives me back a 20x20 pixel output (out of a 200x200 pixel original image, which is not the banner example on the code). What I want is a 200x200 pixel image plotted inside a 20x20 mm square on paper (instead of a 200x200 mm square as I am getting now)

My current code is:

```<code>#!/usr/bin/python

import cairo, urllib, StringIO, Image   # could I do it without Image module?

paper_width = 210
paper_height = 297
margin = 20

point_to_milimeter = 72/25.4

pdfname = "out.pdf"
pdf = cairo.PDFSurface(pdfname , paper_width*point_to_milimeter, paper_height*point_to_milimeter)
cr = cairo.Context(pdf)
cr.scale(point_to_milimeter, point_to_milimeter)

f=urllib.urlopen("http://cairographics.org/cairo-banner.png")
i=StringIO.StringIO(f.read())
im=Image.open(i)

# are these StringIO operations really necessary?

imagebuffer = StringIO.StringIO()
im.save(imagebuffer, format="PNG")
imagebuffer.seek(0)
imagesurface = cairo.ImageSurface.create_from_png(imagebuffer)

### EDIT: best answer from Jeremy, and an alternate answer from mine:
best_answer = True      # put false to use my own alternate answer
if best_answer:
    cr.save()
    cr.scale(0.5, 0.5)
    cr.set_source_surface(imagesurface, margin, margin)
    cr.paint()
    cr.restore()
else:
    cr.set_source_surface(imagesurface, margin, margin)
    pattern = cr.get_source()
    scalematrix = cairo.Matrix()    # this can also be used to shear, rotate, etc.
    scalematrix.scale(2,2)          # matrix numbers seem to be the opposite - the greater the number, the smaller the source
    scalematrix.translate(-margin,-margin)  # this is necessary, don't ask me why - negative values!!
    pattern.set_matrix(scalematrix)
    cr.paint()

pdf.show_page()
</code>```

Note that the beautiful Cairo banner does not even fit the page...
The ideal result would be that I could control the width and height of this image in user space units (milimeters, in this case), to create a nice header image, for example.

Thanks for reading and for any help or comment!!

答:
Try scaling the context when you draw the image.

E.g.

```<code>cr.save()    # push a new context onto the stack
cr.scale(0.5, 0.5)    # scale the context by (x, y)
cr.set_source_surface(imagesurface, margin, margin)
cr.paint()
cr.restore()    # pop the context
</code>```

See: http://cairographics.org/documentation/pycairo/2/reference/context.html for more details.

Body:
I have som PNG image links that I want to download, "convert to thumbnails" and save to PDF using Python and Cairo.

Now, I have a working code, but I don't know how to control image size on paper. Is there a way to resize a PyCairo Surface to the dimensions I want (which happens to be smaller than the original)? I want the original pixels to be "shrinked" to a higher resolution (on paper).

Also, I tried Image.rescale() function from PIL, but it gives me back a 20x20 pixel output (out of a 200x200 pixel original image, which is not the banner example on the code). What I want is a 200x200 pixel image plotted inside a 20x20 mm square on paper (instead of a 200x200 mm square as I am getting now)

My current code is:

#!/usr/bin/python

import cairo, urllib, StringIO, Image   # could I do it without Image module?

paper_width = 210
paper_height = 297
margin = 20

point_to_milimeter = 72/25.4

pdfname = "out.pdf"
pdf = cairo.PDFSurface(pdfname , paper_width*point_to_milimeter, paper_height*point_to_milimeter)
cr = cairo.Context(pdf)
cr.scale(point_to_milimeter, point_to_milimeter)

f=urllib.urlopen("http://cairographics.org/cairo-banner.png")
i=StringIO.StringIO(f.read())
im=Image.open(i)

# are these StringIO operations really necessary?

imagebuffer = StringIO.StringIO()
im.save(imagebuffer, format="PNG")
imagebuffer.seek(0)
imagesurface = cairo.ImageSurface.create_from_png(imagebuffer)

### EDIT: best answer from Jeremy, and an alternate answer from mine:
best_answer = True      # put false to use my own alternate answer
if best_answer:
    cr.save()
    cr.scale(0.5, 0.5)
    cr.set_source_surface(imagesurface, margin, margin)
    cr.paint()
    cr.restore()
else:
    cr.set_source_surface(imagesurface, margin, margin)
    pattern = cr.get_source()
    scalematrix = cairo.Matrix()    # this can also be used to shear, rotate, etc.
    scalematrix.scale(2,2)          # matrix numbers seem to be the opposite - the greater the number, the smaller the source
    scalematrix.translate(-margin,-margin)  # this is necessary, don't ask me why - negative values!!
    pattern.set_matrix(scalematrix)
    cr.paint()

pdf.show_page()

Note that the beautiful Cairo banner does not even fit the page...
The ideal result would be that I could control the width and height of this image in user space units (milimeters, in this case), to create a nice header image, for example.

Thanks for reading and for any help or comment!!

Body:
Try scaling the context when you draw the image.

E.g.

cr.save()    # push a new context onto the stack
cr.scale(0.5, 0.5)    # scale the context by (x, y)
cr.set_source_surface(imagesurface, margin, margin)
cr.paint()
cr.restore()    # pop the context

See: http://cairographics.org/documentation/pycairo/2/reference/context.html for more details.


问:
Use Sveltekit and Tailwind CSS
Sveltekit is finally in public beta. Does anyone know how to use it with Tailwind CSS? There aren't any official docs for this integration.</p>

答:
The OP @Nick states:

There aren't any official docs for this integration.

In fact, there is, at least on TailwindCSS's site:

https://tailwindcss.com/docs/guides/sveltekit

They're not unlike the steps outlined in another answer here (in fact, they may be authored by the same person?)

Start by creating a new SvelteKit project if you don't have one set up already. The most common approach is outlined in the Getting Started with SvelteKit introduction.

```<code>npm init svelte@next my-app
cd my-app
</code>```

Install Tailwind CSS
Install tailwindcss and its peer dependencies via npm, and then run the following commands to generate both tailwind.config.cjs and postcss.config.cjs.

```<code>npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init tailwind.config.cjs -p
mv postcss.config.js postcss.config.cjs
</code>```

Add the paths to all of your template files in your tailwind.config.cjs file.

```<code>module.exports = {
  content: ['./src/**/*.{html,js,svelte,ts}'],
  theme: {
    extend: {}
  },
  plugins: []
};
</code>```

Create a ./src/app.css file and add the @tailwind directives for each of Tailwind’s layers.

```<code><script>
  import "../app.css";
</script>

<slot />
</code>```

Run your build process with npm run dev.

Start using Tailwind’s utility classes to style your content.

```<code><h1 class="text-3xl font-bold underline">
  Hello world!
</h1>
</code>```

Title: Use Sveltekit and Tailwind CSS

Body:
The OP @Nick states:

There aren't any official docs for this integration.

In fact, there is, at least on TailwindCSS's site:

https://tailwindcss.com/docs/guides/sveltekit

They're not unlike the steps outlined in another answer here (in fact, they may be authored by the same person?)

Start by creating a new SvelteKit project if you don't have one set up already. The most common approach is outlined in the Getting Started with SvelteKit introduction.

npm init svelte@next my-app
cd my-app

Install Tailwind CSS
Install tailwindcss and its peer dependencies via npm, and then run the following commands to generate both tailwind.config.cjs and postcss.config.cjs.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init tailwind.config.cjs -p
mv postcss.config.js postcss.config.cjs

Add the paths to all of your template files in your tailwind.config.cjs file.

module.exports = {
  content: ['./src/**/*.{html,js,svelte,ts}'],
  theme: {
    extend: {}
  },
  plugins: []
};

Create a ./src/app.css file and add the @tailwind directives for each of Tailwind’s layers.

<script>
  import "../app.css";
</script>

<slot />

Run your build process with npm run dev.

Start using Tailwind’s utility classes to style your content.

<h1 class="text-3xl font-bold underline">
  Hello world!
</h1>


问:
How to wait for an API response for maximum 15 seconds in react
I have an API which sometimes does not return a response because of some dependencies. I need to wait for maximum 15 seconds for the response, if I don't receive any response within 15 seconds, I want to skip it and make the control goes to next line to execute next set of instructions.
This is how I have the API call:

```<code>const fetchData = async () => {
  const response = await getData() // I want to await max 15 seconds here, if not next line should be executed

  const response2 = await getSecondData()
}
</code>```

How can I implement the same in react ?

答:
You can wrap the getData in a function that has the timeout set, and if it doesn't resolve within than time, than throw error.

```<code>function timeoutPromise(fn, timeout) {
 return new Promise((resolve, reject) => {
    // reject if timeout happens
    setTimeout(() => {
         reject('API_TIMEOUT');
    }, timeout);
    // handle the promise appropriately
    fn().then((data) => resolve(data)).catch((err) => reject(err));
 })
}
</code>```

Inside your code, you can do the following:

```<code>const fetchData = async () => {
  try {
     const response = await timeoutPromise(getData, 15000) // I want to await max 15 seconds here, if not next line should be executed
  } catch(e) {
    // handle error
  }
  const response2 = await getSecondData()
}
</code>```

This will work for Promises in general, but won't do things like cancel API call, meaning, if API times out, the server call won't be cancelled from browser.

Body:
I have an API which sometimes does not return a response because of some dependencies. I need to wait for maximum 15 seconds for the response, if I don't receive any response within 15 seconds, I want to skip it and make the control goes to next line to execute next set of instructions.
This is how I have the API call:

const fetchData = async () => {
  const response = await getData() // I want to await max 15 seconds here, if not next line should be executed

  const response2 = await getSecondData()
}

How can I implement the same in react ?

Body:
You can wrap the getData in a function that has the timeout set, and if it doesn't resolve within than time, than throw error.

function timeoutPromise(fn, timeout) {
 return new Promise((resolve, reject) => {
    // reject if timeout happens
    setTimeout(() => {
         reject('API_TIMEOUT');
    }, timeout);
    // handle the promise appropriately
    fn().then((data) => resolve(data)).catch((err) => reject(err));
 })
}

Inside your code, you can do the following:

const fetchData = async () => {
  try {
     const response = await timeoutPromise(getData, 15000) // I want to await max 15 seconds here, if not next line should be executed
  } catch(e) {
    // handle error
  }
  const response2 = await getSecondData()
}

This will work for Promises in general, but won't do things like cancel API call, meaning, if API times out, the server call won't be cancelled from browser.


问:
wildfly quickstart microprofile-health : NoClassDefFoundError
I use wildfly-25.0.1.Final. I can't test the microprofile-health quickstart :

```<code>Failed to define class org.wildfly.quickstarts.microprofile.health.DatabaseConnectionHealthCheck in Module "deployment.microprofile-health.war" from Service Module Loader: java.lang.NoClassDefFoundError: Failed to link org/wildfly/quickstarts/microprofile/health/DatabaseConnectionHealthCheck (Module "deployment.microprofile-health.war" from Service Module Loader): org/eclipse/microprofile/health/HealthCheck
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1095)
    at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:424)
    at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:555)
    at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:339)
    at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:126)
    at org.jboss.modules.Module.loadModuleClass(Module.java:753)
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:247)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
    at org.jboss.as.weld@25.0.1.Final//org.jboss.as.weld.WeldModuleResourceLoader.classForName(WeldModuleResourceLoader.java:68)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.AnnotatedTypeLoader.loadClass(AnnotatedTypeLoader.java:83)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.AnnotatedTypeLoader.loadAnnotatedType(AnnotatedTypeLoader.java:63)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.FastAnnotatedTypeLoader.loadAnnotatedType(FastAnnotatedTypeLoader.java:108)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:87)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.ConcurrentBeanDeployer$1.doWork(ConcurrentBeanDeployer.java:55)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.ConcurrentBeanDeployer$1.doWork(ConcurrentBeanDeployer.java:52)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:62)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:55)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
    at org.jboss.threads@2.4.0.Final//org.jboss.threads.JBossThread.run(JBossThread.java:513)
</code>```

But the problem disappears if I start wildfly with standalone-microprofile.xml. Unfortunately, the quickstart doesn't say so.

So it looks like the microprofile.health-smallrye has disappeared in wildfly-25.0.1 standalone.xml (it was there in wildfly-20.0.1).

My question is : how to add the microprofile.health-smallrye to an existing standalone.xml ?

答:
It looks like there was a bug filed for this, but it was fixed in WildFly 25. That said I do not see the reference in the default README.

That said it does require the standalone-microprofile.xml. You can also add the subsystem with CLI to standalone.xml and runt it that way as well. The following CLI commands will add the microprofile-health-smallrye to any configuration you start with that does not already include the subsystem.

```<code>/extension=org.wildfly.extension.microprofile.health-smallrye:add
/subsystem=microprofile-health-smallrye:add
</code>```

Body:
I use wildfly-25.0.1.Final. I can't test the microprofile-health quickstart :

Failed to define class org.wildfly.quickstarts.microprofile.health.DatabaseConnectionHealthCheck in Module "deployment.microprofile-health.war" from Service Module Loader: java.lang.NoClassDefFoundError: Failed to link org/wildfly/quickstarts/microprofile/health/DatabaseConnectionHealthCheck (Module "deployment.microprofile-health.war" from Service Module Loader): org/eclipse/microprofile/health/HealthCheck
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1095)
    at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:424)
    at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:555)
    at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:339)
    at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:126)
    at org.jboss.modules.Module.loadModuleClass(Module.java:753)
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:247)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
    at org.jboss.as.weld@25.0.1.Final//org.jboss.as.weld.WeldModuleResourceLoader.classForName(WeldModuleResourceLoader.java:68)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.AnnotatedTypeLoader.loadClass(AnnotatedTypeLoader.java:83)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.AnnotatedTypeLoader.loadAnnotatedType(AnnotatedTypeLoader.java:63)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.FastAnnotatedTypeLoader.loadAnnotatedType(FastAnnotatedTypeLoader.java:108)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:87)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.ConcurrentBeanDeployer$1.doWork(ConcurrentBeanDeployer.java:55)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.bootstrap.ConcurrentBeanDeployer$1.doWork(ConcurrentBeanDeployer.java:52)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:62)
    at org.jboss.weld.core@3.1.8.Final//org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:55)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
    at org.jboss.threads@2.4.0.Final//org.jboss.threads.JBossThread.run(JBossThread.java:513)

But the problem disappears if I start wildfly with standalone-microprofile.xml. Unfortunately, the quickstart doesn't say so.

So it looks like the microprofile.health-smallrye has disappeared in wildfly-25.0.1 standalone.xml (it was there in wildfly-20.0.1).

My question is : how to add the microprofile.health-smallrye to an existing standalone.xml ?

Body:
It looks like there was a bug filed for this, but it was fixed in WildFly 25. That said I do not see the reference in the default README.

That said it does require the standalone-microprofile.xml. You can also add the subsystem with CLI to standalone.xml and runt it that way as well. The following CLI commands will add the microprofile-health-smallrye to any configuration you start with that does not already include the subsystem.

/extension=org.wildfly.extension.microprofile.health-smallrye:add
/subsystem=microprofile-health-smallrye:add


问:
Android: Debug vs. Release (SDK) performance
I've noticed that launching some of the activities in the Android Emulator while running Debug takes about 11 seconds to show, but when I compile it for release, activities take only about 2 seconds to show. I have no breakpoints set. I only have several textviews/editviews/a mapview in these layouts running 2.1 (API Level 7). Is this normal?</p>

答: Yes, debug mode handles exceptions a little differently than release mode.  It allows you to see in more detail of what is going on.  But it also makes your program run slower..</p>


问:
How to stop SQL injection in Django column of a model
So I know that Django naturally handles sql injections for columns in tables but my team want to do more. We have a help_message table in Django and there is a column in that table called Message which is a string. We do not want to save that message directly as a string in that column because of possible sql injection and malicious use. What can we do to stop sql injection and save that message in the table in Django?</p>

答:
send your data to a function like this one:</p>
```<code>if($value!=''){
$value=strip_tags($value);
$first=strlen($value);
$value=addslashes($value);
$value=htmlspecialchars($value,ENT_QUOTES);
$secend=strlen($value);
if($first!=$secend)
$value="";
}
return $value;
}

</code>```

Body:
send your data to a function like this one:

if($value!=''){
$value=strip_tags($value);
$first=strlen($value);
$value=addslashes($value);
$value=htmlspecialchars($value,ENT_QUOTES);
$secend=strlen($value);
if($first!=$secend)
$value="";
}
return $value;
}


问:
django social share button icons
I'm trying to add the functionality to share a workout post to social media, and found that the django-social-share package is the best.

Everything works, but I'm curious how to add an icon over the link, as it currently looks like

```<code>Post to Facebook!
</code>```

which is very bland. I've seen examples of adding CSS, but since the package works like

```<code>{% post_to_facebook object_or_url "Post to Facebook!" %}
</code>```

I'm not sure how you could target that with CSS. Any help is appreciated.

答:
You don't need to override the templates, you don't need to create new templates.

Just write the fontawesome icon code after object_or_url as shown below.

This works perfectly.

```<code> {% post_to_facebook object_or_url '<i class="fab fa-facebook"></i>' %}
</code>```

Title: django social share button icons

Body:
I'm trying to add the functionality to share a workout post to social media, and found that the django-social-share package is the best.

Everything works, but I'm curious how to add an icon over the link, as it currently looks like

Post to Facebook!

which is very bland. I've seen examples of adding CSS, but since the package works like

{% post_to_facebook object_or_url "Post to Facebook!" %}

I'm not sure how you could target that with CSS. Any help is appreciated.

Body:
You don't need to override the templates, you don't need to create new templates.

Just write the fontawesome icon code after object_or_url as shown below.

This works perfectly.

 {% post_to_facebook object_or_url '<i class="fab fa-facebook"></i>' %}


问:
Docker: Advantages of creating NFS-backed volume, vs bind mounting volume mounted on the host?
Let's say I have a Docker container than needs to read and write to an NFS share. There are at least two approaches:

Mounting the NFS share on the host, and then bind-mounting the share on the volume, e.g. mount the share at /my/share and then running the container with -v /my/share:/my/data.

Creating an NFS-backed Docker volume, passing --opt type=nfs in addition to other parameters needed to identify the share, e.g. --opt o=addr=192.168.1.1,rw etc.

Are there any significant advantages using the seconds approach (except ease-of-use) and more specifically, are there any risks or perils connected with the first one?

This question assumes that approach 1 is already used, and that there is a certain cost associated with changing it.

答:
The most obvious advantage would be that:
By directly using the NFS backed volume, you can decouple the container and the host.So you can run the same configuration everywhere
In case of bind mounting, you are coupling both. So you will have to change your configuration when you move to a different server.</p>


问:
Azure policy - "deny" subscription creation if certain tags are not set
I have created the azure policy below but I am still able to create new subscriptions.
The same if conditions are used in an Azure BuiltIn definition that modifies-adds tags to subscriptions.
Any hints?</p>
```<code>{
  "mode": "All",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "type",
          "equals": "Microsoft.Resources/subscriptions"
        },
        {
          "field": "[concat('tags[', parameters('tagName'), ']')]",
          "exists": "false"
        }
      ]
    },
    "then": {
      "effect": "deny"
    }
  },
  "parameters": {
    "tagName": {
      "type": "String",
      "defaultValue": "CostCenter"
    }
  }
}
</code>```

答:
Just got an answer from Microsoft Support. It seems this is the current design that applies only to subscriptions being created from the portal.
If the subscription is deployed programatically, the policy does its job.</p>

Body:
I have created the azure policy below but I am still able to create new subscriptions.
The same if conditions are used in an Azure BuiltIn definition that modifies-adds tags to subscriptions.
Any hints?

{
  "mode": "All",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "type",
          "equals": "Microsoft.Resources/subscriptions"
        },
        {
          "field": "[concat('tags[', parameters('tagName'), ']')]",
          "exists": "false"
        }
      ]
    },
    "then": {
      "effect": "deny"
    }
  },
  "parameters": {
    "tagName": {
      "type": "String",
      "defaultValue": "CostCenter"
    }
  }
}


答:
There aren't any arrays here. [] is for lists.

The reason your code with printArray [Test x y z] = ... doesn't do the trick is that it only matches the case of a list with exactly one element in it. If you want to do this for all elements you can use either

Recursion.

```<code>printTests (Test x y z : tests) = do
              putStr x
              putStr (" " ++ y)
              putStr (" " ++ show z)
              putStrLn $ if z >= 70 then " Y"
                                    else " N"
              printTests tests
printTests [] = return ()
</code>```

A standard looping combinator

```<code>printTests = mapM_ $ \(Test x y z) -> do
               ...
</code>```

...or, perhaps easier to understand

```<code>import Control.Monad (forM_)

printTests tests = forM_ tests $ \(Test x y z) -> do
               ...
</code>```

(Recommended) Separate your concerns: instead of doing nasty IO in a loop setting, start with simple

```<code>showTest :: Test -> String
</code>```

And then use putStrLn (unlines $ map showTest tests) where printing actually is needed.

Title: How to seperate Array in Haskell

Body:
i just learn about haskell
but i've problem about Type Data, ihave type data like below

[Test {name = "name1", Address = "Address1", Score = 80},Test {name = "name2", Address = "Address2", Score = 60}]

my question is how to seperate to =

Name  Address  Score Pass
-------------------------
name1 Address1 80    Y
name2 Address2 60    N

i've try

printArray :: [Test] -> IO()
printArray [Test x y z]  = do
                                putStr x
                                putStr (" " ++ y)
                                putStr (" " ++ show z)
                                if z >= 70 then putStrLn " Y"
                                else putStrLn " N"

but when i executed i got error : Non-exhaustive patterns in function printArray

Thanks in advance

Body:
There aren't any arrays here. [] is for lists.

The reason your code with printArray [Test x y z] = ... doesn't do the trick is that it only matches the case of a list with exactly one element in it. If you want to do this for all elements you can use either

Recursion.

printTests (Test x y z : tests) = do
              putStr x
              putStr (" " ++ y)
              putStr (" " ++ show z)
              putStrLn $ if z >= 70 then " Y"
                                    else " N"
              printTests tests
printTests [] = return ()

A standard looping combinator

printTests = mapM_ $ \(Test x y z) -> do
               ...

...or, perhaps easier to understand

import Control.Monad (forM_)

printTests tests = forM_ tests $ \(Test x y z) -> do
               ...

(Recommended) Separate your concerns: instead of doing nasty IO in a loop setting, start with simple

showTest :: Test -> String

And then use putStrLn (unlines $ map showTest tests) where printing actually is needed.


答: You can short-circuit by checking if the product is undefined or you can use optional chaining like this product?.name

Body:
I'm getting the following error -

ProductDetail.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'name')

import React from 'react';
import {useParams } from 'react-router-dom';
import products from '../products';

const ProductDetail = () => {

    const { id } = useParams();

    const product = products.find((p) => p._id === Number(id));

    return (

            {product.name}

    );
}

export default ProductDetail;

products.js

const products = [
  {
    '_id': '1',
    'name': 'Samsubg A001',
    'description':
      'testinggggg',
    'brand': 'Samsung',
    'category': 'Mobile',
    'price': 10,
    'Stock': 20,
    'rating': 4.5,
    'Reviews': 12,
  },