问:
Laravel_php terminate the request by sending a response at any given condition
I built a login backend where I want to check some conditions before allowing the login.

I could check all conditions in one shoot but I need to send a different response for every failed attempt.

In the index method below all check methods are called, the specific thing I need is that if any condition is true then the request should terminate and the response should be sent back without calling other methods after it.

Currently the return at every method seems not respected.

```<code>public function index(LoginRequest $request){
    $user = User::select('leave','role','id','isActive')->find(request('username'));
    $this->checkRole($user);
    $this->checkAnnualLeave($user);
    $this->checkAccountDisabled($user);
}

public function checkRole($user){
    $Condition1=true;

    if($Condition1){
       return response()->json(['message'=>'user is anauthorized !']);
    }
}

public function checkAnnualLeave($user){
    $Condition2=true;

    if($Condition2){
        return response()->json(['message'=>'user is in Annual leave']);
    }
}

public function checkAccountDisabled($user){
    $ConditioN3=true;

    if($ConditioN3){
       return response()->json(['message'=>'user account is disabled']);
    }
}
</code>```

答:
However, I think using 'Laravel Middleware' can simplify your code, but even in your current code you can use die() in each of your functions after return to stop the script from running. Like bellow:

```<code>if($Condition1){
   return response()->json(['message'=>'user is anauthorized !']);
   die();
}
</code>```

Another option is that check all conditions in one function. For instance, consider the following code:

```<code>public function index(LoginRequest $request){
    $user = User::select('leave','role','id','isActive')->find(request('username'));
    $this->checkUser($user);
}

public function checkUser($user) {
    Switch ($user) {
        case condition1:
            return response()->json(['message'=>'user is anauthorized !']);
            break;
        case condition2:
            return response()->json(['message'=>'user is in Annual leave']);
            break;
        case condition3:
            return response()->json(['message'=>'user account is disabled']);
            break;
        default:
    }
}
</code>```

Or you can use 'if statement' instead of 'switch statement'

Body:
I built a login backend where I want to check some conditions before allowing the login.

I could check all conditions in one shoot but I need to send a different response for every failed attempt.

In the index method below all check methods are called, the specific thing I need is that if any condition is true then the request should terminate and the response should be sent back without calling other methods after it.

Currently the return at every method seems not respected.

public function index(LoginRequest $request){
    $user = User::select('leave','role','id','isActive')->find(request('username'));
    $this->checkRole($user);
    $this->checkAnnualLeave($user);
    $this->checkAccountDisabled($user);
}

public function checkRole($user){
    $Condition1=true;

    if($Condition1){
       return response()->json(['message'=>'user is anauthorized !']);
    }
}

public function checkAnnualLeave($user){
    $Condition2=true;

    if($Condition2){
        return response()->json(['message'=>'user is in Annual leave']);
    }
}

public function checkAccountDisabled($user){
    $ConditioN3=true;

    if($ConditioN3){
       return response()->json(['message'=>'user account is disabled']);
    }
}

Body:
However, I think using 'Laravel Middleware' can simplify your code, but even in your current code you can use die() in each of your functions after return to stop the script from running. Like bellow:

if($Condition1){
   return response()->json(['message'=>'user is anauthorized !']);
   die();
}

Another option is that check all conditions in one function. For instance, consider the following code:

public function index(LoginRequest $request){
    $user = User::select('leave','role','id','isActive')->find(request('username'));
    $this->checkUser($user);
}

public function checkUser($user) {
    Switch ($user) {
        case condition1:
            return response()->json(['message'=>'user is anauthorized !']);
            break;
        case condition2:
            return response()->json(['message'=>'user is in Annual leave']);
            break;
        case condition3:
            return response()->json(['message'=>'user account is disabled']);
            break;
        default:
    }
}

Or you can use 'if statement' instead of 'switch statement'


来源: stackexchange

问:
Issue with preferedWrapContent and ConstraintLayout
I'm using a Composable which take a content @Composable in parameter, and it seems that with the final version of ConstraintLayout, there is no update.

Here is the code

@Composable
fun Example(
    modifier : Modifier = Modifier,
    content : @Composable () -> Unit
) {
     ConstraintLayout(modifier = modifier
            .fillMaxSize()
            .background(color = Color.Blue)
     ) {
        val (title, someContent) = createRefs()

        Text(text = "a text", modifier = Modifier.constrainAs(title) {
            top.linkTo(parent.top)
            height = Dimension.wrapContent
            width = Dimension.wrapContent
        })

        Box(modifier = Modifier
            .constrainAs(someContent) {
                width = Dimension.fillToConstraints
                linkTo(start = parent.start, end = parent.end)
                linkTo(top = parent.top, bottom = parent.bottom, bias = 1.0f)
                height = Dimension.preferredWrapContent
            }
            .background(color = Color.Yellow)) {
            content()
        }
    }
}
```

The Box height is initialized with the fist element received by the composable and does not change anymore.

For example, I send to this composable a Column with [Button + result of a Webservice]. The button is displayed at startup, and then after some times I received the result of the API, it does not recompose correctly, the size of the Box stays wrapcontent with the button only!

Am I doing something wrong ?
Moreover, it seems that the behaviour in a compose MotionLayout is the same (no update)

答:
A recomposition only occurs on a composable when at least one of the parameter values change. Because you are set the content parameter to a function, the parameter never changes.

The content parameter is pointing to a function reference and that reference never changes during recomposition.

If you want your composable to recompose with the updated data, you need to add a mutable state variable inside your composable that your viewmodel updates, or pass in a parameter that will change when you have received new data.

Here's an example of updating a parameter value using a state variable in a view model. Updating the state variable recomposes your composable and provides it with the updated variable (name):

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        startActivity(intent)

        setContent {
            val vm: MyViewModel = viewModel()
            vm.loadData()

            Example(name = vm.name.value) { name ->
                Text("Name: $name")
            }

        }
    }
}

class MyViewModel: ViewModel() {
    val name = mutableStateOf("")

    fun loadData() {
        viewModelScope.launch {
            delay(2000)
            name.value = "Joe Cool"
        }
    }
}

@Composable
fun Example(
modifier : Modifier = Modifier,
name: String,
content : @Composable (name: String) -> Unit
) {
    ConstraintLayout(modifier = modifier
        .fillMaxSize()
        .background(color = Color.Blue)
    ) {
        val (title, someContent) = createRefs()

        Text(text = "a text", modifier = Modifier.constrainAs(title) {
            top.linkTo(parent.top)
            height = Dimension.wrapContent
            width = Dimension.wrapContent
        })

        Box(modifier = Modifier
            .constrainAs(someContent) {
                width = Dimension.fillToConstraints
                linkTo(start = parent.start, end = parent.end)
                linkTo(top = parent.top, bottom = parent.bottom, bias = 1.0f)
                height = Dimension.preferredWrapContent
            }
            .background(color = Color.Yellow)) {
            content(name)
        }
    }
}

```

ContentLicense: CC BY-SA 4.0

Body:
I'm using a Composable which take a content @Composable in parameter, and it seems that with the final version of ConstraintLayout, there is no update.

Here is the code

@Composable
fun Example(
    modifier : Modifier = Modifier,
    content : @Composable () -> Unit
) {
     ConstraintLayout(modifier = modifier
            .fillMaxSize()
            .background(color = Color.Blue)
     ) {
        val (title, someContent) = createRefs()

        Text(text = "a text", modifier = Modifier.constrainAs(title) {
            top.linkTo(parent.top)
            height = Dimension.wrapContent
            width = Dimension.wrapContent
        })

        Box(modifier = Modifier
            .constrainAs(someContent) {
                width = Dimension.fillToConstraints
                linkTo(start = parent.start, end = parent.end)
                linkTo(top = parent.top, bottom = parent.bottom, bias = 1.0f)
                height = Dimension.preferredWrapContent
            }
            .background(color = Color.Yellow)) {
            content()
        }
    }
}

The Box height is initialized with the fist element received by the composable and does not change anymore.

For example, I send to this composable a Column with [Button + result of a Webservice]. The button is displayed at startup, and then after some times I received the result of the API, it does not recompose correctly, the size of the Box stays wrapcontent with the button only!

Am I doing something wrong ?
Moreover, it seems that the behaviour in a compose MotionLayout is the same (no update)


问:
how can i redirect a user to a different server with python?
I'm trying to write a script which will monitor packets (using pypcap) and redirect certain URLs/IPs to something I choose. I know I could just edit the hosts file, but that won't work because I'm not an admin.

I'm thinking that CGI might be useful, but this one has really got me confused.

EDIT:
sorry if it sounded malicious or like a MITM attack. The reason I need this is because I have an (old) application which grabs a page from a site, but the domain has changed recently causing it to not function anymore. I didn't write the application, so I can't just change the domain it accesses.

I basically need to accomplish what can be done by editing the hosts file without having access to it.

答:
pypcap needs administrative rights, so this is not an option.

And you don't have access to the pcs internals, to the source code or to the webserver.

There are a few options left:

Modify the host name in the applications files with a hexeditor and disassembler.

Modify the loaded application in memory with Cheat Engine and other memory tools.

Start the application in a virtual environment which can modify os api calls. A modified wine might be able to do this.

Modify the request between the pc and the webserver with a (transparent)proxy / modified router.

If the application supports the usage of proxies, it might be the easiest solution to set up a local squid with a redirector.

ContentLicense: CC BY-SA 3.0


问:
Can't get products by userId from repository
I have 2 tables. One of them called 'products'

```<code>@Data
@Entity
@Table(name = "products")
@NoArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 100)
@NotBlank(message = "Name must be written")
private String name;
@Column(length = 200)
@NotBlank(message = "Provide image (link in this case) of your product")
private String image;
@PositiveOrZero
private int amount;
@Column(length = 250)
@NotBlank(message = "description must be written")
@Size(min = 10, max = 250, message = "description is too long or empty")
private String description;
@PositiveOrZero
private float price;
@ManyToOne
@JoinColumn(name = "type_id")
private ProductType productType;

public Product(@NotBlank String name, String image, int amount, @NotBlank String description,
@PositiveOrZero float price, ProductType productType) {
this.name = name;
this.image = image;
this.amount = amount;
this.description = description;
this.price = price;
this.productType = productType;
}
}
</code>```

another table is 'users'

```<code>@Data
@Entity
@NoArgsConstructor
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 50)
@Size(min = 2, max = 30, message = "enter appropriate amount of letters, min 2")
private String username;
@Column(length = 100)
@Email(message = "Enter a valid email")
@NotBlank(message = "email should have a value")
private String email;
@Column(length = 50)
@NotBlank(message = "password should have a value")
@Size(min = 6, message = "password should at least consist of 6 characters")
private String password;
private boolean enabled;
private String role;

public User(@Size(min = 2, max = 30, message = "enter appropriate amount of letters, min 2")
String username,
            @Email(message = "Enter a valid email")
            @NotBlank(message = "email should have a value") String email,
            @NotBlank(message = "password should have a value")
            @Size(min = 6, message = "password should at least consist of 6 characters")
String password, boolean enabled, String role) {
    this.username = username;
    this.email = email;
    this.password = password;
    this.enabled = enabled;
    this.role = role;
}
}
</code>```

and also table that include both 'product_user' (many to many relationship)

it looks like this

```<code>@Data
@Entity
@Table(name = "product_user")
@AllArgsConstructor
@NoArgsConstructor
public class ProdAndUser{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;

@ManyToOne
@JoinColumn(name = "product_id")
Product product;

@ManyToOne
@JoinColumn(name = "user_id")
User user;

public ProdAndUser(Product product, User user) {
    this.product = product;
    this.user = user;
}

}
</code>```

then I tried to get them from prodAndUser repository by UserId or by User as obj:

```<code>@Repository
public interface ProdAndUserRepository extends JpaRepository<ProdAndUser, Integer> {
List<ProdAndUser> getProdAndUsersByUserId(Integer id);
List<ProdAndUser> getAllByUser(User user);
}
</code>```

my controller looks like this:

```<code>@ResponseBody
@GetMapping("/findByUsr/{user}")
public List<ProdAndUser> getByUser(@PathVariable User user){
    return prodAndUserRepository.getAllByUser(user);
}
</code>```

error:

```<code>{
 "timestamp": "2022-02-12T05:52:53.165+00:00",
 "status": 404,
 "error": "Not Found",
 "message": "No message available",
 "path": "/Cart/findByUsr"
 }
</code>```

I have tried to find them all by .findAll() and it worked fine. Also another tables work fine on their own

答:
Look at the error it says (404) means something is not right with the path.
The path on the error does not contain user_id.</p>

Body:
I have 2 tables. One of them called 'products'

@Data
@Entity
@Table(name = "products")
@NoArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 100)
@NotBlank(message = "Name must be written")
private String name;
@Column(length = 200)
@NotBlank(message = "Provide image (link in this case) of your product")
private String image;
@PositiveOrZero
private int amount;
@Column(length = 250)
@NotBlank(message = "description must be written")
@Size(min = 10, max = 250, message = "description is too long or empty")
private String description;
@PositiveOrZero
private float price;
@ManyToOne
@JoinColumn(name = "type_id")
private ProductType productType;

public Product(@NotBlank String name, String image, int amount, @NotBlank String description,
@PositiveOrZero float price, ProductType productType) {
this.name = name;
this.image = image;
this.amount = amount;
this.description = description;
this.price = price;
this.productType = productType;
}
}

another table is 'users'

@Data
@Entity
@NoArgsConstructor
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 50)
@Size(min = 2, max = 30, message = "enter appropriate amount of letters, min 2")
private String username;
@Column(length = 100)
@Email(message = "Enter a valid email")
@NotBlank(message = "email should have a value")
private String email;
@Column(length = 50)
@NotBlank(message = "password should have a value")
@Size(min = 6, message = "password should at least consist of 6 characters")
private String password;
private boolean enabled;
private String role;

public User(@Size(min = 2, max = 30, message = "enter appropriate amount of letters, min 2")
String username,
            @Email(message = "Enter a valid email")
            @NotBlank(message = "email should have a value") String email,
            @NotBlank(message = "password should have a value")
            @Size(min = 6, message = "password should at least consist of 6 characters")
String password, boolean enabled, String role) {
    this.username = username;
    this.email = email;
    this.password = password;
    this.enabled = enabled;
    this.role = role;
}
}

and also table that include both 'product_user' (many to many relationship)

it looks like this

@Data
@Entity
@Table(name = "product_user")
@AllArgsConstructor
@NoArgsConstructor
public class ProdAndUser{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;

@ManyToOne
@JoinColumn(name = "product_id")
Product product;

@ManyToOne
@JoinColumn(name = "user_id")
User user;

public ProdAndUser(Product product, User user) {
    this.product = product;
    this.user = user;
}

}

then I tried to get them from prodAndUser repository by UserId or by User as obj:

@Repository
public interface ProdAndUserRepository extends JpaRepository<ProdAndUser, Integer> {
List<ProdAndUser> getProdAndUsersByUserId(Integer id);
List<ProdAndUser> getAllByUser(User user);
}

my controller looks like this:

@ResponseBody
@GetMapping("/findByUsr/{user}")
public List<ProdAndUser> getByUser(@PathVariable User user){
    return prodAndUserRepository.getAllByUser(user);
}

error:

{
 "timestamp": "2022-02-12T05:52:53.165+00:00",
 "status": 404,
 "error": "Not Found",
 "message": "No message available",
 "path": "/Cart/findByUsr"
 }

I have tried to find them all by .findAll() and it worked fine. Also another tables work fine on their own


问:
"'!_needsLayout': is not true" error in Flutter when changing between screens with BottomNavigationBar
I have a Scaffold with BottomNavigationBar:

```<code>class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int _currentIndex = 0;
  final List<Widget> _children = [
    const FirstPage(),
    const SecondPage(),
    const ThirdPage(),
  ];

  void onTabTapped(int index) {
  setState(() {
    _currentIndex = index;
  });
}

  @override
  Widget build(BuildContext context) {

    size = MediaQuery.of(context).size;
    topPadding = MediaQuery.of(context).padding.top;

    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: SizedBox(
        height: 60,
        child: BottomNavigationBar(
          elevation: 0,
          selectedItemColor: Colors.orange,
          unselectedItemColor: Colors.black,
          showSelectedLabels: false,
          showUnselectedLabels: false,
          onTap: onTabTapped,
          currentIndex: _currentIndex, // this will be set when a new tab is tapped
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.video_call_rounded),
              label: "Settings",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.person),
              label: 'Profile',
            )
          ],
        ),
      ),
    );
  }
}
</code>```

But when I switch between screens using BottomNavigationBar I sometimes get an error Unhandled Exception: 'package:flutter/src/painting/text_painter.dart': Failed assertion: line 881 pos 12: '!_needsLayout': is not true.

How to fix this issue?

EDIT

Here is the full code with error logs:

main.dart

```<code>import 'package:cook_it/home.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter App!',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        splashFactory: InkRipple.splashFactory,
      ),
      home: Home(),
    );
  }
}
</code>```

home.dart

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

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int _currentIndex = 0;
  final List<Widget> _children = [
    const ProfilePage(),
    const ProfilePage(),
    const ProfilePage(),
  ];

  void onTabTapped(int index) {
  setState(() {
    _currentIndex = index;
  });
}

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: SizedBox(
        height: 60,
        child: BottomNavigationBar(
          elevation: 0,
          selectedItemColor: Colors.orange,
          unselectedItemColor: Colors.black,
          showSelectedLabels: false,
          showUnselectedLabels: false,
          onTap: onTabTapped,
          currentIndex: _currentIndex, // this will be set when a new tab is tapped
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.video_call_rounded),
              label: "Settings",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.person),
              label: 'Profile',
            )
          ],
        ),
      ),
    );
  }
}
</code>```

profile_page.dart

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

class ProfilePage extends StatefulWidget {
  const ProfilePage({ Key? key }) : super(key: key);

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.red,),
    );
  }
}
</code>```

ERRORS

```<code>E/flutter (15525): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:flutter/src/painting/text_painter.dart': Failed assertion: line 881 pos 12: '!_needsLayout': is not true.
E/flutter (15525): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter (15525): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter (15525): #2      TextPainter.getPositionForOffset
package:flutter/…/painting/text_painter.dart:881
E/flutter (15525): #3      RenderParagraph.hitTestChildren
package:flutter/…/rendering/paragraph.dart:456
E/flutter (15525): #4      RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #5      RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #6      RenderTransform.hitTestChildren.<anonymous closure>
package:flutter/…/rendering/proxy_box.dart:2347
E/flutter (15525): #7      BoxHitTestResult.addWithRawTransform
package:flutter/…/rendering/box.dart:826
E/flutter (15525): #8      BoxHitTestResult.addWithPaintTransform
package:flutter/…/rendering/box.dart:751
E/flutter (15525): #9      RenderTransform.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:2343
E/flutter (15525): #10     RenderTransform.hitTest
package:flutter/…/rendering/proxy_box.dart:2337
E/flutter (15525): #11     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #12     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #13     RenderShiftedBox.hitTestChildren.<anonymous closure>
package:flutter/…/rendering/shifted_box.dart:92
E/flutter (15525): #14     BoxHitTestResult.addWithPaintOffset
package:flutter/…/rendering/box.dart:787
E/flutter (15525): #15     RenderShiftedBox.hitTestChildren
package:flutter/…/rendering/shifted_box.dart:87
E/flutter (15525): #16     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #17     RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<anonymous closure>
package:flutter/…/rendering/box.dart:2775
E/flutter (15525): #18     BoxHitTestResult.addWithPaintOffset
package:flutter/…/rendering/box.dart:787
E/flutter (15525): #19     RenderBoxContainerDefaultsMixin.defaultHitTestChildren
package:flutter/…/rendering/box.dart:2770
E/flutter (15525): #20     RenderFlex.hitTestChildren
package:flutter/…/rendering/flex.dart:1072
E/flutter (15525): #21     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #22     RenderShiftedBox.hitTestChildren.<anonymous closure>
package:flutter/…/rendering/shifted_box.dart:92
E/flutter (15525): #23     BoxHitTestResult.addWithPaintOffset
package:flutter/…/rendering/box.dart:787
E/flutter (15525): #24     RenderShiftedBox.hitTestChildren
package:flutter/…/rendering/shifted_box.dart:87
E/flutter (15525): #25     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #26     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #27     RenderProxyBoxWithHitTestBehavior.hitTest
package:flutter/…/rendering/proxy_box.dart:178
E/flutter (15525): #28     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #29     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #30     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #31     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #32     RenderMouseRegion.hitTest
package:flutter/…/rendering/proxy_box.dart:2905
E/flutter (15525): #33     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #34     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #35     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #36     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #37     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #38     RenderProxyBoxWithHitTestBehavior.hitTest
package:flutter/…/rendering/proxy_box.dart:178
E/flutter (15525): #39     RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<anonymous closure>
package:flutter/…/rendering/box.dart:2775
E/flutter (15525): #40     BoxHitTestResult.addWithPaintOffset
package:flutter/…/rendering/box.dart:787
E/flutter (15525): #41     RenderBoxContainerDefaultsMixin
E/flutter (15525): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:flutter/src/painting/text_painter.dart': Failed assertion: line 881 pos 12: '!_needsLayout': is not true.
E/flutter (15525): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter (15525): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter (15525): #2      TextPainter.getPositionForOffset
package:flutter/…/painting/text_painter.dart:881
E/flutter (15525): #3      RenderParagraph.hitTestChildren
package:flutter/…/rendering/paragraph.dart:456
</code>```

I modified the code a little bit to make it more clear but I tested this code and sometimes it still gives the same error (logs are above).

答:
I also encountered the same problem, and I searched for a long time and couldn't find a better solution.

Looking at the code, the reason for the problem is guessed that the theme has been updated (color, font), which causes the TextPainter object to be re-layout, but before the layout is completed, the HitTest event continues to process, which causes the problem.

This question should be a problem with the discussion here
https://github.com/flutter/flutter/issues/85108
But still haven't found a feasible solution.

The component that will cause this problem is not only BottomNavigationBarItem but also components such as TextButton that respond to HitTest events.

My temporary workaround is

Modify text_painter.dart to add

bool get needsLayout => _paragraph == null;
```
<ol start="2">
<li>Modify paragraph.dart</li>
</ol>
<pre class="lang-dart prettyprint-override"><code>bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
    // Hit test text spans.
    bool hitText = false;
    // add the following three lines
    if (_textPainter.needsLayout) {
        return hitText;
    }
    // This line is the code that caused the exception.
    // Before this, judge whether layout is required. If so,
    // return false directly and do not process the hittest of this process.
    final TextPosition textPosition = _textPainter.getPositionForOffset(position);
}
</code>```

Body:
I have a Scaffold with BottomNavigationBar:

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int _currentIndex = 0;
  final List<Widget> _children = [
    const FirstPage(),
    const SecondPage(),
    const ThirdPage(),
  ];

  void onTabTapped(int index) {
  setState(() {
    _currentIndex = index;
  });
}

  @override
  Widget build(BuildContext context) {

    size = MediaQuery.of(context).size;
    topPadding = MediaQuery.of(context).padding.top;

    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: SizedBox(
        height: 60,
        child: BottomNavigationBar(
          elevation: 0,
          selectedItemColor: Colors.orange,
          unselectedItemColor: Colors.black,
          showSelectedLabels: false,
          showUnselectedLabels: false,
          onTap: onTabTapped,
          currentIndex: _currentIndex, // this will be set when a new tab is tapped
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.video_call_rounded),
              label: "Settings",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.person),
              label: 'Profile',
            )
          ],
        ),
      ),
    );
  }
}

But when I switch between screens using BottomNavigationBar I sometimes get an error Unhandled Exception: 'package:flutter/src/painting/text_painter.dart': Failed assertion: line 881 pos 12: '!_needsLayout': is not true.

How to fix this issue?

EDIT

Here is the full code with error logs:

main.dart

import 'package:cook_it/home.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter App!',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        splashFactory: InkRipple.splashFactory,
      ),
      home: Home(),
    );
  }
}

home.dart

import 'package:cook_it/screens/profile_page.dart';
import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int _currentIndex = 0;
  final List<Widget> _children = [
    const ProfilePage(),
    const ProfilePage(),
    const ProfilePage(),
  ];

  void onTabTapped(int index) {
  setState(() {
    _currentIndex = index;
  });
}

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: SizedBox(
        height: 60,
        child: BottomNavigationBar(
          elevation: 0,
          selectedItemColor: Colors.orange,
          unselectedItemColor: Colors.black,
          showSelectedLabels: false,
          showUnselectedLabels: false,
          onTap: onTabTapped,
          currentIndex: _currentIndex, // this will be set when a new tab is tapped
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.video_call_rounded),
              label: "Settings",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.person),
              label: 'Profile',
            )
          ],
        ),
      ),
    );
  }
}

profile_page.dart

import 'package:flutter/material.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({ Key? key }) : super(key: key);

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.red,),
    );
  }
}

ERRORS

E/flutter (15525): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:flutter/src/painting/text_painter.dart': Failed assertion: line 881 pos 12: '!_needsLayout': is not true.
E/flutter (15525): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter (15525): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter (15525): #2      TextPainter.getPositionForOffset
package:flutter/…/painting/text_painter.dart:881
E/flutter (15525): #3      RenderParagraph.hitTestChildren
package:flutter/…/rendering/paragraph.dart:456
E/flutter (15525): #4      RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #5      RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #6      RenderTransform.hitTestChildren.<anonymous closure>
package:flutter/…/rendering/proxy_box.dart:2347
E/flutter (15525): #7      BoxHitTestResult.addWithRawTransform
package:flutter/…/rendering/box.dart:826
E/flutter (15525): #8      BoxHitTestResult.addWithPaintTransform
package:flutter/…/rendering/box.dart:751
E/flutter (15525): #9      RenderTransform.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:2343
E/flutter (15525): #10     RenderTransform.hitTest
package:flutter/…/rendering/proxy_box.dart:2337
E/flutter (15525): #11     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #12     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #13     RenderShiftedBox.hitTestChildren.<anonymous closure>
package:flutter/…/rendering/shifted_box.dart:92
E/flutter (15525): #14     BoxHitTestResult.addWithPaintOffset
package:flutter/…/rendering/box.dart:787
E/flutter (15525): #15     RenderShiftedBox.hitTestChildren
package:flutter/…/rendering/shifted_box.dart:87
E/flutter (15525): #16     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #17     RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<anonymous closure>
package:flutter/…/rendering/box.dart:2775
E/flutter (15525): #18     BoxHitTestResult.addWithPaintOffset
package:flutter/…/rendering/box.dart:787
E/flutter (15525): #19     RenderBoxContainerDefaultsMixin.defaultHitTestChildren
package:flutter/…/rendering/box.dart:2770
E/flutter (15525): #20     RenderFlex.hitTestChildren
package:flutter/…/rendering/flex.dart:1072
E/flutter (15525): #21     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #22     RenderShiftedBox.hitTestChildren.<anonymous closure>
package:flutter/…/rendering/shifted_box.dart:92
E/flutter (15525): #23     BoxHitTestResult.addWithPaintOffset
package:flutter/…/rendering/box.dart:787
E/flutter (15525): #24     RenderShiftedBox.hitTestChildren
package:flutter/…/rendering/shifted_box.dart:87
E/flutter (15525): #25     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #26     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #27     RenderProxyBoxWithHitTestBehavior.hitTest
package:flutter/…/rendering/proxy_box.dart:178
E/flutter (15525): #28     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #29     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #30     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #31     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #32     RenderMouseRegion.hitTest
package:flutter/…/rendering/proxy_box.dart:2905
E/flutter (15525): #33     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #34     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #35     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #36     RenderBox.hitTest
package:flutter/…/rendering/box.dart:2414
E/flutter (15525): #37     RenderProxyBoxMixin.hitTestChildren
package:flutter/…/rendering/proxy_box.dart:131
E/flutter (15525): #38     RenderProxyBoxWithHitTestBehavior.hitTest
package:flutter/…/rendering/proxy_box.dart:178
E/flutter (15525): #39     RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<anonymous closure>
package:flutter/…/rendering/box.dart:2775
E/flutter (15525): #40     BoxHitTestResult.addWithPaintOffset
package:flutter/…/rendering/box.dart:787
E/flutter (15525): #41     RenderBoxContainerDefaultsMixin
E/flutter (15525): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 'package:flutter/src/painting/text_painter.dart': Failed assertion: line 881 pos 12: '!_needsLayout': is not true.
E/flutter (15525): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter (15525): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter (15525): #2      TextPainter.getPositionForOffset
package:flutter/…/painting/text_painter.dart:881
E/flutter (15525): #3      RenderParagraph.hitTestChildren
package:flutter/…/rendering/paragraph.dart:456

I modified the code a little bit to make it more clear but I tested this code and sometimes it still gives the same error (logs are above).

Body:
I also encountered the same problem, and I searched for a long time and couldn't find a better solution.

Looking at the code, the reason for the problem is guessed that the theme has been updated (color, font), which causes the TextPainter object to be re-layout, but before the layout is completed, the HitTest event continues to process, which causes the problem.

This question should be a problem with the discussion here
https://github.com/flutter/flutter/issues/85108
But still haven't found a feasible solution.

The component that will cause this problem is not only BottomNavigationBarItem but also components such as TextButton that respond to HitTest events.

My temporary workaround is

Modify text_painter.dart to add

bool get needsLayout => _paragraph == null;

Modify paragraph.dart

bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
    // Hit test text spans.
    bool hitText = false;
    // add the following three lines
    if (_textPainter.needsLayout) {
        return hitText;
    }
    // This line is the code that caused the exception.
    // Before this, judge whether layout is required. If so,
    // return false directly and do not process the hittest of this process.
    final TextPosition textPosition = _textPainter.getPositionForOffset(position);
}


问:
How to refresh the same page after select option changes in another component using ionic?
I'm new to ionic. I'm trying to refresh the same page after user selects an option from dropdown. but the my dropdown is in another component(somehow like partial view) and I used this in other components.
I tried navigating but it didn't refresh the page. I want when user selects an option that component will refresh.
the ngOnInit method works fine btw.
This is my partial view component:

```<code> navigateTo(path: string) {
localStorage.setItem('selectedapp', this.appId);
this.router.navigate([path]);
 }
</code>```

this is the html of this component:

```<code>  <ion-item *ngIf="!isPrivate">
  <ion-label>فروشگاه های من</ion-label>
  <ion-select [(ngModel)]="appId" (ionChange)="navigateTo(model[0].url)" ok-text="تایید" cancel-text="کنسل" [value]="00000000-0000-0000-0000-000000000000">
    <ion-select-option value="00000000-0000-0000-0000-000000000000">همه</ion-select-option>
    <ion-select-option value="{{item.applicationId}}" *ngFor="let item of model">{{item.applicationTitle}}</ion-select-option>
    </ion-select>
</ion-item>
</code>```

This is where I used above component's tag in another html page:

```<code> <app-user-applications returnUrl="prizePackages"></app-user-applications>
</code>```

in this case I want to refresh the prizePackages page.
what should I do?

答:
This problem resolved using</p>
```<code>window.location.reload();
</code>```

Body:
I'm new to ionic. I'm trying to refresh the same page after user selects an option from dropdown. but the my dropdown is in another component(somehow like partial view) and I used this in other components.
I tried navigating but it didn't refresh the page. I want when user selects an option that component will refresh.
the ngOnInit method works fine btw.
This is my partial view component:

 navigateTo(path: string) {
localStorage.setItem('selectedapp', this.appId);
this.router.navigate([path]);
 }

this is the html of this component:

  <ion-item *ngIf="!isPrivate">
  <ion-label>فروشگاه های من</ion-label>
  <ion-select [(ngModel)]="appId" (ionChange)="navigateTo(model[0].url)" ok-text="تایید" cancel-text="کنسل" [value]="00000000-0000-0000-0000-000000000000">
    <ion-select-option value="00000000-0000-0000-0000-000000000000">همه</ion-select-option>
    <ion-select-option value="{{item.applicationId}}" *ngFor="let item of model">{{item.applicationTitle}}</ion-select-option>
    </ion-select>
</ion-item>

This is where I used above component's tag in another html page:

 <app-user-applications returnUrl="prizePackages"></app-user-applications>

in this case I want to refresh the prizePackages page.
what should I do?

Body:
This problem resolved using

window.location.reload();


问:
Converting HTML in PHP File to PDF File
I have a php file which queries a database and then writes and updates the html accordingly.

I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:

```<code>FPDF error: Unable to create output file: Entry Report
</code>```

I suspect the problem is because I am passing a php file instead of a html file:

```<code><?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>
</code>```

Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...

Or is there a direct way to convert a php file into a pdf file...

EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...

I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?

Here is the php page:

```<code><?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src = "jQuery.js"></script>
   <script>
   $(document).ready(function(){
       $("#export").click(function(e){
       //post to html2pdfconverter.php
       $("#link").val("Testers/viewentryreport.php");
       $("#nm").val("Entry Report.pdf");
       $("form#sendanswers").submit();
       });
   });
  </script>
  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
  </head>
  <body>
  <h1>Entry Report - <?php echo($date); ?></h1>
  <div id = "buttons">
  <form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
  <input type = "hidden" name = "link" id = "link" value = "">
  <input type = "hidden" name = "nm" id = "nm" value = "">
  <input type = "button" name = "export" id = "export" value = "Export As PDF"/>
  </form>
  </div>
  <h3>Biological Information</h3>
  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("<br/>");
      echo($value['question']." <br/> "."<img src = \"$image\"/>");
      echo("<br/>");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("<br/>");
    $i++;
      }
  ?>
  <h3>Fatigue and Recovery</h3>
  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Illness and Injury</h3>
  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Training Sessions</h3>
  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>General Feedback</h3>
  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       $sectionFive = "User didn't leave any feedback";
       echo("User didn't leave any feedback");
     }
     echo("<br/>");
  ?>
  </body>
</html>
<?php
}
?>
</code>```

and html2pdfconverter.php

```<code><?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>
</code>```

EDIT @TIMFERRIS

I changed my convert function to this based on @TimeFerris' answer:

```<code>function convert($link, $name){

  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $content = file_get_contents( $link ); //shorter than what you did
  ob_start();
  echo $content;
  $pdf->WriteHTML( ob_get_contents() );
  ob_end_clean();
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
</code>```

The PDF file is created but still blank

答: One thing that you could do is run the PHP file, but use output buffering to capture the contents that the PHP script is writing out. Then, save those contents to an .html file and pass that file to the converter.</p>

Title: Converting HTML in PHP File to PDF File

Body:
I have a php file which queries a database and then writes and updates the html accordingly.

I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:

FPDF error: Unable to create output file: Entry Report

I suspect the problem is because I am passing a php file instead of a html file:

<?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>

Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...

Or is there a direct way to convert a php file into a pdf file...

EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...

I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?

Here is the php page:

<?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>

   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>

Entry Report - <?php echo($date); ?>

  <form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
  <input type = "hidden" name = "link" id = "link" value = "">
  <input type = "hidden" name = "nm" id = "nm" value = "">
  <input type = "button" name = "export" id = "export" value = "Export As PDF"/>
  </form>

Biological Information

  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("
");
      echo($value['question']."
 "."");
      echo("
");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("
");
    $i++;
      }
  ?>

Fatigue and Recovery

  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Illness and Injury

  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Training Sessions

  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

General Feedback

  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       $sectionFive = "User didn't leave any feedback";
       echo("User didn't leave any feedback");
     }
     echo("
");
  ?>

<?php
}
?>

and html2pdfconverter.php

<?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>

EDIT @TIMFERRIS

I changed my convert function to this based on @TimeFerris' answer:

function convert($link, $name){

  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $content = file_get_contents( $link ); //shorter than what you did
  ob_start();
  echo $content;
  $pdf->WriteHTML( ob_get_contents() );
  ob_end_clean();
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}

The PDF file is created but still blank


问:
Pandas not appending values to data frame
I have a file called balance.csv. It contains user data such as their discord ID number, their account balance, and the amount of stocks that they own. I'm trying to create a simple command using discord.py that lets them know their account balance. If they don't have an account, it initializes one for them. However, the values aren't being appended to the CSV file when the code tries to initialize the account. I am not sure where the problem is and why it is occurring. I'm using pandas and discord.py.</p>
```<code>balance_data = pd.read_csv('balance.csv')

def init_account(id):
    global balance_data
    balance_data = balance_data.append({"user_id":id, "account_balance":100, "stocks":0}, ignore_index=True)

@client.command(name='bal')
async def balance(ctx):
    if ctx.author.id not in balance_data["user_id"].values:
        await ctx.send("Creating Account...")
        init_account(ctx.author.id)
        await ctx.send("Account created.")
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
    else:
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
</code>```

答:
create an empty dataframe and append it there ..
after that u can use .to_csv to export it

Body:
I have a file called balance.csv. It contains user data such as their discord ID number, their account balance, and the amount of stocks that they own. I'm trying to create a simple command using discord.py that lets them know their account balance. If they don't have an account, it initializes one for them. However, the values aren't being appended to the CSV file when the code tries to initialize the account. I am not sure where the problem is and why it is occurring. I'm using pandas and discord.py.

balance_data = pd.read_csv('balance.csv')

def init_account(id):
    global balance_data
    balance_data = balance_data.append({"user_id":id, "account_balance":100, "stocks":0}, ignore_index=True)

@client.command(name='bal')
async def balance(ctx):
    if ctx.author.id not in balance_data["user_id"].values:
        await ctx.send("Creating Account...")
        init_account(ctx.author.id)
        await ctx.send("Account created.")
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
    else:
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")


问:
AWS Lambda python function - Add error metrics in cloudwatch for handled exception
I would like to be able to see in Cloudwatch metrics (and Lambda metrics) errors for handle exception.

For the moment I see the errors only in Cloudwatch log group for handled errors.

Here is the code I use in my Lambda

def lambda_handler(event, context):
    try:
       raise Exception("My exeception")
    except Exception as e:
       logger.exception(str(e))
       continue
```
<p>And my logger is defined like this</p>
```import logging

logger =  logging.getLogger()
logger.setLevel(logging.INFO)
```

With this configuration I can just see errors in my logs group, but not in the lamda/cloudwatch metrics

答:
According to your given code snippet, the lambda execution was completed successfully.
To track the failure and success you've to just raise the exception in case of failure and handle it in case of success.

def lambda_handler(event, context):
    # try:
    raise Exception("My exception")
    # except Exception as e:
    # logger.exception(str(e))
    # continue
```

The logger will show all the logged error/success messages in the stream.

So, if you'll handle the error, then it won't be a failure execution hence no failure on the graph.

Body:
I would like to be able to see in Cloudwatch metrics (and Lambda metrics) errors for handle exception.

For the moment I see the errors only in Cloudwatch log group for handled errors.

Here is the code I use in my Lambda

def lambda_handler(event, context):
    try:
       raise Exception("My exeception")
    except Exception as e:
       logger.exception(str(e))
       continue

And my logger is defined like this

import logging

logger =  logging.getLogger()
logger.setLevel(logging.INFO)

With this configuration I can just see errors in my logs group, but not in the lamda/cloudwatch metrics

Body:
According to your given code snippet, the lambda execution was completed successfully.
To track the failure and success you've to just raise the exception in case of failure and handle it in case of success.

def lambda_handler(event, context):
    # try:
    raise Exception("My exception")
    # except Exception as e:
    # logger.exception(str(e))
    # continue

The logger will show all the logged error/success messages in the stream.

So, if you'll handle the error, then it won't be a failure execution hence no failure on the graph.


问:
Could not find a version that satisfies the requirement torch>=1.0.0?
Could not find a version that satisfies the requirement torch>=1.0.0
No matching distribution found for torch>=1.0.0 (from stanfordnlp)</p>

答:
If you have python 3.7 already installed along with newer versions then can use below command to install torch using python 3.7

```<code>py -3.7 -m pip install torch
</code>```

But also note that you have to execute the python program using py -3.7

```<code>py -3.7 program_name.py
</code>```

Body:
If you have python 3.7 already installed along with newer versions then can use below command to install torch using python 3.7

py -3.7 -m pip install torch

But also note that you have to execute the python program using py -3.7

py -3.7 program_name.py


问:
Replace part of a string and upper case the result
everything good?
I would like some help from you, I have the following scenario:

```<code>STRING_ONE:
       string_two
   STRING_three     :
                   string_four:
    stringfive:
</code>```

I need to identify words from the beginning of the line that end with :

after identifying the words, I need to erase the spaces and convert them to uppercase,
i tried doing some regex but as the words change I can't set the default for the replacement because i need to keep the same word, just removing the spaces and converting to capital letters

The result I'm trying to get is this:

```<code>STRING_ONE:
       string_two
   STRING_three     :
STRING_FOUR:
STRINGFIVE:
</code>```

I can capture the words that match this pattern, with the following regex, but I don't know how to replace it by just erasing the spaces, keeping the rest of the string the same, and doing the upper case

```<code>^.*\b:
</code>```

I tried to replace like this but it didn't work

```<code>"$1".toUpperCase()
</code>```

Can anyone help please?
Thanks!

答:
As you are not really replacing anything but instead you are looking for a pattern I used the pattern in a String.prototype.match() to identify the lines in which .trim() and .toLowerCase() need to be applied. The .split("\n") turns the initial string into an array over which I can then .map() the individual lines. At the end I .join() everything together again.

const str=`STRING_ONE:
   string_two
   STRING_three     :
               string_four:
stringfive:`;

console.log(str
   .split("\n")
   .map(s=>s.match(/^\s*\w+:\s*$/) && s.trim().toUpperCase() || s )
   .join("\n")
);```

Our regex patterns differ slightly:

while yours (/^.*\b:/) will match any line that has at least one word-end followed by a colon in it

mine (/^\s*\w+:\s*$/) is stricter and demands that there is exactly one word followed by a colon in a line that can optionally be padded by any number of whitespace characters on either side.

Body:
everything good?
I would like some help from you, I have the following scenario:

STRING_ONE:
       string_two
   STRING_three     :
                   string_four:
    stringfive:

I need to identify words from the beginning of the line that end with :

after identifying the words, I need to erase the spaces and convert them to uppercase,
i tried doing some regex but as the words change I can't set the default for the replacement because i need to keep the same word, just removing the spaces and converting to capital letters

The result I'm trying to get is this:

STRING_ONE:
       string_two
   STRING_three     :
STRING_FOUR:
STRINGFIVE:

I can capture the words that match this pattern, with the following regex, but I don't know how to replace it by just erasing the spaces, keeping the rest of the string the same, and doing the upper case

^.*\b:

I tried to replace like this but it didn't work

"$1".toUpperCase()

Can anyone help please?
Thanks!

Body:
As you are not really replacing anything but instead you are looking for a pattern I used the pattern in a String.prototype.match() to identify the lines in which .trim() and .toLowerCase() need to be applied. The .split("\n") turns the initial string into an array over which I can then .map() the individual lines. At the end I .join() everything together again.

const str=`STRING_ONE:
   string_two
   STRING_three     :
               string_four:
stringfive:`;

console.log(str
   .split("\n")
   .map(s=>s.match(/^\s*\w+:\s*$/) && s.trim().toUpperCase() || s )
   .join("\n")
);

Our regex patterns differ slightly:

while yours (/^.*\b:/) will match any line that has at least one word-end followed by a colon in it

mine (/^\s*\w+:\s*$/) is stricter and demands that there is exactly one word followed by a colon in a line that can optionally be padded by any number of whitespace characters on either side.


问:
android garbage collector, freeing objects inside objects
I'm very curious about how this thing works inside Android. I have a class with two List<> inside, instantiated at runtime and loaded with objects created while reading some data, I want to know what happens with those Lists in this situation:

Class A has List B and List C with many other initialized objects
inside.

Another different class get a reference of List C from a
method of Class A, like  public List<myObject> GetList().

Somewhere in code, Class A is no longer used and application
signals that to garbage collector, setting object to null.

What happens with my List C that is referenced by other object?  What happens with Object class A?

I've tried to track garbage collector with Logcat running apk in debugger step-by-step but no luck at all. Sometimes it frees memory, sometimes not, I couldn't pinpoint any specific behaviour.

答: The object of class A will be garbage collected during the next GC-cycle. List B will be GC'ed too. And List C will not be GC'ed because it can be reached from GC roots.</p>


问:
Get env variables inside _middleware Next.js
Inside my nextjs project I have variables added in both .env and next.conf.js files. Inside next.conf.js file it looks like this

```<code>module.exports = {
  env: {
    NEXT_PUBLIC_JWT_SECRET: "...",
  },
  publicRuntimeConfig: {
    NEXT_PUBLIC_JWT_SECRET: "...",
    API_JWT_SECRET: process.env.API_JWT_SECRET,
  },
  serverRuntimeConfig: {
    // Will only be available on the server side
    NEXT_PUBLIC_JWT_SECRET: "...",
    secondSecret: process.env.JWT_SECRET, // Pass through env variables
  },
};
</code>```

I have tried all this ways to get the secret ket in my _middleware file, but none of them worked. From this github issue I assume that there is a way to do that. So could you please show me the correct way to get secret ket inside _middleware?

答:
As hugefunwoo says

Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.

```<code>const { JWT_SECRET } = process.env
</code>```

This will return undefind so I had to replace it by

```<code>const JWT_SECRET = process.env.JWT_SECRET
</code>```

Body:
Inside my nextjs project I have variables added in both .env and next.conf.js files. Inside next.conf.js file it looks like this

module.exports = {
  env: {
    NEXT_PUBLIC_JWT_SECRET: "...",
  },
  publicRuntimeConfig: {
    NEXT_PUBLIC_JWT_SECRET: "...",
    API_JWT_SECRET: process.env.API_JWT_SECRET,
  },
  serverRuntimeConfig: {
    // Will only be available on the server side
    NEXT_PUBLIC_JWT_SECRET: "...",
    secondSecret: process.env.JWT_SECRET, // Pass through env variables
  },
};

I have tried all this ways to get the secret ket in my _middleware file, but none of them worked. From this github issue I assume that there is a way to do that. So could you please show me the correct way to get secret ket inside _middleware?

Body:
As hugefunwoo says

Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.

const { JWT_SECRET } = process.env

This will return undefind so I had to replace it by

const JWT_SECRET = process.env.JWT_SECRET


问:
Infinite scroll conflicts with scroll-snap-align CSS property
To allow infinite scrolling inside a
, I added a 'scroll' event to it. When the first child is in the viewport, I prepend the last child and viceversa.

Ive gotten this to work perfectly until I bring in scroll-snap-align. Here, I have set up an example where one carousel has scroll snap while the other one doesn't.

const scrollInfo = (parent) => {
    let viewWidth = parseInt(getComputedStyle(parent).width),
        realWidth = parent.scrollWidth - viewWidth,
        currentChild = Math.floor((parent.scrollLeft + viewWidth / 3) / viewWidth);
    return {
        current: currentChild,
        view: viewWidth
    };
};

let carousels = [infiniteCarousel1, infiniteCarousel2]

carousels.forEach(carousel => {
carousel.onscroll = () => {
    let info = scrollInfo(carousel),
        scroll = carousel.scrollLeft,
        len = carousel.children.length - 1;
    if (info.current <= 0) {
        carousel.scrollLeft = scroll + info.view;
        carousel.prepend(carousel.children[len]);
    } else if (info.current >= len) {
        carousel.scrollLeft = scroll - info.view;
        carousel.append(carousel.children[0]);
    }
};

window.addEventListener("DOMContentLoaded", () => {
    setTimeout(() => {
        carousel.scrollTo({ left: scrollInfo(carousel).view });
    }, 1000);
})
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    box-sizing: border-box;
}

.carousel {
    display: flex;
    overflow-x: scroll;
    width: 100%;
    height: 100px;
}

.carousel > div {
    display: inherit;
    justify-content: center;
    align-items: center;
    min-width: 100%;
    height: 100%;
    border: 2px solid;
    scroll-snap-align: center;
}

#infiniteCarousel1 {
    scroll-snap-type: x mandatory;
}</code>```

Scroll Snap

1

2

3

4

5

No Scroll Snap

1

2

3

4

5

```

The same example in CodePen.

答: I will tell you a trick i used in the past. Add an extra slide of the last slide to the beginning and an extra slide of the first slide on the end. Then when the selected slide its either of those 2. Scroll to position of the original without animation. Let me know of you need more help.</p>

Body:
To allow infinite scrolling inside a
, I added a 'scroll' event to it. When the first child is in the viewport, I prepend the last child and viceversa.

Ive gotten this to work perfectly until I bring in scroll-snap-align. Here, I have set up an example where one carousel has scroll snap while the other one doesn't.

const scrollInfo = (parent) => {
    let viewWidth = parseInt(getComputedStyle(parent).width),
        realWidth = parent.scrollWidth - viewWidth,
        currentChild = Math.floor((parent.scrollLeft + viewWidth / 3) / viewWidth);
    return {
        current: currentChild,
        view: viewWidth
    };
};

let carousels = [infiniteCarousel1, infiniteCarousel2]

carousels.forEach(carousel => {
carousel.onscroll = () => {
    let info = scrollInfo(carousel),
        scroll = carousel.scrollLeft,
        len = carousel.children.length - 1;
    if (info.current <= 0) {
        carousel.scrollLeft = scroll + info.view;
        carousel.prepend(carousel.children[len]);
    } else if (info.current >= len) {
        carousel.scrollLeft = scroll - info.view;
        carousel.append(carousel.children[0]);
    }
};

window.addEventListener("DOMContentLoaded", () => {
    setTimeout(() => {
        carousel.scrollTo({ left: scrollInfo(carousel).view });
    }, 1000);
})
})

* {
    box-sizing: border-box;
}

.carousel {
    display: flex;
    overflow-x: scroll;
    width: 100%;
    height: 100px;
}

.carousel > div {
    display: inherit;
    justify-content: center;
    align-items: center;
    min-width: 100%;
    height: 100%;
    border: 2px solid;
    scroll-snap-align: center;
}

#infiniteCarousel1 {
    scroll-snap-type: x mandatory;
}

Scroll Snap

1

2

3

4

5

No Scroll Snap

1

2

3

4

5

The same example in CodePen.


问:
List is being split into characters when passed through url
I have a city_list I pass from the first view to the second view through the url. When I pass that list to the second view and iterate through it, it iterates through every character rather than the strings in the list. I'm not sure why this is and was wondering how to have the full list passed with the strings it contains.

first view template

```<code><button id="price_button1" hx-post="{% url 'get_price' price_object.id user_city city_list 1 %}">Click</button>
</code>```

first view

```<code>city_list = ["Montreal", "Milan", "Paris", "Singapore", "Barcelona", "Rome"]
</code>```

second view

```<code>def get_price(request, id, user_city, city_list, number):
    for city in city_list:
        print(city)
</code>```

output is

```<code>[
"
M
O
N
T
R
E
A
L
</code>```

instead of Montreal

答:
Views Parameters are strings, except when the type is defined in urls as int or something else.

I suggest that you convert the city to a json list (which is a string) in the first view and load that JSON string back to list in the 2nd view.

Body:
I have a city_list I pass from the first view to the second view through the url. When I pass that list to the second view and iterate through it, it iterates through every character rather than the strings in the list. I'm not sure why this is and was wondering how to have the full list passed with the strings it contains.

first view template

<button id="price_button1" hx-post="{% url 'get_price' price_object.id user_city city_list 1 %}">Click</button>

first view

city_list = ["Montreal", "Milan", "Paris", "Singapore", "Barcelona", "Rome"]

second view

def get_price(request, id, user_city, city_list, number):
    for city in city_list:
        print(city)

output is

[
"
M
O
N
T
R
E
A
L

instead of Montreal


问:
Issues with threading in c#
I want this method to be threaded out so I can set a timer and not wait for it to finish. It's a call to a service.

```<code>private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
    using (WCFServiceChannelFactory<IValueEngineService> client =
              new WCFServiceChannelFactory<IValueEngineService>(
                  Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
    {
        client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
    }
}
</code>```

I tried threading it out like this:

```<code>System.Threading.Thread newThread;
//RestartValueEngineService();

List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
                              ? allIds.GetRange(counter, 7000)
                              : allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;

// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));
</code>```

But it's saying 'the best overloaded match has some invalid arguments.' What am I doing wrong?

答:
Are you using .NET 4? If so, you can do this:

```<code> Task.Factory.StartNew(() => callValueEng(translatedParams));
</code>```

And it will run your code on a new thread. If you need to do something when it completes, then you can easily do that too:

```<code>Task.Factory.StartNew(() => callValueEng(translatedParams))
    .ContinueWith(() => /* Some Other Code */);
</code>```

Title: Issues with threading in c#

Body:
I want this method to be threaded out so I can set a timer and not wait for it to finish. It's a call to a service.

private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
    using (WCFServiceChannelFactory<IValueEngineService> client =
              new WCFServiceChannelFactory<IValueEngineService>(
                  Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
    {
        client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
    }
}

I tried threading it out like this:

System.Threading.Thread newThread;
//RestartValueEngineService();

List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
                              ? allIds.GetRange(counter, 7000)
                              : allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;

// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));

But it's saying 'the best overloaded match has some invalid arguments.' What am I doing wrong?

Body:
Are you using .NET 4? If so, you can do this:

 Task.Factory.StartNew(() => callValueEng(translatedParams));

And it will run your code on a new thread. If you need to do something when it completes, then you can easily do that too:

Task.Factory.StartNew(() => callValueEng(translatedParams))
    .ContinueWith(() => /* Some Other Code */);


问:
I made a simple encryption and decryption program in c and is not working as expected
```<code>// Write a encryption program which encrypts the string by adding 1 to its ASCII value.
#include <stdio.h>
#include <string.h>

void encrypt(char *str)
{
    char *ptr = str;
    while (*ptr != '\0')
    {
        *ptr = *ptr + 1; // This will add integer 1 to the value of character stored in ptr i.e. its ASCII value.
        *ptr++;
    }
}

void decrypt(char *str){
    char *ptr = str;
    while (*ptr != '\0')
    {
        *ptr = *ptr -1; // This will subtract 1 from the ASCII value and restore the original string.
        *ptr++;
    }

}
int main()
{
    char message[] = "We are what we choose to be!";
    encrypt(message);
    printf("The encrypted message is %s\n\n", message);

    char pwd[20] = "omkaushik";
    char input[20];
    printf("Enter password to decrypt the message\n");
    gets(input);

    int result = strcmp(pwd, input);
   while (result != 0)
   {
     printf("The password entered is wrong\n");
     printf("Enter the password again\n");
     gets(input);
     int result = strcmp(pwd, input);
   }
   decrypt(message);
        printf("The password entered is accepted....\n");
        printf("%s",message);

    return 0;
}
</code>```

In this program when I enter the correct password at the start, it decrypts the message successfully but when I enter a wrong password and later try to enter the correct password, it doesn't exit the loop.

答:
First gets is deprecated and unsafe and should never be used.
Second, and this is your question, inside your loop you declare a local variable instead of updating the one in the outer scope

```<code> int result = strcmp(pwd, input);
</code>```

replace it with

```<code> result = strcmp(pwd, input);
</code>```

Will update the test inside the loop

Body:
// Write a encryption program which encrypts the string by adding 1 to its ASCII value.
#include <stdio.h>
#include <string.h>

void encrypt(char *str)
{
    char *ptr = str;
    while (*ptr != '\0')
    {
        *ptr = *ptr + 1; // This will add integer 1 to the value of character stored in ptr i.e. its ASCII value.
        *ptr++;
    }
}

void decrypt(char *str){
    char *ptr = str;
    while (*ptr != '\0')
    {
        *ptr = *ptr -1; // This will subtract 1 from the ASCII value and restore the original string.
        *ptr++;
    }

}
int main()
{
    char message[] = "We are what we choose to be!";
    encrypt(message);
    printf("The encrypted message is %s\n\n", message);

    char pwd[20] = "omkaushik";
    char input[20];
    printf("Enter password to decrypt the message\n");
    gets(input);

    int result = strcmp(pwd, input);
   while (result != 0)
   {
     printf("The password entered is wrong\n");
     printf("Enter the password again\n");
     gets(input);
     int result = strcmp(pwd, input);
   }
   decrypt(message);
        printf("The password entered is accepted....\n");
        printf("%s",message);

    return 0;
}

In this program when I enter the correct password at the start, it decrypts the message successfully but when I enter a wrong password and later try to enter the correct password, it doesn't exit the loop.

Body:
First gets is deprecated and unsafe and should never be used.
Second, and this is your question, inside your loop you declare a local variable instead of updating the one in the outer scope

 int result = strcmp(pwd, input);

replace it with

 result = strcmp(pwd, input);

Will update the test inside the loop


问:
int** a = new int*[n](); What does this function do?

int** a = new int*[n]();
```

I can't find any explanation for this code, all I find is explanations for code like  int *array = new int[n];. I understand it but I can't completely figure out the code above. What does it mean?

答:
As you (should) know, int *a = new int[n]; allocates an array of ints with size n.

So, in general, T * a = new T[n]; allocates an array of Ts with size n.

Now if you substitute T = int *, you'll get int **a = new int*[n];, which allocates an array of int *s (that is, of pointers to int).

Adding () on the right zeroes every pointer in the array (otherwise they would be uninitialized).

Body:
int** a = new int*[n]();

I can't find any explanation for this code, all I find is explanations for code like  int *array = new int[n];. I understand it but I can't completely figure out the code above. What does it mean?


问:
How to get a custom collection based on a data that is most repeated (from top to bottom))
I have a table like this:

Basically this table is named favourite_products and contains product ids that are added as favourite for users.

Now I wanted to get a collection of most added product from this table.

So in this case, a product with an id of 10 would be on top of the collection.

But I don't know how to get this collection ordering by from most repeated product id (prd_id)...

Here is the Model:

```<code>class FavouriteProduct extends Model
{
    protected $table = 'favourite_products';
    protected $fillable = ['usr_id','prd_id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'usr_id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'prd_id');
    }
}
</code>```

UPDATE #1:

Product.php Model:

```<code>public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }
</code>```

答:
try use this</p>
```<code>public function example()
{
    $data=FavouriteProduct::orderBy('prd_id', 'ASC')->get();
    dd($data);
}
</code>```

Body:
I have a table like this:

Basically this table is named favourite_products and contains product ids that are added as favourite for users.

Now I wanted to get a collection of most added product from this table.

So in this case, a product with an id of 10 would be on top of the collection.

But I don't know how to get this collection ordering by from most repeated product id (prd_id)...

Here is the Model:

class FavouriteProduct extends Model
{
    protected $table = 'favourite_products';
    protected $fillable = ['usr_id','prd_id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'usr_id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'prd_id');
    }
}

UPDATE #1:

Product.php Model:

public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }

Body:
try use this

public function example()
{
    $data=FavouriteProduct::orderBy('prd_id', 'ASC')->get();
    dd($data);
}


问:
E0153 - expression must have class type but it has type "void"
I have been trying to make my program work but I have run into an issue.

The error I get on Visual Studio is: expression must have class type but it has type "void"

The error comes from my main.cpp file on line 24:

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "Robot.h"

using namespace std;
using namespace sdds;

int main()
{
    const int num_robots = 6;
    int broken_robot = 0;
    char replacmentName[] = "C3PO";
    Robot robot[num_robots] = {
        {},
        {"KC1", "kitchen", 25.33, 4.55, 2, 2.2, false},
        {"BR1", "bedroom", 5.22, 2.54, 1, 2.2, true},
        {"Broken", "Bedroom", 10.12, 2.5,1.55, 0, true},
        {"KC2", "kitchen", 20.56, 5, 2, 3.5, true},
        {"BR2", "bedroom", 25.32, 6.5, 2.5, 3.1, true}
    };

    while ((broken_robot = conrtolRooomReport(robot, num_robots)) >= 0) {
        cout << endl << "Attention: There is a broken robot! Fixing the problem..." << endl;
        robot[broken_robot].set(replacmentName, "Control Room", 10.0, 4, 1, 2.09, false).display();
        replacmentName[0]++;
        cout << "Replacement Provided!" << endl << endl;
    }

    return 0;
}
</code>```

The Robot.h header file:

```<code>#ifndef _ROBOT_H
#define _ROBOT_H
namespace sdds {
    class Robot {
        char* name;
        char* location;
        double weight;
        double width;
        double height;
        double speeed;
        bool deployed;
    public:
            // Constructs & Destructor:
        Robot();
        Robot(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy);
        ~Robot();
            // Queries:
        char* getName() const;
        char* getLocation() const;
        bool isDeployed() const;
        bool isValid() const;
        double speed() const;
        void display() const;
            // Modifiers
        void set(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy);
        void setLocation(char* newestLoc);
        void setDeployed(bool deploy);
    };
            // Other Functions:
    int conrtolRooomReport(const Robot robot[], int num_robots);
}
#endif
</code>```

display() function implementation:

```<code>void Robot::display() const{
    cout << "| ";
    cout.setf(ios::left);
    cout.width(10);
    cout << name << " | ";
    cout.width(15);
    cout << location << " | ";
    cout.setf(ios::right);
    cout.setf(ios::fixed);
    cout.width(6);
    cout << setprecision(1) << weight << " | ";
    cout.width(6);
    cout << setprecision(1) << width << " | ";
    cout.width(6);
    cout << setprecision(1) << height << " | ";
    cout.width(6);
    cout << setprecision(1) << speeed << " | ";
    cout.width(8);
    cout.unsetf(ios::right);
    cout.setf(ios::left);
    if(isDeployed() == true)
        cout << "YES" << " |" << endl;
    else
        cout << "NO" << " |" << endl;
    cout.unsetf(ios::left);
}
</code>```

set() function implementation:

```<code>void Robot::set(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy) {
    if (newName[0] != '\0' && newName != nullptr && newLoc[0] != '\0' && newLoc != nullptr && newWeight > 0.00 && newWidth > 0.00 && newHeight > 0.00 && newSpeed > 0.00) {
        name = new char[strlen(newName) + 1];
        strcpy(name, newName);
        location = new char[strlen(newLoc) + 1];
        strcpy(location, newLoc);
        weight = newWeight;
        width = newWidth;
        height = newHeight;
        speeed = newSpeed;
        deployed = deploy;
    }
}
</code>```

Any help would be much appreciated. Tried scouring through Google but couldn't find a solution.

答:
Replace

```<code>robot[broken_robot].set(replacmentName, "Control Room", 10.0, 4, 1, 2.09, false).display();
</code>```

with

```<code>robot[broken_robot].set(replacmentName, "Control Room", 10.0, 4, 1, 2.09, false);
robot[broken_robot].display();
</code>```

Body:
I have been trying to make my program work but I have run into an issue.

The error I get on Visual Studio is: expression must have class type but it has type "void"

The error comes from my main.cpp file on line 24:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "Robot.h"

using namespace std;
using namespace sdds;

int main()
{
    const int num_robots = 6;
    int broken_robot = 0;
    char replacmentName[] = "C3PO";
    Robot robot[num_robots] = {
        {},
        {"KC1", "kitchen", 25.33, 4.55, 2, 2.2, false},
        {"BR1", "bedroom", 5.22, 2.54, 1, 2.2, true},
        {"Broken", "Bedroom", 10.12, 2.5,1.55, 0, true},
        {"KC2", "kitchen", 20.56, 5, 2, 3.5, true},
        {"BR2", "bedroom", 25.32, 6.5, 2.5, 3.1, true}
    };

    while ((broken_robot = conrtolRooomReport(robot, num_robots)) >= 0) {
        cout << endl << "Attention: There is a broken robot! Fixing the problem..." << endl;
        robot[broken_robot].set(replacmentName, "Control Room", 10.0, 4, 1, 2.09, false).display();
        replacmentName[0]++;
        cout << "Replacement Provided!" << endl << endl;
    }

    return 0;
}

The Robot.h header file:

#ifndef _ROBOT_H
#define _ROBOT_H
namespace sdds {
    class Robot {
        char* name;
        char* location;
        double weight;
        double width;
        double height;
        double speeed;
        bool deployed;
    public:
            // Constructs & Destructor:
        Robot();
        Robot(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy);
        ~Robot();
            // Queries:
        char* getName() const;
        char* getLocation() const;
        bool isDeployed() const;
        bool isValid() const;
        double speed() const;
        void display() const;
            // Modifiers
        void set(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy);
        void setLocation(char* newestLoc);
        void setDeployed(bool deploy);
    };
            // Other Functions:
    int conrtolRooomReport(const Robot robot[], int num_robots);
}
#endif

display() function implementation:

void Robot::display() const{
    cout << "| ";
    cout.setf(ios::left);
    cout.width(10);
    cout << name << " | ";
    cout.width(15);
    cout << location << " | ";
    cout.setf(ios::right);
    cout.setf(ios::fixed);
    cout.width(6);
    cout << setprecision(1) << weight << " | ";
    cout.width(6);
    cout << setprecision(1) << width << " | ";
    cout.width(6);
    cout << setprecision(1) << height << " | ";
    cout.width(6);
    cout << setprecision(1) << speeed << " | ";
    cout.width(8);
    cout.unsetf(ios::right);
    cout.setf(ios::left);
    if(isDeployed() == true)
        cout << "YES" << " |" << endl;
    else
        cout << "NO" << " |" << endl;
    cout.unsetf(ios::left);
}

set() function implementation:

void Robot::set(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy) {
    if (newName[0] != '\0' && newName != nullptr && newLoc[0] != '\0' && newLoc != nullptr && newWeight > 0.00 && newWidth > 0.00 && newHeight > 0.00 && newSpeed > 0.00) {
        name = new char[strlen(newName) + 1];
        strcpy(name, newName);
        location = new char[strlen(newLoc) + 1];
        strcpy(location, newLoc);
        weight = newWeight;
        width = newWidth;
        height = newHeight;
        speeed = newSpeed;
        deployed = deploy;
    }
}

Any help would be much appreciated. Tried scouring through Google but couldn't find a solution.

Body:
Replace

robot[broken_robot].set(replacmentName, "Control Room", 10.0, 4, 1, 2.09, false).display();

with

robot[broken_robot].set(replacmentName, "Control Room", 10.0, 4, 1, 2.09, false);
robot[broken_robot].display();


问:
Can't use Pydantic model attributes on type hinting
Like I used to do with FastAPI routes, I want to make a function that is expecting a dict. I want to type hint like in FastAPI with a Pydantic model.

Note that I am just using FastAPI as a reference here and this app serves a total different purpose.

What I did:

models.py

from pydantic import BaseModel

class Mymodel(BaseModel):
  name:str
  age:int
```
<p><code>main.py</code></p>
<pre class="lang-py prettyprint-override"><code>def myfunc(m:Mymodel):
  print(m)
  print(m.name)

myfunc({"name":"abcd","age":3})
</code>```

It prints m as a normal dict and not Mymodel and m.name just throws an AttributeError.
I don't understand why it is behaving like this because the same code would work in FastAPI. Am I missing something here? What should I do to make this work.

I am expecting a dict arg in the func, I want to type hint with a class inherited from pydantic BaseModel. Then I want to acccess the attributes of that class.

I don't want to do:

def myfunc(m):
  m = Mymodel(**m)
```

Thank You.

答:
Since you pass a dict to your custom function, the attribute should be accessed in the following way:

print(m['name'])
# or
print(m.get('name'))
```
<p>Otherwise, to use <code>m.name</code> instead, you need to parse the <code>dict</code> to the corresponding Pydantic model, before passing it to the function, as shwon below:</p>
```data = {"name":"abcd", "age":3}
myfunc(Mymodel(**data))
# or
myfunc(Mymodel.parse_obj(data))
```
<p>The reason that passing <code>{"name":"abcd", "age":3}</code> in FastAPI and later accessing the attributes using the <em>dot</em> operator (e.g., <code>m.name</code>) works, is that FastAPI does the above parsing and validation internally, as soon as a request arrives. This is the reason that you can then convert it back to a dictionary in your endpoint, using <code>m.dict()</code>. Try, for example, passing an incorrect <code>key</code>, e.g., <code>myfunc(Mymodel(**{"name":"abcd","MYage":3}))</code>—you would get a <code>field required (type=value_error.missing)</code> error (as part of Pydantic's Error Handling), similar to what FastAPI would return (as shown below), if a similar request attempted to go through (you could also test that through Swagger UI autodocs at http://127.0.0.1:8000/docs). Otherwise, any dictionary passed by the user (in the way you show in the question) would go through without throwing an error, in case it didn't match the Pydantic model.</p>
```{
  "detail": [
    {
      "loc": [
        "body",
        "age"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}
```
<p>You could alternatively use Pydantic's validation decorator (i.e., <code>@validate_arguments</code>) on your custom function. As per the documentation:</p>
<blockquote>
<p>The <code>validate_arguments</code> decorator allows the arguments passed to a
function to be <strong>parsed and validated</strong> using the function's annotations
before the function is called. While <strong>under the hood this uses the same
approach</strong> of model <em>creation</em> and <em>initialisation</em>; it provides an
extremely easy way to apply validation to your code with minimal
boilerplate.</p>
</blockquote>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>from pydantic import validate_arguments
from pydantic import BaseModel

class Model(BaseModel):
  name: str
  age: int

@validate_arguments
def myfunc(m: Model):
   print(m)
   print(m.name)

myfunc({"name":"abcd","age":3})
</code>```

Body:
Like I used to do with FastAPI routes, I want to make a function that is expecting a dict. I want to type hint like in FastAPI with a Pydantic model.

Note that I am just using FastAPI as a reference here and this app serves a total different purpose.

What I did:

models.py

from pydantic import BaseModel

class Mymodel(BaseModel):
  name:str
  age:int

main.py

def myfunc(m:Mymodel):
  print(m)
  print(m.name)

myfunc({"name":"abcd","age":3})

It prints m as a normal dict and not Mymodel and m.name just throws an AttributeError.
I don't understand why it is behaving like this because the same code would work in FastAPI. Am I missing something here? What should I do to make this work.

I am expecting a dict arg in the func, I want to type hint with a class inherited from pydantic BaseModel. Then I want to acccess the attributes of that class.

I don't want to do:

def myfunc(m):
  m = Mymodel(**m)

Thank You.

Body:
Since you pass a dict to your custom function, the attribute should be accessed in the following way:

print(m['name'])
# or
print(m.get('name'))

Otherwise, to use m.name instead, you need to parse the dict to the corresponding Pydantic model, before passing it to the function, as shwon below:

data = {"name":"abcd", "age":3}
myfunc(Mymodel(**data))
# or
myfunc(Mymodel.parse_obj(data))

The reason that passing {"name":"abcd", "age":3} in FastAPI and later accessing the attributes using the dot operator (e.g., m.name) works, is that FastAPI does the above parsing and validation internally, as soon as a request arrives. This is the reason that you can then convert it back to a dictionary in your endpoint, using m.dict(). Try, for example, passing an incorrect key, e.g., myfunc(Mymodel(**{"name":"abcd","MYage":3}))—you would get a field required (type=value_error.missing) error (as part of Pydantic's Error Handling), similar to what FastAPI would return (as shown below), if a similar request attempted to go through (you could also test that through Swagger UI autodocs at http://127.0.0.1:8000/docs). Otherwise, any dictionary passed by the user (in the way you show in the question) would go through without throwing an error, in case it didn't match the Pydantic model.

{
  "detail": [
    {
      "loc": [
        "body",
        "age"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

You could alternatively use Pydantic's validation decorator (i.e., @validate_arguments) on your custom function. As per the documentation:

The validate_arguments decorator allows the arguments passed to a
function to be parsed and validated using the function's annotations
before the function is called. While under the hood this uses the same
approach of model creation and initialisation; it provides an
extremely easy way to apply validation to your code with minimal
boilerplate.

Example:

from pydantic import validate_arguments
from pydantic import BaseModel

class Model(BaseModel):
  name: str
  age: int

@validate_arguments
def myfunc(m: Model):
   print(m)
   print(m.name)

myfunc({"name":"abcd","age":3})