问:
Facing Jest encountered an unexpected token while using Require with JEST
I have problem like:

Jest encountered an unexpected token

I did not find a correct solution for my boilerplate. I have checked documentation of JEST or some code here but things which I do does not  works. Could you help me at this issue ? I added knowledges below.

My package.json:

```<code>{
  "jest": {
    "testMatch": [
      "<rootDir>/src/**/*.test.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jsdom"
  },
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@babel/core": "^7.17.2",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.10.4",
    "@babel/preset-typescript": "^7.10.4",
    "@svgr/webpack": "^5.5.0",
    "@testing-library/react": "^12.1.2",
    "babel-loader": "^8.2.3",
    "cross-env": "^7.0.2",
    "html-webpack-plugin": "^4.4.1",
    "mini-css-extract-plugin": "^0.11.1",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "typescript": "^4.0.2",
  },
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "babel-jest": "^27.5.1",
    "dotenv": "^8.2.0",
    "dotenv-webpack": "^6.0.2",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.5.1",
    "jest-config": "^27.5.1",
    "react-dotenv": "^0.1.3",
    "ts-jest": "^27.1.3"
  }
}
</code>```

My jest.config.js:

```<code>module.exports = {
  preset: 'ts-jest',
  setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"],
  testEnvironment: "jsdom",
  verbose: true,
  moduleNameMapper: {
    "\\.(css|less|scss|sss|styl)$": "<rootDir>/node_modules/identity-obj-proxy"
  }
};
</code>```

.babelrc :

```<code>{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ]
}
</code>```

Error Image :

答: Don't use require mixed with import</p>

Body:
I have problem like:

Jest encountered an unexpected token

I did not find a correct solution for my boilerplate. I have checked documentation of JEST or some code here but things which I do does not  works. Could you help me at this issue ? I added knowledges below.

My package.json:

{
  "jest": {
    "testMatch": [
      "<rootDir>/src/**/*.test.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jsdom"
  },
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@babel/core": "^7.17.2",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.10.4",
    "@babel/preset-typescript": "^7.10.4",
    "@svgr/webpack": "^5.5.0",
    "@testing-library/react": "^12.1.2",
    "babel-loader": "^8.2.3",
    "cross-env": "^7.0.2",
    "html-webpack-plugin": "^4.4.1",
    "mini-css-extract-plugin": "^0.11.1",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "typescript": "^4.0.2",
  },
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "babel-jest": "^27.5.1",
    "dotenv": "^8.2.0",
    "dotenv-webpack": "^6.0.2",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.5.1",
    "jest-config": "^27.5.1",
    "react-dotenv": "^0.1.3",
    "ts-jest": "^27.1.3"
  }
}

My jest.config.js:

module.exports = {
  preset: 'ts-jest',
  setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"],
  testEnvironment: "jsdom",
  verbose: true,
  moduleNameMapper: {
    "\\.(css|less|scss|sss|styl)$": "<rootDir>/node_modules/identity-obj-proxy"
  }
};

.babelrc :

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ]
}

Error Image :

Body: Don't use require mixed with import


来源: stackexchange

问:
Azure Function (Python) & Azure SQL DB - Error services aren't available right now -
I'm getting an odd error, when trying to create a connection to a azure sql database, through my azure function (Python & consumption). It all works locally, but no once deployed.

The error:

```<code><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=utf-8' http-equiv='content-type'/><style type='text/css'>body {font-family:Arial; margin-left:40px; }img  { border:0 none; }#content { margin-left: auto; margin-right: auto }#message h2 { font-size: 20px; font-weight: normal; color: #000000; margin: 34px 0px 0px 0px }#message p  { font-size: 13px; color: #000000; margin: 7px 0px 0px0px}#errorref { font-size: 11px; color: #737373; margin-top: 41px }</style><title>Service unavailable</title></head><body><div id='content'><div id='message'><h2>Our services aren't available right now</h2><p>We're working to restore all services as soon as possible. Please check back soon.</p></div><div id='errorref'><span>[Some Long Code]=</span></div></div></body></html>
</code>```

The Code:

```<code>import logging
import pyodbc
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    error = ''

    try:
        BB_connection = 'Driver={ODBC Driver 17 for SQL Server};Server=[server]\[instance];Database=[database];Trusted_Connection=yes;'

        cnxn = pyodbc.connect(BB_connection)
    except Exception as e:
        error = str(e)

    return func.HttpResponse(f"Error: {error}")
</code>```

in requirements.txt I have added pyodbc==4.0.31 I've tried looking around, but have not been able to find, a question where someone else, gets the same output.

Is there some link between my azure sql data base and the azure function, that has to be established? I'm just wondering why, it works locally, but not once deployed.

答:
My problem was the need of Azure Function IP permission in Azure SQL Database. After adding a range of IPs, I was able to access the database using the pyodbc library through the Azure Function itself.

First, I figured out the list of possible IPs for my Azure Function:

Then I sorted the IPs and added the range in the AzureSQL firewall settings:

Furthermore, even though the AzureSQL Database connection string indicates the Driver 'ODBC Driver 13 for SQL Server, I was only able to run the script when I set it to 'ODBC Driver 17 for SQL Server.

ContentLicense: CC BY-SA 4.0

Body:
I'm getting an odd error, when trying to create a connection to a azure sql database, through my azure function (Python & consumption). It all works locally, but no once deployed.

The error:

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><meta content='text/html; charset=utf-8' http-equiv='content-type'/><title>Service unavailable</title>

Our services aren't available right now

We're working to restore all services as soon as possible. Please check back soon.

[Some Long Code]=

The Code:

import logging
import pyodbc
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    error = ''

    try:
        BB_connection = 'Driver={ODBC Driver 17 for SQL Server};Server=[server]\[instance];Database=[database];Trusted_Connection=yes;'

        cnxn = pyodbc.connect(BB_connection)
    except Exception as e:
        error = str(e)

    return func.HttpResponse(f"Error: {error}")

in requirements.txt I have added pyodbc==4.0.31 I've tried looking around, but have not been able to find, a question where someone else, gets the same output.

Is there some link between my azure sql data base and the azure function, that has to be established? I'm just wondering why, it works locally, but not once deployed.


问:
PyQt How to remove a layout from a layout
```<code>datainputHbox = QHBoxLayout()
layout = QVBoxLayout(self)
layout.addLayout(datainputHbox)

pagedatainputdeletboxbutton1.clicked.connect(lambda:self.boxdelete(datainputHbox))

def boxdelete(self, box):
</code>```

This is the PyQt proragm
How write boxdelete funtion in order to remove datainputHbox form layout. I try a lot of. However I just can remove all the widgets but cannot remove layout.

答:
A single function that implements TheTrowser's answer, arguably cleaner:

def clear_item(self, item):
    if hasattr(item, "layout"):
        if callable(item.layout):
            layout = item.layout()
    else:
        layout = None

    if hasattr(item, "widget"):
        if callable(item.widget):
            widget = item.widget()
    else:
        widget = None

    if widget:
        widget.setParent(None)
    elif layout:
        for i in reversed(range(layout.count())):
            self.clear_item(layout.itemAt(i))
```

ContentLicense: CC BY-SA 3.0

Body:
datainputHbox = QHBoxLayout()
layout = QVBoxLayout(self)
layout.addLayout(datainputHbox)

pagedatainputdeletboxbutton1.clicked.connect(lambda:self.boxdelete(datainputHbox))

def boxdelete(self, box):

This is the PyQt proragm
How write boxdelete funtion in order to remove datainputHbox form layout. I try a lot of. However I just can remove all the widgets but cannot remove layout.


问:
Ungroup list items using linq c#
I have a class which stores the menus data in below format.

public class MenuCondiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long[] CondimentIds { get; set; }
}
```
<p>e.g.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>GroupId</th>
<th>Name</th>
<th>CondimentIds</th>
</tr>
</thead>
<tbody>
<tr>
<td>21</td>
<td>Veg Burger</td>
<td>100032,100033,100045,100056</td>
</tr>
<tr>
<td>22</td>
<td>Chiken Burger</td>
<td>100067,100040,100034</td>
</tr>
</tbody>
</table>
</div>
<p>Now, I want the output data as below in the class by using linq.</p>
<pre class="lang-cs prettyprint-override"><code>public class Condiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long CondimentIds { get; set; }
}
</code>```

GroupId
Name
CondimentIds

21
Veg Burger
100032

21
Veg Burger
100033

21
Veg Burger
100045

21
Veg Burger
100056

21
Chiken Burger
100067

22
Chiken Burger
100040

22
Chiken Burger
100034

Can someone assist here?

答:
You can try using classic foreach language construct. Below should give you idea.</p>
```<code>var menuCondimentList = new System.Collections.Generic.List<MenuCondiments>
{
    new MenuCondiments {GroupId = 21, Name = "Veg Burger", CondimentIds = new long[] { 100032, 100033, 100045, 100056 } },
    new MenuCondiments {GroupId = 22, Name = "Chicken Burger", CondimentIds = new long[] { 100067, 100040, 100034 } }
};

var condimentList = new System.Collections.Generic.List<Condiments>();
// Using foreach
foreach ( var menuCondiment in menuCondimentList )
{
    foreach(var c in menuCondiment.CondimentIds )
    {
        condimentList.Add(new Condiments
        {
            GroupId = menuCondiment.GroupId,
            Name = menuCondiment.Name,
            CondimentId = c
        });
    }
}
</code>```

Title: Ungroup list items using linq c#

Body:
I have a class which stores the menus data in below format.

public class MenuCondiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long[] CondimentIds { get; set; }
}

e.g.

GroupId
Name
CondimentIds

21
Veg Burger
100032,100033,100045,100056

22
Chiken Burger
100067,100040,100034

Now, I want the output data as below in the class by using linq.

public class Condiments
{
   public int GroupId { get; set; }
   public string Name { get; set; }
   public long CondimentIds { get; set; }
}

GroupId
Name
CondimentIds

21
Veg Burger
100032

21
Veg Burger
100033

21
Veg Burger
100045

21
Veg Burger
100056

21
Chiken Burger
100067

22
Chiken Burger
100040

22
Chiken Burger
100034

Can someone assist here?

Body:
You can try using classic foreach language construct. Below should give you idea.

var menuCondimentList = new System.Collections.Generic.List<MenuCondiments>
{
    new MenuCondiments {GroupId = 21, Name = "Veg Burger", CondimentIds = new long[] { 100032, 100033, 100045, 100056 } },
    new MenuCondiments {GroupId = 22, Name = "Chicken Burger", CondimentIds = new long[] { 100067, 100040, 100034 } }
};

var condimentList = new System.Collections.Generic.List<Condiments>();
// Using foreach
foreach ( var menuCondiment in menuCondimentList )
{
    foreach(var c in menuCondiment.CondimentIds )
    {
        condimentList.Add(new Condiments
        {
            GroupId = menuCondiment.GroupId,
            Name = menuCondiment.Name,
            CondimentId = c
        });
    }
}


问:
Creating a stored procedure or view in SQL that will run in Big Query that fills payment history based on first payment and last payment
I have a file that have this structure

```<code>Account_ID  first_payment   Last_payment   Status
----------------------------------------------------
     1       10/15/2021          NA        Active
     2       09/22/2021       11/22/2021   Canceled
     .            .              .           .
</code>```

I am trying to create a payment record file based on this information, so if a customer is active it will create 1 payment monthly till the next valid current date, and if he is canceled then it will create 1 monthly payment until the cancel date.

So the final result for this file will be

```<code>Account_id  payment
----------------------
1           10/15/2021
1           11/15/2021
1           12/15/2021
1           01/15/2022
2           09/15/2021
2           10/15/2021
2           11/15/2021
</code>```

Thanks for the help

答:
Consider below approach

```<code>select Account_ID, payment
from your_table,
unnest(generate_date_array(first_payment, ifnull(last_payment, current_date), interval 1 month)) payment
</code>```

if applied to sample data in your question

```<code>with your_table as (
  select 1 Account_ID, date '2021-10-15' first_payment, cast(null as date) last_payment, 'Active' Status union all
  select 2, '2021-09-22', '2021-11-22', 'Canceled'
)
</code>```

output is

Body:
I have a file that have this structure

Account_ID  first_payment   Last_payment   Status
----------------------------------------------------
     1       10/15/2021          NA        Active
     2       09/22/2021       11/22/2021   Canceled
     .            .              .           .

I am trying to create a payment record file based on this information, so if a customer is active it will create 1 payment monthly till the next valid current date, and if he is canceled then it will create 1 monthly payment until the cancel date.

So the final result for this file will be

Account_id  payment
----------------------
1           10/15/2021
1           11/15/2021
1           12/15/2021
1           01/15/2022
2           09/15/2021
2           10/15/2021
2           11/15/2021

Thanks for the help

Body:
Consider below approach

select Account_ID, payment
from your_table,
unnest(generate_date_array(first_payment, ifnull(last_payment, current_date), interval 1 month)) payment

if applied to sample data in your question

with your_table as (
  select 1 Account_ID, date '2021-10-15' first_payment, cast(null as date) last_payment, 'Active' Status union all
  select 2, '2021-09-22', '2021-11-22', 'Canceled'
)

output is


问:
Why does my tablet display the button differently than it does on my computer?
Why does my tablet display the button differently than it does on my computer?

Code:

<!DOCTYPE HTML>

ENTER CODE

        <form action="topage.php" method="post">
            <input name="code" type="number" oninput="this.value = this.value.slice(0, 8);">

            <input type="submit" value="SUBMIT">
        </form>

```

Website in my tablet:

Website in my computer:

Ma tahan et tahvelarvutis näeks see samasugune välja kui arvutis.

Both screenshots are made in Chrome, my computer is linux and the tablet is an iPad.

Thank you very much to all the respondents!

答:
Different user-agents have different default styles for html elements. Many websites and frameworks start with specially crafted CSS to normalize or reset styles consistently across different browsers and operating systems, and then layer on their own styles afterward.

Try using one of these systems to start from a consistent point across user-agents. Alternatively, you'll need to test on various user-agents and determine which styles need to be overwritten. For instance, it looks like the tablet has a gradient on the button, which you'd need to override using the background property instead of the background-color property.

Body:
Why does my tablet display the button differently than it does on my computer?

Code:

<!DOCTYPE HTML>

ENTER CODE

        <form action="topage.php" method="post">
            <input name="code" type="number" oninput="this.value = this.value.slice(0, 8);">

            <input type="submit" value="SUBMIT">
        </form>

Website in my tablet:

Website in my computer:

Ma tahan et tahvelarvutis näeks see samasugune välja kui arvutis.

Both screenshots are made in Chrome, my computer is linux and the tablet is an iPad.

Thank you very much to all the respondents!


问:
Unity: Why GetRootGameObjects() in Unity SceneManager always return empty array if scene was Additivly preloaded?
```<code>public void FindSceneHandler(int sceneToLoad)
{
    var scene = SceneManager.GetSceneAt(SceneManager.sceneCount - 1);
    var sceneOtherApproach = SceneManager.GetSceneByBuildIndex(sceneToLoad);

    var sceneObjs = scene.GetRootGameObjects();
    print(sceneObjs.Length); // 0

    sceneObjs = sceneOtherApproach.GetRootGameObjects();
    print(sceneObjs.Length); // 0
}
</code>```

This code works fine when I load scene through script and wait until it loads before calling this method. But when I load same scene additive through Unity Editor it always results in empty array.

Actually, problem is bit bigger than that. My main scene depends on data from another one, so I'm trying to loop through new scene's objects to get needed references. Maybe there's another way of getting cross scene data?

答: Just fixed the problem. It seems that "Awake()" is called before scenes are fully loaded. I switched it to "Start()" and now everything works perfectly.</p>

Body:
public void FindSceneHandler(int sceneToLoad)
{
    var scene = SceneManager.GetSceneAt(SceneManager.sceneCount - 1);
    var sceneOtherApproach = SceneManager.GetSceneByBuildIndex(sceneToLoad);

    var sceneObjs = scene.GetRootGameObjects();
    print(sceneObjs.Length); // 0

    sceneObjs = sceneOtherApproach.GetRootGameObjects();
    print(sceneObjs.Length); // 0
}

This code works fine when I load scene through script and wait until it loads before calling this method. But when I load same scene additive through Unity Editor it always results in empty array.

Actually, problem is bit bigger than that. My main scene depends on data from another one, so I'm trying to loop through new scene's objects to get needed references. Maybe there's another way of getting cross scene data?


问:
sending mail to multiple email address in codeigniter php not working
i am trying to send mails to emails selected using checkbox in codeigniter website using phpmailer,

```<code><input class="acb" type="checkbox"  name="email[]" value="<?= $val->email?>"  />
</code>```

PHP

```<code>$this->load->library('phpmailer_lib');
$mail = $this->phpmailer_lib->load();
$mail->isSMTP();
$mail->Host     = '';
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->SMTPSecure = 'ssl';
$mail->Port     = 465;
$mail->setFrom('admin@', 'Test');
$mail->addReplyTo('admin@', 'Test');
$mail->addAddress(implode(', ', $this->input->post('email')));
$mail->Subject = 'Important';
$mail->isHTML(true);
$mailContent = $this->input->post('content');
$mail->Body = $mailContent;
$mail->send();
</code>```

However this does not work; it gives me error.

Can anyone please tell me how to fix it?

Thanks in advance.

答:
This is actually PHPMailer code you're using, and PHPMailer's addAddress does not accept multiple email addresses.

http://phpmailer.github.io/PHPMailer/classes/PHPMailer-PHPMailer-PHPMailer.html#method_addAddress

You will need to loop through the list and add each individually if you want to use that method.

There is no PHP-generated error because passing extra parameters to a method  does not generate any kind of error in PHP; they are passed into the method via the $argv array but do not have unique variable names because you do not have parameter placeholders defined for them.

EDIT

What I just said is still true but looking at it again I see now you're only passing in a single argument, the resulting string from implode so it doesn't apply to this specifically.

Body:
i am trying to send mails to emails selected using checkbox in codeigniter website using phpmailer,

<input class="acb" type="checkbox"  name="email[]" value="<?= $val->email?>"  />

PHP

$this->load->library('phpmailer_lib');
$mail = $this->phpmailer_lib->load();
$mail->isSMTP();
$mail->Host     = '';
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->SMTPSecure = 'ssl';
$mail->Port     = 465;
$mail->setFrom('admin@', 'Test');
$mail->addReplyTo('admin@', 'Test');
$mail->addAddress(implode(', ', $this->input->post('email')));
$mail->Subject = 'Important';
$mail->isHTML(true);
$mailContent = $this->input->post('content');
$mail->Body = $mailContent;
$mail->send();

However this does not work; it gives me error.

Can anyone please tell me how to fix it?

Thanks in advance.


问:
Flex DateChooser events for individual days?
I'm using a DateChooser, and want to show different information in a tooltip as the user rolls over each day. Is there an event that fires as I'm rolling around the calendar that will tell me what day I'm currently over?</p>

答: What about change?

OwnerDisplayName: sprugman

ContentLicense: CC BY-SA 2.5

Body: What about change?

OwnerDisplayName: dirkgently


问:
Remove multiple spaces and new lines inside of String
Suppose we have string like this:

```<code>Hello, my\n       name is Michael.
</code>```

How can I remove that new line and strip those spaces after that into one inside of string to get this?

```<code>Hello, my name is Michael.
</code>```

答:
this regex will replace instance of 1 or more white spaces with 1 white space, p.s \s will replace all white space characters which includes \s\t\r\n\f:

```<code>a_string.gsub!(/\s+/, ' ')
</code>```

Similarly for only carriage return

```<code>str.gsub!(/\n/, " ")
</code>```

First replace all \n with white space, then use the remove multiple white space regex.

Body:
Suppose we have string like this:

Hello, my\n       name is Michael.

How can I remove that new line and strip those spaces after that into one inside of string to get this?

Hello, my name is Michael.

Body:
this regex will replace instance of 1 or more white spaces with 1 white space, p.s \s will replace all white space characters which includes \s\t\r\n\f:

a_string.gsub!(/\s+/, ' ')

Similarly for only carriage return

str.gsub!(/\n/, " ")

First replace all \n with white space, then use the remove multiple white space regex.


问:
bazel connect find_package from cmake
I'm trying to use bazel's cmake from rules_foreign_cc to build a library called fcl. That package has, in it's CMakeLists.txt, a find_package(ccd QUIET) statement. It wants to find the ccd (or libccd) package. I build that package as well, but just using cc_library. How can I get the find_package statement to find the package that I build?

So

```<code>cc_library(
    name = "libccd",
    visibility = ["//visibility:public"],
    include_prefix = "libccd/src",
    hdrs = [stuff],
    srcs = [stuff],
}

cmake(
    name = "fcl",
    cache_entries = {
        ?maybe this?
    },
    env_vars = {
        ?maybe this?
    },
    lib_source = "@fcl//:all",
    deps = [
        ":libccd",
    ],
)
</code>```

答:
I build that package as well, but just using cc_library. How can I get the find_package statement to find the package that I build?

You have shot yourself in the foot, here.

fcl's find_package statement is going to search for a file called ccd-config.cmake, using the search procedure documented here: https://cmake.org/cmake/help/latest/command/find_package.html#config-mode-search-procedure

If you had that file, I would suggest setting the cache variable ccd_ROOT to whichever local prefix into which you have installed ccd. But since you went through Bazel, that file will not exist.

You therefore have three options:

Use CMake to build ccd to get it to generate the correct package configuration files.

Write your own Findccd.cmake find module, setting the cache variable CMAKE_MODULE_PATH in fcl's build to whichever directory in your source tree contains it. This find module will have to locate the Bazel-produced artifacts and replicate upstream ccd's interface, including variable and target naming.

Write a Bazel build for fcl.

Writing find modules is very annoying, especially when the upstream has put in the effort to create CMake package configuration files. There is documentation for doing so here, though: https://cmake.org/cmake/help/latest/manual/cmake-developer.7.html#a-sample-find-module

Title: bazel connect find_package from cmake

Body:
I'm trying to use bazel's cmake from rules_foreign_cc to build a library called fcl. That package has, in it's CMakeLists.txt, a find_package(ccd QUIET) statement. It wants to find the ccd (or libccd) package. I build that package as well, but just using cc_library. How can I get the find_package statement to find the package that I build?

So

cc_library(
    name = "libccd",
    visibility = ["//visibility:public"],
    include_prefix = "libccd/src",
    hdrs = [stuff],
    srcs = [stuff],
}

cmake(
    name = "fcl",
    cache_entries = {
        ?maybe this?
    },
    env_vars = {
        ?maybe this?
    },
    lib_source = "@fcl//:all",
    deps = [
        ":libccd",
    ],
)


问:
How to make a table responsive, created in javascript
I have a js, which generates a table for me, I show it in the html, but I can't make it responsive; how could i fix it

The code is the following, I have modified with responsive table, but it still does not work for me

```<code>var tabla   = document.createElement("table");
tabla.className="table";

var thead = document.createElement("thead");

let row_1 = document.createElement('tr');
let heading_1 = document.createElement('th');
heading_1.scope="col";
heading_1.innerHTML = "Mes";
let heading_2 = document.createElement('th');
heading_2.innerHTML = "Cuota";
heading_2.scope="col";
let heading_3 = document.createElement('th');
heading_3.innerHTML = "Interes";
heading_3.scope="col";
let heading_4 = document.createElement('th');
heading_4.innerHTML = "Amorti.";
heading_4.scope="col";
let heading_5 = document.createElement('th');
heading_5.innerHTML = "Capital";
heading_5.scope="col";
let heading_6 = document.createElement('th');
heading_6.innerHTML = "Seguro Desgrav.";
heading_6.scope="col";
let heading_7 = document.createElement('th');
heading_7.innerHTML = "Seguro Inmobil.";
heading_7.scope="col";

let heading_8 = document.createElement('th');
heading_8.innerHTML = "Gastos Adm.";
heading_8.scope="col";

let heading_9 = document.createElement('th');
heading_9.innerHTML = "Cuota Final";
heading_9.scope="col";

row_1.appendChild(heading_1);
row_1.appendChild(heading_2);
row_1.appendChild(heading_3);
row_1.appendChild(heading_4);
row_1.appendChild(heading_5);
row_1.appendChild(heading_6);
row_1.appendChild(heading_7);
row_1.appendChild(heading_8);
row_1.appendChild(heading_9);
thead.appendChild(row_1);
</code>```

答: This might help if you are not using any of responsive CSS frameworks like Bootstrap or my favourites (for the simplicity it offers) W3.CSS</p>

Body:
I have a js, which generates a table for me, I show it in the html, but I can't make it responsive; how could i fix it

The code is the following, I have modified with responsive table, but it still does not work for me

var tabla   = document.createElement("table");
tabla.className="table";

var thead = document.createElement("thead");

let row_1 = document.createElement('tr');
let heading_1 = document.createElement('th');
heading_1.scope="col";
heading_1.innerHTML = "Mes";
let heading_2 = document.createElement('th');
heading_2.innerHTML = "Cuota";
heading_2.scope="col";
let heading_3 = document.createElement('th');
heading_3.innerHTML = "Interes";
heading_3.scope="col";
let heading_4 = document.createElement('th');
heading_4.innerHTML = "Amorti.";
heading_4.scope="col";
let heading_5 = document.createElement('th');
heading_5.innerHTML = "Capital";
heading_5.scope="col";
let heading_6 = document.createElement('th');
heading_6.innerHTML = "Seguro Desgrav.";
heading_6.scope="col";
let heading_7 = document.createElement('th');
heading_7.innerHTML = "Seguro Inmobil.";
heading_7.scope="col";

let heading_8 = document.createElement('th');
heading_8.innerHTML = "Gastos Adm.";
heading_8.scope="col";

let heading_9 = document.createElement('th');
heading_9.innerHTML = "Cuota Final";
heading_9.scope="col";

row_1.appendChild(heading_1);
row_1.appendChild(heading_2);
row_1.appendChild(heading_3);
row_1.appendChild(heading_4);
row_1.appendChild(heading_5);
row_1.appendChild(heading_6);
row_1.appendChild(heading_7);
row_1.appendChild(heading_8);
row_1.appendChild(heading_9);
thead.appendChild(row_1);


问:
how to expand MudBlazor Expansion Panel according to screen size
This is an effort to expand a mudBlazor expansion panel according to the screen size.

```<code>@using MudBlazor.Services
@implements IAsyncDisposable

<MudCard Class="pa-5">

            <MudExpansionPanel Text="Panel One" MaxHeight="150" IsInitiallyExpanded="@(_breakpoint==Breakpoint.Md ? true:false)">
                Panel One Content
            </MudExpansionPanel>

</MudCard>

@code
{
    [Inject] IBreakpointService BreakpointListener { get; set; }

    private Breakpoint _breakpoint = new();

    private Guid _subscriptionId;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var subscriptionResult = await BreakpointListener.Subscribe((breakpoint) =>
            {
                _breakpoint= breakpoint ;
                InvokeAsync(StateHasChanged);
            }, new ResizeOptions
            {
                ReportRate = 250,
                NotifyOnBreakpointOnly = true,
            });

            _subscriptionId = subscriptionResult.SubscriptionId;

            StateHasChanged();
        }

        await base.OnAfterRenderAsync(firstRender);
    }

    public async ValueTask DisposeAsync() => await BreakpointListener.Unsubscribe(_subscriptionId);
}
</code>```

I have tried to expand the panel when the screen size reaches Md and Up, otherwise, it should be collapsed.
but it is not working.is this process is correct to do this or wrong or if you have another way to do this please help me.

答:
It is because you are using IsInitiallyExpanded. This only sets the initial state from the beginning. If you change it to IsExpanded it will work.
See MusExpansionPanelAPI

Working example/demo

The working code will be:

@using MudBlazor.Services
@implements IAsyncDisposable

@_breakpoint
<MudCard Class="pa-5">

            <MudExpansionPanel Text="Panel One" MaxHeight="150" IsExpanded="@(_breakpoint==Breakpoint.Md ? true:false)">
                Panel One Content
            </MudExpansionPanel>

</MudCard>

@code
{
    [Inject] IBreakpointService BreakpointListener { get; set; }

    private Breakpoint _breakpoint = new();

    private Guid _subscriptionId;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var subscriptionResult = await BreakpointListener.Subscribe((breakpoint) =>
            {
                _breakpoint= breakpoint ;
                InvokeAsync(StateHasChanged);
            }, new ResizeOptions
            {
                ReportRate = 250,
                NotifyOnBreakpointOnly = true,
            });

            _subscriptionId = subscriptionResult.SubscriptionId;

            StateHasChanged();
        }

        await base.OnAfterRenderAsync(firstRender);
    }

    public async ValueTask DisposeAsync() => await BreakpointListener.Unsubscribe(_subscriptionId);
}
```

Body:
This is an effort to expand a mudBlazor expansion panel according to the screen size.

@using MudBlazor.Services
@implements IAsyncDisposable

<MudCard Class="pa-5">

            <MudExpansionPanel Text="Panel One" MaxHeight="150" IsInitiallyExpanded="@(_breakpoint==Breakpoint.Md ? true:false)">
                Panel One Content
            </MudExpansionPanel>

</MudCard>

@code
{
    [Inject] IBreakpointService BreakpointListener { get; set; }

    private Breakpoint _breakpoint = new();

    private Guid _subscriptionId;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var subscriptionResult = await BreakpointListener.Subscribe((breakpoint) =>
            {
                _breakpoint= breakpoint ;
                InvokeAsync(StateHasChanged);
            }, new ResizeOptions
            {
                ReportRate = 250,
                NotifyOnBreakpointOnly = true,
            });

            _subscriptionId = subscriptionResult.SubscriptionId;

            StateHasChanged();
        }

        await base.OnAfterRenderAsync(firstRender);
    }

    public async ValueTask DisposeAsync() => await BreakpointListener.Unsubscribe(_subscriptionId);
}

I have tried to expand the panel when the screen size reaches Md and Up, otherwise, it should be collapsed.
but it is not working.is this process is correct to do this or wrong or if you have another way to do this please help me.


问:
Solana Candy machine TypeError: Cannot read properties of undefined (reading '_bn')
I'm following this article as a practice.

```<code>ts-node packages/cli/src/candy-machine-cli.ts verify --env devnet --keypair "C:\Windows\System32\~\.config\solana\devnet.json"
</code>```

While trying to verify candy machine, I ran into

TypeError: Cannot read properties of undefined (reading '_bn')
at isPublicKeyData (C:\Users\my-userName\Source\Repos\metaplex\js\node_modules@solana\web3.js\src\publickey.ts:29:35)
at new PublicKey (C:\Users\my-userName\Source\Repos\metaplex\js\node_modules@solana\web3.js\src\publickey.ts:45:9)
at C:\Users\my-userName\Source\Repos\metaplex\js\packages\cli\src\candy-machine-cli.ts:326:27
at step (C:\Users\my-userName\Source\Repos\metaplex\js\packages\cli\src\candy-machine-cli.ts:64:23)
at Object.next (C:\Users\my-userName\Source\Repos\metaplex\js\packages\cli\src\candy-machine-cli.ts:45:53)
at fulfilled (C:\Users\my-userName\Source\Repos\metaplex\js\packages\cli\src\candy-machine-cli.ts:36:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

By a quick search on the internet, some people say I need to first create the candy machine. So I ran

```<code>ts-node packages/cli/src/candy-machine-cli.ts create_candy_machine --env devnet --keypair "C:\Windows\System32\~\.config\solana\devnet.json"
</code>```

But it gave me the same error.

Appreciate any advice about how I may solve this.

答:
For anyone who sees this from now on (at least until any other update makes this obsolete), you can also get this error simply because you're trying to create a Candy Machine v1, which I was told on the Metaplex discord won't work anymore.

Make sure you follow the steps for using v2 (as of the date I write this), as covered in the official docs here: https://docs.metaplex.com/candy-machine-v2/configuration. You'll simply use a different command for the v2 package.

Look over the docs to check to confirm you're ready, but as reassurance, if your assets are set up and ready to go, do start here on Step 2 configuration (you can create the config file anywhere as long as you paste the correct path to it once it's required), then go to Step 4.

Body:
I'm following this article as a practice.

ts-node packages/cli/src/candy-machine-cli.ts verify --env devnet --keypair "C:\Windows\System32\~\.config\solana\devnet.json"

While trying to verify candy machine, I ran into

TypeError: Cannot read properties of undefined (reading '_bn')
at isPublicKeyData (C:\Users\my-userName\Source\Repos\metaplex\js\node_modules@solana\web3.js\src\publickey.ts:29:35)
at new PublicKey (C:\Users\my-userName\Source\Repos\metaplex\js\node_modules@solana\web3.js\src\publickey.ts:45:9)
at C:\Users\my-userName\Source\Repos\metaplex\js\packages\cli\src\candy-machine-cli.ts:326:27
at step (C:\Users\my-userName\Source\Repos\metaplex\js\packages\cli\src\candy-machine-cli.ts:64:23)
at Object.next (C:\Users\my-userName\Source\Repos\metaplex\js\packages\cli\src\candy-machine-cli.ts:45:53)
at fulfilled (C:\Users\my-userName\Source\Repos\metaplex\js\packages\cli\src\candy-machine-cli.ts:36:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

By a quick search on the internet, some people say I need to first create the candy machine. So I ran

ts-node packages/cli/src/candy-machine-cli.ts create_candy_machine --env devnet --keypair "C:\Windows\System32\~\.config\solana\devnet.json"

But it gave me the same error.

Appreciate any advice about how I may solve this.


问:
text processing question: remove rows where one column does not contain a particular value
I have a tab delimited file that looks like this:

```<code>input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYSGGYEQY 1.00    33843   KTAYSHLSTSK polymerase  Hepatitis B virus (hepatitis B virus (HBV))
ASSYSGGYEQY ASSYSGGYEQY 1.00    131430  KLSYGIATV   orf1ab polyprotein [Severe acute respiratory syndrome coronavirus 2]    SARS-CoV2
ASSYSGGYEQY ASSFSGGYEQY 0.97    82603   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYAGGYEQY 0.98    133155  FVCNLLLLFVTVYSHLLLV ORF3a protein [Severe acute respiratory syndrome coronavirus 2] SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
</code>```

I want to keep 'input_sequence' that only match with 'organism' = SARS-CoV2 and nothing else. So in this example I would keep only line 2 and line 7 and discard lines 3,4,5,6 because here this 'input_sequence' has also a hit with Hepatitis B virus.

In total I have over 20.000 rows in my file.

results required:

```<code>input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
</code>```

Is there a way to quickly do this using awk or bash (without writing a long script)? Any tips are welcome.

I thought to use awk to count the occurences of each value in column 1 and occurences of SARS-COV2 in column 7, and then only keep those that match... but I don't know how to do this. I only got this far (counting the number of occurrences in column one):

```<code>awk '{for(i=1;i<=NF;i++)if($i ~ /^/)x++;print x;x=0}' file
</code>```

Thanks!

答:
You may consider this awk that joins same file on 1st column:

awk -F'\t' 'NR==FNR {$NF != "SARS-CoV2" && bad[$1]; next}
FNR == 1 || !($1 in bad)' file{,} | column -s $'\t' -t

input_sequence  match_sequence  score  receptor_group  epitope      antigen                                                                          organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00   25735           EPLPQGQLTAY  Trans-activator protein BZLF1 [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00   92508           FTISVTTEIL   surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]           SARS-CoV2
```
<p>PS: <code>column -s $'\t' -t</code> has been used for tabular display only. You can remove it.</p>
<hr />
<p>If you want to remove dues based on 1st column then use:</p>
<pre class="lang-sh prettyprint-override"><code>awk -F'\t' 'NR==FNR {$NF != "SARS-CoV2" && bad[$1]; next}
FNR == 1 || (!($1 in bad) && !seen[$1]++)' file{,}
</code>```

Body:
I have a tab delimited file that looks like this:

input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYSGGYEQY 1.00    33843   KTAYSHLSTSK polymerase  Hepatitis B virus (hepatitis B virus (HBV))
ASSYSGGYEQY ASSYSGGYEQY 1.00    131430  KLSYGIATV   orf1ab polyprotein [Severe acute respiratory syndrome coronavirus 2]    SARS-CoV2
ASSYSGGYEQY ASSFSGGYEQY 0.97    82603   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYAGGYEQY 0.98    133155  FVCNLLLLFVTVYSHLLLV ORF3a protein [Severe acute respiratory syndrome coronavirus 2] SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2

I want to keep 'input_sequence' that only match with 'organism' = SARS-CoV2 and nothing else. So in this example I would keep only line 2 and line 7 and discard lines 3,4,5,6 because here this 'input_sequence' has also a hit with Hepatitis B virus.

In total I have over 20.000 rows in my file.

results required:

input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2

Is there a way to quickly do this using awk or bash (without writing a long script)? Any tips are welcome.

I thought to use awk to count the occurences of each value in column 1 and occurences of SARS-COV2 in column 7, and then only keep those that match... but I don't know how to do this. I only got this far (counting the number of occurrences in column one):

awk '{for(i=1;i<=NF;i++)if($i ~ /^/)x++;print x;x=0}' file

Thanks!

Body:
You may consider this awk that joins same file on 1st column:

awk -F'\t' 'NR==FNR {$NF != "SARS-CoV2" && bad[$1]; next}
FNR == 1 || !($1 in bad)' file{,} | column -s $'\t' -t

input_sequence  match_sequence  score  receptor_group  epitope      antigen                                                                          organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00   25735           EPLPQGQLTAY  Trans-activator protein BZLF1 [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00   92508           FTISVTTEIL   surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]           SARS-CoV2

PS: column -s $'\t' -t has been used for tabular display only. You can remove it.

If you want to remove dues based on 1st column then use:

awk -F'\t' 'NR==FNR {$NF != "SARS-CoV2" && bad[$1]; next}
FNR == 1 || (!($1 in bad) && !seen[$1]++)' file{,}


问:
openssl s_server mutual TLS
I can use the openssl s_server command to accept TLS sessions from clients, and to require mutual TLS - i.e. request client certificate - using a command such as: -

```<code>openssl s_server -accept 4433 -cert myCert.crt -key -myKey.pem -Verify 2 -CAfile myCA.crt
</code>```

When I connect from a client, I can see from tracing that s_client sends a certificate request, correctly stipulating the certificate contained within myCA.crt. However it seems that s_server will accept any client certificate, regardless of whether it was signed by myCA.crt or not - i.e. it doesn't care which client cert is sent.

Does anyone know if this is expected behaviour, or am I doing something wrong?

答: openssl s_server and s_client by default verify the peers certificate and show the verification status but don't stop on errors. If this is necessary use the -verify_return_error option.

Title: openssl s_server mutual TLS

Body:
I can use the openssl s_server command to accept TLS sessions from clients, and to require mutual TLS - i.e. request client certificate - using a command such as: -

openssl s_server -accept 4433 -cert myCert.crt -key -myKey.pem -Verify 2 -CAfile myCA.crt

When I connect from a client, I can see from tracing that s_client sends a certificate request, correctly stipulating the certificate contained within myCA.crt. However it seems that s_server will accept any client certificate, regardless of whether it was signed by myCA.crt or not - i.e. it doesn't care which client cert is sent.

Does anyone know if this is expected behaviour, or am I doing something wrong?


问:
Can an iframe check if itself is in viewport or not?
I'm creating an iframe with a small HTML5 video. the video shouldn't start playing unless the iframe is in the viewport.

I noticed that this isn't as easy as I would like since the iframe is like a sandboxed environment. Is it even possible for an iframe to know if it is in the viewport?

答:
You can use IntersectionObserver to monitor if the iframe enters viewport.
The code is pretty simple and clean if you go this way.

Here is a quick example of showing a youtube video on and off based on if the iframe is inside viewport.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .container {
          display: flex;
          flex-direction: column;
          gap: 1rem;
          align-items: flex-start;
        }

        .box {
          background-color:lightblue;
          color: white;
          font-size: 4rem;
          text-align: center;
          margin: auto;
          height: 200px;
          width: 300px;
          border: 1px solid black;
          border-radius: 0.25rem;
          padding: 0.5rem;
        }
    </style>

</head>
<body>
    <div class="container">
        <div class="box">1</div>
        <div class="box">2</div>
        <div class="box">3</div>
        <div class="box">4</div>
        <div class="box">5</div>

        <div class="box" id="divFrame">
            <iframe></iframe>
        </div>

        <div class="box">6</div>
        <div class="box">7</div>
        <div class="box">8</div>
        <div class="box">9</div>
        <div class="box">10</div>
    </div>

    <script>
        const iframeOserver = new IntersectionObserver((entries) => {
            const iframe = entries[0].target.firstElementChild;
            iframe.src = entries[0].isIntersecting ? "https://www.youtube.com/embed/tgbNymZ7vqY?autoplay=1&mute=1": "";
            console.log("video " + (entries[0].isIntersecting ? "started" : "stopped"));
        }, { threshold: 0.5});

        iframeOserver.observe(document.getElementById("divFrame"));

    </script>

</body>
</html>
</code>```

I set the threshold of intersection to 50% (threshold: 0.5) in the above example. You can change it as you needed.

Please refer to the following link for details about IntersectionObserver:
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

Body:
You can use IntersectionObserver to monitor if the iframe enters viewport.
The code is pretty simple and clean if you go this way.

Here is a quick example of showing a youtube video on and off based on if the iframe is inside viewport.

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .container {
          display: flex;
          flex-direction: column;
          gap: 1rem;
          align-items: flex-start;
        }

        .box {
          background-color:lightblue;
          color: white;
          font-size: 4rem;
          text-align: center;
          margin: auto;
          height: 200px;
          width: 300px;
          border: 1px solid black;
          border-radius: 0.25rem;
          padding: 0.5rem;
        }
    </style>

</head>
<body>
    <div class="container">
        <div class="box">1</div>
        <div class="box">2</div>
        <div class="box">3</div>
        <div class="box">4</div>
        <div class="box">5</div>

        <div class="box" id="divFrame">
            <iframe></iframe>
        </div>

        <div class="box">6</div>
        <div class="box">7</div>
        <div class="box">8</div>
        <div class="box">9</div>
        <div class="box">10</div>
    </div>

    <script>
        const iframeOserver = new IntersectionObserver((entries) => {
            const iframe = entries[0].target.firstElementChild;
            iframe.src = entries[0].isIntersecting ? "https://www.youtube.com/embed/tgbNymZ7vqY?autoplay=1&mute=1": "";
            console.log("video " + (entries[0].isIntersecting ? "started" : "stopped"));
        }, { threshold: 0.5});

        iframeOserver.observe(document.getElementById("divFrame"));

    </script>

</body>
</html>

I set the threshold of intersection to 50% (threshold: 0.5) in the above example. You can change it as you needed.

Please refer to the following link for details about IntersectionObserver:
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API


问:
Spring Boot not serving static content
I can't get my Spring-boot project to serve static content.

I've placed a folder named static under src/main/resources. Inside it I have a folder named images. When I package the app and run it, it can't find the images I have put on that folder.

I've tried to put the static files in public, resources and META-INF/resources but nothing works.

If I jar -tvf app.jar I can see that the files are inside the jar on the right folder:
/static/images/head.png for example, but calling: http://localhost:8080/images/head.png, all I get is a 404

Any ideas why spring-boot is not finding this? (I'm using 1.1.4 BTW)

答:
Works for Thymeleaf, you can link the stylesheet using</p>
```<code>    <link th:href="@{/css/style.css}" rel="stylesheet" />
</code>```

Title: Spring Boot not serving static content

Body:
Works for Thymeleaf, you can link the stylesheet using

    <link th:href="@{/css/style.css}" rel="stylesheet" />


问:
coloring cell xlsx in angular
I have a problem I want according to a value put a red or green color at the line of my exel to download :
How could I set a specify cell's color in a worksheet.
here is the ts class that handles the exel format:

exelgest:

```<code>import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import { formatDate } from '@angular/common';
import { ExcelColMapper } from 'src/app/shared/services/excelexport/ExcelColMapper';

const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
const EXCEL_DATE_FORMAT = 'yyyyMMdd';
@Injectable({
  providedIn: 'root'
})

export class ExcelService {

  constructor() { }
  public exportAsExcelFile(json: any[], excelFileName: string): void {
    // liste des width des colonnes
    const wscols = [];
    Object.values(ExcelColMapper.keys).forEach(element => {
      wscols.push({ wch: element.length });
    });
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json, { dateNF: 'YYYYMMDD HH:mm:ss'});
    const range = XLSX.utils.decode_range(worksheet['!ref']);
    for (let C = range.s.r, index = 0; C <= range.e.r; ++C, index++) {
      const col = XLSX.utils.encode_col(C) + '1';
      if (!worksheet[col]) { continue; }
      worksheet[col].v = Object.values(ExcelColMapper.keys)[index];
    }
    worksheet['!cols'] = wscols;
    worksheet.write_row("A1:C1", ['Ray','Ray2','Ray3']);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], { type: EXCEL_TYPE});
    FileSaver.saveAs(data, fileName + formatDate(new Date(), EXCEL_DATE_FORMAT, 'en') + EXCEL_EXTENSION);
  }

}
</code>```

thanks

答:
```<code>cell.s = {
    fill: {
        bgColor: {rgb: "${color_code}"}
    },
    font: {
        color: {rgb: "${hashed_color_code}"}
    },
}
</code>```

Refer to official library document for more details:
https://www.npmjs.com/package/xlsx-with-styles

Title: coloring cell xlsx in angular

Body:
I have a problem I want according to a value put a red or green color at the line of my exel to download :
How could I set a specify cell's color in a worksheet.
here is the ts class that handles the exel format:

exelgest:

import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import { formatDate } from '@angular/common';
import { ExcelColMapper } from 'src/app/shared/services/excelexport/ExcelColMapper';

const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
const EXCEL_DATE_FORMAT = 'yyyyMMdd';
@Injectable({
  providedIn: 'root'
})

export class ExcelService {

  constructor() { }
  public exportAsExcelFile(json: any[], excelFileName: string): void {
    // liste des width des colonnes
    const wscols = [];
    Object.values(ExcelColMapper.keys).forEach(element => {
      wscols.push({ wch: element.length });
    });
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json, { dateNF: 'YYYYMMDD HH:mm:ss'});
    const range = XLSX.utils.decode_range(worksheet['!ref']);
    for (let C = range.s.r, index = 0; C <= range.e.r; ++C, index++) {
      const col = XLSX.utils.encode_col(C) + '1';
      if (!worksheet[col]) { continue; }
      worksheet[col].v = Object.values(ExcelColMapper.keys)[index];
    }
    worksheet['!cols'] = wscols;
    worksheet.write_row("A1:C1", ['Ray','Ray2','Ray3']);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], { type: EXCEL_TYPE});
    FileSaver.saveAs(data, fileName + formatDate(new Date(), EXCEL_DATE_FORMAT, 'en') + EXCEL_EXTENSION);
  }

}

thanks

Body:
cell.s = {
    fill: {
        bgColor: {rgb: "${color_code}"}
    },
    font: {
        color: {rgb: "${hashed_color_code}"}
    },
}

Refer to official library document for more details:
https://www.npmjs.com/package/xlsx-with-styles


问:
0 Supported devices on android playstore
So I'm trying to upload a new version of my app to the play store, when i upload the bundle it says that my app uses 13 feature and is supported by 0 android devices.

Here are the features it uses

```<code>android.hardware.bluetooth,
android.hardware.bluetooth_le,
android.hardware.camera,
android.hardware.camera.autofocus,
android.hardware.camera.flash,
android.hardware.camera.front,
android.hardware.camera2,
android.hardware.faketouch,
android.hardware.location,
android.hardware.nfc,
android.hardware.screen.landscape,
android.hardware.screen.portrait,
android.hardware.wifi
</code>```

So I check my previous release and it had 12 features, which were the exact same as above except without the feature android.hardware.camera2.

I'm not sure why this feature started showing up as something my app uses, i noticed this line in my gradle file:

<uses-feature android:name="android.hardware.camera2" android:required="false"/>

So I deleted that line and rebuilt the bundle but apparently the feature is still required by my app, any ideas of how I can fix this?

答:
If you don't specify the android:required attribute it defaults to "true". Thus, Google Play Store will assume that the application will not work without them.

Once you set android:required to false as given below, Play Store will accept the APK and will show a list of devices available for the application.

set android:required to false for the features like:

```<code><uses-feature android:name="android.hardware.camera" android:required="false"/>
</code>```

Body:
So I'm trying to upload a new version of my app to the play store, when i upload the bundle it says that my app uses 13 feature and is supported by 0 android devices.

Here are the features it uses

android.hardware.bluetooth,
android.hardware.bluetooth_le,
android.hardware.camera,
android.hardware.camera.autofocus,
android.hardware.camera.flash,
android.hardware.camera.front,
android.hardware.camera2,
android.hardware.faketouch,
android.hardware.location,
android.hardware.nfc,
android.hardware.screen.landscape,
android.hardware.screen.portrait,
android.hardware.wifi

So I check my previous release and it had 12 features, which were the exact same as above except without the feature android.hardware.camera2.

I'm not sure why this feature started showing up as something my app uses, i noticed this line in my gradle file:

<uses-feature android:name="android.hardware.camera2" android:required="false"/>

So I deleted that line and rebuilt the bundle but apparently the feature is still required by my app, any ideas of how I can fix this?

Body:
If you don't specify the android:required attribute it defaults to "true". Thus, Google Play Store will assume that the application will not work without them.

Once you set android:required to false as given below, Play Store will accept the APK and will show a list of devices available for the application.

set android:required to false for the features like:

<uses-feature android:name="android.hardware.camera" android:required="false"/>


问:
Idiomatic way to call an async Rust function that takes a reference, when I'd want to pass ownership to the function
There's a pattern I'm frequently encountering when writing async Rust code. Let's say I have a Foo struct (in real code, this could be something like a network client) and an async function that takes a reference to an instance of this struct:

struct Foo {
    i: i32
}

async fn use_foo(foo: &Foo) -> () {
    // do something with foo
}
```
<p>Then, I want to run several <code>use_foo</code> concurrently, each with its own reference to a different <code>Foo</code>. A natural (but incorrect) way to do this would be:</p>
<pre class="lang-rust prettyprint-override"><code>use futures::stream::FuturesUnordered;

async fn foo_in_a_loop() {
    let futures = FuturesUnordered::new();
    for i in 0..10 {
        let foo = Foo { i };
        // does not compile: `foo` is dropped before the future is dropped
        futures.push(use_foo(&foo));
    }
}
</code>```

which doesn't compile:

```<code>error[E0597]: `foo` does not live long enough
  --> src/main.rs:53:30
   |
53 |         futures.push(use_foo(&foo));
   |                              ^^^^ borrowed value does not live long enough
54 |     }
   |     - `foo` dropped here while still borrowed
55 | }
   | - borrow might be used here, when `futures` is dropped and runs the `Drop` code for type `FuturesUnordered`
   |
   = note: values in a scope are dropped in the opposite order they are defined

For more information about this error, try `rustc --explain E0597`
</code>```

My question boils down to: what's the most idiomatic way to fix this error? I'd like to "force" use_foo to take ownership of the Foo instance.

Right now, I'm using a helper function that takes ownership of foo:

```<code>async fn use_foo_owned(foo: Foo) -> () {
    use_foo(&foo).await
}

async fn foo_in_a_loop_owned() {
    let futures = FuturesUnordered::new();
    for i in 0..10 {
        let foo = Foo { i };
        futures.push(use_foo_owned(foo));
    }
}
</code>```

which does compile, but introducing an extra function just to please the borrow checker is clunky.

Note that sometimes use_foo may come from another crate and I may not be able to change its signature, but if there's an elegant solution that involves modifying use_foo, I'm interested too.

答:
Use an async move {} block to create a future that takes ownership of foo and calls use_foo:

```<code>futures.push(async move { use_foo(&foo).await });
</code>```

Body:
There's a pattern I'm frequently encountering when writing async Rust code. Let's say I have a Foo struct (in real code, this could be something like a network client) and an async function that takes a reference to an instance of this struct:

struct Foo {
    i: i32
}

async fn use_foo(foo: &Foo) -> () {
    // do something with foo
}

Then, I want to run several use_foo concurrently, each with its own reference to a different Foo. A natural (but incorrect) way to do this would be:

use futures::stream::FuturesUnordered;

async fn foo_in_a_loop() {
    let futures = FuturesUnordered::new();
    for i in 0..10 {
        let foo = Foo { i };
        // does not compile: `foo` is dropped before the future is dropped
        futures.push(use_foo(&foo));
    }
}

which doesn't compile:

error[E0597]: `foo` does not live long enough
  --> src/main.rs:53:30
   |
53 |         futures.push(use_foo(&foo));
   |                              ^^^^ borrowed value does not live long enough
54 |     }
   |     - `foo` dropped here while still borrowed
55 | }
   | - borrow might be used here, when `futures` is dropped and runs the `Drop` code for type `FuturesUnordered`
   |
   = note: values in a scope are dropped in the opposite order they are defined

For more information about this error, try `rustc --explain E0597`

My question boils down to: what's the most idiomatic way to fix this error? I'd like to "force" use_foo to take ownership of the Foo instance.

Right now, I'm using a helper function that takes ownership of foo:

async fn use_foo_owned(foo: Foo) -> () {
    use_foo(&foo).await
}

async fn foo_in_a_loop_owned() {
    let futures = FuturesUnordered::new();
    for i in 0..10 {
        let foo = Foo { i };
        futures.push(use_foo_owned(foo));
    }
}

which does compile, but introducing an extra function just to please the borrow checker is clunky.

Note that sometimes use_foo may come from another crate and I may not be able to change its signature, but if there's an elegant solution that involves modifying use_foo, I'm interested too.

Body:
Use an async move {} block to create a future that takes ownership of foo and calls use_foo:

futures.push(async move { use_foo(&foo).await });


问:
Adding a Dash in the editText automatically in Android
Have a look at my codes:

```<code>txt_HomeNo.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            boolean flag = true;
            String eachBlock[] = txt_HomeNo.getText().toString().split("-");
            for (int i = 0; i < eachBlock.length; i++) {
                if (eachBlock[i].length() > 3) {
                    flag = false;
                }
            }

            if (flag) {

                txt_HomeNo.setOnKeyListener(new OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {

                        if (keyCode == KeyEvent.KEYCODE_DEL)
                            keyDel = 1;
                        return false;
                    }
                });

                if (keyDel == 0) {

                    if (((txt_HomeNo.getText().length() + 1) % 4) == 0) {

                        if (txt_HomeNo.getText().toString().split("-").length <= 3) {
                            txt_HomeNo.setText(txt_HomeNo.getText() + "-");
                            txt_HomeNo.setSelection(txt_HomeNo.getText().length());
                        }
                    }
                    a = txt_HomeNo.getText().toString();
                } else {
                    a = txt_HomeNo.getText().toString();
                    keyDel = 0;
                }

            } else {
                txt_HomeNo.setText(a);
            }

        }
</code>```

The maximum length of the phone number is only 7. And when I already inputted 3 digits, it appends dash (that's what I'd like to happen) but my problem here is that the next 3 digits also appends dash (Like this: 511-871-)... My question is how can I do the codings with the next 4 digit number with having a dash on it. Please help me with this. thanks!

答: Check Hyphen in onTextChanged Method based on substring of previous text getting from beforeTextChange method.

Body:
Have a look at my codes:

txt_HomeNo.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            boolean flag = true;
            String eachBlock[] = txt_HomeNo.getText().toString().split("-");
            for (int i = 0; i < eachBlock.length; i++) {
                if (eachBlock[i].length() > 3) {
                    flag = false;
                }
            }

            if (flag) {

                txt_HomeNo.setOnKeyListener(new OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {

                        if (keyCode == KeyEvent.KEYCODE_DEL)
                            keyDel = 1;
                        return false;
                    }
                });

                if (keyDel == 0) {

                    if (((txt_HomeNo.getText().length() + 1) % 4) == 0) {

                        if (txt_HomeNo.getText().toString().split("-").length <= 3) {
                            txt_HomeNo.setText(txt_HomeNo.getText() + "-");
                            txt_HomeNo.setSelection(txt_HomeNo.getText().length());
                        }
                    }
                    a = txt_HomeNo.getText().toString();
                } else {
                    a = txt_HomeNo.getText().toString();
                    keyDel = 0;
                }

            } else {
                txt_HomeNo.setText(a);
            }

        }

The maximum length of the phone number is only 7. And when I already inputted 3 digits, it appends dash (that's what I'd like to happen) but my problem here is that the next 3 digits also appends dash (Like this: 511-871-)... My question is how can I do the codings with the next 4 digit number with having a dash on it. Please help me with this. thanks!


答:
```<code>my_string = "Hello, my\n       name is Michael."
my_string = my_string.gsub( /\s+/, " " )
</code>```

Title: Remove multiple spaces and new lines inside of String

Body:
Suppose we have string like this:

Hello, my\n       name is Michael.

How can I remove that new line and strip those spaces after that into one inside of string to get this?

Hello, my name is Michael.


问:
Read error info while API throwing 401 authentication error
My API returned 401 error while the user token expired or was not valid and it's returning status code 401 and payload with the error message and code like below.

I want to read this response body while getting 401 errors.

I can able to read status code like below

```<code>let response = request.task?.response as? HTTPURLResponse
if let statusCode = response?.statusCode, statusCode == 401 {
   //Retry with new token
}
</code>```

How to read response body message?

Can anyone help me with this?

Through postman (check above screenshot for reference) I can see the message and 401 code but on Swift with Alamofire How can I read the message?

EDIT:

I am trying to read this body/data in Request intercpter like below:

```<code>func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
    let response = request.task?.response as? HTTPURLResponse
    if let statusCode = response?.statusCode, statusCode == 401, request.retryCount < retryLimit {
       //Refresh token and retry
    }
}
</code>```

答:
HTTPURLResponse doesn't have the data, but the request, as a DataRequest has it:

```<code>if let dataRequest = request as? DataRequest, let data = request.data {
    // parse the data
}
</code>```

Body:
My API returned 401 error while the user token expired or was not valid and it's returning status code 401 and payload with the error message and code like below.

I want to read this response body while getting 401 errors.

I can able to read status code like below

let response = request.task?.response as? HTTPURLResponse
if let statusCode = response?.statusCode, statusCode == 401 {
   //Retry with new token
}

How to read response body message?

Can anyone help me with this?

Through postman (check above screenshot for reference) I can see the message and 401 code but on Swift with Alamofire How can I read the message?

EDIT:

I am trying to read this body/data in Request intercpter like below:

func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
    let response = request.task?.response as? HTTPURLResponse
    if let statusCode = response?.statusCode, statusCode == 401, request.retryCount < retryLimit {
       //Refresh token and retry
    }
}

Body:
HTTPURLResponse doesn't have the data, but the request, as a DataRequest has it:

if let dataRequest = request as? DataRequest, let data = request.data {
    // parse the data
}


问:
React Navigation 6 - Icons not appearing on tabNavigator
I am using React Navigation 6 createBottomTabNavigator and trying to provide Icon to tabBarIcon but the screen is coming up blank. and if I don't provide any icon then a box with a cross is coming Below is my code

```<code>import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Home from '../screens/app/home';
import Login from '../screens/auth/login';
import {Icon} from 'react-native-elements';
import Ionicons from 'react-native-vector-icons/Ionicons';

const Tab = createBottomTabNavigator();

const TabNavigator = () => {
  return (
    <Tab.Navigator
      screenOptions={{
        tabBarShowLabel: false,
        tabBarStyle: {backgroundColor: 'cyan'},
      }}>
      <Tab.Screen
        options={{
          tabBarIcon: ({color, size}) => {
            <Ionicons name="logo-bitcoin" />;
          },
        }}
        name="Home"
        component={Home}
      />
      <Tab.Screen
        options={{
          tabBarIcon: ({color, size}) => {
            <Icon
              type="font-awesome-5"
              name="coins"
              color={color}
              size={size}
            />;
          },
        }}
        name="Login"
        component={Login}
      />
      <Tab.Screen name="Login2" component={Login} />
    </Tab.Navigator>
  );
};

export default TabNavigator;
</code>```

p.s. - I've tried including apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" in my android/app/build.gradle

答:
you miss RETURN in "tabBarIcon"

tabBarIcon: ({color, size}) => {
            return <Ionicons name="logo-bitcoin" />;
          },
```
<p>or without return</p>
<pre class="lang-js prettyprint-override"><code>tabBarIcon: ({color, size}) => <Ionicons name="logo-bitcoin" />
</code>```

Body:
I am using React Navigation 6 createBottomTabNavigator and trying to provide Icon to tabBarIcon but the screen is coming up blank. and if I don't provide any icon then a box with a cross is coming Below is my code

import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Home from '../screens/app/home';
import Login from '../screens/auth/login';
import {Icon} from 'react-native-elements';
import Ionicons from 'react-native-vector-icons/Ionicons';

const Tab = createBottomTabNavigator();

const TabNavigator = () => {
  return (
    <Tab.Navigator
      screenOptions={{
        tabBarShowLabel: false,
        tabBarStyle: {backgroundColor: 'cyan'},
      }}>
      <Tab.Screen
        options={{
          tabBarIcon: ({color, size}) => {
            <Ionicons name="logo-bitcoin" />;
          },
        }}
        name="Home"
        component={Home}
      />
      <Tab.Screen
        options={{
          tabBarIcon: ({color, size}) => {
            <Icon
              type="font-awesome-5"
              name="coins"
              color={color}
              size={size}
            />;
          },
        }}
        name="Login"
        component={Login}
      />
      <Tab.Screen name="Login2" component={Login} />
    </Tab.Navigator>
  );
};

export default TabNavigator;

p.s. - I've tried including apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" in my android/app/build.gradle

Body:
you miss RETURN in "tabBarIcon"

tabBarIcon: ({color, size}) => {
            return <Ionicons name="logo-bitcoin" />;
          },

or without return

tabBarIcon: ({color, size}) => <Ionicons name="logo-bitcoin" />


问:
How to select multiple items in a TTreeView in code
I'm trying to select all the child node of a parent node when the parent is clicked, but when I for each node set the Selected = true i only end up with the last one being selected.
MultiSelect is true and I can do it with the mouse, so the setup should be ok.

For testing I use this code:

```<code>TTreeNode *node = Tv->Items->GetFirstNode();
node->Selected = true;
node = node->GetNext();
node->Selected = true;
node = node->GetNext();
node->Selected = true;
node = node->GetNext();
node->Selected = true;
</code>```

Any tricks to make this work?

答:
The TTreeNode::Selected property does not support multiple selections when toggling the node's selection state.  Internally, it will call the Win32 TreeView_SelectItem() API, which selects a single node only.

For multi-select, use the TTreeView::Select() method instead:

The select method selects one or more tree nodes.

That being said, your example is attempting to select (potentially) every node in the TreeView, not just the child nodes of a parent node, as you claim.

Try this:

void AddNodeAndChildrenToList(TList *List, TTreeNode *Node)
{
    List->Add(Node);
    TTreeNode *child = Node->getFirstChild();
    while (child)
    {
        AddNodeAndChildrenToList(List, child);
        child = child->getNextSibling();
    }
}

...

TList *nodes = new TList;
try
{
    TTreeNode *parent = ...;
    AddNodeAndChildrenToList(nodes, parent);
    Tv->Select(nodes);
}
__finally
{
    delete nodes;
}
```

Body:
I'm trying to select all the child node of a parent node when the parent is clicked, but when I for each node set the Selected = true i only end up with the last one being selected.
MultiSelect is true and I can do it with the mouse, so the setup should be ok.

For testing I use this code:

TTreeNode *node = Tv->Items->GetFirstNode();
node->Selected = true;
node = node->GetNext();
node->Selected = true;
node = node->GetNext();
node->Selected = true;
node = node->GetNext();
node->Selected = true;

Any tricks to make this work?


问:
Why is xcode running my SwiftUI app as a macOS app when it was created as an iOS app?
I have created a SwiftUI app for iOS. Under deployment info, I have only Iphone and Ipad checked off.

I have plugged in my iOS physical device.

When I click the run (triangle play button) it launches a macOs desktop app instead of on my iOS device.

How do I change the configuration to run on my iOS device?

答:
I'm guessing that this is occurring because you have one of the newer Macs with an Apple Silicon processor. These computers allow you to run your iOS apps as Mac apps (you can even download some iOS/iPadOS apps on the Mac App Store.

To make it run on a Simulator or on your physical iOS device, select the device from the devices/simulators dropdown at the top of Xcode. If your iOS device is connected to your Mac, you can select it in this dropdown,  or you can select a device.

location of devices/simulators dropdown in Xcode


问:
Knative suggested way to store binaries
Knative does only support persistent volumes of type secret, configMap or projected. Here in the doc is mentioned a workaround to work with other persistent volumes.
It's not clear to me what is the suggested way, and not a workaround, to store binaries in a private cloud system, that does not rely on something like S3 or other cloud storages.

Marco.

答:
The suggested way is to expose storage as an external service (SQL database, Redis, S3-compatible object storage like Minio or Ceph, or custom API).

If you're running a recent Knative build, there are feature flags which can enable PersistentVolumeClaims, but these shared filesystems can introduce scaling issues (and data corruption bugs, depending on locking implementation), so are not enabled by default.

Title: Knative suggested way to store binaries


问:
How to Make Python Print something at nth Iteration within a For Loop?
I want to preface my question by saying that I am very new to Python and have only started using it for a specific class in grad school.

I have written a script to find the root of a function using iterative methods such as the Fixed-point, Bisection, and Newton-Raphson methods. The python code for my algorithms are as follows:

Fixed-Point Method:

```<code>def fixedpoint(func, g_func,x0,tol, MAXIT):

    def g(x):
        return eval(g_func)

    print(f"Seeking root of {func}.")
    print("FIXED POINT ITERATION:")
    iterated_x = g(x0)
    for i in range(0, MAXIT):
        iterated_x = g(iterated_x)
        print("Iteration", i + 1, iterated_x)
        condition = abs(g(iterated_x) - (iterated_x))
        if condition < tol:
            print(f"The root converges to {iterated_x} after {i+1} iterations.")
            break
        if i == MAXIT and condition >= tol:
            print("ERROR: The root did not converge after maximum iterations.")

fixedpoint('x**2 - 4*x + 2', '(x**2+2)/4', 0.75, 10**(-4), 100)
fixedpoint('math.exp(-x) + x - 7 ', '7 - math.exp(-x)', 0.75, 10**(-4), 100)
</code>```

Bisection Method:

```<code>def bisection(func,a, b, tol, MAXIT):

    def f(x):
        return eval(func)

    print(f"Seeking root of {func}")
    print("BISECTION METHOD:")
    if f(a)*f(b) <0:
        for i in range(0, MAXIT):
            c = (a+b)/2
            if f(a)*f(c) < 0:
                a = a
                b = c
                print(f"Iteration", i + 1, f(c))
            elif f(b)*f(c) < 0:
                b = b
                a = c
                print(f"Iteration", i + 1, f(c))
            if f(c) == 0 or abs(f(c)) < tol:
                print ("Exact Solution Found")
                print(f"Iteration", i + 1, c)
                print("The root converges to", c, "after", i + 1, "iterations.")
                break
            elif i == MAXIT and abs(f(c)) > tol:
                print("Bisection method fails.")

    return None

bisection('x**2 - 4*x + 2',0.5, 1, 10**(-4), 100)
bisection('math.exp(-x) + x - 7',6, 8, 10**(-4), 100)
</code>```

Newton-Raphson Method:

```<code>def newtonraphson(func, deriv, x0, tol, MAXIT):

    def f(x):
        return eval(func)

    def ddx(x):
        return eval(deriv)

    print(f"Seeking root of {func}.")
    print("NEWTON-RAPHSON METHOD:")

    for i in range(1, MAXIT):
        iterated_x = x0 - (f(x0)/ddx(x0))
        x0 = iterated_x
        print(f"Iteration", i, x0)

        if f(x0) < tol:
            print(f"The root converges to {x0} after {i} iterations.")
            break
        elif i==MAXIT and f(x0) > tol:
            print("After maximum iterations, root was not found.")

newtonraphson('x**2-4*x+2', '2*x-4', 0.75,10**(-4), 100)
newtonraphson('math.exp(-x) + x - 7', '-(math.exp(-x)) + 1', 0.75,10**(-4), 100)
</code>```

While my script is successfully able to find the roots for the equations I am interested in, I am stuck with a simpler problem. Basically, I want to tell my program that if after maximum iterations, my tolerance condition is not fulfilled, print "Method Failed".

However, my code does not print the statement I want it to when I experiment with functions that don't coverage when maximum iterations is set at 100 and tolerance is set to 0.0001.

Is my syntax right for the fail print statement?

Do conditions like "if i==MAXIT and f(x0) > tol" make sense in the context of the function I have written?

I would appreciate any and all advice for this issue as I am trying hard to improve at Python.

Thank you.

答:
A good way to achieve this in Python is to use the for\else construct.  Essentially, if you hang an "else" clause off of your for loop, it will execute if the loop doesn't terminate early due to a break statement.  It's very useful for loops that are searching for something, and root finding definitely fits that mold.  So your fixed point iteration loop would look like:

```<code>for i in range(0, MAXIT):
    iterated_x = g(iterated_x)
    condition = abs(g(iterated_x) - (iterated_x))
    if condition < tol:
        print(f"The root converges to {iterated_x} after {i+1} iterations.")
        break
else:
    print("ERROR: The root did not converge after maximum iterations.")
</code>```

One advantage of doing it this way is that it doesn't matter if you change your success criteria in the loop--the else clause runs if you don't declare success with the break statement no matter how success is defined.

Body:
I want to preface my question by saying that I am very new to Python and have only started using it for a specific class in grad school.

I have written a script to find the root of a function using iterative methods such as the Fixed-point, Bisection, and Newton-Raphson methods. The python code for my algorithms are as follows:

Fixed-Point Method:

def fixedpoint(func, g_func,x0,tol, MAXIT):

    def g(x):
        return eval(g_func)

    print(f"Seeking root of {func}.")
    print("FIXED POINT ITERATION:")
    iterated_x = g(x0)
    for i in range(0, MAXIT):
        iterated_x = g(iterated_x)
        print("Iteration", i + 1, iterated_x)
        condition = abs(g(iterated_x) - (iterated_x))
        if condition < tol:
            print(f"The root converges to {iterated_x} after {i+1} iterations.")
            break
        if i == MAXIT and condition >= tol:
            print("ERROR: The root did not converge after maximum iterations.")

fixedpoint('x**2 - 4*x + 2', '(x**2+2)/4', 0.75, 10**(-4), 100)
fixedpoint('math.exp(-x) + x - 7 ', '7 - math.exp(-x)', 0.75, 10**(-4), 100)

Bisection Method:

def bisection(func,a, b, tol, MAXIT):

    def f(x):
        return eval(func)

    print(f"Seeking root of {func}")
    print("BISECTION METHOD:")
    if f(a)*f(b) <0:
        for i in range(0, MAXIT):
            c = (a+b)/2
            if f(a)*f(c) < 0:
                a = a
                b = c
                print(f"Iteration", i + 1, f(c))
            elif f(b)*f(c) < 0:
                b = b
                a = c
                print(f"Iteration", i + 1, f(c))
            if f(c) == 0 or abs(f(c)) < tol:
                print ("Exact Solution Found")
                print(f"Iteration", i + 1, c)
                print("The root converges to", c, "after", i + 1, "iterations.")
                break
            elif i == MAXIT and abs(f(c)) > tol:
                print("Bisection method fails.")

    return None

bisection('x**2 - 4*x + 2',0.5, 1, 10**(-4), 100)
bisection('math.exp(-x) + x - 7',6, 8, 10**(-4), 100)

Newton-Raphson Method:

def newtonraphson(func, deriv, x0, tol, MAXIT):

    def f(x):
        return eval(func)

    def ddx(x):
        return eval(deriv)

    print(f"Seeking root of {func}.")
    print("NEWTON-RAPHSON METHOD:")

    for i in range(1, MAXIT):
        iterated_x = x0 - (f(x0)/ddx(x0))
        x0 = iterated_x
        print(f"Iteration", i, x0)

        if f(x0) < tol:
            print(f"The root converges to {x0} after {i} iterations.")
            break
        elif i==MAXIT and f(x0) > tol:
            print("After maximum iterations, root was not found.")

newtonraphson('x**2-4*x+2', '2*x-4', 0.75,10**(-4), 100)
newtonraphson('math.exp(-x) + x - 7', '-(math.exp(-x)) + 1', 0.75,10**(-4), 100)

While my script is successfully able to find the roots for the equations I am interested in, I am stuck with a simpler problem. Basically, I want to tell my program that if after maximum iterations, my tolerance condition is not fulfilled, print "Method Failed".

However, my code does not print the statement I want it to when I experiment with functions that don't coverage when maximum iterations is set at 100 and tolerance is set to 0.0001.

Is my syntax right for the fail print statement?

Do conditions like "if i==MAXIT and f(x0) > tol" make sense in the context of the function I have written?

I would appreciate any and all advice for this issue as I am trying hard to improve at Python.

Thank you.

Body:
A good way to achieve this in Python is to use the for\else construct.  Essentially, if you hang an "else" clause off of your for loop, it will execute if the loop doesn't terminate early due to a break statement.  It's very useful for loops that are searching for something, and root finding definitely fits that mold.  So your fixed point iteration loop would look like:

for i in range(0, MAXIT):
    iterated_x = g(iterated_x)
    condition = abs(g(iterated_x) - (iterated_x))
    if condition < tol:
        print(f"The root converges to {iterated_x} after {i+1} iterations.")
        break
else:
    print("ERROR: The root did not converge after maximum iterations.")

One advantage of doing it this way is that it doesn't matter if you change your success criteria in the loop--the else clause runs if you don't declare success with the break statement no matter how success is defined.


问:
Collapsed Sidebar
I would like to have a collapsed sidebar like this https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapse_sidebar.

However, I do not want the main div to move to the right after the sidebar is opened. Instead, I wish the division can be resize to be fit with the screen size at the moment.

I would greatly appreciate if anyone can help me with this issue.

答:
You can avoid the main div from being pushed right by simply setting the style.marginLeft = "0px" in the openNav() function.

function openNav() {
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "0px";
}

function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: "Lato", sans-serif;
}

.sidebar {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebar a:hover {
  color: #f1f1f1;
}

.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.openbtn {
  font-size: 20px;
  cursor: pointer;
  background-color: #111;
  color: white;
  padding: 10px 15px;
  border: none;
}

.openbtn:hover {
  background-color: #444;
}

#main {
  transition: margin-left .5s;
  padding: 16px;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
  .sidebar {padding-top: 15px;}
  .sidebar a {font-size: 18px;}
}</code>```

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

  ×
  About
  Services
  Clients
  Contact

  <button class="openbtn" onclick="openNav()">☰ Open Sidebar</button>

Collapsed Sidebar

Click on the hamburger menu/bar icon to open the sidebar, and push this content to the right.

 ```

Title: Collapsed Sidebar

Body:
You can avoid the main div from being pushed right by simply setting the style.marginLeft = "0px" in the openNav() function.

function openNav() {
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "0px";
}

function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
}

body {
  font-family: "Lato", sans-serif;
}

.sidebar {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebar a:hover {
  color: #f1f1f1;
}

.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.openbtn {
  font-size: 20px;
  cursor: pointer;
  background-color: #111;
  color: white;
  padding: 10px 15px;
  border: none;
}

.openbtn:hover {
  background-color: #444;
}

#main {
  transition: margin-left .5s;
  padding: 16px;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
  .sidebar {padding-top: 15px;}
  .sidebar a {font-size: 18px;}
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div id="mySidebar" class="sidebar">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>

<div id="main">
  <button class="openbtn" onclick="openNav()">☰ Open Sidebar</button>
  <h2>Collapsed Sidebar</h2>
  <p>Click on the hamburger menu/bar icon to open the sidebar, and push this content to the right.</p>
</div>

</body>
</html>


问:
Is there a way to do an LDAP query to get records where a particular attribute is the same?
I am trying to find an example LDAP query where I can find records where a particular attribute matches one or more other records.  For instance, a user object where the userid is different, but the employee ids are the same.  Is this even possible?</p>

答:
I found this example for 'myattribute'. Needs some polish, and depending on the size of your directory, it could take a while to run. If that's the case, I'd break it up by attribute sections {attr=aa*, attr=ab*, attr=ac*, etc.}.</p>
```<code>ldapsearch -x -h ldapserver.domain.com -b ou=myldap,o=mydomain.com "(&(myattribute=aa*))" myattribute | grep '^myattribute:' | sort | uniq -c| sort -n|awk '$1 > 1 { print }'
</code>```

Body:
I found this example for 'myattribute'. Needs some polish, and depending on the size of your directory, it could take a while to run. If that's the case, I'd break it up by attribute sections {attr=aa*, attr=ab*, attr=ac*, etc.}.

ldapsearch -x -h ldapserver.domain.com -b ou=myldap,o=mydomain.com "(&(myattribute=aa*))" myattribute | grep '^myattribute:' | sort | uniq -c| sort -n|awk '$1 > 1 { print }'


问:
How do I turn a one-to-many relationship into a list property using SauceDB?
Using SauceDB, how do I turn a one-to-many relationship, between say table "A" and table "B" respectively, into a list property (containing B objects) in the class that corresponds to table A? The relationship is represented by a foreign key in table B referring to table A (so that many B records can belong to one A record).</p>

答:
Sauce does not support Linq2SQL style navigation properties.  However, there are two supported ways to work around this depending on your requirements.

1) Just do the join in your code

IDataStore dstore = .GetDataStore();

```<code>var query = from i in dstore.Query<MyTable>()
            join x in dstore.Query<MyTable>() on i.Name equals x.Name
            select new {  };
</code>```

2) Another way to do it is as follows, and gives a more Navigation Property Style use.  Modify your object definition to contain a list and use an [AdditionalInit]

```<code>public class Foo
{
  public int ID { get; set; }
  public string Name { get; set; }

  [IgnoredField]
  public List<Bar> Bars { get; set; }

  [AdditionalInit]
  private void LoadBars(IDataStore dstore)
  {
    Bars = dstore.Query<Bar>().Where(r=> r.Foo = this.ID).ToList();
  }
}
</code>```

That should do what you seek, if you have any more questions let me know.

Body:
Sauce does not support Linq2SQL style navigation properties.  However, there are two supported ways to work around this depending on your requirements.

1) Just do the join in your code

IDataStore dstore = .GetDataStore();

var query = from i in dstore.Query<MyTable>()
            join x in dstore.Query<MyTable>() on i.Name equals x.Name
            select new {  };

2) Another way to do it is as follows, and gives a more Navigation Property Style use.  Modify your object definition to contain a list and use an [AdditionalInit]

public class Foo
{
  public int ID { get; set; }
  public string Name { get; set; }

  [IgnoredField]
  public List<Bar> Bars { get; set; }

  [AdditionalInit]
  private void LoadBars(IDataStore dstore)
  {
    Bars = dstore.Query<Bar>().Where(r=> r.Foo = this.ID).ToList();
  }
}

That should do what you seek, if you have any more questions let me know.


问:
How can I get server and stream key from AWS MediaLive
I need to configure live streaming using OBS studio software, live streaming has already been setup on AWS using ElementalMediaLive(auto wizard). but I am unable to figure out the way to find the server address and stream key which are required the configure the OBS studio.
can some one please guid me where can I find the above required information into AWS panel?
Thanks

答:
Have a look here:

https://aws.amazon.com/de/blogs/media/connecting-obs-studio-to-aws-media-services-in-the-cloud/

Especially this document:

https://d2908q01vomqb2.cloudfront.net/fb644351560d8296fe6da332236b1f8d61b2828a/2020/04/14/Connecting-OBS-Studio-to-AWS-Media-Services-in-the-Cloud-v2.pdf

Where it says:

STEP C: CONFIGURE THE APPLIANCE

Launch OBS Studio on the source system. Choose Settings to open the settings window. Choose Stream to access the streaming settings.

Complete the fields:

For Stream Type, choose Custom Streaming Server.

For URL, copy one of the endpoint URLs from the input you created in    Step B. Remove the /<stream_name> at the end of the URL.

For Stream key, type the stream name.

Leave the Use authentication box unchecked.

Choose Apply to save your changes.


问:
How to get the number of pixels a user has scrolled down the page?
Suppose we have a html page with large height.So there will be a vertical scrollbar.

As the user scrolls down I want to know how much he has scrolled using javascript (jquery) I suppose... Is this possible?

答:
This will work fine in chrome</p>
```<code>window.addEventListener('scroll', function() {
    console.log(scrollY);
});
</code>```

Body:
This will work fine in chrome

window.addEventListener('scroll', function() {
    console.log(scrollY);
});