尐籹人

文章 评论 浏览 32

尐籹人 2025-02-16 22:38:13

在前面,我认为您只能做摘要(CARS $ speed)以获取想要的东西。

summary(cars$speed)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#     4.0    12.0    15.0    15.4    19.0    25.0 

如果您想要多个列,而 speed 只是一个示例,请尝试以下操作:

cars_summary <- lapply(cars, summary)
cars_summary$speed
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#     4.0    12.0    15.0    15.4    19.0    25.0 

但是,还有其他一些事情正在进行。

  1. 摘要矩阵的列名被缓冲/填充,因此名称似乎以统计数据为中心。这纯粹是美学,但它们确实使捕获有点不可预测(嗯,不容易)。

      cars_summary&lt;  - 摘要(CARS)
    dimnames(cars_summary)
    #[[1]]
    #[1]“”“”“”“”“”“”
    #[[2]]
    #[1]“速度”“ dist”
     
  2. 它是矩阵,因此您不能在其上使用 $ indexing。相反,人们需要使用 [,“ speed”] 或其他。

      cars_summary [,“ speed”]
    #                                                                                                       
    #“最小:4.0”“ 1st Qu.:112.0”“中间:15.0”“平均值:15.4”“ 3rd Qu.:19.0”“ Max。:25.0” 
    
    ###或也许
    colnames(cars_summary)&lt;  - 名称(汽车)
    cars_summary [,“ speed”]
    #                                                                                                       
    #“最小:4.0”“ 1st Qu.:112.0”“中间:15.0”“平均值:15.4”“ 3rd Qu.:19.0”“ Max。:25.0” 
     
  3. hrrmmm,它是一个矩阵,但它是 strings 的矩阵,如上所述:

      ###返回原始cars_summary
    str(cars_summary)
    #'table'chr [1:6,1:2]“ min。:4.0”“ 1st qu.:112.0”“中间:15.0”“平均值:15.4”“” 3rd Qu. :19.0“最大:25.0” ...
    #- attr(*,“ dimnames”)= 2的列表
    #.. $:chr [1:6]“”“”“”“ ...
    #.. $:chr [1:2]“速度”“ dist”
     

    虽然一个 肯定可以使用一些模式或这样提取这些数字,但 是精确/准确性的丧失。

Up front, I think you can do just summary(cars$speed) to get what you want.

summary(cars$speed)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#     4.0    12.0    15.0    15.4    19.0    25.0 

If you will want this for multiple columns, and speed is just one example, then try this:

cars_summary <- lapply(cars, summary)
cars_summary$speed
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#     4.0    12.0    15.0    15.4    19.0    25.0 

However, there are some other things going on.

  1. The column names of the summary matrix are buffered/padded so that the names appear to be centered over the stats. This is purely aesthetic, but they do make it a little unpredictable (well, not-easy) to capture.

    cars_summary <- summary(cars)
    dimnames(cars_summary)
    # [[1]]
    # [1] "" "" "" "" "" ""
    # [[2]]
    # [1] "    speed" "     dist"
    
  2. It's a matrix, so you cannot use $-indexing on it. One would instead need to use [,"speed"] or whatever.

    cars_summary[,"    speed"]
    #                                                                                                       
    # "Min.   : 4.0  " "1st Qu.:12.0  " "Median :15.0  " "Mean   :15.4  " "3rd Qu.:19.0  " "Max.   :25.0  " 
    
    ### or perhaps
    colnames(cars_summary) <- names(cars)
    cars_summary[,"speed"]
    #                                                                                                       
    # "Min.   : 4.0  " "1st Qu.:12.0  " "Median :15.0  " "Mean   :15.4  " "3rd Qu.:19.0  " "Max.   :25.0  " 
    
  3. Hrrmmm, it's a matrix, but it's a matrix of strings, as you can see above and here:

    ### back to the original cars_summary
    str(cars_summary)
    #  'table' chr [1:6, 1:2] "Min.   : 4.0  " "1st Qu.:12.0  " "Median :15.0  " "Mean   :15.4  " "3rd Qu.:19.0  " "Max.   :25.0  " ...
    #  - attr(*, "dimnames")=List of 2
    #   ..$ : chr [1:6] "" "" "" "" ...
    #   ..$ : chr [1:2] "    speed" "     dist"
    

    While one could certainly use some patterns or such to extract those numbers, there will be loss of precision/accuracy.

如何仅访问摘要()输出的特定柱面?

尐籹人 2025-02-16 19:14:49

您可以在父元素上使用网格解决此问题。我们将两个柱子围起来,一个具有 auto (它将一直缩小),第二个具有 1fr 。在动画中,将价值​​的宽度从 fit-content 更改为 100%

body {
  display: grid;
  grid-template-columns: auto 1fr;
}

.typewriter {
  grid-column: 1;
  overflow: hidden;
  white-space: nowrap;
  transition: all 0.3s;
  animation: animated-text 2.5s steps(30, end) 1s 1 normal both;
  border: 1px solid red;
}

@keyframes animated-text {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}
<h1 class="typewriter">Hello Admin</h1>

You can to solve this with a grid on the parent element. We creae two colums, one with auto (it will shrink all the time) the second has 1fr. And in the animation, change width of value from fit-content to 100%.

body {
  display: grid;
  grid-template-columns: auto 1fr;
}

.typewriter {
  grid-column: 1;
  overflow: hidden;
  white-space: nowrap;
  transition: all 0.3s;
  animation: animated-text 2.5s steps(30, end) 1s 1 normal both;
  border: 1px solid red;
}

@keyframes animated-text {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}
<h1 class="typewriter">Hello Admin</h1>

如何处理动画&#x2B;自动容器尺寸

尐籹人 2025-02-16 10:23:34

嘿,我讨论了您失败的交易 https://ropsten.etherscan.io /TX/0X9561B25C1D95D436839D3246D3BBBBBB590D2974BB4BB4FA41A4117A51A75E28553416E

上述表明应该是允许的问题(自有:

enter image description here

Hey, I debuged your failed transaction https://ropsten.etherscan.io/tx/0x9561b25c1d95d436839d3246d3bbb590d2974bb4fa4a4117a51a75e28553416e

The above shows that it should be a permission problem (Ownable: caller is not the owner)

尽管批准了,但仍无法将其归属于农场合同?

尐籹人 2025-02-16 08:36:46

您还可以在服务总线上发布延迟消息(事件)。如果您不使用消息总线系统,则可以应用玉米员系统,并在发布事件(如果已发布事件)中进行跟踪。

You can also publish delayed messages(events) on the service bus. If you don't use a message bus system you can apply a cornjob system and keep track in the aggregate if events have been published.

如何在达到日期时仅创建一次事件?

尐籹人 2025-02-16 07:46:39

显然,您的Expelfile包含一个宏,当您打开Excel工作表时试图打开以下文件:

/Library/Application/Application Support/Adobe/MACPDFM/MacPDF.framework/Versions/A/MacPDFM

当不存在此文件时,您会收到上述错误消息。
看到了目录的结构,我相信只能在MAC计算机上打开Expelfile(Microsoft-Computers没有上述目录结构)。

验证您是否正在使用MAC计算机或Windows-Computer处理,并且在MAC中,请检查提到的文件的存在(和读取权限)。

Apparently your Excelfile contains a macro, who tries to open the following file when you open an Excel worksheet:

/Library/Application/Application Support/Adobe/MACPDFM/MacPDF.framework/Versions/A/MacPDFM

When this file is not present, you get the mentioned error message.
Seen the structure of the directory, I believe the Excelfile only can be opened on a Mac-computer (Microsoft-computers don't have the mentioned directory structure).

Verify if you're working on a Mac-computer or a Windows-computer and in case of Mac, check the presence (and read permissions) of the mentioned file.

如何在没有VBA错误消息的情况下打开我的Excel表?

尐籹人 2025-02-15 23:02:27

希望这是您要寻找的解决方案。

df=pd.DataFrame({'ID': [1,2],
                 'User A': ['titi', 'tata'],
                 'ROLES1': ['Reader', 'Manage'],
                 'Rights': [['a','b','d'], ['b','f','g']],
                 'SOME INFO': ['blalbalbla', 'blalbalbla'],
                 'USER B': ['tutu', 'toto'],
                 'ROLES2': ['writer', 'reader'],
                 'RIGHTS': [['c','d','f','a'], ['a','b','d']]})

df['diff'] = df.apply(lambda x: list(set(x['Rights']) - set(x['RIGHTS'])), axis = 1)

print(df)

Hope this is the solution you are looking for.

df=pd.DataFrame({'ID': [1,2],
                 'User A': ['titi', 'tata'],
                 'ROLES1': ['Reader', 'Manage'],
                 'Rights': [['a','b','d'], ['b','f','g']],
                 'SOME INFO': ['blalbalbla', 'blalbalbla'],
                 'USER B': ['tutu', 'toto'],
                 'ROLES2': ['writer', 'reader'],
                 'RIGHTS': [['c','d','f','a'], ['a','b','d']]})

df['diff'] = df.apply(lambda x: list(set(x['Rights']) - set(x['RIGHTS'])), axis = 1)

print(df)

将两个列与文字列表进行比较,并突出显示数据框架的差异

尐籹人 2025-02-15 22:27:48

我想你需要这样的东西。 GIF是图像文件类型,因此您必须保存它才能拥有一个。

#! /usr/bin/env python3

import numpy as np
from PIL import Image


im = []
for n in range(20):
    arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
    im.append(Image.fromarray(arr.astype('uint8')))

im[0].save('im.gif', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
#im[0].show()

然后使用浏览器或一些可以显示动画gif的应用程序打开 im.gif

如果您真的不想保存GIF,而只是显示它,您可以做这样的事情

#! /usr/bin/env python3
import base64
import io
import numpy as np
from PIL import Image
from viaduc import Viaduc


im = []
for n in range(20):
    arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
    im.append(Image.fromarray(arr.astype('uint8')))


buffer = io.BytesIO()
im[0].save(buffer, format='GIF', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
buffer.seek(0)
data_uri = base64.b64encode(buffer.read()).decode('ascii')



class Presentation(Viaduc.Presentation):
    width = 300
    height = 300
    title = 'gif'
    html = '''
<!DOCTYPE html>
  <head>
    {{bootstrap_meta}} {{bootstrap_css}}
    <title>{{title}}</title>
  </head>
  <body>
    <img src="data:image/gif;base64,''' + data_uri + '''">
    {{bootstrap_js}}
  </body>  
 </html>
'''


if __name__ == '__main__':
    Viaduc(presentation=Presentation())

I guess you need something like this. GIF is an image file type so you have to save it to have one.

#! /usr/bin/env python3

import numpy as np
from PIL import Image


im = []
for n in range(20):
    arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
    im.append(Image.fromarray(arr.astype('uint8')))

im[0].save('im.gif', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
#im[0].show()

Then open im.gif with a browser or some app that can show animated GIFs.

If you really don't want to save the GIF but just show it, you can do something like this

#! /usr/bin/env python3
import base64
import io
import numpy as np
from PIL import Image
from viaduc import Viaduc


im = []
for n in range(20):
    arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
    im.append(Image.fromarray(arr.astype('uint8')))


buffer = io.BytesIO()
im[0].save(buffer, format='GIF', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
buffer.seek(0)
data_uri = base64.b64encode(buffer.read()).decode('ascii')



class Presentation(Viaduc.Presentation):
    width = 300
    height = 300
    title = 'gif'
    html = '''
<!DOCTYPE html>
  <head>
    {{bootstrap_meta}} {{bootstrap_css}}
    <title>{{title}}</title>
  </head>
  <body>
    <img src="data:image/gif;base64,''' + data_uri + '''">
    {{bootstrap_js}}
  </body>  
 </html>
'''


if __name__ == '__main__':
    Viaduc(presentation=Presentation())

如何在不保存/导入图像文件的情况下生成GIF?

尐籹人 2025-02-15 20:26:14

pandas.series 转换为简单的python列表并摆脱一些额外的材料将解决问题

class PDFsDataset(torch.utils.data.Dataset):
    def __init__(self, encodings, labels):
        self.encodings = encodings
        self.labels = labels

    def __getitem__(self, idx):
        item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
        item['labels'] = torch.tensor(self.labels[idx])
        return item

    def __len__(self):
        return len(self.labels)

class HFTransformer:
    def __init__ (self):
        pass

    def import_from_json(self):
        #Prompts user to select json file
        self.json_file_path = '/content/truncated_data.json'
        #opens json file and loads data
        with open(self.json_file_path, "r") as json_file:
                try:
                    json_load = json.load(json_file)
                except:
                    raise ValueError("No PDFs to convert to JSON")
        self.pdfs = json_load
        #converts json file data to dataframe for easier manipulation
        self.pdfs = pd.DataFrame.from_dict(self.pdfs)

        for index in range(len(self.pdfs["new_tags"])):
            if self.pdfs["new_tags"][index] == "":
                self.pdfs["new_tags"][index] = self.pdfs["most_similar_label"][index]

        self.pdfs["labels"] = self.pdfs["new_tags"].apply(lambda val: self.change_tag_to_num(val))
        # for label in self.data["labels"]:
     
    def change_tag_to_num(self, value):
        if value == "Quantum":
            return 0
        elif value == "Artificial intelligence":
            return 1
        elif value == "Materials":
            return 2
        elif value == "Energy":
            return 3
        elif value == "Defense":
            return 4
        elif value == "Satellite":
            return 5
        elif value == "Other":
            return 6

    def tokenize_dataset(self):
        tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")

        X_train, X_test, y_train, y_test = train_test_split(self.pdfs["text_clean"].to_list(), self.pdfs["labels"].to_list(),test_size=0.2)
        train_encodings = tokenizer(X_train, truncation=True, padding=True,max_length=100)
        test_encodings = tokenizer(X_test, truncation=True, padding=True,max_length=100)
        self.train_dataset = PDFsDataset(train_encodings, y_train)
    
        self.eval_dataset = PDFsDataset(test_encodings,y_test)
    
    def train_transformer(self):
        model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=7)
        training_args = TrainingArguments(output_dir="test_trainer")
        self.metric = load_metric("accuracy")
        training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch", )
    
        trainer = Trainer(
            model=model,
            args=training_args,
            train_dataset=self.train_dataset,
            eval_dataset=self.eval_dataset,
            compute_metrics=self.compute_metrics
        )
        trainer.train()
    def compute_metrics(self, eval_pred):
        logits, labels = eval_pred
        predictions = np.argmax(logits, axis=-1)
        return self.metric.compute(predictions=predictions, references=labels)


if __name__  == "__main__":
    tr = HFTransformer()
    tr.import_from_json()
    tr.tokenize_dataset()
    tr.train_transformer()

Converting pandas.Series into a simple python list and getting rid of some extra materials would fix the issue

class PDFsDataset(torch.utils.data.Dataset):
    def __init__(self, encodings, labels):
        self.encodings = encodings
        self.labels = labels

    def __getitem__(self, idx):
        item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
        item['labels'] = torch.tensor(self.labels[idx])
        return item

    def __len__(self):
        return len(self.labels)

class HFTransformer:
    def __init__ (self):
        pass

    def import_from_json(self):
        #Prompts user to select json file
        self.json_file_path = '/content/truncated_data.json'
        #opens json file and loads data
        with open(self.json_file_path, "r") as json_file:
                try:
                    json_load = json.load(json_file)
                except:
                    raise ValueError("No PDFs to convert to JSON")
        self.pdfs = json_load
        #converts json file data to dataframe for easier manipulation
        self.pdfs = pd.DataFrame.from_dict(self.pdfs)

        for index in range(len(self.pdfs["new_tags"])):
            if self.pdfs["new_tags"][index] == "":
                self.pdfs["new_tags"][index] = self.pdfs["most_similar_label"][index]

        self.pdfs["labels"] = self.pdfs["new_tags"].apply(lambda val: self.change_tag_to_num(val))
        # for label in self.data["labels"]:
     
    def change_tag_to_num(self, value):
        if value == "Quantum":
            return 0
        elif value == "Artificial intelligence":
            return 1
        elif value == "Materials":
            return 2
        elif value == "Energy":
            return 3
        elif value == "Defense":
            return 4
        elif value == "Satellite":
            return 5
        elif value == "Other":
            return 6

    def tokenize_dataset(self):
        tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")

        X_train, X_test, y_train, y_test = train_test_split(self.pdfs["text_clean"].to_list(), self.pdfs["labels"].to_list(),test_size=0.2)
        train_encodings = tokenizer(X_train, truncation=True, padding=True,max_length=100)
        test_encodings = tokenizer(X_test, truncation=True, padding=True,max_length=100)
        self.train_dataset = PDFsDataset(train_encodings, y_train)
    
        self.eval_dataset = PDFsDataset(test_encodings,y_test)
    
    def train_transformer(self):
        model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=7)
        training_args = TrainingArguments(output_dir="test_trainer")
        self.metric = load_metric("accuracy")
        training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch", )
    
        trainer = Trainer(
            model=model,
            args=training_args,
            train_dataset=self.train_dataset,
            eval_dataset=self.eval_dataset,
            compute_metrics=self.compute_metrics
        )
        trainer.train()
    def compute_metrics(self, eval_pred):
        logits, labels = eval_pred
        predictions = np.argmax(logits, axis=-1)
        return self.metric.compute(predictions=predictions, references=labels)


if __name__  == "__main__":
    tr = HFTransformer()
    tr.import_from_json()
    tr.tokenize_dataset()
    tr.train_transformer()

在训练拥抱脸型变压器时获得钥匙架

尐籹人 2025-02-14 23:00:21

这对我有用,尽管更新您的代码以类似于 docs

        try{
            cashAppPay.attach('#cash-app-pay', buttonOptions);
        } catch (e) {
            console.log("Initialize error",e)
            //get the exact message and match it to the if statement
            //the exact error i got when trying to update the amount before destroying was as per my .match() in the if statement below
            console.log(e.message)
            const error_msg = e.message
            if(error_msg.match('already rendered')){
                await cashAppPay.destroy();
                await cashAppPay.attach('#cash-app-pay', buttonOptions);
            }
    }

基本上,您要销毁先前的QR码,并在升级金额值或任何所需选项时附加新的QR码。我只放置了正确的代码,以适合您的代码,如果您使用异步,请根据文档等待。然后,物品的写作和筑巢往往过多

。希望您找到比我的更好的解决方案。

This worked for me although update your code to resemble the docs

        try{
            cashAppPay.attach('#cash-app-pay', buttonOptions);
        } catch (e) {
            console.log("Initialize error",e)
            //get the exact message and match it to the if statement
            //the exact error i got when trying to update the amount before destroying was as per my .match() in the if statement below
            console.log(e.message)
            const error_msg = e.message
            if(error_msg.match('already rendered')){
                await cashAppPay.destroy();
                await cashAppPay.attach('#cash-app-pay', buttonOptions);
            }
    }

basically you are to destroy the previous qr code and attach a new one when upating the amount value or any of its required options. I've only placed the correct code to try suit your code if you use async await as per the docs. Thenables tend to be too much writing and nesting

Good luck. Hope you find a better solution than mine.

无法更新Square Cash应用中的总价值

尐籹人 2025-02-14 21:18:24

根据“颤音”文档,widgetsbindingobserver类是用于注册小部件层绑定的类的接口。

您可以检查此链接以获取更多信息 nofollow noreferrer“> widegetsbindingobserver class

According to the flutter documentation the WidgetsBindingObserver class is an Interface for classes that register with the Widgets layer binding.

you can check this link for more info WidgetsBindingObserver class

在这种情况下,小部件绑定的用途是什么?

尐籹人 2025-02-14 16:21:16

您的问题是,在 中,mysql是 选择Sleep(5); ,而在 sql中是 等待延迟(5); 这就是为什么它不起作用的原因。

SET GLOBAL max_execution_time = 4;
SELECT SLEEP(5);

示例:

Your problem is that in mysql is SELECT SLEEP(5); while in sql is WAITFOR DELAY (5); that's why it doesn't work.

SET GLOBAL max_execution_time = 4;
SELECT SLEEP(5);

Example : https://www.db-fiddle.com/f/3PnzHErrf2fZFGZY67K12X/440

如何在mySQL中删除默认超时持续时间

尐籹人 2025-02-14 15:40:02

从测试您的程序,您在重试的用户/密码条目中的问题是,您不会将计数器“ I”重置为零。因此,您的程序只是不断将输入的字符添加到字符数组的末尾。当我添加一些代码以重新初始化密码字符数组并在代码行中添加以将“ i”的值重置为零,则该验证在重试时可行。

for (int j = 0; j < 100; j++)
{
    password[j] = 0; /* This might be overkill, but this ensures that the character array does not have leftover characters */
}

i = 0;

printf("\nPassword: ");
    do
    {
        password[i] = getch();
        printf("*");
        i++;
    }
    while(password[i-1] != '\r');

这是进行这些修订后终端输出的样本。

Incorrect Username or Password!
Please enter your username: username

Password: *********
Welcome to the POS!
*Placeholder*

希望能阐明事情。

问候。

From testing out your program, your issue on the retries for user/password entry is that you do not reset the counter "i" back to zero. Therefore, your program just keeps on adding the entered characters to the end of the character array. When I added some code in to reinitialize the password character array and added in the line of code to reset the value of "i" to zero, the validation worked on the retry.

for (int j = 0; j < 100; j++)
{
    password[j] = 0; /* This might be overkill, but this ensures that the character array does not have leftover characters */
}

i = 0;

printf("\nPassword: ");
    do
    {
        password[i] = getch();
        printf("*");
        i++;
    }
    while(password[i-1] != '\r');

Here is a sample of the terminal output after making those revisions.

Incorrect Username or Password!
Please enter your username: username

Password: *********
Welcome to the POS!
*Placeholder*

Hope that clarifies things.

Regards.

在重新提出用户重试的用户后,程序不接受正确的用户名和密码

尐籹人 2025-02-14 07:44:25

在您的表观视图中,将ContentInsetAdjustmentBehavior在Controller中不在

tableView.contentInsetAdjustmentBehavior = .never

控制器中,再次更新导航栏UI

  override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        DispatchQueue.main.async { [weak self] in
            self?.navigationController?.navigationBar.sizeToFit()
        }
       
    }

,这是导航控制器

class BaseNavigationController: UINavigationController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 15.0, *) {
            let scrollAppearance = UINavigationBarAppearance()
            scrollAppearance.shadowColor = .white
            scrollAppearance.backgroundColor = .white
            let navigationBarAppearance = UINavigationBarAppearance()
            navigationBarAppearance.configureWithDefaultBackground()
            navigationBarAppearance.backgroundColor = .white
            navigationBarAppearance.largeTitleTextAttributes = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26),
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            navigationBarAppearance.titleTextAttributes = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            UINavigationBar.appearance().backIndicatorImage = UIImage(named: "back-arrow")
            UINavigationBar.appearance().standardAppearance = navigationBarAppearance
            UINavigationBar.appearance().compactAppearance = navigationBarAppearance
            UINavigationBar.appearance().scrollEdgeAppearance = scrollAppearance
            navigationBar.tintColor = .black
            navigationBar.prefersLargeTitles = true
            navigationBar.isTranslucent = false
            navigationItem.largeTitleDisplayMode = .automatic
        } else {
            navigationBar.largeTitleTextAttributes = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26),
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            navigationBar.titleTextAttributes = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            navigationBar.tintColor = .black
            navigationBar.prefersLargeTitles = true
            navigationBar.isTranslucent = false
            navigationItem.largeTitleDisplayMode = .automatic
            navigationBar.barTintColor = .white
        }
        
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .darkContent
    }

    
}

,这是Tabbar Controller

class TabbarController:UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let c1 = C1()
        let c2 = C2()
        let c3 = C3()
        
        c1.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named:  "home786"), tag: 0)
        c1.tabBarItem.tag = 0
        let nav1 = BaseNavigationController(rootViewController: c1)
        
        c2.tabBarItem = UITabBarItem(title: "Setting", image: UIImage(named:  "home786"), tag: 0)
        c2.tabBarItem.tag = 1
        let nav2 = BaseNavigationController(rootViewController: c2)
        c2.tabBarItem = UITabBarItem(title: "User", image: UIImage(named:  "home786"), tag: 0)
        c2.tabBarItem.tag = 2
        let nav3 = BaseNavigationController(rootViewController: c3)
        viewControllers = [nav1,nav2,nav3]
        selectedViewController = nav1
        tabBarController?.viewControllers?.first?.view.backgroundColor = .red
        
    }
}

in your tableView set contentInsetAdjustmentBehavior to never

tableView.contentInsetAdjustmentBehavior = .never

in controller update the ui of navigation bar again

  override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        DispatchQueue.main.async { [weak self] in
            self?.navigationController?.navigationBar.sizeToFit()
        }
       
    }

here is the navigation controller

class BaseNavigationController: UINavigationController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 15.0, *) {
            let scrollAppearance = UINavigationBarAppearance()
            scrollAppearance.shadowColor = .white
            scrollAppearance.backgroundColor = .white
            let navigationBarAppearance = UINavigationBarAppearance()
            navigationBarAppearance.configureWithDefaultBackground()
            navigationBarAppearance.backgroundColor = .white
            navigationBarAppearance.largeTitleTextAttributes = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26),
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            navigationBarAppearance.titleTextAttributes = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            UINavigationBar.appearance().backIndicatorImage = UIImage(named: "back-arrow")
            UINavigationBar.appearance().standardAppearance = navigationBarAppearance
            UINavigationBar.appearance().compactAppearance = navigationBarAppearance
            UINavigationBar.appearance().scrollEdgeAppearance = scrollAppearance
            navigationBar.tintColor = .black
            navigationBar.prefersLargeTitles = true
            navigationBar.isTranslucent = false
            navigationItem.largeTitleDisplayMode = .automatic
        } else {
            navigationBar.largeTitleTextAttributes = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26),
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            navigationBar.titleTextAttributes = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
                NSAttributedString.Key.foregroundColor: UIColor.black
            ]
            navigationBar.tintColor = .black
            navigationBar.prefersLargeTitles = true
            navigationBar.isTranslucent = false
            navigationItem.largeTitleDisplayMode = .automatic
            navigationBar.barTintColor = .white
        }
        
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .darkContent
    }

    
}

here is the Tabbar Controller

class TabbarController:UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let c1 = C1()
        let c2 = C2()
        let c3 = C3()
        
        c1.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named:  "home786"), tag: 0)
        c1.tabBarItem.tag = 0
        let nav1 = BaseNavigationController(rootViewController: c1)
        
        c2.tabBarItem = UITabBarItem(title: "Setting", image: UIImage(named:  "home786"), tag: 0)
        c2.tabBarItem.tag = 1
        let nav2 = BaseNavigationController(rootViewController: c2)
        c2.tabBarItem = UITabBarItem(title: "User", image: UIImage(named:  "home786"), tag: 0)
        c2.tabBarItem.tag = 2
        let nav3 = BaseNavigationController(rootViewController: c3)
        viewControllers = [nav1,nav2,nav3]
        selectedViewController = nav1
        tabBarController?.viewControllers?.first?.view.backgroundColor = .red
        
    }
}

uinavigationbar大标题当滚动查看时不会出现

尐籹人 2025-02-14 06:10:18

如果您只想在迭代顺序中的第一个元素,无论发生什么事,

first = next(iter(obj))

请提高 stopiteration 如果 obj 是空的,否则它将获得您的第一个项目从 obj 迭代。至少很便宜;在 o(1)时间内运行,因此即使 obj 中有100万个项目,它也会快速运行(其中 list(obj)[0] < /代码>对于越来越长的 obj )。

需要清楚, set s具有任意顺序;即使您第一次运行此代码,也会产生'execute',也无法保证 set 具有相同的内容,以不同的顺序构造或> SET 在程序的不同运行中以相同的方式构造,将以相同的顺序迭代。 next(iter(obj))正在为您提供有效的任意元素,除了在此 set set set set 元素>以这种特定的方式构建,在程序的这种特定运行中。

If you just want the first element in iteration order, whatever that happens to be, do:

first = next(iter(obj))

That'll raise StopIteration if obj is empty, otherwise it gets the first item you'd iterate over from obj. It's cheap at least; running in O(1) time, so even if obj has a million items in it, it will run quickly (where list(obj)[0] will take longer and longer for bigger and bigger obj).

To be clear, sets have arbitrary order; even if the first time you run this code it produces 'Execute', there's no guarantee a set with the same contents, constructed in a different order, or a set constructed the same way in a different run of the program, will iterate in the same order. next(iter(obj)) is getting you an effectively arbitrary element, it has no meaning beyond being arbitrarily first in the iteration order for this set, built in this specific way, in this specific run of the program.

如何在列表中获取第一个值

尐籹人 2025-02-13 08:43:39

httpresponse.redirecttoroute方法通过使用路由参数值,路由名称或两者都将请求重定向到新URL,这意味着您无法继续使用最后一个url

httpresponse.redirecttoroute方法

但是您可以从其他动作结果中返回值,

var result = await controller.GetTodosAsync();

以便您可以使用类似的结果。这 :

        [HttpGet(Name = "Profile")]
        public async Task<string> GetProfile(string username)
        {
           return await Task.Run(()=> "hello") ;
        }

        [HttpPost(Name = "Profile")]
        public async Task<string> PostProfile(string username)
        {
            string result = await this.GetProfile(username);

            result = result + " from post";
            return await Task.Run(() => result);
        }

HttpResponse.RedirectToRoute Method Redirects a request to a new URL by using route parameter values, a route name, or both this means that you cannot continue with the last URL

HttpResponse.RedirectToRoute Method

but you can return value from another action result like

var result = await controller.GetTodosAsync();

so you can use like this :

        [HttpGet(Name = "Profile")]
        public async Task<string> GetProfile(string username)
        {
           return await Task.Run(()=> "hello") ;
        }

        [HttpPost(Name = "Profile")]
        public async Task<string> PostProfile(string username)
        {
            string result = await this.GetProfile(username);

            result = result + " from post";
            return await Task.Run(() => result);
        }

获取ASP.NET核心的路线结果

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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