骄傲

文章 评论 浏览 32

骄傲 2025-02-11 15:36:09

中有3个条件检查如果名称==“ kevin”或“ jon”或“ inbar”:

  • name ==“ kevin”
  • “ jon”
  • “ inbar”

,此if语句等同于

if name == "Kevin":
    print("Access granted.")
elif "Jon":
    print("Access granted.")
elif "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

自<<代码> elif“ jon” 将始终是正确的,因此可以访问任何用户的

解决方案,


下使用任何一种方法

您可以在 fast> fast

if name in ["Kevin", "Jon", "Inbar"]:
    print("Access granted.")
else:
    print("Access denied.")

slow> slow

if name == "Kevin" or name == "Jon" or name == "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

slow + slow + 不必要的代码

if name == "Kevin":
    print("Access granted.")
elif name == "Jon":
    print("Access granted.")
elif name == "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

There are 3 condition checks in if name == "Kevin" or "Jon" or "Inbar":

  • name == "Kevin"
  • "Jon"
  • "Inbar"

and this if statement is equivalent to

if name == "Kevin":
    print("Access granted.")
elif "Jon":
    print("Access granted.")
elif "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

Since elif "Jon" will always be true so access to any user is granted

Solution


You can use any one method below

Fast

if name in ["Kevin", "Jon", "Inbar"]:
    print("Access granted.")
else:
    print("Access denied.")

Slow

if name == "Kevin" or name == "Jon" or name == "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

Slow + Unnecessary code

if name == "Kevin":
    print("Access granted.")
elif name == "Jon":
    print("Access granted.")
elif name == "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

为什么要“ a == x或y或z”总是评估为真?我如何比较“ a”所有这些?

骄傲 2025-02-11 03:28:38

您可以通过将字符串与 r 前缀前缀

print(r'.\numbers.txt')

或使用 \\ 逃脱后斜线来使用原始字符串。

print('.\\numbers.txt')

You can use the raw string by prefixing the string with r

print(r'.\numbers.txt')

Or escape the backslashes with \\

print('.\\numbers.txt')

如何在没有其逃生效果的情况下使用\

骄傲 2025-02-10 10:48:11

使用灵活而不是扩展的,并且确实为 mainaxissizizizizizizizizizizizizizion row 窗口小部件提供。

 Row(children: [
                          Row(
                            mainAxisSize: MainAxisSize.min,
    
                            children: [
                              Icon(
                                Icons.groups,
                                color: Colors.green,
                              ),
                              SizedBox(width: 15),
                              Flexible(
                                child: Text(
                                  'imSolver',
                                )
                              ),
                            ],
                          ),
                        ]),

Use Flexible instead of Expanded and do provide mainAxisSize to the Row Widget.

 Row(children: [
                          Row(
                            mainAxisSize: MainAxisSize.min,
    
                            children: [
                              Icon(
                                Icons.groups,
                                color: Colors.green,
                              ),
                              SizedBox(width: 15),
                              Flexible(
                                child: Text(
                                  'imSolver',
                                )
                              ),
                            ],
                          ),
                        ]),

为什么使用扩展会使我的文字消失?

骄傲 2025-02-10 03:06:07

根据@LMC的评论,我做了一个示例项目,以使用JMX获得httpsession的大小:

请注意,因为您无法访问 org.apache.catalina.session.session.managerbase ,因此此项目使用 byteman 。将 ManagerBase 将对象存储到MBEAN sessionmonitor 的静态字段中,并使用Byteman类似:

RULE Set ManagerBase object to MBean
CLASS ^org.apache.catalina.session.ManagerBase
METHOD initInternal
AT EXIT
IF TRUE
DO
    traceln("SETTING SessionManager");
    com.example.sessionsize.SessionMonitor.setSessionManager($this);
ENDRULE

并在JMX接口中使用它,例如:

package com.example.sessionsize;

import org.apache.catalina.Manager;
import org.apache.catalina.Session;

import net.sourceforge.sizeof.SizeOf;

public class SessionMonitor implements SessionMonitorMBean {

    private static Manager sessionManager = null;

    public static void setSessionManager(Manager manager) {
        sessionManager = manager;
    }

    @Override
    public long getMemoryConsumption() {
        if (sessionManager != null) {
            try {
                Session [] sessions = sessionManager.findSessions();
                return SizeOf.deepSizeOf(sessions);
            } catch(RuntimeException e) {
                // Falied to get size of HttpSession object
                e.printStackTrace();
                return -2;
            }
        } else {
            // SessionManager is not ready
            return -1;
        }
    }

    @Override
    public long getNumberOfActiveHttpSession() {
        return sessionManager.findSessions().length;
    }
}

According to the comment from @LMC, I made a sample project to get the size of HttpSession with JMX: https://github.com/satob/SessionSize

Note that because you cannot access org.apache.catalina.session.ManagerBase directly, this project uses ByteMan. Store the ManagerBase object to a static field of the MBean SessionMonitor with Byteman like:

RULE Set ManagerBase object to MBean
CLASS ^org.apache.catalina.session.ManagerBase
METHOD initInternal
AT EXIT
IF TRUE
DO
    traceln("SETTING SessionManager");
    com.example.sessionsize.SessionMonitor.setSessionManager($this);
ENDRULE

and use it in the JMX interface like:

package com.example.sessionsize;

import org.apache.catalina.Manager;
import org.apache.catalina.Session;

import net.sourceforge.sizeof.SizeOf;

public class SessionMonitor implements SessionMonitorMBean {

    private static Manager sessionManager = null;

    public static void setSessionManager(Manager manager) {
        sessionManager = manager;
    }

    @Override
    public long getMemoryConsumption() {
        if (sessionManager != null) {
            try {
                Session [] sessions = sessionManager.findSessions();
                return SizeOf.deepSizeOf(sessions);
            } catch(RuntimeException e) {
                // Falied to get size of HttpSession object
                e.printStackTrace();
                return -2;
            }
        } else {
            // SessionManager is not ready
            return -1;
        }
    }

    @Override
    public long getNumberOfActiveHttpSession() {
        return sessionManager.findSessions().length;
    }
}

enter image description here

用tomcat中的所有httpsess在任意时间点测量记忆消耗

骄傲 2025-02-08 17:15:34

您可以使用 translate()

返回一些字符后提供的字符串作为第一个参数
第二个参数中指定的转换为目标集
第三个参数中指定的字符。

trim(translate(site, '0123456789', '          '))

trim() 是在翻译后删除字符串开始或结束的任何空间

you can use translate()

Returns the string provided as a first argument after some characters
specified in the second argument are translated into a destination set
of characters specified in the third argument.

trim(translate(site, '0123456789', '          '))

trim() is to remove any space at the start or end of the string after translate

在字符串中拆分一个数字

骄傲 2025-02-08 04:45:23

这是一个与WebPack相关的问题,而不是Gatsby 本身。我认为您可以解决此通过使用Postcss 来创建并将语法和功能扩展到现代的,浏览器友好的CSS中,因此您只需要添加规则,PostCSS就会处理跨浏览器和后备兼容性(如果有的话,您可以按照现在的方式添加自己的自己)。

通过:

npm install postcss gatsby-plugin-postcss

要与CSS模块一起使用它,您需要在 gatsby-config.js 中添加以下内容:

plugins: [
  {
    resolve: `gatsby-plugin-postcss`,
    options: {
      postCssPlugins: [require(`postcss-preset-env`)({ stage: 0 })],
    },
  },
],

如果要包括 autoprefixer 可以通过添加额外的Postcss插件来完成:

plugins: [
  {
    resolve: `gatsby-plugin-postcss`,
    options: {
      postCssPlugins: [
        require(`postcss-preset-env`)({ stage: 0 }),
        require('autoprefixer'),
      ],
    },
  },
];

从: gatsby-plugin-plugin-plugin-postcss + autopReopReoPrefixer + browserslist + browserslist

It's a webpack-related issue, not Gatsby per se. I think you can solve this by using PostCSS to create and extend syntaxes and features into modern, browser-friendly CSS so you will only need to add your rule and PostCSS will handle the cross-browser and fallback compatibility (if there's any, you can add your own as you are doing right now).

Install it by:

npm install postcss gatsby-plugin-postcss

To use it with CSS modules you'll need to add the following in your gatsby-config.js:

plugins: [
  {
    resolve: `gatsby-plugin-postcss`,
    options: {
      postCssPlugins: [require(`postcss-preset-env`)({ stage: 0 })],
    },
  },
],

If you want to include autoprefixer can be done by adding an extra PostCSS plugin:

plugins: [
  {
    resolve: `gatsby-plugin-postcss`,
    options: {
      postCssPlugins: [
        require(`postcss-preset-env`)({ stage: 0 }),
        require('autoprefixer'),
      ],
    },
  },
];

Modified from: Gatsby plugin settings for gatsby-plugin-postcss + autoprefixer + browserslist

为什么盖茨比删除重复/后备CSS属性

骄傲 2025-02-08 00:36:28

几天前,我遇到了同样的问题,并提出了这个解决方案:

您要做的第一件事就是将文件上传到非公共目录。我的应用程序正在存储扫描发票,因此我将它们放入存储/应用/发票中。上传文件并生成URL的代码将是:

// This goes inside your controller method handling the POST request.

$path = $request->file('invoice')->store('invoices');
$url = env('APP_URL') . Illuminate\Support\Facades\Storage::url($path);

返回的URL应导致 httpp ://yourdomain.com/storage/invoices/uniquefilename.jpg

现在,您必须创建一个使用验证中间件来确保用户身份验证的控制器。然后,定义一种从私人目录中获取文件并将其作为文件响应返回的方法。那将是:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function __invoke($file_path)
    {
        if (!Storage::disk('local')->exists($file_path)) {
            abort(404);
        }

        $local_path = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $file_path;

        return response()->file($local_path);
    }
}

最后一件事是注册路由/web.php文件内的路由:

Route::get('/storage/{file_name}', 'FileController')->where(['file_name' => '.*'])

因此,您有一个可重复使用的片段,用于所有处理私人文件的项目:)

I got the same issue some days ago and came up with this solution:

First thing you have to do is upload the file to a non-public directory. My app is storing scanned invoices, so I'm going to place them inside storage/app/invoices. The code for uploading the file and generating the url would be:

// This goes inside your controller method handling the POST request.

$path = $request->file('invoice')->store('invoices');
$url = env('APP_URL') . Illuminate\Support\Facades\Storage::url($path);

The url returned should result in something like http://yourdomain.com/storage/invoices/uniquefilename.jpg

Now you have to create a controller that uses the auth middleware to ensure the user is authenticated. Then, define a method that grabs the file from the private directory and returns it as a file response. That would be:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function __invoke($file_path)
    {
        if (!Storage::disk('local')->exists($file_path)) {
            abort(404);
        }

        $local_path = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $file_path;

        return response()->file($local_path);
    }
}

The last thing is register the route inside your routes/web.php file:

Route::get('/storage/{file_name}', 'FileController')->where(['file_name' => '.*'])

So there you have it, a pretty reusable snippet for all your projects that deals with private files :)

将图像存储在公共文件夹Laravel上

骄傲 2025-02-07 19:40:56

实际类型是纹理&lt; gfx_device_gl :: Resources&gt; ,而不是 texture&lt; gfx :: Resources&gt;

请注意,特质,不是类型。在纹理中; gfx_device_gl :: Resources 实现 GFX :: Resources 的确,但这并不意味着 texture&lt; gfx_device_gl :: Resources&gt; >和纹理&lt; dyn GFX :: Resources&gt; 是兼容类型。 ( r 类型参数也需要协变。)

如果要确保失败 texture 而无需提供特定的资源类型,您可以使用注释纹理&lt; _&gt; ,它允许编译器推断 texture 的通用类型参数。


进一步阅读:

The actual type is Texture<gfx_device_gl::Resources>, not Texture<gfx::Resources>.

Note that gfx::Resources is a trait, not a type. In Texture<R> the R generic type must not be covariant, and even if it were the type would likely need to be Texture<dyn gfx::Resources>. While it's true that gfx_device_gl::Resources implements gfx::Resources, that doesn't on its own imply that Texture<gfx_device_gl::Resources> and Texture<dyn gfx::Resources> are compatible types. (The R type parameter would also need to be covariant.)

If you want to ensure that failing is a Texture without giving a particular resource type, you could use the annotation Texture<_> instead, which permits the compiler to infer Texture's generic type argument.


Further reading:

锈活塞可以找到正确的类型提示

骄傲 2025-02-07 05:52:39

尝试将您的代码隔离到这样的函数中:

来自ETH_ACCOUNT IMPOCT帐户
进口秘密

from eth_account import Account
import secrets

def gen(private_key_prefix:str = "0x"):
    priv = secrets.token_hex(32)
    private_key = private_key_prefix + priv
    return private_key, Account.from_key(private_key).address
    
    
print([gen() for _ in range(10)])

此回报10差异的秘密地址的组合

Try to isolate your code into a function like this:

from eth_account import Account
import secrets

from eth_account import Account
import secrets

def gen(private_key_prefix:str = "0x"):
    priv = secrets.token_hex(32)
    private_key = private_key_prefix + priv
    return private_key, Account.from_key(private_key).address
    
    
print([gen() for _ in range(10)])

This return 10 differens combinations of secret address address

如何创建重复n次的每个结果的不同列表?

骄傲 2025-02-07 02:09:18

有了列表理解,一行就足够了。首先迭代列表并进行测试。然后在集合中转换以消除重复。返回列表之后:

list({x for x in list1 if x % 2 <= 0})

输出:[8、2、4、6]

在评论和澄清之后,另一个代码就足够:

[list1[x] for x in [0] if list1[x] % 2 <= 0] + [list1[i] for i in range(len(list1)) if list1[i] % 2 <= 0 and list1[i] not in list1[0: i - 1]]

输出:[2、4、6、8]

With list comprehension, one line is enough. First iterate over the list and test for even. Then convert in set to eliminate duplicates. After return to list:

list({x for x in list1 if x % 2 <= 0})

Output: [8, 2, 4, 6]

After comments and clarifies, another code is enough:

[list1[x] for x in [0] if list1[x] % 2 <= 0] + [list1[i] for i in range(len(list1)) if list1[i] % 2 <= 0 and list1[i] not in list1[0: i - 1]]

Output: [2, 4, 6, 8]

仅在python列表中重复相同数字的情况下仅选择一次数字

骄傲 2025-02-06 19:27:39

请按照以下步骤从React Router Router DOM V5迁移到V6。

首先,从Dev依赖项中删除当前版本的React Router Dom,

  "devDependencies": {
    "react-router-dom": "^5.3.0"
  }

对于该删除,

"react-router-dom": "^5.3.0"

安装React Router Router DOM V6。

npm i -D [email protected]

现在,您的DevDections应该像,

  "devDependencies": {
    "react-router-dom": "^6.3.0"
  }

使用以下代码应用React Rout Router Dom V6,

app.js

import { Home } from "./home";
import { Listings } from "./listings";
import {
  Navigate,
  Route,
  Routes,
  BrowserRouter as Router
} from "react-router-dom";

export function App() {
  // const auth = useRecoilValue(authAtom);

  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/browse" element={<Listings />} />
        <Route path="*" element={<Navigate from="*" to="/" />} />
      </Routes>
    </Router>
  );
}

export default App;

home.jsx

export function Home() {
    return <h1>Hello, Home</h1>;
}

listing.jsx

export function Listings(props) {
    return <h1>Hello, Listing</h1>;
}

Follow the below procedure to migrate from React Router Dom v5 to v6.

First of all, remove the current version of react router dom from dev dependencies,

  "devDependencies": {
    "react-router-dom": "^5.3.0"
  }

For that delete,

"react-router-dom": "^5.3.0"

Install react router dom v6.

npm i -D [email protected]

Now your devDependencies should be like,

  "devDependencies": {
    "react-router-dom": "^6.3.0"
  }

Use the below code to apply react router dom v6,

App.js

import { Home } from "./home";
import { Listings } from "./listings";
import {
  Navigate,
  Route,
  Routes,
  BrowserRouter as Router
} from "react-router-dom";

export function App() {
  // const auth = useRecoilValue(authAtom);

  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/browse" element={<Listings />} />
        <Route path="*" element={<Navigate from="*" to="/" />} />
      </Routes>
    </Router>
  );
}

export default App;

home.jsx

export function Home() {
    return <h1>Hello, Home</h1>;
}

listing.jsx

export function Listings(props) {
    return <h1>Hello, Listing</h1>;
}

React路由器DOM V6- untureck TypeError:无法破坏属性&#x27; path&#x27;匹配&#x27;因为它不确定

骄傲 2025-02-06 12:38:30

如果您想知道后端格式如何并发送响应,请检查问题的正文。

以下是对后端执行GET请求的服务方法。

export class PowerPlantService {
  constructor(private http: HttpClient) { }

  getAll() {
    return this.http.get(baseUrl);
  }

以下是订阅答案并将元素添加到地图中的组件方法。

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  private latitude: number = 45.6427;
  private longitude: number = 25.5887;
   
  private map!: L.Map;
  private centroid: L.LatLngExpression = [this.latitude, this.longitude];

  ngOnInit(): void {
    this.initMap();
  }
  
  constructor(private powerPlantService: PowerPlantService) { 
  }

  private initMap(): void {
    this.map = L.map('map', {
      center: this.centroid,
      zoom: 2.8
    });

    const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
    {
      minZoom: 2.8,
      attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    });

    tiles.addTo(this.map);
    
    this.powerPlantService.getAll().subscribe((data: any)=>{
      console.log(data);
      L.geoJSON(data).addTo(this.map) 
    }) 

If you want to know how the back end formats and sends the response, please check in the body of the question.

Below is the service method that performs a GET request to the back end.

export class PowerPlantService {
  constructor(private http: HttpClient) { }

  getAll() {
    return this.http.get(baseUrl);
  }

Below is the component method that subscribes to the answer and adds the elements to the map.

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  private latitude: number = 45.6427;
  private longitude: number = 25.5887;
   
  private map!: L.Map;
  private centroid: L.LatLngExpression = [this.latitude, this.longitude];

  ngOnInit(): void {
    this.initMap();
  }
  
  constructor(private powerPlantService: PowerPlantService) { 
  }

  private initMap(): void {
    this.map = L.map('map', {
      center: this.centroid,
      zoom: 2.8
    });

    const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
    {
      minZoom: 2.8,
      attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    });

    tiles.addTo(this.map);
    
    this.powerPlantService.getAll().subscribe((data: any)=>{
      console.log(data);
      L.geoJSON(data).addTo(this.map) 
    }) 

分析字符串API响应包含geojson featurecollection to Angular,并将其添加为带有传单图上弹出信息的引脚

骄傲 2025-02-06 10:10:44

尝试一下!

const populations = [42000000, 9500000, 3500000, 8400000];

function calculateAverageCountryPopulation(populations) {
  const initialValue = 0;
  return populations.length>0 ? populations.reduce((a, b) => a + b, initialValue) / populations.length:0
};

console.log(calculateAverageCountryPopulation(populations));

Try this !

const populations = [42000000, 9500000, 3500000, 8400000];

function calculateAverageCountryPopulation(populations) {
  const initialValue = 0;
  return populations.length>0 ? populations.reduce((a, b) => a + b, initialValue) / populations.length:0
};

console.log(calculateAverageCountryPopulation(populations));

函数&#x27; calculateaveragecountrypopulation&#x27;应该为空数组工作

骄傲 2025-02-06 06:10:53

由于您需要使用其他连接和操作,因此您需要为每部电影的董事创建一个CTE,然后使用该CTE表代替董事表。

WITH cte
AS (
 SELECT COALESCE(directors.id, d2.id) AS id
  ,COALESCE(directors.name, d2.name) AS name
  ,COALESCE(movies.id, d2.movieid) AS movieid
 FROM movies
 LEFT JOIN directors ON directors.movieid = movies.id
 LEFT JOIN directors d2 ON d2.movieid = 1
 )
SELECT *
FROM movies
LEFT JOIN cte ON cte.movieid = movies.id

带有附加数据的输出:

ID 标题 ID 名称 MovieID
1 矩阵 1 Steve 1
2 Titanic 1 Steve 2
3 Avatar 2 Mark 3
MARK 3 MARK 3 MASS 3 不可能 1 Steve 1 Steve 4

See 此小提琴

如果在 Movieid 字段中,您需要它与董事的表匹配,请在CTE 中添加另一个字段,Cocece(directors.movi​​eid,d2.Movieid)作为dmovieid ,并使用该字段在中,选择语句(但请勿在JOIN中使用它)。例如

Since you need to work with additional joins and operations, you need to create a CTE for directors of each movie and then use that CTE table instead of the directors table.

WITH cte
AS (
 SELECT COALESCE(directors.id, d2.id) AS id
  ,COALESCE(directors.name, d2.name) AS name
  ,COALESCE(movies.id, d2.movieid) AS movieid
 FROM movies
 LEFT JOIN directors ON directors.movieid = movies.id
 LEFT JOIN directors d2 ON d2.movieid = 1
 )
SELECT *
FROM movies
LEFT JOIN cte ON cte.movieid = movies.id

Output with additional data:

id title id name movieid
1 Matrix 1 Steve 1
2 Titanic 1 Steve 2
3 Avatar 2 Mark 3
4 Mission Impossible 1 Steve 4

See this fiddle.

In case in movieid field you require it to match with directors' table, add another field in cte ,COALESCE(directors.movieid, d2.movieid) AS dmovieid and use that in SELECT statement (but don't use it in the join). E.g. here

如何左加入b = c,但是如果加入表为null,请在x上加入(postgres)sql?

骄傲 2025-02-06 00:44:01

我实际上缺少进口,文档没有提及这一点,但是您必须使用

来自selenium.webdriver.support.relative_locator import locate_with

以使用locate_with()

I was in fact missing an import, the documentation doesn't mention this but u have to use

from selenium.webdriver.support.relative_locator import locate_with

to use locate_with()

试图与Python一起使用Selenium中的相对定位器,但是我可以找到&#x27; locate_with&#x27;不是定义错误

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文