问:
T3PO3 v10: How to use RouteEnhancer with ArrayPaginator?
I'm using the ArrayPaginator for my Extbase list view, since Fluid widget functionality will no longer be available in TYPO3 v11.

And I'm currently trying to use the RouteEnhancer with this.

My list action just receives the argument for the current page as integer.

And the code for the RouteEnhancer looks like this:

```<code>  RefList:
    type: Extbase
    limitToPages:
      - 142
    extension: Ref
    plugin: Pi2
    routes:
      -
        routePath: /seite-{page}
        _controller: 'Ref::list'
        _arguments:
          page: currentPage
    defaultController: 'Ref::list'
    requirements:
      page: \d+
    aspects:
      page:
        type: StaticRangeMapper
        start: '1'
        end: '1000'
</code>```

I've seen a lot examples for the Fluid pagination widget that contained the value @widget_0/currentPage for the argument page.

The URL is generated correctly if I switch to another page but the content displayed from the list view is still the same as on page 1.

What am I missing here?

答:
You can us a QueryResultPaginator instead of a ArrayPaginator.

Route

```<code>routeEnhancers:
  RefList:
    type: Extbase
    extension: Ref
    plugin: Pi2
    routes:
      - routePath: '/'
        _controller: 'Ref::list'
      - routePath: '/{page}'
        _controller: 'Ref::list'
        _arguments:
          page: current-page
    defaultController: 'Ref::list'
    aspects:
      current-page:
        type: StaticRangeMapper
        start: '1'
        end: '100'
</code>```

RefController.php Get current-page from request

```<code>public function listAction()
{
    $refs = $this->refRepository->findAll();

    $currentPage = $this->request->hasArgument('current-page') ? $this->request->getArgument('current-page') : 1;
    $paginatedRefs = new QueryResultPaginator($refs, $currentPage, $this->itemsPerPage);
    $simplePagination = new SimplePagination($paginatedRefs);
    $pagination = $this->buildSimplePagination($simplePagination, $paginatedRefs);

    $this->view->assignMultiple([
        'refs' => $paginatedRefs,
        'pagination' => $pagination,
    ]);
}

/**
 * Build simple pagination
 *
 * @param SimplePagination $simplePagination
 * @param QueryResultPaginator $paginator
 * @return array
 */
protected function buildSimplePagination(SimplePagination $simplePagination, QueryResultPaginator $paginator): array
{
    $firstPage = $simplePagination->getFirstPageNumber();
    $lastPage = $simplePagination->getLastPageNumber();
    return [
        'lastPageNumber' => $lastPage,
        'firstPageNumber' => $firstPage,
        'nextPageNumber' => $simplePagination->getNextPageNumber(),
        'previousPageNumber' => $simplePagination->getPreviousPageNumber(),
        'startRecordNumber' => $simplePagination->getStartRecordNumber(),
        'endRecordNumber' => $simplePagination->getEndRecordNumber(),
        'currentPageNumber' => $paginator->getCurrentPageNumber(),
        'pages' => range($firstPage, $lastPage)
    ];
}
</code>```

List.html add pagination template

```<code><f:for each="{refs.paginatedItems}" as="ref">
    <f:render partial="List/ListItem" arguments="{ref: ref}" />
</f:for>
<f:render partial="List/Pagination" arguments="{pagination:pagination, action:'list'}" />
</code>```

Partial List/Pagination.html

add links for pagination: previous

```<code><f:link.action action="{action}" arguments="{current-page:pagination.previousPageNumber}">previous</f:link.action>
</code>```

add links for pagination: pages

```<code><f:link.action action="{action}" arguments="{current-page:page}">{page}</f:link.action>
</code>```

add links for pagination: next

```<code><f:link.action action="{action}" arguments="{current-page: pagination.nextPageNumber}">next</f:link.action>
</code>```

Body:
I'm using the ArrayPaginator for my Extbase list view, since Fluid widget functionality will no longer be available in TYPO3 v11.

And I'm currently trying to use the RouteEnhancer with this.

My list action just receives the argument for the current page as integer.

And the code for the RouteEnhancer looks like this:

  RefList:
    type: Extbase
    limitToPages:
      - 142
    extension: Ref
    plugin: Pi2
    routes:
      -
        routePath: /seite-{page}
        _controller: 'Ref::list'
        _arguments:
          page: currentPage
    defaultController: 'Ref::list'
    requirements:
      page: \d+
    aspects:
      page:
        type: StaticRangeMapper
        start: '1'
        end: '1000'

I've seen a lot examples for the Fluid pagination widget that contained the value @widget_0/currentPage for the argument page.

The URL is generated correctly if I switch to another page but the content displayed from the list view is still the same as on page 1.

What am I missing here?

Body:
You can us a QueryResultPaginator instead of a ArrayPaginator.

Route

routeEnhancers:
  RefList:
    type: Extbase
    extension: Ref
    plugin: Pi2
    routes:
      - routePath: '/'
        _controller: 'Ref::list'
      - routePath: '/{page}'
        _controller: 'Ref::list'
        _arguments:
          page: current-page
    defaultController: 'Ref::list'
    aspects:
      current-page:
        type: StaticRangeMapper
        start: '1'
        end: '100'

RefController.php Get current-page from request

public function listAction()
{
    $refs = $this->refRepository->findAll();

    $currentPage = $this->request->hasArgument('current-page') ? $this->request->getArgument('current-page') : 1;
    $paginatedRefs = new QueryResultPaginator($refs, $currentPage, $this->itemsPerPage);
    $simplePagination = new SimplePagination($paginatedRefs);
    $pagination = $this->buildSimplePagination($simplePagination, $paginatedRefs);

    $this->view->assignMultiple([
        'refs' => $paginatedRefs,
        'pagination' => $pagination,
    ]);
}

/**
 * Build simple pagination
 *
 * @param SimplePagination $simplePagination
 * @param QueryResultPaginator $paginator
 * @return array
 */
protected function buildSimplePagination(SimplePagination $simplePagination, QueryResultPaginator $paginator): array
{
    $firstPage = $simplePagination->getFirstPageNumber();
    $lastPage = $simplePagination->getLastPageNumber();
    return [
        'lastPageNumber' => $lastPage,
        'firstPageNumber' => $firstPage,
        'nextPageNumber' => $simplePagination->getNextPageNumber(),
        'previousPageNumber' => $simplePagination->getPreviousPageNumber(),
        'startRecordNumber' => $simplePagination->getStartRecordNumber(),
        'endRecordNumber' => $simplePagination->getEndRecordNumber(),
        'currentPageNumber' => $paginator->getCurrentPageNumber(),
        'pages' => range($firstPage, $lastPage)
    ];
}

List.html add pagination template

<f:for each="{refs.paginatedItems}" as="ref">
    <f:render partial="List/ListItem" arguments="{ref: ref}" />
</f:for>
<f:render partial="List/Pagination" arguments="{pagination:pagination, action:'list'}" />

Partial List/Pagination.html

add links for pagination: previous

<f:link.action action="{action}" arguments="{current-page:pagination.previousPageNumber}">previous</f:link.action>

add links for pagination: pages

<f:link.action action="{action}" arguments="{current-page:page}">{page}</f:link.action>

add links for pagination: next

<f:link.action action="{action}" arguments="{current-page: pagination.nextPageNumber}">next</f:link.action>


来源: stackexchange

问:
Best practices for building a chat app? (REST vs Websockets)
As the title suggests, I'm building a simple chat app in Node/Express + React, and I'm using socket.io to get real time updates.

However, other than the chatting itself, rest of my app is very basic (registering, signing in, creating rooms etc), and while it's definitely doable to make all those requests just socket emits, it feels like bit of an overkill.

So I was thinking of creating a regular REST API for that stuff and outsourcing it into a separate file, then creating another file just for the chatting function itself, where I'd use socket.io, but I'm afraid that it may seem a bit unprofessional, or leave an impression that I don't know how to use sockets well enough.

Key point: When finished, this app will be posted to my portfolio, so I'm not very concerned about what just "can work", but rather what's the best and cleanest way to do it? Should I switch everything to sockets and use them even for basic fetching of lists and stuff? Or is it better practice to mix the two, and use REST for, well, the rest?

答:
In my experience, To mix the two is the best way to do that.
I did that in many projects and it worked well.
I surely think that modularity is the best way to make code clean and qualified.
So, to use both of regular REST API and websocket is more professional.
Thank you.</p>

ContentLicense: CC BY-SA 4.0


问:
Different ways to add functions to Javascript object
In Javascript is there any difference between these two ways of adding a function to an object?  Is one preferable for any reason?  </p>

```<code>function ObjA() {
    this.AlertA = function() { alert("A"); };
}
ObjA.prototype.AlertB = function() { alert("B"); };

var A = new ObjA();
A.AlertA();
A.AlertB();
</code>```

答: Using the object constructor will assign a copy of that function to every new instance of your object.  Using prototyping will result in one function being shared across all instances.</p>

ContentLicense: CC BY-SA 3.0

Body:
In Javascript is there any difference between these two ways of adding a function to an object?  Is one preferable for any reason?

function ObjA() {
    this.AlertA = function() { alert("A"); };
}
ObjA.prototype.AlertB = function() { alert("B"); };

var A = new ObjA();
A.AlertA();
A.AlertB();


问:
Convert "enquireScreen" js written for jsx to typescript?
Currently, I am trying to learn typescript through ionic react by creating simple webpages. I came across this interesting navigation bar but it is written in jsx. Hence, I want to write in tsx with the help of this website.

Code in jsx

```<code>import { enquireScreen } from 'enquire-js';

let isMobile;

enquireScreen((b) => {
  isMobile = b;
});

class Home extends React.PureComponent {
  state = {
    isMobile,
  }
  componentDidMount() {
    enquireScreen((b) => {
      this.setState({
        isMobile: !!b,
      });
    });
  }
</code>```

How do I write this in typescript? I have tried changing stuff like the declaration of the variable but could not get it to work. Thanks.

答:
This works for me.

Create a new file name enquire-js.d.ts (I just put in on the root of the project)

```<code>declare module 'enquire-js' {
  var enquireJs: {
    enquireScreen: {
      cb: unknown,
      query?: string
    }
  }

  export = enquireJs
}
</code>```

The warning goes away and compile without error.

(BTW, I am using enquire-js with next.js and antd)

Body:
Currently, I am trying to learn typescript through ionic react by creating simple webpages. I came across this interesting navigation bar but it is written in jsx. Hence, I want to write in tsx with the help of this website.

Code in jsx

import { enquireScreen } from 'enquire-js';

let isMobile;

enquireScreen((b) => {
  isMobile = b;
});

class Home extends React.PureComponent {
  state = {
    isMobile,
  }
  componentDidMount() {
    enquireScreen((b) => {
      this.setState({
        isMobile: !!b,
      });
    });
  }

How do I write this in typescript? I have tried changing stuff like the declaration of the variable but could not get it to work. Thanks.

Body:
This works for me.

Create a new file name enquire-js.d.ts (I just put in on the root of the project)

declare module 'enquire-js' {
  var enquireJs: {
    enquireScreen: {
      cb: unknown,
      query?: string
    }
  }

  export = enquireJs
}

The warning goes away and compile without error.

(BTW, I am using enquire-js with next.js and antd)


问:
Is there a way to render files from a MySQL database into a website?
I'm tasked to build a web document management system where files (PDFs, and perhaps images) will be uploaded and viewed later in the website. Currently what I have is the upload goes into MySQl workbench, in a longblob data type field.

I want to render the files on the webpage somewhat like research journal websites that have a PDF viewer of some sort in their pages.

I tried selecting the File value off the database table, and placing it in iframe's src attribute but it does not do anything. Though iframe does render the file if given a file address on my computer.

答: The src attribute contains an URL, not file content. You should make the src attribute name an URL that calls a code handler. Then develop the code for that handler, which loads the content from the database and returns it as the response, after setting the response header for "Content-Type: application/pdf".</p>


问:
Setting up firebase notifications
So I've been working on setting up firebase notifications using cloud messaging and I've run into a problem. I've been following this tutorial, so if I did anything else wrong, which hopefully I didn't, please let me know. I've also been looking at this one.

Here's my AppDelegate code, which is the spot in which they told me to put all the stuff. I also did the certificate stuff, and hopefully, that works fine:

```<code>
import UIKit
import Firebase
import FirebaseMessaging

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions
      launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
  ) -> Bool {

      FirebaseApp.configure()
      // 2
      FirebaseConfiguration.shared.setLoggerLevel(.min)

      UNUserNotificationCenter.current().delegate = self
      // 2
      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions) { _, _ in }
      // 3
      application.registerForRemoteNotifications()

      Messaging.messaging().delegate = self //Here is one of the problems
    return true
  }
}

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

extension AppDelegate: UNUserNotificationCenterDelegate {
  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler:
    @escaping (UNNotificationPresentationOptions) -> Void
  ) {
    completionHandler([[.banner, .sound]])
  }

  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
  ) {
    completionHandler()
  }
}

func application(
  _ application: UIApplication,
  didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
  Messaging.messaging().apnsToken = deviceToken //Here's the other problem
}

extension AppDelegate: MessagingDelegate {
  func messaging(
    _ messaging: Messaging,
    didReceiveRegistrationToken fcmToken: String?
  ) {
    let tokenDict = ["token": fcmToken ?? ""]
    NotificationCenter.default.post(
      name: Notification.Name("FCMToken"),
      object: nil,
      userInfo: tokenDict)
  }
}
</code>```

The problem:

```<code>Type 'Messaging' has no member 'messaging'
</code>```

答:
Yay. I found the solution. Pretty simple actually. I accidentally had a swift view in my app named Messaging which was throwing off the syntax.

If you're having this problem. Make sure nothing in your project is named Messaging.

Title: Setting up firebase notifications

Body:
So I've been working on setting up firebase notifications using cloud messaging and I've run into a problem. I've been following this tutorial, so if I did anything else wrong, which hopefully I didn't, please let me know. I've also been looking at this one.

Here's my AppDelegate code, which is the spot in which they told me to put all the stuff. I also did the certificate stuff, and hopefully, that works fine:

import UIKit
import Firebase
import FirebaseMessaging

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions
      launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
  ) -> Bool {

      FirebaseApp.configure()
      // 2
      FirebaseConfiguration.shared.setLoggerLevel(.min)

      UNUserNotificationCenter.current().delegate = self
      // 2
      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions) { _, _ in }
      // 3
      application.registerForRemoteNotifications()

      Messaging.messaging().delegate = self //Here is one of the problems
    return true
  }
}

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

extension AppDelegate: UNUserNotificationCenterDelegate {
  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler:
    @escaping (UNNotificationPresentationOptions) -> Void
  ) {
    completionHandler([[.banner, .sound]])
  }

  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
  ) {
    completionHandler()
  }
}

func application(
  _ application: UIApplication,
  didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
  Messaging.messaging().apnsToken = deviceToken //Here's the other problem
}

extension AppDelegate: MessagingDelegate {
  func messaging(
    _ messaging: Messaging,
    didReceiveRegistrationToken fcmToken: String?
  ) {
    let tokenDict = ["token": fcmToken ?? ""]
    NotificationCenter.default.post(
      name: Notification.Name("FCMToken"),
      object: nil,
      userInfo: tokenDict)
  }
}

The problem:

Type 'Messaging' has no member 'messaging'


问:
Container does not expand status bar area after switching full-screen in Flutter
I want to fully fill the screen, but when I switch to full-screen mode, the container doesn't cover the status bar.

Here is how I switch full-screen view:

```<code>onTap: () {
              setState(() {
                if (_fullscreen) {
                  SystemChrome.setEnabledSystemUIOverlays([]);
                  _fullscreen = false;
                } else {
                  SystemChrome.setEnabledSystemUIOverlays(
                      SystemUiOverlay.values);
                  _fullscreen = true;
                }
              });
            }
</code>```

In normal view, container cover status bar, but in full-screen view it does not. Actually, the screen slides down a bit.

Here is my entire code of body:

```<code>  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: new InkWell(
                onTap: () {
                  titleStateSelector();
                },
                child: Container(
                  color: _colorContainer,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
</code>```

答:
Try this Use
 SystemChrome.setEnabledSystemUIOverlays([]) in your initState() like this:

```<code>  void initState() {
    super.initState();
    print("Splash");

    // Start full screen
    SystemChrome.setEnabledSystemUIOverlays([]);
  }
</code>```

to start the screen in full-screen mode.

Next use
 SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values)
in your dispose() function to exit full-screen mode for next screens.

```<code>  void dispose() {
    super.dispose();
    // Exit full screen
    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
  }
</code>```

Body:
I want to fully fill the screen, but when I switch to full-screen mode, the container doesn't cover the status bar.

Here is how I switch full-screen view:

onTap: () {
              setState(() {
                if (_fullscreen) {
                  SystemChrome.setEnabledSystemUIOverlays([]);
                  _fullscreen = false;
                } else {
                  SystemChrome.setEnabledSystemUIOverlays(
                      SystemUiOverlay.values);
                  _fullscreen = true;
                }
              });
            }

In normal view, container cover status bar, but in full-screen view it does not. Actually, the screen slides down a bit.

Here is my entire code of body:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: new InkWell(
                onTap: () {
                  titleStateSelector();
                },
                child: Container(
                  color: _colorContainer,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

Body:
Try this Use
 SystemChrome.setEnabledSystemUIOverlays([]) in your initState() like this:

  void initState() {
    super.initState();
    print("Splash");

    // Start full screen
    SystemChrome.setEnabledSystemUIOverlays([]);
  }

to start the screen in full-screen mode.

Next use
 SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values)
in your dispose() function to exit full-screen mode for next screens.

  void dispose() {
    super.dispose();
    // Exit full screen
    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
  }


问:
Relational database design for photography website
I'm creating a database for a photography website and I want it to allow three main things -

Allow the owner/admin to create client accounts and credentials,

Specifying which photos should go into three different portfolio galleries on the site, and,

Displaying a unique client's photos (and only their photos!) to them when they log in.

This is my first database design ever - based on responses below, I've added that emphasis ;) and edited the design as below.

IMAGES
image_id,
filename,
description,
client_id,
date_uploaded,

USERS/CLIENTS

client_id,

client_name

username,

password,

PORTFOLIO

portfolio_id,

portfolio_name,

PORTFOLIO_IMAGES

id,

image_id,

portfolio_id,

Am I correct in thinking that the final id in PORTFOLIO_IMAGES would allow me to display one image in multiple galleries?

Thanks

答:
Within the tables images and users, you will be referencing the clients id, not the name.

I would create a separate table for the galleries, as clients tend to have new wishes every three month. So you maybe need to add more galleries.

table "galleries"

id

name

table "image_is_in_gallery"

image_id

gallery_id

PRIMARY(image_id, gallery_id)


问:
How can I get a string returned from a function executed from a byte array?
I have a working C program that has the simple function that returns a d character encoded in a byte array.

```<code>char foo() {
  return 'd';
}
</code>```

char byte_array[] = {0xb8,0x64,0x00,0x00,0x00,0xc3};

Then, it executes this function from the byte_array and prints its output.

```<code>#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>

char byte_array[] = {0xb8,0x64,0x00,0x00,0x00,0xc3};

int main() {
  void *addr = (void*)((unsigned long)byte_array & ((0UL - 1UL) ^ 0xfff)); /*get memory page*/
  int ans = mprotect(addr, 1, PROT_READ|PROT_WRITE|PROT_EXEC); /*set page attributes*/

  if (ans) {
    perror("mprotect");
    exit(EXIT_FAILURE);
  }

  char (*func)();
  func = (char (*)()) byte_array;
  char function_return = (char)(*func)();

  printf("%c\n", function_return);

  return 0;
}
</code>```

How can I change this code in order to handle functions like the following?

```<code>const char* foo() {
  return "string";
}
</code>```

I've tried this way, but it just prints a weird character to the console:

```<code>const char* (*func)();
func = (const char* (*)()) byte_array;
const char* function_return = (const char*)(*func)();
</code>```

答:
gcc and similar

String literals are stored in the .rodata segment. It is very unlikely your program to have .rodata at the same address as when you compile your "bytecode".

There is no simple workaround as you also cant have this array stored in the .data segment for exactly the same reason as when you put your data into .rodata segment.

I have found some workaround I believe:

```<code>const char * __attribute__((noinline)) foo(void)
{
    code_start:
    asm volatile("call get_ip");
    asm volatile("get_ip:");
    asm volatile("pop %rax");
    asm volatile("jmp_start:");
    asm volatile("add $str_start, %rax");
    asm volatile("sub $get_ip, %rax");
    asm volatile("jmp str_end");
    str_start:
    asm volatile("str_start:");
    asm volatile(".string \"Hello world\"");
    asm volatile("str_end:");
}
</code>```

Body:
I have a working C program that has the simple function that returns a d character encoded in a byte array.

char foo() {
  return 'd';
}

char byte_array[] = {0xb8,0x64,0x00,0x00,0x00,0xc3};

Then, it executes this function from the byte_array and prints its output.

#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>

char byte_array[] = {0xb8,0x64,0x00,0x00,0x00,0xc3};

int main() {
  void *addr = (void*)((unsigned long)byte_array & ((0UL - 1UL) ^ 0xfff)); /*get memory page*/
  int ans = mprotect(addr, 1, PROT_READ|PROT_WRITE|PROT_EXEC); /*set page attributes*/

  if (ans) {
    perror("mprotect");
    exit(EXIT_FAILURE);
  }

  char (*func)();
  func = (char (*)()) byte_array;
  char function_return = (char)(*func)();

  printf("%c\n", function_return);

  return 0;
}

How can I change this code in order to handle functions like the following?

const char* foo() {
  return "string";
}

I've tried this way, but it just prints a weird character to the console:

const char* (*func)();
func = (const char* (*)()) byte_array;
const char* function_return = (const char*)(*func)();

Body:
gcc and similar

String literals are stored in the .rodata segment. It is very unlikely your program to have .rodata at the same address as when you compile your "bytecode".

There is no simple workaround as you also cant have this array stored in the .data segment for exactly the same reason as when you put your data into .rodata segment.

I have found some workaround I believe:

const char * __attribute__((noinline)) foo(void)
{
    code_start:
    asm volatile("call get_ip");
    asm volatile("get_ip:");
    asm volatile("pop %rax");
    asm volatile("jmp_start:");
    asm volatile("add $str_start, %rax");
    asm volatile("sub $get_ip, %rax");
    asm volatile("jmp str_end");
    str_start:
    asm volatile("str_start:");
    asm volatile(".string \"Hello world\"");
    asm volatile("str_end:");
}


问:
how to make only the function sleep instead of the entire program in kivy
so like basically, sleep stops the entire script and this isnt good and I most likely dont want that, so any solutions to this? (it is for this boy right here):

```<code>    def on_button_click(self):
        global started
        if started==False:
            started=True
            enemyname = self.ids.starta.text
            self.type_text("")
            self.hide_widget(self.ids.starta)
            self.hide_widget(self.ids.startb)

            self.ids.thingy.opacity = 1
            self.ids.thingys.opacity = 1
            self.ids.thingyss.opacity = 1
            self.type_text("type this text")
            sleep(3)
            print("yes")
</code>```

as you can see right here, I've tested stuff and the function right above the sleep gets delayed for 3 seconds but the print is printed instantly no idea how to explain it completely but this causes problems for sure as you can see, anyway I can fix this? (self.type_text uses Clock.schedule_interval and the function is from another question I've asked recently)

so yeah the main question is: how do I make it so that only this button function pauses instead of the whole thing

all related parts:

```<code>Builder.load_string("""

<BoxLayout>:
    orientation:"vertical"
    spacing:"10dp"
    TextInput:
        text: "type enemy name"
        size_hint:1,3
        id: starta
    Button:
        text:"Start"
        on_press: root.on_button_click()
        size_hint:1,3
        id: startb
    Label:
        id: label
        text: "Enter enemy name and press 'start'"
    Button:
        text:"Fight"
        size_hint: 1,.3
        color:1,0,0,1
        background_color:.5,0,0
        opacity:0
        id: thingy
    Button:
        text:"Guard"
        size_hint: 1,.3
        color:0,0,1,1
        background_color:0,0,.5
        opacity:0
        id: thingys
    Button:
        text:"Heal"
        size_hint: 1,.3
        color:0,1,0,1
        background_color:0,.5,0
        opacity:0
        id: thingyss

""")

class TextBox(BoxLayout):
    cache_text = StringProperty("") # For storing the entered text.
    index = NumericProperty(0) # For iteration over cache_text.
    global started
    def hide_widget(self, wid, dohide=True):
        if hasattr(wid, 'saved_attrs'):
            if not dohide:
                wid.height, wid.size_hint_y, wid.opacity, wid.disabled = wid.saved_attrs
                del wid.saved_attrs
        elif dohide:
            wid.saved_attrs = wid.height, wid.size_hint_y, wid.opacity, wid.disabled
            wid.height, wid.size_hint_y, wid.opacity, wid.disabled = 0, None, 0, True

    def type_text(self, txt, time=0.07):
        self.ids.label.text = ""  # Comment it out to retain the text.
        self.cache_text = txt # Store the entered text here.
        # For more control you may use method Clock.create_trigger.
        self.ev = Clock.schedule_interval(self.update_text, time) # Update text after every 0.25 sec.

    def update_text(self, *args):
            if self.index < len(self.cache_text):
                val = self.cache_text[self.index]
                self.ids.label.text += val # Appending to existing text.
                self.index += 1
            else:
                self.index = 0 # Reset index.
                self.cache_text = "" # Clear cache.
                self.ev.cancel() # Cancel text updation.
    def on_button_click(self):
        global started
        if started==False:
            started=True
            enemyname = self.ids.starta.text
            self.type_text("")
            self.hide_widget(self.ids.starta)
            self.hide_widget(self.ids.startb)

            self.ids.thingy.opacity = 1
            self.ids.thingys.opacity = 1
            self.ids.thingyss.opacity = 1
            self.type_text("who you are fighting againist is %s, be careful. they are strong."% enemyname)

class Test(App):
    def build(self):
        return TextBox()

Test().run()
</code>```

答:
It seems you are doing some kind of GUI.

The standard for GUI is to make a second thread to do the actual processing.

That is because if you process in the same thread the GUI is running, it actually remains frozen, as it can't handle the events from the user.

The processing thread must also send events to the GUI thread, to notify that the processing is completed.

So you want something like this:

```<code>from time import sleep
from threading import Thread

class ProcessingThread(Thread):
    def run(self):
        sleep(20)
        print('ciao')

p=ProcessingThread()
p.start()
</code>```

Note that you implement a run function, but you call start.

If you call run directly, it just runs like a normal function, but start is the method from the Thread class that actually creates the thread and then internally calls the run function.

Body:
so like basically, sleep stops the entire script and this isnt good and I most likely dont want that, so any solutions to this? (it is for this boy right here):

    def on_button_click(self):
        global started
        if started==False:
            started=True
            enemyname = self.ids.starta.text
            self.type_text("")
            self.hide_widget(self.ids.starta)
            self.hide_widget(self.ids.startb)

            self.ids.thingy.opacity = 1
            self.ids.thingys.opacity = 1
            self.ids.thingyss.opacity = 1
            self.type_text("type this text")
            sleep(3)
            print("yes")

as you can see right here, I've tested stuff and the function right above the sleep gets delayed for 3 seconds but the print is printed instantly no idea how to explain it completely but this causes problems for sure as you can see, anyway I can fix this? (self.type_text uses Clock.schedule_interval and the function is from another question I've asked recently)

so yeah the main question is: how do I make it so that only this button function pauses instead of the whole thing

all related parts:

Builder.load_string("""

<BoxLayout>:
    orientation:"vertical"
    spacing:"10dp"
    TextInput:
        text: "type enemy name"
        size_hint:1,3
        id: starta
    Button:
        text:"Start"
        on_press: root.on_button_click()
        size_hint:1,3
        id: startb
    Label:
        id: label
        text: "Enter enemy name and press 'start'"
    Button:
        text:"Fight"
        size_hint: 1,.3
        color:1,0,0,1
        background_color:.5,0,0
        opacity:0
        id: thingy
    Button:
        text:"Guard"
        size_hint: 1,.3
        color:0,0,1,1
        background_color:0,0,.5
        opacity:0
        id: thingys
    Button:
        text:"Heal"
        size_hint: 1,.3
        color:0,1,0,1
        background_color:0,.5,0
        opacity:0
        id: thingyss

""")

class TextBox(BoxLayout):
    cache_text = StringProperty("") # For storing the entered text.
    index = NumericProperty(0) # For iteration over cache_text.
    global started
    def hide_widget(self, wid, dohide=True):
        if hasattr(wid, 'saved_attrs'):
            if not dohide:
                wid.height, wid.size_hint_y, wid.opacity, wid.disabled = wid.saved_attrs
                del wid.saved_attrs
        elif dohide:
            wid.saved_attrs = wid.height, wid.size_hint_y, wid.opacity, wid.disabled
            wid.height, wid.size_hint_y, wid.opacity, wid.disabled = 0, None, 0, True

    def type_text(self, txt, time=0.07):
        self.ids.label.text = ""  # Comment it out to retain the text.
        self.cache_text = txt # Store the entered text here.
        # For more control you may use method Clock.create_trigger.
        self.ev = Clock.schedule_interval(self.update_text, time) # Update text after every 0.25 sec.

    def update_text(self, *args):
            if self.index < len(self.cache_text):
                val = self.cache_text[self.index]
                self.ids.label.text += val # Appending to existing text.
                self.index += 1
            else:
                self.index = 0 # Reset index.
                self.cache_text = "" # Clear cache.
                self.ev.cancel() # Cancel text updation.
    def on_button_click(self):
        global started
        if started==False:
            started=True
            enemyname = self.ids.starta.text
            self.type_text("")
            self.hide_widget(self.ids.starta)
            self.hide_widget(self.ids.startb)

            self.ids.thingy.opacity = 1
            self.ids.thingys.opacity = 1
            self.ids.thingyss.opacity = 1
            self.type_text("who you are fighting againist is %s, be careful. they are strong."% enemyname)

class Test(App):
    def build(self):
        return TextBox()

Test().run()

Body:
It seems you are doing some kind of GUI.

The standard for GUI is to make a second thread to do the actual processing.

That is because if you process in the same thread the GUI is running, it actually remains frozen, as it can't handle the events from the user.

The processing thread must also send events to the GUI thread, to notify that the processing is completed.

So you want something like this:

from time import sleep
from threading import Thread

class ProcessingThread(Thread):
    def run(self):
        sleep(20)
        print('ciao')

p=ProcessingThread()
p.start()

Note that you implement a run function, but you call start.

If you call run directly, it just runs like a normal function, but start is the method from the Thread class that actually creates the thread and then internally calls the run function.


问:
Calculating number of people ahead in queue pandas
I have a dataframe with customer arrival date/time and customer seen time (all are seen the same day they arrive), and want to determine for each customer, the number of people ahead in the queue upon their arrival time.

So for instance, df_have.head()

```<code>    Cust_ID Arrive_Date Arrive_Time Seen_Time  Depart_Date   Depart_Time
0   475     2019-01-01  00:17:00    02:11:00   2019-01-01    11:30:00
1   331     2019-01-01  00:35:00    03:01:00   2019-01-01    07:35:00
2   434     2019-01-01  00:55:00    01:08:00   2019-01-01    01:18:00
</code>```

What I want to do is, using the all my columns, determine the number of customers ahead in the queue of a customer before they are seen.

So for example, Customer 1 has 1 person ahead of him - Customer 0 - who arrived before Customer 1 and is seen before Customer 1 is seen.

Two rules can be used to see if there is another customer ahead in the queue.

Rule 1: Eligibility check if Arrival_Date & Arrival_Time (incoming customer) <= Depart_Date & Depart_Time  (previous customers) [existing customers must still be in the system to be ahead in the queue]

Rule 2: Queue check if Seen_Time (incoming customer) > Seen_Time (previous customers) [existing customers must be seen before to be ahead in the queue]

If both of these rules are met, there is someone ahead in the queue. Otherwise, there is no one ahead in the queue.

In this example, we can see there are 1 people ahead of Customer 475, since rule 2 fails:

Rule 1: Arrival_Date & Arrival_Time (cust 475) <= Depart_Date & Depart_Time (cust 331,434)

Rule 2:  Seen_Time (cust 475) > Seen_Time (cust 434)

Similarly, for Customer 331:

Rule 1: Arrival_Date & Arrival_Time (cust 331) <= Depart_Date & Depart_Time (cust 475,434)

Rule 2:  Seen_Time (cust 331) > Seen_Time (cust 475,434)

So there are two people ahead in the queue.

So the output would then be:

df_want.head()

```<code>    Cust_ID Arrive_Date Arrive_Time Seen_Time   People_Ahead
0   475     2019-01-01  00:17:00    02:11:00    1
1   331     2019-01-01  00:35:00    03:01:00    2
2   434     2019-01-01  00:55:00    01:08:00    0
</code>```

I am not sure how to code in these two rules, so any help or guidance would be appreciated!

答:
As I understand it, I worked as follows:</p>
```<code>from datetime import datetime

df['Arrive'] = df.apply(lambda cust: datetime.strptime(cust.Arrive_Date + ' ' + cust.Arrive_Time, '%Y-%m-%y %H:%M:%S'), axis=1)
df['Seen'] = df.apply(lambda cust: datetime.strptime(cust.Arrive_Date + ' ' + cust.Seen_Time, '%Y-%m-%y %H:%M:%S'), axis=1)
df['Depart'] = df.apply(lambda cust: datetime.strptime(cust.Depart_Date + ' ' + cust.Depart_Time, '%Y-%m-%y %H:%M:%S'), axis=1)
df['People_Ahead'] = df.apply(lambda cust: sum((cust.Arrive <= df['Depart']) & (cust.Seen > df['Seen'])), axis=1)
df[['Cust_ID', 'Arrive_Date', 'Arrive_Time', 'Seen_Time', 'People_Ahead']]
</code>```

Body:
I have a dataframe with customer arrival date/time and customer seen time (all are seen the same day they arrive), and want to determine for each customer, the number of people ahead in the queue upon their arrival time.

So for instance, df_have.head()

    Cust_ID Arrive_Date Arrive_Time Seen_Time  Depart_Date   Depart_Time
0   475     2019-01-01  00:17:00    02:11:00   2019-01-01    11:30:00
1   331     2019-01-01  00:35:00    03:01:00   2019-01-01    07:35:00
2   434     2019-01-01  00:55:00    01:08:00   2019-01-01    01:18:00

What I want to do is, using the all my columns, determine the number of customers ahead in the queue of a customer before they are seen.

So for example, Customer 1 has 1 person ahead of him - Customer 0 - who arrived before Customer 1 and is seen before Customer 1 is seen.

Two rules can be used to see if there is another customer ahead in the queue.

Rule 1: Eligibility check if Arrival_Date & Arrival_Time (incoming customer) <= Depart_Date & Depart_Time  (previous customers) [existing customers must still be in the system to be ahead in the queue]

Rule 2: Queue check if Seen_Time (incoming customer) > Seen_Time (previous customers) [existing customers must be seen before to be ahead in the queue]

If both of these rules are met, there is someone ahead in the queue. Otherwise, there is no one ahead in the queue.

In this example, we can see there are 1 people ahead of Customer 475, since rule 2 fails:

Rule 1: Arrival_Date & Arrival_Time (cust 475) <= Depart_Date & Depart_Time (cust 331,434)

Rule 2:  Seen_Time (cust 475) > Seen_Time (cust 434)

Similarly, for Customer 331:

Rule 1: Arrival_Date & Arrival_Time (cust 331) <= Depart_Date & Depart_Time (cust 475,434)

Rule 2:  Seen_Time (cust 331) > Seen_Time (cust 475,434)

So there are two people ahead in the queue.

So the output would then be:

df_want.head()

    Cust_ID Arrive_Date Arrive_Time Seen_Time   People_Ahead
0   475     2019-01-01  00:17:00    02:11:00    1
1   331     2019-01-01  00:35:00    03:01:00    2
2   434     2019-01-01  00:55:00    01:08:00    0

I am not sure how to code in these two rules, so any help or guidance would be appreciated!

Body:
As I understand it, I worked as follows:

from datetime import datetime

df['Arrive'] = df.apply(lambda cust: datetime.strptime(cust.Arrive_Date + ' ' + cust.Arrive_Time, '%Y-%m-%y %H:%M:%S'), axis=1)
df['Seen'] = df.apply(lambda cust: datetime.strptime(cust.Arrive_Date + ' ' + cust.Seen_Time, '%Y-%m-%y %H:%M:%S'), axis=1)
df['Depart'] = df.apply(lambda cust: datetime.strptime(cust.Depart_Date + ' ' + cust.Depart_Time, '%Y-%m-%y %H:%M:%S'), axis=1)
df['People_Ahead'] = df.apply(lambda cust: sum((cust.Arrive <= df['Depart']) & (cust.Seen > df['Seen'])), axis=1)
df[['Cust_ID', 'Arrive_Date', 'Arrive_Time', 'Seen_Time', 'People_Ahead']]


问:
Inheritance problem in C#
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

```<code>public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}
</code>```

ISvdPredictor uses ISvdModel:

```<code>public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}
</code>```

Now I want to implement another variation:

```<code>public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}
</code>```

Which uses IBiasSvdModel which derives from ISvdModel:

```<code>public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}
</code>```

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.

答:
You could use generics and constraints.</p>

```<code>public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}

public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}

public interface ISvdPredictor<in TSvdModel>
    where TSvdModel : ISvdModel // Require that TSvdModel implements ISvdModel
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }

    float PredictRating(TSvdModel model, string user, string artist);
    float PredictRating(TSvdModel model, int userIndex, int artistIndex);
}

// I would actually avoid declaring this interface. Rather, see comment on the class.
public interface IBiasSvdPredictor : ISvdPredictor<IBiasSvdModel> { }

class BiasSvdPredictor : IBiasSvdPredictor // Preferred : ISvdPredictor<IBiasSvdModel>
{
    // ...
    public float PredictRating(IBiasSvdModel model, string user, string artist) { }
    public float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex) { }
}
</code>```

Title: Inheritance problem in C#

Body:
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}

ISvdPredictor uses ISvdModel:

public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}

Now I want to implement another variation:

public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}

Which uses IBiasSvdModel which derives from ISvdModel:

public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.

Body:
You could use generics and constraints.

public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}

public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}

public interface ISvdPredictor<in TSvdModel>
    where TSvdModel : ISvdModel // Require that TSvdModel implements ISvdModel
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }

    float PredictRating(TSvdModel model, string user, string artist);
    float PredictRating(TSvdModel model, int userIndex, int artistIndex);
}

// I would actually avoid declaring this interface. Rather, see comment on the class.
public interface IBiasSvdPredictor : ISvdPredictor<IBiasSvdModel> { }

class BiasSvdPredictor : IBiasSvdPredictor // Preferred : ISvdPredictor<IBiasSvdModel>
{
    // ...
    public float PredictRating(IBiasSvdModel model, string user, string artist) { }
    public float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex) { }
}


问:
Create another Widget when OnTap() is triggered
Does anyone know how to generate a new widget in Flutter when OnTap() is triggered?

In my case, I want to create a new column inside a container, when the column icon is pressed.

The icon is wrapped with an InkWell().

InkWell(
  onTap: () {
    print("Create Column in another Container");
  },
  child: Column(
    children: const [
      Icon(
        Icons.view_agenda,
        color: iconGreyColor,
        size: 20.0,
      ),
    ],
  ),
),

```
<p>The Goal shut look like this.</p>
<pre class="lang-dart prettyprint-override"><code>    Container(child: Column(children:[]),)
</code>```

答:
Inside OnTap(), you can pass a function that can create a Widget.

e.g.

    Widget buildContainer(){ return Container(child: Text("Stack Overflow"))}
```

Insert this function before your build method and then call it during the OnTap() event. You can, of course, modify the Container according to your exact requirements.

The important thing to understand here is that you can create functions with any permissible return type, even a specific Widget, this is especially useful when you want to create multiple identical widgets, as it reduces redundant code.

Body:
Does anyone know how to generate a new widget in Flutter when OnTap() is triggered?

In my case, I want to create a new column inside a container, when the column icon is pressed.

The icon is wrapped with an InkWell().

InkWell(
  onTap: () {
    print("Create Column in another Container");
  },
  child: Column(
    children: const [
      Icon(
        Icons.view_agenda,
        color: iconGreyColor,
        size: 20.0,
      ),
    ],
  ),
),

The Goal shut look like this.

    Container(child: Column(children:[]),)

Body:
Inside OnTap(), you can pass a function that can create a Widget.

e.g.

    Widget buildContainer(){ return Container(child: Text("Stack Overflow"))}

Insert this function before your build method and then call it during the OnTap() event. You can, of course, modify the Container according to your exact requirements.

The important thing to understand here is that you can create functions with any permissible return type, even a specific Widget, this is especially useful when you want to create multiple identical widgets, as it reduces redundant code.


问:
C# Prohibiting user typing Words instead of numbers
Having some problems with my Console Calculator
I want to prohibit user inputing a words instead of numbers.
I wrote this code and its converting words to zero but i want user to type a number instead of words. And if user still typing words program should ask user to type number.

internal class Program
{
static void Main(string[] args)

```<code>    {
        Console.WriteLine("----------------------");
        Console.WriteLine("------Calculator------");
        Console.WriteLine("----------------------");
        do
        {

            double num1 = 0;
            double num2 = 0;
            double result = 0;
            bool result0;

            Console.WriteLine("Enter number one: ");

            try
            {
                double.TryParse(Console.ReadLine(), out num1);
                if ()
                {
                    Console.WriteLine("Incorrect number!\nType another number:");
                    num1 = Convert.ToDouble(Console.ReadLine());
                }

            }
             catch (Exception e)
            {

            }

            Console.WriteLine("Enter number two: ");

            num2 = Convert.ToDouble(Console.ReadLine());
</code>```

答:
You have to use double.TryParse() inside a if condition with negation operator.

If you want to force user to show "Incorrect number!\nType another number:" message till the user enters correct integer, use while() loop instead of if() condition.

```<code>while (!double.TryParse(Console.ReadLine(), out num1))
    Console.WriteLine("Incorrect number!\nType another number:");
</code>```

Why we should use double.TryParse() inside if condition?

double.TryParse(), parse string value to double and return true if conversion succeeded or not.

In your case, if user enters word instead of number then conversion will fail and use of !(negation) will iterate the loop again.

Body:
Having some problems with my Console Calculator
I want to prohibit user inputing a words instead of numbers.
I wrote this code and its converting words to zero but i want user to type a number instead of words. And if user still typing words program should ask user to type number.

internal class Program
{
static void Main(string[] args)

    {
        Console.WriteLine("----------------------");
        Console.WriteLine("------Calculator------");
        Console.WriteLine("----------------------");
        do
        {

            double num1 = 0;
            double num2 = 0;
            double result = 0;
            bool result0;

            Console.WriteLine("Enter number one: ");

            try
            {
                double.TryParse(Console.ReadLine(), out num1);
                if ()
                {
                    Console.WriteLine("Incorrect number!\nType another number:");
                    num1 = Convert.ToDouble(Console.ReadLine());
                }

            }
             catch (Exception e)
            {

            }

            Console.WriteLine("Enter number two: ");

            num2 = Convert.ToDouble(Console.ReadLine());

Body:
You have to use double.TryParse() inside a if condition with negation operator.

If you want to force user to show "Incorrect number!\nType another number:" message till the user enters correct integer, use while() loop instead of if() condition.

while (!double.TryParse(Console.ReadLine(), out num1))
    Console.WriteLine("Incorrect number!\nType another number:");

Why we should use double.TryParse() inside if condition?

double.TryParse(), parse string value to double and return true if conversion succeeded or not.

In your case, if user enters word instead of number then conversion will fail and use of !(negation) will iterate the loop again.


问:
Why Laravel don't show or execute new Routes?
I don't know if I'm so stupid or my laravel is broken, BUT, here it is.

That's my api.php:

```<code>Route::get('/airport', [\App\Http\Controllers\AirportsController::class, 'index']);
Route::post('/airports', [\App\Http\Controllers\AirportsController::class, 'create']);
Route::get('/registrator', [\App\Http\Controllers\RegistrationController::class, 'index']);
</code>```

The airport and airports work great. It's add all data in db or get data from db.
But registartor just don't work. It shows ERROR 404 and that's all.

RegistrationController:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RegistrationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return 1;
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
</code>```

It's just show ERROR 404 in anyway, not matter what request I do. I mean, I can rename airport in airportt and restart my server, but It still will show me ERROR 404, until I change airportt to airport

答:
You could do

```<code>php artisan optimize
</code>```

in your command it will clear multiple things like

```<code>Configuration cache cleared!
Configuration cached successfully!
Route cache cleared!
Routes cached successfully!
Files cached successfully!
</code>```

Body:
I don't know if I'm so stupid or my laravel is broken, BUT, here it is.

That's my api.php:

Route::get('/airport', [\App\Http\Controllers\AirportsController::class, 'index']);
Route::post('/airports', [\App\Http\Controllers\AirportsController::class, 'create']);
Route::get('/registrator', [\App\Http\Controllers\RegistrationController::class, 'index']);

The airport and airports work great. It's add all data in db or get data from db.
But registartor just don't work. It shows ERROR 404 and that's all.

RegistrationController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RegistrationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return 1;
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

It's just show ERROR 404 in anyway, not matter what request I do. I mean, I can rename airport in airportt and restart my server, but It still will show me ERROR 404, until I change airportt to airport

Body:
You could do

php artisan optimize

in your command it will clear multiple things like

Configuration cache cleared!
Configuration cached successfully!
Route cache cleared!
Routes cached successfully!
Files cached successfully!


问:
egit - not authorized
I just connected to GIT from Eclipse Juno using EGit, and successfully cloned a certain remote repository. During the clone I entered my Github username and password, but chose not to save them.

Then I tried to "Fetch from Upstream". I got this error:

```https://github.com/biunlp/nlp-lab.git: not authorized```

I had no chance of entering my username and password...

This is strange since I connected to this repository in order to clone...

答:
This worked for me:

Go to Git profile-> Settings -> developer settings-> personal access tokens
delete if any existing token and generate a new token [provide note, specify no.of days and repo checked] ->Copy the new token generated
Goto eclipse and now when the same login prompt appears, try providing the personal token generated as password instead of Git password.

Title: egit - not authorized

Body:
I just connected to GIT from Eclipse Juno using EGit, and successfully cloned a certain remote repository. During the clone I entered my Github username and password, but chose not to save them.

Then I tried to "Fetch from Upstream". I got this error:

https://github.com/biunlp/nlp-lab.git: not authorized

I had no chance of entering my username and password...

This is strange since I connected to this repository in order to clone...


问:
How to fix black screen in flutter while Navigating?
I am creating a multi-paged app on flutter. When I am using the navigation in it, I am getting a black screen.

```<code>import 'package:flutter/material.dart';

    void main() => runApp(MyHomePage());

    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Page0(),
        );
      }
    }

    class Page0 extends StatefulWidget {
      @override
      _Page0State createState() => _Page0State();
    }

    class _Page0State extends State<Page0> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Color(0xFF493597),
          body: ListView(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 15.0, left: 10.0),
              ),
              SizedBox(
                height: 25.0,
              ),
              Padding(
                padding: EdgeInsets.only(left: 40.0),
                child: Row(
                  children: <Widget>[
                    Text(
                      'Expense',
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 25.0),
                    ),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      'What',
                      style: TextStyle(
                        fontFamily: 'Montserrat',
                        color: Colors.white,
                        fontSize: 25.0,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 60.0),
              Container(
                margin: EdgeInsets.only(
                  left: 10.0,
                  right: 10.0,
                ),
                height: MediaQuery.of(context).size.height - 150,
                decoration: BoxDecoration(
                  color: Color(0xFFFCFCFC),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(75.0),
                    topRight: Radius.circular(75.0),
                  ),
                ),
                child: ListView(
                  primary: false,
                  padding: EdgeInsets.only(
                    left: 15.0,
                    right: 20.0,
                    top: 25.0,
                  ),
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(
                        top: 30.0,
                      ),
                      child: Column(
                        children: <Widget>[
                          //greeting text
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Center(
                                  child: Text(
                                    'Hello! :)',
                                    style: TextStyle(
                                      fontFamily: 'Permanent-Marker',
                                      color: Colors.black,
                                      fontSize: 30.0,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),

                          SizedBox(
                            height: 30.0,
                          ),

                          //add button
                          Row(children: <Widget>[
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: 100.0,
                                width: 100.0,
                                child: FittedBox(
                                  child: FloatingActionButton(
                                    elevation: 10.0,
                                    backgroundColor: Colors.white,
                                    child: Icon(
                                      Icons.add,
                                      color: Colors.black,
                                    ),
                                    onPressed: () {
                                       Navigator.push(context,MaterialPageRoute(builder: (context) => NewTrip()),);
                                    },
                                  ),``
                                ),
                              ),
                            ),

                            //add text
                            Expanded(
                              flex: 1,
                              child: Text(
                                'New trip',
                                style: TextStyle(
                                  fontFamily: 'Nanum',
                                  fontSize: 30.0,
                                ),
                              ),
                            ),
                          ]),

                          SizedBox(
                            height: 30.0,
                          ),

                          //previous trip button
                          Row(
                            children: <Widget>[
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: 100.0,
                                  width: 100.0,
                                  child: FittedBox(
                                    child: FloatingActionButton(
                                      elevation: 10.0,
                                      backgroundColor: Colors.white,
                                      onPressed: () {},
                                      child: Icon(
                                        Icons.assessment,
                                        color: Colors.black,
                                      ),
                                    ),
                                  ),
                                ),
                              ),

                              //previous trip text
                              Expanded(
                                flex: 1,
                                child: Text(
                                  'Previous trips',
                                  style: TextStyle(
                                    fontFamily: 'Nanum',
                                    fontSize: 30.0,
                                  ),
                                ),
                              )
                            ],
                          ),

                          SizedBox(
                            height: 50.0,
                          ),

                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      }
    }
</code>```

And the NewTrip widget is as follows

```<code>class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
              body: Text('NEW TRIP'),
            ),
    );
  }
}
</code>```

The home page is loading fine but as soon as I click the new trip button, it shows a black screen. Probably there is an issue with MaterialApp or Scaffold but I am not able to fix it yet. Can anyone tell me what's the problem and how to fix it?

Updated the full code as requested in the comments.

答:
Before:

```<code>class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Text('NEW TRIP'),
    );
  }
}
</code>```

So to Solve this problem we wrap the new navigate widget with scaffold widget

Solution After:

```<code>class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Material(
        child: Text('NEW TRIP'),
      ),
    );
  }
}
</code>```

Body:
I am creating a multi-paged app on flutter. When I am using the navigation in it, I am getting a black screen.

import 'package:flutter/material.dart';

    void main() => runApp(MyHomePage());

    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Page0(),
        );
      }
    }

    class Page0 extends StatefulWidget {
      @override
      _Page0State createState() => _Page0State();
    }

    class _Page0State extends State<Page0> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Color(0xFF493597),
          body: ListView(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 15.0, left: 10.0),
              ),
              SizedBox(
                height: 25.0,
              ),
              Padding(
                padding: EdgeInsets.only(left: 40.0),
                child: Row(
                  children: <Widget>[
                    Text(
                      'Expense',
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 25.0),
                    ),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      'What',
                      style: TextStyle(
                        fontFamily: 'Montserrat',
                        color: Colors.white,
                        fontSize: 25.0,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 60.0),
              Container(
                margin: EdgeInsets.only(
                  left: 10.0,
                  right: 10.0,
                ),
                height: MediaQuery.of(context).size.height - 150,
                decoration: BoxDecoration(
                  color: Color(0xFFFCFCFC),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(75.0),
                    topRight: Radius.circular(75.0),
                  ),
                ),
                child: ListView(
                  primary: false,
                  padding: EdgeInsets.only(
                    left: 15.0,
                    right: 20.0,
                    top: 25.0,
                  ),
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(
                        top: 30.0,
                      ),
                      child: Column(
                        children: <Widget>[
                          //greeting text
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Center(
                                  child: Text(
                                    'Hello! :)',
                                    style: TextStyle(
                                      fontFamily: 'Permanent-Marker',
                                      color: Colors.black,
                                      fontSize: 30.0,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),

                          SizedBox(
                            height: 30.0,
                          ),

                          //add button
                          Row(children: <Widget>[
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: 100.0,
                                width: 100.0,
                                child: FittedBox(
                                  child: FloatingActionButton(
                                    elevation: 10.0,
                                    backgroundColor: Colors.white,
                                    child: Icon(
                                      Icons.add,
                                      color: Colors.black,
                                    ),
                                    onPressed: () {
                                       Navigator.push(context,MaterialPageRoute(builder: (context) => NewTrip()),);
                                    },
                                  ),``
                                ),
                              ),
                            ),

                            //add text
                            Expanded(
                              flex: 1,
                              child: Text(
                                'New trip',
                                style: TextStyle(
                                  fontFamily: 'Nanum',
                                  fontSize: 30.0,
                                ),
                              ),
                            ),
                          ]),

                          SizedBox(
                            height: 30.0,
                          ),

                          //previous trip button
                          Row(
                            children: <Widget>[
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: 100.0,
                                  width: 100.0,
                                  child: FittedBox(
                                    child: FloatingActionButton(
                                      elevation: 10.0,
                                      backgroundColor: Colors.white,
                                      onPressed: () {},
                                      child: Icon(
                                        Icons.assessment,
                                        color: Colors.black,
                                      ),
                                    ),
                                  ),
                                ),
                              ),

                              //previous trip text
                              Expanded(
                                flex: 1,
                                child: Text(
                                  'Previous trips',
                                  style: TextStyle(
                                    fontFamily: 'Nanum',
                                    fontSize: 30.0,
                                  ),
                                ),
                              )
                            ],
                          ),

                          SizedBox(
                            height: 50.0,
                          ),

                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      }
    }

And the NewTrip widget is as follows

class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
              body: Text('NEW TRIP'),
            ),
    );
  }
}

The home page is loading fine but as soon as I click the new trip button, it shows a black screen. Probably there is an issue with MaterialApp or Scaffold but I am not able to fix it yet. Can anyone tell me what's the problem and how to fix it?

Updated the full code as requested in the comments.

Body:
Before:

class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Text('NEW TRIP'),
    );
  }
}

So to Solve this problem we wrap the new navigate widget with scaffold widget

Solution After:

class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Material(
        child: Text('NEW TRIP'),
      ),
    );
  }
}


问:
Is it advisable to write a test case for every class in your program?
Im am just getting introduced to unit testing and test driven development. Thus far, I have only used Junit as testing framework. A question which emerged and for which I have not yet found a definite answer is: how much test cases do I need to write? Do I have to write a test case for every single class in my program? Or is this a stupid question because unit testing implies testing at the lowest (i.e. class) level?

I think writing a test case for every class is probably the more safe way to go (after all the more you test the lower the number of unforeseen bugs). But I was wondering if there are any widely agreed upon strategies regarding the amount of test cases to write?

答:
If you're doing TDD and extreme programming, (I think this helps explain it), you program in pairs.  The first person writes a test for a feature that doesn't yet exist.  The test should prove that the feature is 100% functional and handles all required cases.  The second programmer then writes the code that makes the test pass perfectly.  It must be rewritten until it completely satisfies the test.  Usually you maintain a test suite for TDD which can be rerun constantly, detecting any failures and generating a report - though this is ambitious for personal use.

In any case, for TDD a new feature cannot exist without a new test being made first - the test Drives the Development.  So, your test is there for every feature by default if you're doing it right.


问:
Rounding numbers to n decimals in clojure
When I do, for example, (/ 1.0 7.0), I only get 17 digits: 0.14285714285714285. How can I get more then that?</p>

答: Clojure (and pretty much all lisps) has ratio type that way you do not lose precision. do all your calculations with ratio and convert to double/float at the last minute to avoid precision problems.</p>


问:
How to replace an element in a list with an existing variable?
I can't replace an element in a list with a variable and I'm not sure how. I've checked everywhere and I can't find it. Can someone let me know how to? Cheers</p>
```<code>import random
passcode = "x"
while passcode == "x":
  randomword = list(input("Please enter a random word: "))
  randomwordtwo = list(input("Please enter a second random word: "))
  randomwordthree = list(input("Please enter a final random word: "))
  randomword.extend(randomwordtwo)
  randomword.extend(randomwordthree)
  symbol = ["!","`","~","@","#","$","%","^","&","*","-","_","?",",","<",">",","]
  number = ["0","1","2","3","4","5","6","7","8","9"]
  print(randomword)
  randsymb = (random.choice(symbol))
  for i in range(len(randomword)):
    if randomword[i] == "a":
      randomword[i] = (randsymb)
</code>```

答:
From what you have written, your final line replaces the letter "a" with a randomly selected symbol and so appears to answer your own question. Therefore, I will try and help with what I think you mean.

If you want to try and replace a random letter within your list instead of strictly the letter "a", try:

```<code>import random
import string
passcode = "x"
while passcode == "x":
    randomword = list(input("Please enter a random word: ").lower().strip())
    randomwordtwo = list(input("Please enter a second random word: ").lower().strip())
    randomwordthree = list(input("Please enter a final random word: ").lower().strip())
    randomword.extend(randomwordtwo)
    randomword.extend(randomwordthree)
    symbol = ["!","`","~","@","#","$","%","^","&","*","-","_","?",",","<",">",","]
    number = ["0","1","2","3","4","5","6","7","8","9"]
    print(randomword)
    randsymb = (random.choice(symbol))
    random_letter = ""
    while random_letter not in randomword:
        # finds random letter from randomword to replace
        random_letter = random.choice(string.ascii_letters)
    for i in range(len(randomword)):
        # replaces random letter with symbol
        if randomword[i] == f"{random_letter}":
            randomword[i] = randsymb
    # produces final random word
    final_word = "".join(randomword)
    print(final_word)
</code>```

Body:
I can't replace an element in a list with a variable and I'm not sure how. I've checked everywhere and I can't find it. Can someone let me know how to? Cheers

import random
passcode = "x"
while passcode == "x":
  randomword = list(input("Please enter a random word: "))
  randomwordtwo = list(input("Please enter a second random word: "))
  randomwordthree = list(input("Please enter a final random word: "))
  randomword.extend(randomwordtwo)
  randomword.extend(randomwordthree)
  symbol = ["!","`","~","@","#","$","%","^","&","*","-","_","?",",","<",">",","]
  number = ["0","1","2","3","4","5","6","7","8","9"]
  print(randomword)
  randsymb = (random.choice(symbol))
  for i in range(len(randomword)):
    if randomword[i] == "a":
      randomword[i] = (randsymb)

Body:
From what you have written, your final line replaces the letter "a" with a randomly selected symbol and so appears to answer your own question. Therefore, I will try and help with what I think you mean.

If you want to try and replace a random letter within your list instead of strictly the letter "a", try:

import random
import string
passcode = "x"
while passcode == "x":
    randomword = list(input("Please enter a random word: ").lower().strip())
    randomwordtwo = list(input("Please enter a second random word: ").lower().strip())
    randomwordthree = list(input("Please enter a final random word: ").lower().strip())
    randomword.extend(randomwordtwo)
    randomword.extend(randomwordthree)
    symbol = ["!","`","~","@","#","$","%","^","&","*","-","_","?",",","<",">",","]
    number = ["0","1","2","3","4","5","6","7","8","9"]
    print(randomword)
    randsymb = (random.choice(symbol))
    random_letter = ""
    while random_letter not in randomword:
        # finds random letter from randomword to replace
        random_letter = random.choice(string.ascii_letters)
    for i in range(len(randomword)):
        # replaces random letter with symbol
        if randomword[i] == f"{random_letter}":
            randomword[i] = randsymb
    # produces final random word
    final_word = "".join(randomword)
    print(final_word)


问:
making html list to behave in certain way only with CSS
I am making a website with pure css and html , I want to behave in certain way with only using css.

i have a list and every time,i hover on any  of them , i want others to take different color.
what i have written , doesnt behave same way!

when i hover on any of them , only the items below it ,changes color:

```<code> <div class="sketch">
                    <div class="sketch-div">
                        <a href="#">Sketch</a>
                    </div>

                    <div class="hide">
                        <img  width="50%" src="images/sketchcloud.jpg"
                            alt="Sketch Cloud">
                    </div>
                </div>
                <div class="WeTransfer">
                    <div class="WeTransfer-div">
                        <a href="#">WeTransfer</a>
                    </div>
                    <div class="hide">
                        <video width="50%" webkit-playsinline="webkit-playsinline">
                            <source src="images/wetransfer-preview.3b6e83b8.mp4" type="video/mp4">
                        </video>
                    </div>
                </div>

                <div class="Coffee">
                    <div>
                        <a href="#">Coffee by Benjamin</a>
                    </div>
                    <div class="hide">
                        <img width="50%" src="images/coffeebybenjamin.jpg"
                            alt="Coffee by Benjamin">
                    </div>
                </div>

                <div class="Beam">
                    <div>
                        <a href="#">Beam</a>
                    </div>
                    <div class="hide">
                        <video width="50%" webkit-playsinline="webkit-playsinline">
                            <source src="images/beam-preview.940b40c4.mp4" type="video/mp4">
                        </video>
                    </div>
                </div>
                <div class="More">
                    <div>
                        <a class="arrow" href="#">More</a>
                    </div>
                    <div class="hide">

                    </div>

                </div>
</code>```

above is inside nav element.

this is css code for it :

```<code>.sketch:hover ~ .WeTransfer  a{
   color:  #ccc;
}

.sketch:hover ~ .Coffee  a{
    color:  #ccc;
}

.sketch:hover ~ .Beam  a{
    color:  #ccc;
}

.sketch:hover ~ .More  a{
    color:  #ccc;
}
/* Wetransfer  */
.WeTransfer:hover ~ .sketch  a{
    color:  #ccc ;
 }

 .WeTransfer:hover  ~ .Coffee  a{
     color:  #ccc;
 }

 .WeTransfer:hover ~ .Beam  a{
     color:  #ccc;
 }

 .WeTransfer:hover ~ .More  a{
     color:  #ccc;
 }
/* Coffee */
.Coffee:hover ~ .WeTransfer a{
    color:  #ccc;
 }

 .Coffee:hover ~ .sketch  a{
     color:  #ccc;
 }

 .Coffee:hover ~ .Beam  a{
     color:  #ccc;
 }

 .Coffee:hover ~ .More  a{
     color:  #ccc;
 }
</code>```

here im hovering on coffee by benjamin and elements below it get the different color , but the elements top of it wont change colors.

how can i do this just with css and html ?

答:
It seems that you're making the nav section of your webpage. If that's the case, I recommend using li tags instead of using divs!

So for example...

Sketch

WeTransfer

Coffee by Benjami

Beam

```
</div>
</div>
</p>
<p>But use the li tag:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  list-style: none;
 }

.list-1:hover ~ .list-2,.list-1:hover ~ .list-3,.list-1:hover ~ .list-4 { background-color: yellow; }</code>```

Sketch

WeTransfer

Coffee by Benjami

Beam

```

Boom! It's this .list-1:hover ~ .list-2,.list-1:hover ~ .list-3,.list-1:hover ~ .list-4 { background-color: yellow; } simple line of code to solve your problem! As you can see, by hovering on top of the first list item("Sketch"), it changed the color of the second list item(which has not been hovered)

This person explained it very well link

Body:
I am making a website with pure css and html , I want to behave in certain way with only using css.

i have a list and every time,i hover on any  of them , i want others to take different color.
what i have written , doesnt behave same way!

when i hover on any of them , only the items below it ,changes color:

                        Sketch

                        WeTransfer

                        <video width="50%" webkit-playsinline="webkit-playsinline">
                            <source src="images/wetransfer-preview.3b6e83b8.mp4" type="video/mp4">
                        </video>

                        Coffee by Benjamin

                        Beam

                        <video width="50%" webkit-playsinline="webkit-playsinline">
                            <source src="images/beam-preview.940b40c4.mp4" type="video/mp4">
                        </video>

                        More

above is inside nav element.

this is css code for it :

.sketch:hover ~ .WeTransfer  a{
   color:  #ccc;
}

.sketch:hover ~ .Coffee  a{
    color:  #ccc;
}

.sketch:hover ~ .Beam  a{
    color:  #ccc;
}

.sketch:hover ~ .More  a{
    color:  #ccc;
}
/* Wetransfer  */
.WeTransfer:hover ~ .sketch  a{
    color:  #ccc ;
 }

 .WeTransfer:hover  ~ .Coffee  a{
     color:  #ccc;
 }

 .WeTransfer:hover ~ .Beam  a{
     color:  #ccc;
 }

 .WeTransfer:hover ~ .More  a{
     color:  #ccc;
 }
/* Coffee */
.Coffee:hover ~ .WeTransfer a{
    color:  #ccc;
 }

 .Coffee:hover ~ .sketch  a{
     color:  #ccc;
 }

 .Coffee:hover ~ .Beam  a{
     color:  #ccc;
 }

 .Coffee:hover ~ .More  a{
     color:  #ccc;
 }

here im hovering on coffee by benjamin and elements below it get the different color , but the elements top of it wont change colors.

how can i do this just with css and html ?

Body:
It seems that you're making the nav section of your webpage. If that's the case, I recommend using li tags instead of using divs!

So for example...

<!-- don't use <div> tags -->

<nav>
  <div>
    <div>Sketch</div>
   </div>

  <div>
    <div>WeTransfer</div>
   </div>

  <div>
    <div>Coffee by Benjami</div>
   </div>

  <div>
    <div>Beam</div>
   </div>
</nav>

But use the li tag:

ul {
  list-style: none;
 }

.list-1:hover ~ .list-2,.list-1:hover ~ .list-3,.list-1:hover ~ .list-4 { background-color: yellow; }

<ul>
  <li class="list-1">Sketch</li>
  <li class="list-2">WeTransfer</li>
  <li class="list-3">Coffee by Benjami</li>
  <li class="list-4">Beam</li>
 </ul>

Boom! It's this .list-1:hover ~ .list-2,.list-1:hover ~ .list-3,.list-1:hover ~ .list-4 { background-color: yellow; } simple line of code to solve your problem! As you can see, by hovering on top of the first list item("Sketch"), it changed the color of the second list item(which has not been hovered)

This person explained it very well link


问:
Compute average of properties in objects array
Suppose to have an array of two or more objects as:

```<code>const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}]
</code>```

How can I efficiently compute average values for each property in the objects comprising the array?
I don't know in advance the properties in each object and even if there are common properties.
I would expect a result:

```<code>{PM1:15, PM10:25, CO:27, NO2:30}
</code>```

I suppose that I can use reduce but I can't figure it out how.

答:
You can loop through the property names of an object using either for-in (which includes inherited properties) or an array from Object.keys (which doesn't). In both cases, only enumerable properties are included.

For instance:

```<code>const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}];

const result = {};
const counts = new Map();
for (const element of arr) {
    for (const key in element) {
        if (Object.hasOwn(element, key)) {
            // Count this property
            counts.set(key, (counts.get(key) ?? 0) + 1);
            // Add it to the sum
            result[key] = (result[key] ?? 0) + element[key];
        }
    }
}
// Update with the averages
for (const [key, count] of counts) {
    result[key] = result[key] / counts.get(key);
}
</code>```

Live Example:

// Quick-and-dirty polyfill for older environments without `Object.hasOwn`:
if (!Object.hasOwn) {
    Object.defineProperty(Object, "hasOwn", {
        value: Function.prototype.call.bind(Object.prototype.hasOwnProperty),
        writable: true,
        configurable: true,
    });
}

const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}];

const result = {};
const counts = new Map();
for (const element of arr) {
    for (const key in element) {
        if (Object.hasOwn(element, key)) {
            // Count this property
            counts.set(key, (counts.get(key) ?? 0) + 1);
            // Add it to the sum
            result[key] = (result[key] ?? 0) + element[key];
        }
    }
}
// Update with the averages
for (const [key, count] of counts) {
    result[key] = result[key] / counts.get(key);
}

console.log(result);```

Body:
Suppose to have an array of two or more objects as:

const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}]

How can I efficiently compute average values for each property in the objects comprising the array?
I don't know in advance the properties in each object and even if there are common properties.
I would expect a result:

{PM1:15, PM10:25, CO:27, NO2:30}

I suppose that I can use reduce but I can't figure it out how.

Body:
You can loop through the property names of an object using either for-in (which includes inherited properties) or an array from Object.keys (which doesn't). In both cases, only enumerable properties are included.

For instance:

const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}];

const result = {};
const counts = new Map();
for (const element of arr) {
    for (const key in element) {
        if (Object.hasOwn(element, key)) {
            // Count this property
            counts.set(key, (counts.get(key) ?? 0) + 1);
            // Add it to the sum
            result[key] = (result[key] ?? 0) + element[key];
        }
    }
}
// Update with the averages
for (const [key, count] of counts) {
    result[key] = result[key] / counts.get(key);
}

Live Example:

// Quick-and-dirty polyfill for older environments without `Object.hasOwn`:
if (!Object.hasOwn) {
    Object.defineProperty(Object, "hasOwn", {
        value: Function.prototype.call.bind(Object.prototype.hasOwnProperty),
        writable: true,
        configurable: true,
    });
}

const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}];

const result = {};
const counts = new Map();
for (const element of arr) {
    for (const key in element) {
        if (Object.hasOwn(element, key)) {
            // Count this property
            counts.set(key, (counts.get(key) ?? 0) + 1);
            // Add it to the sum
            result[key] = (result[key] ?? 0) + element[key];
        }
    }
}
// Update with the averages
for (const [key, count] of counts) {
    result[key] = result[key] / counts.get(key);
}

console.log(result);


问:
Getting error line 132: ARCHS[@]: unbound variable
I have Xcode 13.2,
App Deployment target 12.0,
Swift version 4

Getting line 132: ARCHS[@]: unbound variable error while running in the real device. In the simulator, it is running fine.

I have also tried -

added arm64 in excluded architecture.

Build active architecture to Yes/No (no impact)

Xcode Snap

答: I added $(ARCHS_STANDARD) to the "build settings > user defined > VALID_ARCHS" setting in the project file and it was fixed. I hope it will solve your problem.